repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
srsudar/SemCache
extension/test/scripts/content-script/cs-evaluation-test.js
14556
/*jshint esnext:true*/ 'use strict'; const proxyquire = require('proxyquire'); const sinon = require('sinon'); const test = require('tape'); let evaluation = require('../../../app/scripts/content-script/cs-evaluation'); /** * Proxyquire the object with proxies passed as the proxied modules. */ function proxyquireEvaluation(proxies) { evaluation = proxyquire( '../../../app/scripts/content-script/cs-evaluation', proxies ); } /** * Manipulating the object directly leads to polluting the require cache. Any * test that modifies the required object should call this method to get a * fresh version */ function resetEvaluation() { delete require.cache[ require.resolve('../../../app/scripts/content-script/cs-evaluation') ]; evaluation = require('../../../app/scripts/content-script/cs-evaluation'); } function storageGetHelper(key, expected, fnName, t) { let getResult = {}; getResult[key] = expected; let getSpy = sinon.stub().resolves(getResult); proxyquireEvaluation({ '../chrome-apis/storage': { get: getSpy } }); // Unfortunately, b/c we proxyquire in the helper, we pass the method name. evaluation[fnName]().then(actual => { t.deepEqual(actual, expected); t.deepEqual(getSpy.args[0], [key]); t.end(); resetEvaluation(); }) .catch(err => { console.log(err); }); } test('isPerformingTrial correct if not set', function(t) { let getSpy = sinon.stub().resolves({}); proxyquireEvaluation({ '../chrome-apis/storage': { get: getSpy } }); evaluation.isPerformingTrial() .then(actual => { t.false(actual); t.deepEqual(getSpy.args[0], [evaluation.KEY_PERFORMING_TRIAL]); t.end(); resetEvaluation(); }); }); test('isPerformingTrial returns result if present', function(t) { let expected = 'value from set'; storageGetHelper( evaluation.KEY_PERFORMING_TRIAL, expected, 'isPerformingTrial', t ); }); test('getParameters returns results', function(t) { let expected = { key: 'logKey', numIterations: 15, currentIter: 2, urlList: ['url0', 'url1', 'url2'], urlListIndex: 1, activeUrl: 'url1' }; let expectedGetArg = [ evaluation.KEY_NUM_ITERATIONS, evaluation.KEY_CURRENT_ITERATION, evaluation.KEY_LOG_KEY, exports.KEY_URL_LIST, exports.KEY_URL_LIST_INDEX ]; let getResult = {}; getResult[evaluation.KEY_NUM_ITERATIONS] = expected.numIterations; getResult[evaluation.KEY_CURRENT_ITERATION] = expected.currentIter; getResult[evaluation.KEY_LOG_KEY] = expected.key; getResult[evaluation.KEY_URL_LIST] = expected.urlList; getResult[evaluation.KEY_URL_LIST_INDEX] = expected.urlListIndex; let getSpy = sinon.stub().withArgs(expectedGetArg).resolves(getResult); proxyquireEvaluation({ '../chrome-apis/storage': { get: getSpy } }); evaluation.getParameters() .then(actual => { t.deepEqual(actual, expected); t.end(); resetEvaluation(); }); }); test('requestSavePage sends message and resolves', function(t) { let expectedMessage = { type: 'savePageForContentScript' }; let expected = 'response from sendMessage'; let sendMessageSpy = function(actualMessage, callback) { t.deepEqual(actualMessage, expectedMessage); callback(expected); }; proxyquireEvaluation({ '../chrome-apis/runtime': { sendMessage: sendMessageSpy } }); evaluation.requestSavePage() .then(actual => { t.deepEqual(actual, expected); t.end(); resetEvaluation(); }); }); test('savePage resolves as expected', function(t) { let loadTime = 10101.2; let savePageResult = { timeToWrite: 1982.2 }; let totalTime = loadTime + savePageResult.timeToWrite; let getFullLoadTimeSpy = sinon.stub().returns(loadTime); let requestSavePageSpy = sinon.stub().resolves(savePageResult); let getOnCompletePromiseSpy = sinon.stub().resolves(); let expected = { domCompleteTime: loadTime, timeToWrite: savePageResult.timeToWrite, totalTime: totalTime }; proxyquireEvaluation({ './cs-api': { getFullLoadTime: getFullLoadTimeSpy }, '../util/util': { getOnCompletePromise: getOnCompletePromiseSpy } }); evaluation.requestSavePage = requestSavePageSpy; evaluation.savePage() .then(actual => { t.deepEqual(actual, expected); t.equal(getOnCompletePromiseSpy.callCount, 1); t.end(); resetEvaluation(); }); }); test('createMetadataForLog correct', function(t) { let dateStr = 'april happy day'; let href = 'www.fancy.org#ugh'; let getWindowSpy = sinon.stub().returns({ location: { href: href } }); let getTodaySpy = sinon.stub().returns({ toString: sinon.stub().returns(dateStr) }); proxyquireEvaluation({ '../util/util': { getWindow: getWindowSpy, getToday: getTodaySpy } }); let expected = { href: href, date: dateStr }; let actual = evaluation.createMetadataForLog(); t.deepEqual(actual, expected); t.end(); resetEvaluation(); }); test('deleteStorageHelperValues deletes and resolves', function(t) { let removeSpy = sinon.stub().resolves(); proxyquireEvaluation({ '../chrome-apis/storage': { remove: removeSpy } }); evaluation.deleteStorageHelperValues() .then(() => { t.deepEqual( removeSpy.args[0], [ [ evaluation.KEY_PERFORMING_TRIAL, evaluation.KEY_NUM_ITERATIONS, evaluation.KEY_CURRENT_ITERATION, evaluation.KEY_LOG_KEY, evaluation.KEY_URL_LIST, evaluation.KEY_URL_LIST_INDEX ] ] ); t.end(); resetEvaluation(); }); }); test('runSavePageIteration returns save result', function(t) { // let key = 'googleCom'; // let numIter = 8; // let totalIterations = 10; let timingInfo = { time: 'for tea' }; // let metadata = { // soMeta: '#hashtag' // }; // let expectedLogArg = { // time: timingInfo.time, // metadata: metadata // }; // let expectedSetArg = {}; // expectedSetArg[evaluation.KEY_CURRENT_ITERATION] = numIter + 1; let savePageSpy = sinon.stub().resolves(timingInfo); // let createMetadataForLogSpy = sinon.stub().returns(metadata); // let logTimeSpy = sinon.stub(); // let setSpy = sinon.stub().resolves(); // let reloadSpy = sinon.stub(); // let getWindowSpy = sinon.stub().returns({ // location: { // reload: reloadSpy // } // }); proxyquireEvaluation({ '../util/util': { wait: sinon.stub().resolves() }, }); evaluation.savePage = savePageSpy; evaluation.runSavePageIteration() .then(actual => { t.equal(actual, timingInfo); t.end(); resetEvaluation(); }); }); test('onPageLoadComplete deletes values if no more iterations', function(t) { let key = 'googleCom'; // this will be the last iteration let numIter = 9; let totalIterations = 10; let urlList = ['url0', 'url1', 'url2']; let urlListIndex = 2; // the last one let activeUrl = urlList[urlListIndex]; let params = { key: key, numIterations: totalIterations, currentIter: numIter, urlList: urlList, urlListIndex: urlListIndex, activeUrl: activeUrl }; let getParametersSpy = sinon.stub().resolves(params); let timingInfo = { time: 'for tea' }; let metadata = { soMeta: '#hashtag' }; let expectedLogArg = { timing: timingInfo, metadata: metadata, iteration: params.currentIter, numIterations: params.numIterations, url: params.activeUrl, urlListIndex: params.urlListIndex }; let createMetadataForLogSpy = sinon.stub().returns(metadata); let logTimeSpy = sinon.stub(); let deleteStorageHelperValuesSpy = sinon.stub().resolves(); let logResultSpy = sinon.stub(); let runSavePageIterationSpy = sinon.stub().resolves(timingInfo); proxyquireEvaluation({ '../../../../chromeapp/app/scripts/evaluation': { logTime: logTimeSpy } }); evaluation.createMetadataForLog = createMetadataForLogSpy; evaluation.deleteStorageHelperValues = deleteStorageHelperValuesSpy; evaluation.logResult = logResultSpy; evaluation.getParameters = getParametersSpy; evaluation.runSavePageIteration = runSavePageIterationSpy; evaluation.isPerformingTrial = sinon.stub().resolves(true); evaluation.getHref = sinon.stub().returns(activeUrl); evaluation.onPageLoadComplete() .then(actual => { // We expect no resolved value t.equal(actual, undefined); t.deepEqual(deleteStorageHelperValuesSpy.args[0], []); t.true(deleteStorageHelperValuesSpy.calledOnce); t.deepEqual(logTimeSpy.args[0], [key, expectedLogArg]); t.deepEqual(logResultSpy.args[0], [key]); t.end(); resetEvaluation(); }); }); test('onPageLoadComplete increments iteration variables', function(t) { let key = 'googleCom'; // this will be the last iteration let numIter = 8; let totalIterations = 10; let urlList = ['url0', 'url1', 'url2']; let urlListIndex = 2; // the last one let activeUrl = urlList[urlListIndex]; let params = { key: key, numIterations: totalIterations, currentIter: numIter, urlList: urlList, urlListIndex: urlListIndex, activeUrl: activeUrl }; let getParametersSpy = sinon.stub().resolves(params); let timingInfo = { time: 'for tea' }; let metadata = { soMeta: '#hashtag' }; let expectedLogArg = { timing: timingInfo, metadata: metadata, iteration: params.currentIter, numIterations: params.numIterations, url: params.activeUrl, urlListIndex: params.urlListIndex }; let createMetadataForLogSpy = sinon.stub().returns(metadata); let logTimeSpy = sinon.stub(); let logResultSpy = sinon.stub(); let runSavePageIterationSpy = sinon.stub().resolves(timingInfo); let setSpy = sinon.stub().resolves(); let deleteStorageHelperValuesSpy = sinon.stub().resolves(); let reloadSpy = sinon.stub(); let windowObj = { location: { reload: reloadSpy } }; let getWindowSpy = sinon.stub().returns(windowObj); proxyquireEvaluation({ '../chrome-apis/storage': { set: setSpy }, '../../../../chromeapp/app/scripts/evaluation': { logTime: logTimeSpy }, '../util/util': { getWindow: getWindowSpy } }); evaluation.createMetadataForLog = createMetadataForLogSpy; evaluation.logResult = logResultSpy; evaluation.getParameters = getParametersSpy; evaluation.runSavePageIteration = runSavePageIterationSpy; evaluation.isPerformingTrial = sinon.stub().resolves(true); evaluation.getHref = sinon.stub().returns(activeUrl); evaluation.deleteStorageHelperValues = deleteStorageHelperValuesSpy; let setArg = {}; setArg[evaluation.KEY_CURRENT_ITERATION] = numIter + 1; evaluation.onPageLoadComplete() .then(actual => { // We expect no resolved value t.equal(actual, undefined); t.deepEqual(setSpy.args[0], [setArg]); t.deepEqual(logTimeSpy.args[0], [key, expectedLogArg]); t.deepEqual(logResultSpy.args[0], [key]); t.deepEqual(reloadSpy.args[0], [true]); t.equal(deleteStorageHelperValuesSpy.callCount, 0); t.end(); resetEvaluation(); }); }); test('onPageLoadComplete moves to next url', function(t) { let key = 'googleCom'; // this will be the last iteration let numIter = 9; let totalIterations = 10; let urlList = ['url0', 'url1', 'url2']; let urlListIndex = 1; let activeUrl = urlList[urlListIndex]; let params = { key: key, numIterations: totalIterations, currentIter: numIter, urlList: urlList, urlListIndex: urlListIndex, activeUrl: activeUrl }; let getParametersSpy = sinon.stub().resolves(params); let timingInfo = { time: 'for tea' }; let metadata = { soMeta: '#hashtag' }; let expectedLogArg = { timing: timingInfo, metadata: metadata, iteration: params.currentIter, numIterations: params.numIterations, url: params.activeUrl, urlListIndex: params.urlListIndex }; let createMetadataForLogSpy = sinon.stub().returns(metadata); let logTimeSpy = sinon.stub(); let logResultSpy = sinon.stub(); let runSavePageIterationSpy = sinon.stub().resolves(timingInfo); let setSpy = sinon.stub().resolves(); let deleteStorageHelperValuesSpy = sinon.stub().resolves(); let windowObj = { location: { href: null } }; let getWindowSpy = sinon.stub().returns(windowObj); proxyquireEvaluation({ '../chrome-apis/storage': { set: setSpy }, '../../../../chromeapp/app/scripts/evaluation': { logTime: logTimeSpy }, '../util/util': { getWindow: getWindowSpy } }); evaluation.createMetadataForLog = createMetadataForLogSpy; evaluation.logResult = logResultSpy; evaluation.getParameters = getParametersSpy; evaluation.runSavePageIteration = runSavePageIterationSpy; evaluation.isPerformingTrial = sinon.stub().resolves(true); evaluation.getHref = sinon.stub().returns(activeUrl); evaluation.deleteStorageHelperValues = deleteStorageHelperValuesSpy; let setArg = {}; setArg[evaluation.KEY_CURRENT_ITERATION] = 0; setArg[evaluation.KEY_URL_LIST_INDEX] = urlListIndex + 1; evaluation.onPageLoadComplete() .then(actual => { // We expect no resolved value t.equal(actual, undefined); t.deepEqual(setSpy.args[0], [setArg]); t.deepEqual(logTimeSpy.args[0], [key, expectedLogArg]); t.deepEqual(logResultSpy.args[0], [key]); t.deepEqual(windowObj.location.href, urlList[urlListIndex + 1]); t.equal(deleteStorageHelperValuesSpy.callCount, 0); t.end(); resetEvaluation(); }); }); test('startSavePageTrial sets variables and reloads', function(t) { let urls = ['url0', 'url1']; let setSpy = sinon.stub().resolves(); let numIterations = 10; let key = 'firstTry'; let setArg = {}; setArg[evaluation.KEY_NUM_ITERATIONS] = numIterations; setArg[evaluation.KEY_PERFORMING_TRIAL] = true; setArg[evaluation.KEY_CURRENT_ITERATION] = 0; setArg[evaluation.KEY_LOG_KEY] = key; setArg[evaluation.KEY_URL_LIST] = urls; setArg[evaluation.KEY_URL_LIST_INDEX] = 0; proxyquireEvaluation({ '../chrome-apis/storage': { set: setSpy }, '../util/util': { wait: sinon.stub().resolves() } }); evaluation.startSavePageTrial(urls, numIterations, key) .then(() => { t.deepEqual(setSpy.args[0], [setArg]); t.end(); resetEvaluation(); }); });
mit
HasanSa/hackathon
node_modules/react-visibility-sensor/karma.conf.js
1575
// Karma configuration // Generated on Thu Sep 18 2014 10:13:19 GMT+1000 (EST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha'], // list of files / patterns to load in the browser files: [ './tests/bundle.js' ], // list of files to exclude exclude: [ ], // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: [ process.env.TRAVIS === "true" ? 'Chrome_travis_ci' : 'Chrome' ], customLaunchers: { Chrome_travis_ci: { base: 'Chrome', flags: ['--no-sandbox'] } }, // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
mit
fernandozamoraj/DirectoryWiz
DirectoryWiz.UnitTests/RemoveHandlerTests.cs
3864
using DirectoryWiz.Framework.Api; using DirectoryWiz.Framework.CommandLineHelpers; using DirectoryWiz.Framework.CommandLineHelpers.Handlers; using Moq; using NUnit.Framework; namespace DirectoryWiz.UnitTests { public class RemoveHandlerContext { protected RemoveHandler RemoveHandler; protected Moq.Mock<IFileRemover> _fileRemoverMock; protected Moq.Mock<IDivLogger> _divLoggerMock; [TestFixtureSetUp] public virtual void Context() { _divLoggerMock = new Mock<IDivLogger>(); _fileRemoverMock = new Mock<IFileRemover>(); } } [TestFixture] public class When_remove_by_folder_extensions_is_called : RemoveHandlerContext { public override void Context() { base.Context(); _fileRemoverMock.Setup( fileRemover => fileRemover.RemoveFileByExtensions(It.IsAny<string>(), It.IsAny<string[]>())) .AtMostOnce(); RemoveHandler = new RemoveHandler(_fileRemoverMock.Object); RemoveHandler.HandleRequest(new[]{"--remove", "-e", "rootpath", ".ext1 .ext2"}, _divLoggerMock.Object); } [Test] public void Should_execute_the_remove_file_by_extensions_method() { _fileRemoverMock.Verify(x => x.RemoveFileByExtensions(It.IsAny<string>(), It.IsAny<string[]>())); } } [TestFixture] public class When_remove_by_folder_filename_is_called : RemoveHandlerContext { public override void Context() { base.Context(); _fileRemoverMock.Setup( fileRemover => fileRemover.RemoveFileByName(It.IsAny<string>(), It.IsAny<string[]>())) .AtMostOnce(); RemoveHandler = new RemoveHandler(_fileRemoverMock.Object); RemoveHandler.HandleRequest(new[] { "--remove", "-n", "rootpath", "file2.txt file2.txt" }, _divLoggerMock.Object); } [Test] public void Should_execute_the_remove_file_by_extensions_method() { _fileRemoverMock.Verify(x => x.RemoveFileByName(It.IsAny<string>(), It.IsAny<string[]>())); } } [TestFixture] public class When_remove_by_folder_name : RemoveHandlerContext { public override void Context() { base.Context(); _fileRemoverMock.Setup( fileRemover => fileRemover.RemoveFolderByName(It.IsAny<string>(), It.IsAny<string[]>())) .AtMostOnce(); RemoveHandler = new RemoveHandler(_fileRemoverMock.Object); RemoveHandler.HandleRequest(new[] { "--remove", "-fn", "rootpath", ".svn bin debug" }, _divLoggerMock.Object); } [Test] public void Should_execute_the_remove_file_by_extensions_method() { _fileRemoverMock.Verify(x => x.RemoveFolderByName(It.IsAny<string>(), It.IsAny<string[]>())); } } [TestFixture] public class When_remove_by_regular_expression : RemoveHandlerContext { public override void Context() { base.Context(); _fileRemoverMock.Setup( fileRemover => fileRemover.RemoveByRegularExpression(It.IsAny<string>(), It.IsAny<string>())) .AtMostOnce(); RemoveHandler = new RemoveHandler(_fileRemoverMock.Object); RemoveHandler.HandleRequest(new[] { "--remove", "-rx", "rootpath", "[A-Z][a-z]" }, _divLoggerMock.Object); } [Test] public void Should_execute_the_remove_file_by_extensions_method() { _fileRemoverMock.Verify(x => x.RemoveByRegularExpression(It.IsAny<string>(), It.IsAny<string>())); } } }
mit
mahemrai/SinglePay
src/PaymentService/Element/Express/Type/ExtendedParameters.php
246
<?php namespace SinglePay\PaymentService\Element\Express\Type; class ExtendedParameters { public $Key; public $Value; public function __construct($key, $value) { $this->Key = $key; $this->Value = $value; } }
mit
shreyshahi/bchydro
bchydro/gmm.py
3365
''' Implementation of the BC Hydro model''' import numpy as np import itertools import model def interpolateSpectra(spectra1 , spectra2 , period1, period2, period): slope = (spectra2 - spectra1)/(np.log(period2) - np.log(period1)) return spectra1 + slope*(np.log(period) - np.log(period1)) def fixPeriods(augmentedSpectra, periods, augmentedPeriods): fixedSpectra = np.zeros((augmentedSpectra.shape[0], periods.shape[0])) sortedAugmented = sorted(augmentedPeriods) for i, per in enumerate(periods): if per in augmentedPeriods: fixedSpectra[:, i] = augmentedSpectra[:, 0] fixedSpectra[:, i] = augmentedSpectra[:, np.nonzero(augmentedPeriods == per)[0][0]] else: idxLow = np.nonzero(sortedAugmented < per)[0][-1] perLow = sortedAugmented[idxLow] idxLow = np.nonzero(augmentedPeriods == perLow)[0][0] idxHigh = np.nonzero(sortedAugmented > per)[0][0] perHigh = sortedAugmented[idxHigh] idxHigh = np.nonzero(augmentedPeriods == perHigh)[0][0] fixedSpectra[:, i] = interpolateSpectra(augmentedSpectra[:, idxLow] , augmentedSpectra[:, idxHigh] , augmentedPeriods[idxLow] , augmentedPeriods[idxHigh] , per) return fixedSpectra def augmentPeriods(periods): availablePeriods = np.array([0.01, 0.02, 0.05, 0.075, 0.1, 0.15, 0.2, 0.250, 0.3, 0.4, 0.5, 0.6, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 6.0, 7.5, 10.0]) modifiedPeriods = [] for period in periods: if period in availablePeriods: modifiedPeriods.append(period) else: idxLow = np.nonzero(availablePeriods < period)[0][-1] modifiedPeriods.append(availablePeriods[idxLow]) idxHigh = np.nonzero(availablePeriods > period)[0][0] modifiedPeriods.append(availablePeriods[idxHigh]) return modifiedPeriods def spectra(M, Rrup, Rhyp, eventType, Z, Faba, Vs30, periods): periods = np.array(periods) idx = np.nonzero(periods <= 0.01)[0] periods[idx] = 0.01 # Periods less than eq to 0.01 are essentially pga. Setting this allows us to avoid errors while interpolating in log-log scale. augmentedPeriods = augmentPeriods(periods) # compute R based on event type R = [rrup if ev == 0 else rhyp for rrup, rhyp, ev in itertools.izip(Rrup, Rhyp, eventType)] nRow = len(M) nCol = len(augmentedPeriods) M = np.array([M] * nCol).transpose() R = np.array([R] * nCol).transpose() eventType = np.array([eventType] * nCol).transpose() Z = np.array([Z] * nCol).transpose() Faba = np.array([Faba] * nCol).transpose() Vs30 = np.array([Vs30] * nCol).transpose() augmentedPeriods = np.array([augmentedPeriods] * nRow) augmentedSpectra = np.array([[model.computeSpectra(mag, r, evt, z, faba, vs, per) for mag, r, evt, z, faba, vs, per in itertools.izip(mags, rs, evts, zs, fabas, vss, pers)] for mags, rs, evts, zs, fabas, vss, pers in itertools.izip(M, R, eventType, Z, Faba, Vs30, augmentedPeriods)]) fixedSpectra = fixPeriods(augmentedSpectra, periods, augmentedPeriods[0]) intraEventSigma = np.ones(fixedSpectra.shape) * model.intraEventSigma() interEventSigma = np.ones(fixedSpectra.shape) * model.interEventSigma() return (np.exp(fixedSpectra)).tolist(), intraEventSigma.tolist(), interEventSigma.tolist()
mit
tranngoclam/fast-list
app/src/main/java/io/github/tranngoclam/fastlist/RxRecyclerViewAdapterCallback.java
822
package io.github.tranngoclam.fastlist; import android.support.v7.widget.RecyclerView; public abstract class RxRecyclerViewAdapterCallback<T> extends RxSortedListCallback<T> { private final RecyclerView.Adapter mAdapter; public RxRecyclerViewAdapterCallback(RecyclerView.Adapter adapter) { mAdapter = adapter; } @Override public void onChanged(int position, int count) { mAdapter.notifyItemChanged(position, count); } @Override public void onInserted(int position, int count) { mAdapter.notifyItemRangeInserted(position, count); } @Override public void onMoved(int fromPosition, int toPosition) { mAdapter.notifyItemMoved(fromPosition, toPosition); } @Override public void onRemoved(int position, int count) { mAdapter.notifyItemRangeRemoved(position, count); } }
mit
mabarroso/associator
spec/dummy/rails_app/app/models/six.rb
35
class Six < ActiveRecord::Base end
mit
obsidiancoin/obsidiancoin
src/net.cpp
52988
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "db.h" #include "net.h" #include "init.h" #include "strlcpy.h" #include "addrman.h" #include "ui_interface.h" #ifdef WIN32 #include <string.h> #endif using namespace std; using namespace boost; static const int MAX_OUTBOUND_CONNECTIONS = 8; void ThreadMessageHandler2(void* parg); void ThreadSocketHandler2(void* parg); void ThreadOpenConnections2(void* parg); void ThreadOpenAddedConnections2(void* parg); void ThreadDNSAddressSeed2(void* parg); bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false); struct LocalServiceInfo { int nScore; int nPort; }; // // Global state variables // bool fClient = false; bool fDiscover = true; uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK); static CCriticalSection cs_mapLocalHost; static map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; uint64 nLocalHostNonce = 0; array<int, THREAD_MAX> vnThreadsRunning; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; map<CInv, int64> mapAlreadyAskedFor; static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; static CSemaphore *semOutbound = NULL; void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", GetDefaultPort())); } void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd) { // Filter out duplicate requests if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd) return; pindexLastGetBlocksBegin = pindexBegin; hashLastGetBlocksEnd = hashEnd; PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (fNoListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService("0.0.0.0",0),0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); } return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; loop { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { if (fShutdown) return false; if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { Sleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed printf("socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); printf("recv failed: %d\n", nErr); return false; } } } } // used when scores of local addresses may have changed // pushes better local address to peers void static AdvertizeLocal() { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal) { pnode->PushAddress(addrLocal); pnode->addrLocal = addrLocal; } } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore; info.nPort = addr.GetPort() + (fAlready ? 1 : 0); } SetReachable(addr.GetNetwork()); } AdvertizeLocal(); return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } AdvertizeLocal(); return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { LOCK(cs_mapLocalHost); enum Network net = addr.GetNetwork(); return vfReachable[net] && !vfLimited[net]; } bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet) { SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str()); send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL); string strLine; while (RecvLine(hSocket, strLine)) { if (strLine.empty()) // HTTP response is separated from headers by blank line { loop { if (!RecvLine(hSocket, strLine)) { closesocket(hSocket); return false; } if (pszKeyword == NULL) break; if (strLine.find(pszKeyword) != string::npos) { strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword)); break; } } closesocket(hSocket); if (strLine.find("<") != string::npos) strLine = strLine.substr(0, strLine.find("<")); strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r")); while (strLine.size() > 0 && isspace(strLine[strLine.size()-1])) strLine.resize(strLine.size()-1); CService addr(strLine,0,true); printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str()); if (!addr.IsValid() || !addr.IsRoutable()) return false; ipRet.SetIP(addr); return true; } } closesocket(hSocket); return error("GetMyExternalIP() : connection closed"); } // We now get our external IP from the IRC server first and only use this as a backup bool GetMyExternalIP(CNetAddr& ipRet) { CService addrConnect; const char* pszGet; const char* pszKeyword; for (int nLookup = 0; nLookup <= 1; nLookup++) for (int nHost = 1; nHost <= 2; nHost++) { // We should be phasing out our use of sites like these. If we need // replacements, we should ask for volunteers to put this simple // php file on their webserver that prints the client IP: // <?php echo $_SERVER["REMOTE_ADDR"]; ?> if (nHost == 1) { addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org if (nLookup == 1) { CService addrIP("checkip.dyndns.org", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET / HTTP/1.1\r\n" "Host: checkip.dyndns.org\r\n" "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = "Address:"; } else if (nHost == 2) { addrConnect = CService("74.208.43.192", 80); // www.showmyip.com if (nLookup == 1) { CService addrIP("www.showmyip.com", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET /simple/ HTTP/1.1\r\n" "Host: www.showmyip.com\r\n" "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = NULL; // Returns just IP address } if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet)) return true; } return false; } void ThreadGetMyExternalIP(void* parg) { // Make this thread recognisable as the external IP detection thread RenameThread("bitcoin-ext-ip"); CNetAddr addrLocalHost; if (GetMyExternalIP(addrLocalHost)) { printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str()); AddLocal(addrLocalHost, LOCAL_HTTP); } } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } CNode* FindNode(const CNetAddr& ip) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); } return NULL; } CNode* FindNode(std::string addrName) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CService)pnode->addr == addr) return (pnode); } return NULL; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout) { if (pszDest == NULL) { if (IsLocal(addrConnect)) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { if (nTimeout != 0) pnode->AddRef(nTimeout); else pnode->AddRef(); return pnode; } } /// debug print printf("trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString().c_str(), pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket)) { addrman.Attempt(addrConnect); /// debug print printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str()); // Set to nonblocking #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError()); #else if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno); #endif // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); if (nTimeout != 0) pnode->AddRef(nTimeout); else pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); return pnode; } else { return NULL; } } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { printf("disconnecting node %s\n", addrName.c_str()); closesocket(hSocket); hSocket = INVALID_SOCKET; vRecv.clear(); } } void CNode::Cleanup() { } void CNode::PushVersion() { /// when NTP implemented, change to just nTime = GetAdjustedTime() int64 nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0))); CAddress addrMe = GetLocalAddress(&addr); RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str()); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight); } std::map<CNetAddr, int64> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64 t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Misbehaving(int howmuch) { if (addr.IsLocal()) { printf("Warning: local node %s misbehaving\n", addrName.c_str()); return false; } nMisbehavior += howmuch; if (nMisbehavior >= GetArg("-banscore", 100)) { int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } CloseSocketDisconnect(); printf("Disconnected %s for misbehavior (score=%d)\n", addrName.c_str(), nMisbehavior); return true; } return false; } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(strSubVer); X(fInbound); X(nReleaseTime); X(nStartingHeight); X(nMisbehavior); } #undef X void ThreadSocketHandler(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg)); // Make this thread recognisable as the networking thread RenameThread("bitcoin-net"); try { vnThreadsRunning[THREAD_SOCKETHANDLER]++; ThreadSocketHandler2(parg); vnThreadsRunning[THREAD_SOCKETHANDLER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_SOCKETHANDLER]--; PrintException(&e, "ThreadSocketHandler()"); } catch (...) { vnThreadsRunning[THREAD_SOCKETHANDLER]--; throw; // support pthread_cancel() } printf("ThreadSocketHandler exited\n"); } void ThreadSocketHandler2(void* parg) { printf("ThreadSocketHandler started\n"); list<CNode*> vNodesDisconnected; unsigned int nPrevNodeCount = 0; loop { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); pnode->Cleanup(); // hold in disconnected pool until all refs are released pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60); if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecv, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_mapRequests, lockReq); if (lockReq) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if (vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(vNodes.size()); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) { FD_SET(hListenSocket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket); } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetRecv); FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend && !pnode->vSend.empty()) FD_SET(pnode->hSocket, &fdsetSend); } } } vnThreadsRunning[THREAD_SOCKETHANDLER]--; int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); vnThreadsRunning[THREAD_SOCKETHANDLER]++; if (fShutdown) return; if (nSelect == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (hSocketMax != INVALID_SOCKET) { printf("socket select error %d\n", nErr); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); Sleep(timeout.tv_usec/1000); } // // Accept new connections // BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv)) { #ifdef USE_IPV6 struct sockaddr_storage sockaddr; #else struct sockaddr sockaddr; #endif socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) printf("warning: unknown socket family\n"); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { if (WSAGetLastError() != WSAEWOULDBLOCK) printf("socket error accept failed: %d\n", WSAGetLastError()); } else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS) { { LOCK(cs_setservAddNodeAddresses); if (!setservAddNodeAddresses.count(addr)) closesocket(hSocket); } } else if (CNode::IsBanned(addr)) { printf("connection from %s dropped (banned)\n", addr.ToString().c_str()); closesocket(hSocket); } else { printf("accepted connection %s\n", addr.ToString().c_str()); CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (fShutdown) return; // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecv, lockRecv); if (lockRecv) { CDataStream& vRecv = pnode->vRecv; unsigned int nPos = vRecv.size(); if (nPos > ReceiveBufferSize()) { if (!pnode->fDisconnect) printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size()); pnode->CloseSocketDisconnect(); } else { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { vRecv.resize(nPos + nBytes); memcpy(&vRecv[nPos], pchBuf, nBytes); pnode->nLastRecv = GetTime(); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) printf("socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) printf("socket recv error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { CDataStream& vSend = pnode->vSend; if (!vSend.empty()) { int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { vSend.erase(vSend.begin(), vSend.begin() + nBytes); pnode->nLastSend = GetTime(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { printf("socket send error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Inactivity checking // if (pnode->vSend.empty()) pnode->nLastSendEmpty = GetTime(); if (GetTime() - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60) { printf("socket not sending\n"); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastRecv > 90*60) { printf("socket inactivity timeout\n"); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } Sleep(10); } } // DNS seeds // Each pair gives a source name and a seed name. // The first name is used as information source for addrman. // The second name should resolve to a list of seed addresses. static const char *strDNSSeed[][2] = { {"null", "null"}, }; void ThreadDNSAddressSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadDNSAddressSeed(parg)); // Make this thread recognisable as the DNS seeding thread RenameThread("bitcoin-dnsseed"); try { vnThreadsRunning[THREAD_DNSSEED]++; ThreadDNSAddressSeed2(parg); vnThreadsRunning[THREAD_DNSSEED]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_DNSSEED]--; PrintException(&e, "ThreadDNSAddressSeed()"); } catch (...) { vnThreadsRunning[THREAD_DNSSEED]--; throw; // support pthread_cancel() } printf("ThreadDNSAddressSeed exited\n"); } void ThreadDNSAddressSeed2(void* parg) { printf("ThreadDNSAddressSeed started\n"); int found = 0; if (!fTestNet) { printf("Loading addresses from DNS seeds (could take a while)\n"); for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) { if (GetNameProxy()) { AddOneShot(strDNSSeed[seed_idx][1]); } else { vector<CNetAddr> vaddr; vector<CAddress> vAdd; if (LookupHost(strDNSSeed[seed_idx][1], vaddr)) { BOOST_FOREACH(CNetAddr& ip, vaddr) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true)); } } } printf("%d addresses found from DNS seeds\n", found); } unsigned int pnSeed[] = { 0x2EFDCB71, 0xCC1B3AD6, 0xADA77149, }; void DumpAddresses() { int64 nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n", addrman.size(), GetTimeMillis() - nStart); } void ThreadDumpAddress2(void* parg) { vnThreadsRunning[THREAD_DUMPADDRESS]++; while (!fShutdown) { DumpAddresses(); vnThreadsRunning[THREAD_DUMPADDRESS]--; Sleep(100000); vnThreadsRunning[THREAD_DUMPADDRESS]++; } vnThreadsRunning[THREAD_DUMPADDRESS]--; } void ThreadDumpAddress(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadDumpAddress(parg)); // Make this thread recognisable as the address dumping thread RenameThread("bitcoin-adrdump"); try { ThreadDumpAddress2(parg); } catch (std::exception& e) { PrintException(&e, "ThreadDumpAddress()"); } printf("ThreadDumpAddress exited\n"); } void ThreadOpenConnections(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg)); // Make this thread recognisable as the connection opening thread RenameThread("bitcoin-opencon"); try { vnThreadsRunning[THREAD_OPENCONNECTIONS]++; ThreadOpenConnections2(parg); vnThreadsRunning[THREAD_OPENCONNECTIONS]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_OPENCONNECTIONS]--; PrintException(&e, "ThreadOpenConnections()"); } catch (...) { vnThreadsRunning[THREAD_OPENCONNECTIONS]--; PrintException(NULL, "ThreadOpenConnections()"); } printf("ThreadOpenConnections exited\n"); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections2(void* parg) { printf("ThreadOpenConnections started\n"); // Connect to specific addresses if (mapArgs.count("-connect")) { for (int64 nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { Sleep(500); if (fShutdown) return; } } } } // Initiate network connections int64 nStart = GetTime(); loop { ProcessOneShot(); vnThreadsRunning[THREAD_OPENCONNECTIONS]--; Sleep(500); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; if (fShutdown) return; vnThreadsRunning[THREAD_OPENCONNECTIONS]--; CSemaphoreGrant grant(*semOutbound); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; if (fShutdown) return; // Add seed nodes if IRC isn't working if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet) { std::vector<CAddress> vAdd; for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64 nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek; vAdd.push_back(addr); } addrman.Add(vAdd, CNetAddr("127.0.0.1")); } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64 nANow = GetAdjustedTime(); int nTries = 0; loop { // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections) CAddress addr = addrman.Select(10 + min(nOutbound,8)*10); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; nTries++; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadOpenAddedConnections(parg)); // Make this thread recognisable as the connection opening thread RenameThread("bitcoin-opencon"); try { vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++; ThreadOpenAddedConnections2(parg); vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; PrintException(&e, "ThreadOpenAddedConnections()"); } catch (...) { vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; PrintException(NULL, "ThreadOpenAddedConnections()"); } printf("ThreadOpenAddedConnections exited\n"); } void ThreadOpenAddedConnections2(void* parg) { printf("ThreadOpenAddedConnections started\n"); if (mapArgs.count("-addnode") == 0) return; if (GetNameProxy()) { while(!fShutdown) { BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); Sleep(500); } vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; Sleep(120000); // Retry every 2 minutes vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++; } return; } vector<vector<CService> > vservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0)) { vservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH(CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } loop { vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd; // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++) BOOST_FOREACH(CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = vservConnectAddresses.erase(it); it--; break; } } BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(*(vserv.begin())), &grant); Sleep(500); if (fShutdown) return; } if (fShutdown) return; vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; Sleep(120000); // Retry every 2 minutes vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++; if (fShutdown) return; } } // if succesful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot) { // // Initiate outbound network connection // if (fShutdown) return false; if (!strDest) if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort().c_str())) return false; if (strDest && FindNode(strDest)) return false; vnThreadsRunning[THREAD_OPENCONNECTIONS]--; CNode* pnode = ConnectNode(addrConnect, strDest); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; if (fShutdown) return false; if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } void ThreadMessageHandler(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg)); // Make this thread recognisable as the message handling thread RenameThread("bitcoin-msghand"); try { vnThreadsRunning[THREAD_MESSAGEHANDLER]++; ThreadMessageHandler2(parg); vnThreadsRunning[THREAD_MESSAGEHANDLER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MESSAGEHANDLER]--; PrintException(&e, "ThreadMessageHandler()"); } catch (...) { vnThreadsRunning[THREAD_MESSAGEHANDLER]--; PrintException(NULL, "ThreadMessageHandler()"); } printf("ThreadMessageHandler exited\n"); } void ThreadMessageHandler2(void* parg) { printf("ThreadMessageHandler started\n"); SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (!fShutdown) { vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; BOOST_FOREACH(CNode* pnode, vNodesCopy) { // Receive messages { TRY_LOCK(pnode->cs_vRecv, lockRecv); if (lockRecv) ProcessMessages(pnode); } if (fShutdown) return; // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SendMessages(pnode, pnode == pnodeTrickle); } if (fShutdown) return; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } // Wait and allow messages to bunch up. // Reduce vnThreadsRunning so StopNode has permission to exit while // we're sleeping, but we must always check fShutdown after doing this. vnThreadsRunning[THREAD_MESSAGEHANDLER]--; Sleep(100); if (fRequestShutdown) StartShutdown(); vnThreadsRunning[THREAD_MESSAGEHANDLER]++; if (fShutdown) return; } } bool BindListenPort(const CService &addrBind, string& strError) { strError = ""; int nOne = 1; #ifdef WIN32 // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR) { strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret); printf("%s\n", strError.c_str()); return false; } #endif // Create socket for listening for incoming connections #ifdef USE_IPV6 struct sockaddr_storage sockaddr; #else struct sockaddr sockaddr; #endif socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str()); printf("%s\n", strError.c_str()); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif #ifndef WIN32 // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif #ifdef WIN32 // Set to nonblocking, incoming connections will also inherit this if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR) #else if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) #endif { strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef USE_IPV6 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #ifdef WIN32 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */; int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */; // this call is allowed to fail setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int)); #endif } #endif if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. Obsidian is probably already running."), addrBind.ToString().c_str()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr)); printf("%s\n", strError.c_str()); return false; } printf("Bound to %s\n", addrBind.ToString().c_str()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } vhListenSocket.push_back(hListenSocket); if (addrBind.IsRoutable() && fDiscover) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover() { if (!fDiscover) return; #ifdef WIN32 // Get local host ip char pszHostName[1000] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr &addr, vaddr) { AddLocal(addr, LOCAL_IF); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } #ifdef USE_IPV6 else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } #endif } freeifaddrs(myaddrs); } #endif CreateThread(ThreadGetMyExternalIP, NULL); } void StartNode(void* parg) { // Make this thread recognisable as the startup thread RenameThread("bitcoin-start"); if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125)); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(); // // Start threads // // if (!GetBoolArg("-dnsseed", true)) printf("DNS seeding disabled\n"); // else // if (!CreateThread(ThreadDNSAddressSeed, NULL)) // printf("Error: CreateThread(ThreadDNSAddressSeed) failed\n"); // Get addresses from IRC and advertise ours if (!CreateThread(ThreadIRCSeed, NULL)) printf("Error: CreateThread(ThreadIRCSeed) failed\n"); // Send and receive from sockets, accept connections if (!CreateThread(ThreadSocketHandler, NULL)) printf("Error: CreateThread(ThreadSocketHandler) failed\n"); // Initiate outbound connections from -addnode if (!CreateThread(ThreadOpenAddedConnections, NULL)) printf("Error: CreateThread(ThreadOpenAddedConnections) failed\n"); // Initiate outbound connections if (!CreateThread(ThreadOpenConnections, NULL)) printf("Error: CreateThread(ThreadOpenConnections) failed\n"); // Process messages if (!CreateThread(ThreadMessageHandler, NULL)) printf("Error: CreateThread(ThreadMessageHandler) failed\n"); // Dump network addresses if (!CreateThread(ThreadDumpAddress, NULL)) printf("Error; CreateThread(ThreadDumpAddress) failed\n"); // Generate coins in the background GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain); } bool StopNode() { printf("StopNode()\n"); fShutdown = true; nTransactionsUpdated++; int64 nStart = GetTime(); if (semOutbound) for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); do { int nThreadsRunning = 0; for (int n = 0; n < THREAD_MAX; n++) nThreadsRunning += vnThreadsRunning[n]; if (nThreadsRunning == 0) break; if (GetTime() - nStart > 20) break; Sleep(20); } while(true); if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n"); if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n"); if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n"); if (vnThreadsRunning[THREAD_MINER] > 0) printf("ThreadBitcoinMiner still running\n"); if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n"); if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n"); if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n"); if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n"); if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n"); while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0) Sleep(20); Sleep(50); DumpAddresses(); return true; } class CNetCleanup { public: CNetCleanup() { } ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) closesocket(pnode->hSocket); BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET) if (closesocket(hListenSocket) == SOCKET_ERROR) printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError()); #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup;
mit
MStaehling/TIY-Etsy
bower_components/vue/src/api/global.js
3032
var _ = require('../util') var config = require('../config') /** * Expose useful internals */ exports.util = _ exports.nextTick = _.nextTick exports.config = require('../config') exports.compiler = require('../compiler') exports.parsers = { path: require('../parsers/path'), text: require('../parsers/text'), template: require('../parsers/template'), directive: require('../parsers/directive'), expression: require('../parsers/expression') } /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ exports.cid = 0 var cid = 1 /** * Class inehritance * * @param {Object} extendOptions */ exports.extend = function (extendOptions) { extendOptions = extendOptions || {} var Super = this var Sub = createClass( extendOptions.name || Super.options.name || 'VueComponent' ) Sub.prototype = Object.create(Super.prototype) Sub.prototype.constructor = Sub Sub.cid = cid++ Sub.options = _.mergeOptions( Super.options, extendOptions ) Sub['super'] = Super // allow further extension Sub.extend = Super.extend // create asset registers, so extended classes // can have their private assets too. createAssetRegisters(Sub) return Sub } /** * A function that returns a sub-class constructor with the * given name. This gives us much nicer output when * logging instances in the console. * * @param {String} name * @return {Function} */ function createClass (name) { return new Function( 'return function ' + _.classify(name) + ' (options) { this._init(options) }' )() } /** * Plugin system * * @param {Object} plugin */ exports.use = function (plugin) { // additional parameters var args = _.toArray(arguments, 1) args.unshift(this) if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args) } else { plugin.apply(null, args) } return this } /** * Define asset registration methods on a constructor. * * @param {Function} Constructor */ function createAssetRegisters (Constructor) { /* Asset registration methods share the same signature: * * @param {String} id * @param {*} definition */ config._assetTypes.forEach(function (type) { Constructor[type] = function (id, definition) { if (!definition) { return this.options[type + 's'][id] } else { this.options[type + 's'][id] = definition } } }) /** * Component registration needs to automatically invoke * Vue.extend on object values. * * @param {String} id * @param {Object|Function} definition */ Constructor.component = function (id, definition) { if (!definition) { return this.options.components[id] } else { if (_.isPlainObject(definition)) { definition.name = id definition = _.Vue.extend(definition) } this.options.components[id] = definition } } } createAssetRegisters(exports)
mit
koodikindral/emailservice
src/main/java/email/ManifestInfo.java
2205
package email; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.net.URL; import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; public class ManifestInfo { private static Logger logger = LoggerFactory.getLogger(ManifestInfo.class); public static final String PROJECT = "Implementation-Title"; public static final String VERSION = "Implementation-Version"; public static final String BUILT_BY = "Built-By"; public static final String BUILT_JDK = "Built-JDK"; public static final String BUILD_TIME = "Build-Time"; private final Properties properties = new Properties(); private final String infoString; public ManifestInfo(Class<?> clazz) { try { URL url = clazz.getProtectionDomain().getCodeSource().getLocation(); File file = new File(url.toURI()); JarFile jar = null; try { jar = new JarFile(file); Manifest manifest = jar.getManifest(); loadProperties(manifest); } finally { if (jar != null) { jar.close(); } } } catch (Exception e) { logger.warn("Loading ManifestInfo failed. Cause: " + e.getMessage()); } infoString = clazz.getSimpleName() + ": " + properties.toString(); } private void loadProperties(Manifest manifest) { Attributes attributes = manifest.getMainAttributes(); properties.setProperty(PROJECT, attributes.getValue(PROJECT)); properties.setProperty(VERSION, attributes.getValue(VERSION)); properties.setProperty(BUILT_BY, attributes.getValue(BUILT_BY)); properties.setProperty(BUILT_JDK, attributes.getValue(BUILT_JDK)); properties.setProperty(BUILD_TIME, attributes.getValue(BUILD_TIME)); } public String getManifestInfo() { return infoString; } public String getProject() { return properties.getProperty(PROJECT, "LOCAL"); } public String getVersion() { return properties.getProperty(VERSION, "LOCAL"); } }
mit
stevecoward/dork-enum
dorkenum/mixins/user_actions.py
211
import simplejson as json class UserActions(): directives = {} def __init__(self, file): try: self.directives = json.loads(file) except Exception as e: print e
mit
vigetlabs/ars-arsenal
src/components/scroll-monitor.tsx
2234
import * as React from 'react' import { findDOMNode } from 'react-dom' interface Props { page: number refresh: string onPage: (number: number) => void } class ScrollMonitor extends React.Component<Props, null> { teardown = () => {} lastChild: HTMLElement = null container: HTMLElement = null getElement(): HTMLElement { return findDOMNode(this) as HTMLElement } getScrollContainer(): HTMLElement { return this.getElement().querySelector('[data-scroll-container]') } getScrollTrigger(): HTMLElement | null { return this.getElement().querySelector('[data-scroll="true"]') } subscribe() { let element = this.getScrollContainer() if (element != null && element !== this.container) { this.container = element element.addEventListener('scroll', this.check, { passive: true }) this.teardown = () => element.removeEventListener('scroll', this.check) this.check() } } componentDidMount() { this.subscribe() } componentDidUpdate(lastProps: Props) { if (this.props.page < lastProps.page) { this.lastChild = null } if (this.props.refresh != lastProps.refresh) { this.resetScroll() this.check() } this.subscribe() } componentWillUnmount() { this.teardown() } resetScroll() { if (this.container) { this.container.scrollTop = 0 } } check = () => { let endChild = this.getScrollTrigger() if (!endChild || endChild === this.lastChild) { return } // This value represents the lower fence a child element a child must // cross through to trigger a new page let lowerFence = this.container.scrollTop // Start by pushing the fence to the bottom of the container element // Then add the look ahead value; how far below the viewable window to // proactively fetch a new page. lowerFence += this.container.offsetHeight * 2 // If the end child's offset in the container is less than the lower // fence, trigger pagination if (lowerFence > endChild.offsetTop) { this.lastChild = endChild this.props.onPage(this.props.page + 1) } } render() { return this.props.children } } export default ScrollMonitor
mit
lamuertepeluda/react-mapbox-gl
src/__tests__/overlays.test.ts
1493
jest.mock('mapbox-gl', () => ({ default: {}, LngLat: {} })); import { overlayTransform, OverlayProps, anchors, Anchor } from '../util/overlays'; describe('overlayTransform', () => { it('Should transform position anchor and offset accordingly', () => { const overlayProps: OverlayProps = { anchor: anchors[1] as Anchor, offset: { x: 10, y: 20 }, position: { x: 1000, y: 2000 } }; const res = overlayTransform(overlayProps); expect(res).toEqual( ['translate(1000px, 2000px)', 'translate(10px, 20px)', 'translate(-50%, 0)'] ); }); it('Should transform position and offset only', () => { const overlayProps: OverlayProps = { offset: { x: 10, y: 20 }, position: { x: 1000, y: 2000 } }; const res = overlayTransform(overlayProps); expect(res).toEqual( ['translate(1000px, 2000px)', 'translate(10px, 20px)'] ); }); it('Should not add an undefined offset', () => { const overlayProps: OverlayProps = { offset: { x: undefined, y: 20 }, position: { x: 1000, y: 2000 } }; const res = overlayTransform(overlayProps); expect(res).toEqual(['translate(1000px, 2000px)']); }); it('Should add offset of 0', () => { const overlayProps: OverlayProps = { offset: { x: 0, y: 20 }, position: { x: 1000, y: 2000 } }; const res = overlayTransform(overlayProps); expect(res).toEqual(['translate(1000px, 2000px)', 'translate(0px, 20px)']); }); });
mit
thushanp/thushanp.github.io
vendor/twilio/sdk/Twilio/Rest/Api/V2010/Account/Address/DependentPhoneNumberList.php
5083
<?php /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ namespace Twilio\Rest\Api\V2010\Account\Address; use Twilio\ListResource; use Twilio\Values; use Twilio\Version; class DependentPhoneNumberList extends ListResource { /** * Construct the DependentPhoneNumberList * * @param Version $version Version that contains the resource * @param string $accountSid The account_sid * @param string $addressSid The sid * @return \Twilio\Rest\Api\V2010\Account\Address\DependentPhoneNumberList */ public function __construct(Version $version, $accountSid, $addressSid) { parent::__construct($version); // Path Solution $this->solution = array( 'accountSid' => $accountSid, 'addressSid' => $addressSid, ); $this->uri = '/Accounts/' . rawurlencode($accountSid) . '/Addresses/' . rawurlencode($addressSid) . '/DependentPhoneNumbers.json'; } /** * Streams DependentPhoneNumberInstance records from the API as a generator * stream. * This operation lazily loads records as efficiently as possible until the * limit * is reached. * The results are returned as a generator, so this operation is memory * efficient. * * @param int $limit Upper limit for the number of records to return. stream() * guarantees to never return more than limit. Default is no * limit * @param mixed $pageSize Number of records to fetch per request, when not set * will use the default value of 50 records. If no * page_size is defined but a limit is defined, stream() * will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @return \Twilio\Stream stream of results */ public function stream($limit = null, $pageSize = null) { $limits = $this->version->readLimits($limit, $pageSize); $page = $this->page($limits['pageSize']); return $this->version->stream($page, $limits['limit'], $limits['pageLimit']); } /** * Reads DependentPhoneNumberInstance records from the API as a list. * Unlike stream(), this operation is eager and will load `limit` records into * memory before returning. * * @param int $limit Upper limit for the number of records to return. read() * guarantees to never return more than limit. Default is no * limit * @param mixed $pageSize Number of records to fetch per request, when not set * will use the default value of 50 records. If no * page_size is defined but a limit is defined, read() * will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @return DependentPhoneNumberInstance[] Array of results */ public function read($limit = null, $pageSize = null) { return iterator_to_array($this->stream($limit, $pageSize), false); } /** * Retrieve a single page of DependentPhoneNumberInstance records from the API. * Request is executed immediately * * @param mixed $pageSize Number of records to return, defaults to 50 * @param string $pageToken PageToken provided by the API * @param mixed $pageNumber Page Number, this value is simply for client state * @return \Twilio\Page Page of DependentPhoneNumberInstance */ public function page($pageSize = Values::NONE, $pageToken = Values::NONE, $pageNumber = Values::NONE) { $params = Values::of(array( 'PageToken' => $pageToken, 'Page' => $pageNumber, 'PageSize' => $pageSize, )); $response = $this->version->page( 'GET', $this->uri, $params ); return new DependentPhoneNumberPage($this->version, $response, $this->solution); } /** * Retrieve a specific page of DependentPhoneNumberInstance records from the * API. * Request is executed immediately * * @param string $targetUrl API-generated URL for the requested results page * @return \Twilio\Page Page of DependentPhoneNumberInstance */ public function getPage($targetUrl) { $response = $this->version->getDomain()->getClient()->request( 'GET', $targetUrl ); return new DependentPhoneNumberPage($this->version, $response, $this->solution); } /** * Provide a friendly representation * * @return string Machine friendly representation */ public function __toString() { return '[Twilio.Api.V2010.DependentPhoneNumberList]'; } }
mit
ubivar/ubivar-python
oriskami/test/resources/test_listable.py
950
import oriskami from oriskami.test.helper import ( OriskamiApiTestCase, MyListable ) class ListableAPIResourceTests(OriskamiApiTestCase): def test_all(self): self.mock_response({ 'object': 'events', 'data': [ { 'object': 'events', 'name': 'jose', }, { 'object': 'events', 'name': 'curly', } ], 'url': '/events', 'has_more': False, }) res = MyListable.list() self.requestor_mock.request.assert_called_with( 'get', '/mylistable', {}) self.assertEqual(2, len(res.data)) self.assertTrue(all(isinstance(obj, oriskami.Event) for obj in res.data)) self.assertEqual('jose', res.data[0].name) self.assertEqual('curly', res.data[1].name)
mit
tmcgee/cmv-wab-widgets
wab/2.13/jimu.js/OnScreenWidgetPanel.js
14641
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define(['dojo/_base/declare', 'dojo/_base/lang', 'dojo/_base/html', 'dojo/on', 'dojo/dnd/move', 'dijit/_TemplatedMixin', 'jimu/BaseWidgetPanel', 'jimu/utils', 'dojox/layout/ResizeHandle', "./a11y/OnScreenWidgetPanel", 'dojo/touch' ], function( declare, lang, html, on, Move, _TemplatedMixin, BaseWidgetPanel, utils, ResizeHandle, a11y ) { /* global jimuConfig */ var clazz = declare([BaseWidgetPanel, _TemplatedMixin], { baseClass: 'jimu-panel jimu-on-screen-widget-panel jimu-main-background', _positionInfoBox: null, _originalBox: null, widgetIcon: null, _resizeOnOpen: true, templateString: '<div data-dojo-attach-point="boxNode">' + '<div class="jimu-panel-title jimu-main-background" data-dojo-attach-point="titleNode">' + '<div class="title-label jimu-vcenter-text jimu-float-leading jimu-leading-padding1"' + 'data-dojo-attach-point="titleLabelNode">${label}</div>' + '<div class="btns-container">' + '<div tabindex="0" class="foldable-btn jimu-vcenter" aria-label="${headerNls.foldWindow}" role="button"' + 'data-dojo-attach-point="foldableNode"' + 'data-dojo-attach-event="onclick:_onFoldableBtnClicked,onkeydown:_onFoldableBtnKeyDown"></div>' + '<div tabindex="0" class="max-btn jimu-vcenter" aria-label="${headerNls.maxWindow}" role="button"' + 'data-dojo-attach-point="maxNode"' + 'data-dojo-attach-event="onclick:_onMaxBtnClicked,onkeydown:_onMaxBtnKeyDown"></div>' + '<div tabindex="0" class="close-btn jimu-vcenter" aria-label="${headerNls.closeWindow}" role="button"' + 'data-dojo-attach-point="closeNode"' + 'data-dojo-attach-event="onclick:_onCloseBtnClicked,onkeydown:_onCloseBtnKey"></div>' + '</div></div>' + '<div class="jimu-panel-content" data-dojo-attach-point="containerNode"></div>' + '</div>', postMixInProperties:function(){ this.headerNls = window.jimuNls.panelHeader; }, postCreate: function() { this._originalBox = { w: 400, h: 410 }; }, startup: function() { this.inherited(arguments); this._normalizePositionObj(this.position); this._makeOriginalBox(); this.makePositionInfoBox(); this.makeMoveable(this._positionInfoBox.w, this._positionInfoBox.w * 0.25); this.a11y_init(); }, _onMaxBtnClicked: function(evt) { evt.stopPropagation(); var posInfo = this._getPositionInfo(); if (posInfo.isRunInMobile) { if (this.windowState === 'maximized') { html.setAttr(this.maxNode, 'aria-label', this.headerNls.maxWindow); this.panelManager.normalizePanel(this); } else { html.setAttr(this.maxNode, 'aria-label', this.headerNls.restoreWindow); this.panelManager.maximizePanel(this); //set foldable btn's styles html.removeClass(this.foldableNode, 'fold-up'); html.addClass(this.foldableNode, 'fold-down'); html.setAttr(this.foldableNode, 'aria-label', this.headerNls.foldWindow); } this._setMobilePosition(); } this.panelManager.activatePanel(this); }, _onFoldableBtnClicked: function(evt) { if(evt){ evt.stopPropagation(); } var posInfo = this._getPositionInfo(); if (posInfo.isRunInMobile) { if (this.windowState === 'minimized') { html.removeClass(this.foldableNode, 'fold-up'); html.addClass(this.foldableNode, 'fold-down'); html.setAttr(this.foldableNode, 'aria-label', this.headerNls.foldWindow); this.panelManager.normalizePanel(this); } else { html.removeClass(this.foldableNode, 'fold-down'); html.addClass(this.foldableNode, 'fold-up'); html.setAttr(this.foldableNode, 'aria-label', this.headerNls.unfoldWindow); this.panelManager.minimizePanel(this); } //set max btn's label html.setAttr(this.maxNode, 'aria-label', this.headerNls.maxWindow); this._setMobilePosition(); } }, _onCloseBtnClicked: function(evt) { //avoid to touchEvent pass through the closeBtn evt.preventDefault(); evt.stopPropagation(); this.panelManager.closePanel(this); }, _normalizePositionObj: function(position) { var layoutBox = this._getLayoutBox(); position.left = isFinite(position.left) ? position.left : layoutBox.w - position.right; position.top = isFinite(position.top) ? position.top : layoutBox.h - position.bottom; delete position.right; delete position.bottom; this.position = lang.mixin(lang.clone(this.position), position); }, makePositionInfoBox: function() { this._positionInfoBox = { w: this.position.width || 400, h: this.position.height || 410, l: this.position.left || 0, t: this.position.top || 0 }; }, _makeOriginalBox: function() { this._originalBox = { w: this.position.width || 400, h: this.position.height || 410, l: this.position.left || 0, t: this.position.top || 0 }; }, makeResizable: function() { this.disableResizable(); this.resizeHandle = new ResizeHandle({ targetId: this, minWidth: this._originalBox.w, minHeight: this._originalBox.h, activeResize: false }).placeAt(this.domNode); this.resizeHandle.startup(); }, disableResizable: function() { if (this.resizeHandle) { this.resizeHandle.destroy(); this.resizeHandle = null; } }, makeMoveable: function(width, tolerance) { this.disableMoveable(); var containerBox = html.getMarginBox(jimuConfig.layoutId); containerBox.l = containerBox.l - width + tolerance; containerBox.w = containerBox.w + 2 * (width - tolerance); this.moveable = new Move.boxConstrainedMoveable(this.domNode, { box: containerBox, handle: this.titleNode, within: true }); this.own(on(this.moveable, 'Moving', lang.hitch(this, this.onMoving))); this.own(on(this.moveable, 'MoveStop', lang.hitch(this, this.onMoveStop))); }, disableMoveable: function() { if (this.moveable) { this.moveable.destroy(); this.moveable = null; } }, createHandleNode: function() { return this.titleNode; }, onOpen: function() { if (this._resizeOnOpen) { this.resize(); this._resizeOnOpen = false; } if (window.appInfo.isRunInMobile) { this._setMobilePosition(); if(utils.isInNavMode() && this.windowState === 'minimized') { this._onFoldableBtnClicked(); } } this.inherited(arguments); }, _switchToMobileUI: function() { html.removeClass(this.titleNode, 'title-normal'); html.addClass(this.titleNode, 'title-full'); html.setStyle(this.foldableNode, 'display', 'block'); html.setStyle(this.maxNode, 'display', 'block'); if (this.windowState === 'normal') { html.removeClass(this.foldableNode, 'fold-up'); html.addClass(this.foldableNode, 'fold-down'); html.setAttr(this.foldableNode, 'aria-label', this.headerNls.foldWindow); } else { html.removeClass(this.foldableNode, 'fold-down'); html.addClass(this.foldableNode, 'fold-up'); html.setAttr(this.foldableNode, 'aria-label', this.headerNls.unfoldWindow); } }, _switchToDesktopUI: function() { html.removeClass(this.titleNode, 'title-full'); html.addClass(this.titleNode, 'title-normal'); html.setStyle(this.foldableNode, 'display', 'none'); html.setStyle(this.maxNode, 'display', 'none'); }, resize: function(tmp) { var posInfo = this._getPositionInfo(); var _pos = { left: posInfo.position.left, top: posInfo.position.top, width: this._positionInfoBox.w, height: this._positionInfoBox.h }; if (tmp) { tmp.t = this.domNode.offsetTop; _pos.left = isFinite(tmp.l) ? tmp.l : _pos.left; _pos.top = isFinite(tmp.t) ? tmp.t : _pos.top; _pos.width = isFinite(tmp.w) ? tmp.w : _pos.width; _pos.height = isFinite(tmp.h) ? tmp.h : _pos.height; this._normalizePositionObj(lang.clone(_pos)); this.makePositionInfoBox(); _pos.width = this._positionInfoBox.w; _pos.height = this._positionInfoBox.h; } posInfo.position = _pos; this._onResponsible(posInfo); this.inherited(arguments); }, _onResponsible: function(posInfo) { if (posInfo.isRunInMobile) { this._setMobilePosition(); this.disableMoveable(); this.disableResizable(); this._switchToMobileUI(); } else { this._setDesktopPosition(posInfo.position); this.makeResizable(); this.makeMoveable(this._positionInfoBox.w, this._positionInfoBox.w * 0.25); this._switchToDesktopUI(); } }, setPosition: function(position) { this._normalizePositionObj(position); this.makePositionInfoBox(); var posInfo = this._getPositionInfo(); this._onResponsible(posInfo); }, destroy: function() { this.widgetIcon = null; this.inherited(arguments); }, _getLayoutBox: function() { var pid = jimuConfig.layoutId; if (this.position.relativeTo === 'map') { pid = jimuConfig.mapId; } else { pid = jimuConfig.layoutId; } return html.getMarginBox(pid); }, _getPositionInfo: function() { var result = { isRunInMobile: false, position: { left: 0, top: 5 } }; var layoutBox = this._getLayoutBox(); //judge width var leftBlankWidth = this._positionInfoBox.l; if (!window.appInfo.isRunInMobile) { if (window.isRTL) { result.position.left = layoutBox.w - leftBlankWidth; // prevent the panel out of map content if ((result.position.left + this._positionInfoBox.w) > layoutBox.w) { result.position.left -= this._positionInfoBox.w; if (result.position.left < 0) { result.position.left = layoutBox.w - this._positionInfoBox.w; } } } else { result.position.left = leftBlankWidth; // prevent the panel out of map content if ((result.position.left + this._positionInfoBox.w) > layoutBox.w) { if (layoutBox.w > this._positionInfoBox.w) { result.position.left = layoutBox.w - this._positionInfoBox.w; } else { result.position.left = 0; } } } } else { result.isRunInMobile = true; return result; } //judge height // preloadIcon height is 40px, tolerance is 3px var topBlankHeight = this._positionInfoBox.t; var bottomBlankHeight = layoutBox.h - topBlankHeight; if (topBlankHeight >= bottomBlankHeight) { if (topBlankHeight >= this._positionInfoBox.h) { // preloadIcon height is 40px result.position.top = this._positionInfoBox.t - this._positionInfoBox.h - 40 - 3; } } else { if (bottomBlankHeight >= this._positionInfoBox.h) { result.position.top = this._positionInfoBox.t + 40 + 3; // preloadIcon height is 40px } } return result; }, _setMobilePosition: function() { if (window.appInfo.isRunInMobile && this.domNode && this.domNode.parentNode !== html.byId(jimuConfig.layoutId)) { html.place(this.domNode, jimuConfig.layoutId); } var pos = this.panelManager.getPositionOnMobile(this); if (this.position.zIndex) { pos.zIndex = this.position.zIndex; } var style = utils.getPositionStyle(pos); lang.mixin(style, pos.borderRadiusStyle); html.setStyle(this.domNode, style); }, _setDesktopPosition: function(position) { if(!window.appInfo.isRunInMobile && this.domNode && this.domNode.parentNode !== html.byId(jimuConfig.mapId)) { html.place(this.domNode, jimuConfig.mapId); } html.setStyle(this.domNode, { left: position.left + 'px', right: 'auto', top: position.top + 'px', width: (position.width || this.position.width || this._originalBox.w) + 'px', height: (position.height || this.position.height || this._originalBox.h) + 'px' }); }, onMoving: function(mover) { html.setStyle(mover.node, 'opacity', 0.9); }, onMoveStop: function(mover) { html.setStyle(mover.node, 'opacity', 1); var panelBox = html.getMarginBox(mover.node); var _pos = { left: panelBox.l, top: panelBox.t, width: panelBox.w, height: panelBox.h }; this._normalizePositionObj(lang.clone(_pos)); this.makePositionInfoBox(); } }); clazz.extend(a11y);//for a11y return clazz; });
mit
Azure/azure-sdk-for-java
sdk/synapse/azure-resourcemanager-synapse/src/samples/java/com/azure/resourcemanager/synapse/generated/DataMaskingPoliciesGetSamples.java
882
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.synapse.generated; import com.azure.core.util.Context; /** Samples for DataMaskingPolicies Get. */ public final class DataMaskingPoliciesGetSamples { /* * x-ms-original-file: specification/synapse/resource-manager/Microsoft.Synapse/stable/2021-06-01/examples/DataMaskingPolicyGet.json */ /** * Sample code: Get data masking policy. * * @param manager Entry point to SynapseManager. */ public static void getDataMaskingPolicy(com.azure.resourcemanager.synapse.SynapseManager manager) { manager .dataMaskingPolicies() .getWithResponse("sqlcrudtest-6852", "sqlcrudtest-2080", "sqlcrudtest-331", Context.NONE); } }
mit
PLfW/lab-5-BabalaV
node_modules/mongoose/lib/model.js
101803
/*! * Module dependencies. */ var Document = require('./document'); var MongooseError = require('./error'); var VersionError = MongooseError.VersionError; var DivergentArrayError = MongooseError.DivergentArrayError; var Query = require('./query'); var Aggregate = require('./aggregate'); var Schema = require('./schema'); var utils = require('./utils'); var hasOwnProperty = utils.object.hasOwnProperty; var isMongooseObject = utils.isMongooseObject; var EventEmitter = require('events').EventEmitter; var MongooseArray = require('./types/array'); var util = require('util'); var tick = utils.tick; var parallel = require('async/parallel'); var PromiseProvider = require('./promise_provider'); var VERSION_WHERE = 1, VERSION_INC = 2, VERSION_ALL = VERSION_WHERE | VERSION_INC; var POJO_TO_OBJECT_OPTIONS = { depopulate: true, transform: false, _skipDepopulateTopLevel: true }; /** * Model constructor * * Provides the interface to MongoDB collections as well as creates document instances. * * @param {Object} doc values with which to create the document * @inherits Document http://mongoosejs.com/docs/api.html#document-js * @event `error`: If listening to this event, it is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event. * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed. * @api public */ function Model(doc, fields, skipId) { Document.call(this, doc, fields, skipId); } /*! * Inherits from Document. * * All Model.prototype features are available on * top level (non-sub) documents. */ Model.prototype.__proto__ = Document.prototype; /** * Connection the model uses. * * @api public * @property db */ Model.prototype.db; /** * Collection the model uses. * * @api public * @property collection */ Model.prototype.collection; /** * The name of the model * * @api public * @property modelName */ Model.prototype.modelName; /** * If this is a discriminator model, `baseModelName` is the name of * the base model. * * @api public * @property baseModelName */ Model.prototype.baseModelName; Model.prototype.$__handleSave = function(options, callback) { var _this = this; if (!options.safe && this.schema.options.safe) { options.safe = this.schema.options.safe; } if (typeof options.safe === 'boolean') { options.safe = null; } if (this.isNew) { // send entire doc var toObjectOptions = {}; toObjectOptions.retainKeyOrder = this.schema.options.retainKeyOrder; toObjectOptions.depopulate = 1; toObjectOptions._skipDepopulateTopLevel = true; toObjectOptions.transform = false; var obj = this.toObject(toObjectOptions); if (!utils.object.hasOwnProperty(obj || {}, '_id')) { // documents must have an _id else mongoose won't know // what to update later if more changes are made. the user // wouldn't know what _id was generated by mongodb either // nor would the ObjectId generated my mongodb necessarily // match the schema definition. setTimeout(function() { callback(new Error('document must have an _id before saving')); }, 0); return; } this.$__version(true, obj); this.collection.insert(obj, options.safe, function(err, ret) { if (err) { _this.isNew = true; _this.emit('isNew', true); callback(err); return; } callback(null, ret); }); this.$__reset(); this.isNew = false; this.emit('isNew', false); // Make it possible to retry the insert this.$__.inserting = true; } else { // Make sure we don't treat it as a new object on error, // since it already exists this.$__.inserting = false; var delta = this.$__delta(); if (delta) { if (delta instanceof Error) { callback(delta); return; } var where = this.$__where(delta[0]); if (where instanceof Error) { callback(where); return; } this.collection.update(where, delta[1], options.safe, function(err, ret) { if (err) { callback(err); return; } callback(null, ret); }); } else { this.$__reset(); callback(); return; } this.emit('isNew', false); } }; /*! * ignore */ Model.prototype.$__save = function(options, callback) { var _this = this; _this.$__handleSave(options, function(error, result) { if (error) { return _this.schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { callback(error); }); } _this.$__reset(); _this.$__storeShard(); var numAffected = 0; if (result) { if (Array.isArray(result)) { numAffected = result.length; } else if (result.result && result.result.n !== undefined) { numAffected = result.result.n; } else if (result.result && result.result.nModified !== undefined) { numAffected = result.result.nModified; } else { numAffected = result; } } // was this an update that required a version bump? if (_this.$__.version && !_this.$__.inserting) { var doIncrement = VERSION_INC === (VERSION_INC & _this.$__.version); _this.$__.version = undefined; if (numAffected <= 0) { // the update failed. pass an error back var err = new VersionError(_this); return callback(err); } // increment version if was successful if (doIncrement) { var key = _this.schema.options.versionKey; var version = _this.getValue(key) | 0; _this.setValue(key, version + 1); } } _this.emit('save', _this, numAffected); callback(null, _this, numAffected); }); }; /** * Saves this document. * * ####Example: * * product.sold = Date.now(); * product.save(function (err, product, numAffected) { * if (err) .. * }) * * The callback will receive three parameters * * 1. `err` if an error occurred * 2. `product` which is the saved `product` * 3. `numAffected` will be 1 when the document was successfully persisted to MongoDB, otherwise 0. Unless you tweak mongoose's internals, you don't need to worry about checking this parameter for errors - checking `err` is sufficient to make sure your document was properly saved. * * As an extra measure of flow control, save will return a Promise. * ####Example: * product.save().then(function(product) { * ... * }); * * For legacy reasons, mongoose stores object keys in reverse order on initial * save. That is, `{ a: 1, b: 2 }` will be saved as `{ b: 2, a: 1 }` in * MongoDB. To override this behavior, set * [the `toObject.retainKeyOrder` option](http://mongoosejs.com/docs/api.html#document_Document-toObject) * to true on your schema. * * @param {Object} [options] options optional options * @param {Object} [options.safe] overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe) * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. * @param {Function} [fn] optional callback * @return {Promise} Promise * @api public * @see middleware http://mongoosejs.com/docs/middleware.html */ Model.prototype.save = function(options, fn) { if (typeof options === 'function') { fn = options; options = undefined; } if (!options) { options = {}; } if (fn) { fn = this.constructor.$wrapCallback(fn); } return this.$__save(options, fn); }; /*! * Determines whether versioning should be skipped for the given path * * @param {Document} self * @param {String} path * @return {Boolean} true if versioning should be skipped for the given path */ function shouldSkipVersioning(self, path) { var skipVersioning = self.schema.options.skipVersioning; if (!skipVersioning) return false; // Remove any array indexes from the path path = path.replace(/\.\d+\./, '.'); return skipVersioning[path]; } /*! * Apply the operation to the delta (update) clause as * well as track versioning for our where clause. * * @param {Document} self * @param {Object} where * @param {Object} delta * @param {Object} data * @param {Mixed} val * @param {String} [operation] */ function operand(self, where, delta, data, val, op) { // delta op || (op = '$set'); if (!delta[op]) delta[op] = {}; delta[op][data.path] = val; // disabled versioning? if (self.schema.options.versionKey === false) return; // path excluded from versioning? if (shouldSkipVersioning(self, data.path)) return; // already marked for versioning? if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; switch (op) { case '$set': case '$unset': case '$pop': case '$pull': case '$pullAll': case '$push': case '$pushAll': case '$addToSet': break; default: // nothing to do return; } // ensure updates sent with positional notation are // editing the correct array element. // only increment the version if an array position changes. // modifying elements of an array is ok if position does not change. if (op === '$push' || op === '$pushAll' || op === '$addToSet') { self.$__.version = VERSION_INC; } else if (/^\$p/.test(op)) { // potentially changing array positions self.increment(); } else if (Array.isArray(val)) { // $set an array self.increment(); } else if (/\.\d+\.|\.\d+$/.test(data.path)) { // now handling $set, $unset // subpath of array self.$__.version = VERSION_WHERE; } } /*! * Compiles an update and where clause for a `val` with _atomics. * * @param {Document} self * @param {Object} where * @param {Object} delta * @param {Object} data * @param {Array} value */ function handleAtomics(self, where, delta, data, value) { if (delta.$set && delta.$set[data.path]) { // $set has precedence over other atomics return; } if (typeof value.$__getAtomics === 'function') { value.$__getAtomics().forEach(function(atomic) { var op = atomic[0]; var val = atomic[1]; if (self.schema.options.usePushEach && op === '$pushAll') { op = '$push'; val = { $each: val }; } operand(self, where, delta, data, val, op); }); return; } // legacy support for plugins var atomics = value._atomics, ops = Object.keys(atomics), i = ops.length, val, op; if (i === 0) { // $set if (isMongooseObject(value)) { value = value.toObject({depopulate: 1, _isNested: true}); } else if (value.valueOf) { value = value.valueOf(); } return operand(self, where, delta, data, value); } function iter(mem) { return isMongooseObject(mem) ? mem.toObject({depopulate: 1, _isNested: true}) : mem; } while (i--) { op = ops[i]; val = atomics[op]; if (isMongooseObject(val)) { val = val.toObject({depopulate: true, transform: false, _isNested: true}); } else if (Array.isArray(val)) { val = val.map(iter); } else if (val.valueOf) { val = val.valueOf(); } if (op === '$addToSet') { val = {$each: val}; } operand(self, where, delta, data, val, op); } } /** * Produces a special query document of the modified properties used in updates. * * @api private * @method $__delta * @memberOf Model */ Model.prototype.$__delta = function() { var dirty = this.$__dirty(); if (!dirty.length && VERSION_ALL !== this.$__.version) return; var where = {}, delta = {}, len = dirty.length, divergent = [], d = 0; where._id = this._doc._id; if (where._id.toObject) { where._id = where._id.toObject({ transform: false, depopulate: true }); } for (; d < len; ++d) { var data = dirty[d]; var value = data.value; var match = checkDivergentArray(this, data.path, value); if (match) { divergent.push(match); continue; } var pop = this.populated(data.path, true); if (!pop && this.$__.selected) { // If any array was selected using an $elemMatch projection, we alter the path and where clause // NOTE: MongoDB only supports projected $elemMatch on top level array. var pathSplit = data.path.split('.'); var top = pathSplit[0]; if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) { // If the selected array entry was modified if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') { where[top] = this.$__.selected[top]; pathSplit[1] = '$'; data.path = pathSplit.join('.'); } // if the selected array was modified in any other way throw an error else { divergent.push(data.path); continue; } } } if (divergent.length) continue; if (undefined === value) { operand(this, where, delta, data, 1, '$unset'); } else if (value === null) { operand(this, where, delta, data, null); } else if (value._path && value._atomics) { // arrays and other custom types (support plugins etc) handleAtomics(this, where, delta, data, value); } else if (value._path && Buffer.isBuffer(value)) { // MongooseBuffer value = value.toObject(); operand(this, where, delta, data, value); } else { value = utils.clone(value, {depopulate: 1, _isNested: true}); operand(this, where, delta, data, value); } } if (divergent.length) { return new DivergentArrayError(divergent); } if (this.$__.version) { this.$__version(where, delta); } return [where, delta]; }; /*! * Determine if array was populated with some form of filter and is now * being updated in a manner which could overwrite data unintentionally. * * @see https://github.com/Automattic/mongoose/issues/1334 * @param {Document} doc * @param {String} path * @return {String|undefined} */ function checkDivergentArray(doc, path, array) { // see if we populated this path var pop = doc.populated(path, true); if (!pop && doc.$__.selected) { // If any array was selected using an $elemMatch projection, we deny the update. // NOTE: MongoDB only supports projected $elemMatch on top level array. var top = path.split('.')[0]; if (doc.$__.selected[top + '.$']) { return top; } } if (!(pop && array && array.isMongooseArray)) return; // If the array was populated using options that prevented all // documents from being returned (match, skip, limit) or they // deselected the _id field, $pop and $set of the array are // not safe operations. If _id was deselected, we do not know // how to remove elements. $pop will pop off the _id from the end // of the array in the db which is not guaranteed to be the // same as the last element we have here. $set of the entire array // would be similarily destructive as we never received all // elements of the array and potentially would overwrite data. var check = pop.options.match || pop.options.options && hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted pop.options.options && pop.options.options.skip || // 0 is permitted pop.options.select && // deselected _id? (pop.options.select._id === 0 || /\s?-_id\s?/.test(pop.options.select)); if (check) { var atomics = array._atomics; if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) { return path; } } } /** * Appends versioning to the where and update clauses. * * @api private * @method $__version * @memberOf Model */ Model.prototype.$__version = function(where, delta) { var key = this.schema.options.versionKey; if (where === true) { // this is an insert if (key) this.setValue(key, delta[key] = 0); return; } // updates // only apply versioning if our versionKey was selected. else // there is no way to select the correct version. we could fail // fast here and force them to include the versionKey but // thats a bit intrusive. can we do this automatically? if (!this.isSelected(key)) { return; } // $push $addToSet don't need the where clause set if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { where[key] = this.getValue(key); } if (VERSION_INC === (VERSION_INC & this.$__.version)) { if (!delta.$set || typeof delta.$set[key] === 'undefined') { delta.$inc || (delta.$inc = {}); delta.$inc[key] = 1; } } }; /** * Signal that we desire an increment of this documents version. * * ####Example: * * Model.findById(id, function (err, doc) { * doc.increment(); * doc.save(function (err) { .. }) * }) * * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey * @api public */ Model.prototype.increment = function increment() { this.$__.version = VERSION_ALL; return this; }; /** * Returns a query object which applies shardkeys if they exist. * * @api private * @method $__where * @memberOf Model */ Model.prototype.$__where = function _where(where) { where || (where = {}); var paths, len; if (!where._id) { where._id = this._doc._id; } if (this.$__.shardval) { paths = Object.keys(this.$__.shardval); len = paths.length; for (var i = 0; i < len; ++i) { where[paths[i]] = this.$__.shardval[paths[i]]; } } if (this._doc._id == null) { return new Error('No _id found on document!'); } return where; }; /** * Removes this document from the db. * * ####Example: * product.remove(function (err, product) { * if (err) return handleError(err); * Product.findById(product._id, function (err, product) { * console.log(product) // null * }) * }) * * * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recive errors * * ####Example: * product.remove().then(function (product) { * ... * }).onRejected(function (err) { * assert.ok(err) * }) * * @param {function(err,product)} [fn] optional callback * @return {Promise} Promise * @api public */ Model.prototype.remove = function remove(options, fn) { if (typeof options === 'function') { fn = options; options = undefined; } if (!options) { options = {}; } if (this.$__.removing) { if (fn) { this.$__.removing.then( function(res) { fn(null, res); }, function(err) { fn(err); }); } return this; } var _this = this; var Promise = PromiseProvider.get(); if (fn) { fn = this.constructor.$wrapCallback(fn); } this.$__.removing = new Promise.ES6(function(resolve, reject) { var where = _this.$__where(); if (where instanceof Error) { reject(where); fn && fn(where); return; } if (!options.safe && _this.schema.options.safe) { options.safe = _this.schema.options.safe; } _this.collection.remove(where, options, function(err) { if (!err) { _this.emit('remove', _this); resolve(_this); fn && fn(null, _this); return; } reject(err); fn && fn(err); }); }); return this.$__.removing; }; /** * Returns another Model instance. * * ####Example: * * var doc = new Tank; * doc.model('User').findById(id, callback); * * @param {String} name model name * @api public */ Model.prototype.model = function model(name) { return this.db.model(name); }; /** * Adds a discriminator type. * * ####Example: * * function BaseSchema() { * Schema.apply(this, arguments); * * this.add({ * name: String, * createdAt: Date * }); * } * util.inherits(BaseSchema, Schema); * * var PersonSchema = new BaseSchema(); * var BossSchema = new BaseSchema({ department: String }); * * var Person = mongoose.model('Person', PersonSchema); * var Boss = Person.discriminator('Boss', BossSchema); * * @param {String} name discriminator model name * @param {Schema} schema discriminator model schema * @api public */ Model.discriminator = function discriminator(name, schema) { var CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { toJSON: true, toObject: true, _id: true, id: true }; if (!(schema && schema.instanceOfSchema)) { throw new Error('You must pass a valid discriminator Schema'); } if (this.schema.discriminatorMapping && !this.schema.discriminatorMapping.isRoot) { throw new Error('Discriminator "' + name + '" can only be a discriminator of the root model'); } var key = this.schema.options.discriminatorKey; if (schema.path(key)) { throw new Error('Discriminator "' + name + '" cannot have field with name "' + key + '"'); } function merge(schema, baseSchema) { utils.merge(schema, baseSchema); var obj = {}; obj[key] = { default: name, set: function(newName) { if (newName === name) { return name; } throw new Error('Can\'t set discriminator key "' + key + '"'); } }; obj[key][schema.options.typeKey] = String; schema.add(obj); schema.discriminatorMapping = {key: key, value: name, isRoot: false}; if (baseSchema.options.collection) { schema.options.collection = baseSchema.options.collection; } var toJSON = schema.options.toJSON; var toObject = schema.options.toObject; var _id = schema.options._id; var id = schema.options.id; var keys = Object.keys(schema.options); for (var i = 0; i < keys.length; ++i) { var _key = keys[i]; if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) { if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) { throw new Error('Can\'t customize discriminator option ' + _key + ' (can only modify ' + Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') + ')'); } } } schema.options = utils.clone(baseSchema.options); if (toJSON) schema.options.toJSON = toJSON; if (toObject) schema.options.toObject = toObject; if (typeof _id !== 'undefined') { schema.options._id = _id; } schema.options.id = id; schema.callQueue = baseSchema.callQueue.concat(schema.callQueue.slice(schema._defaultMiddleware.length)); schema._requiredpaths = undefined; // reset just in case Schema#requiredPaths() was called on either schema } // merges base schema into new discriminator schema and sets new type field. merge(schema, this.schema); if (!this.discriminators) { this.discriminators = {}; } if (!this.schema.discriminatorMapping) { this.schema.discriminatorMapping = {key: key, value: null, isRoot: true}; } if (this.discriminators[name]) { throw new Error('Discriminator with name "' + name + '" already exists'); } if (this.db.models[name]) { throw new MongooseError.OverwriteModelError(name); } this.discriminators[name] = this.db.model(name, schema, this.collection.name); this.discriminators[name].prototype.__proto__ = this.prototype; Object.defineProperty(this.discriminators[name], 'baseModelName', { value: this.modelName, configurable: true, writable: false }); // apply methods and statics applyMethods(this.discriminators[name], schema); applyStatics(this.discriminators[name], schema); return this.discriminators[name]; }; // Model (class) features /*! * Give the constructor the ability to emit events. */ for (var i in EventEmitter.prototype) { Model[i] = EventEmitter.prototype[i]; } /** * Called when the model compiles. * * @api private */ Model.init = function init() { if ((this.schema.options.autoIndex) || (this.schema.options.autoIndex === null && this.db.config.autoIndex)) { this.ensureIndexes({ __noPromise: true, _automatic: true }); } this.schema.emit('init', this); }; /** * Sends `ensureIndex` commands to mongo for each index declared in the schema. * * ####Example: * * Event.ensureIndexes(function (err) { * if (err) return handleError(err); * }); * * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. * * ####Example: * * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) * var Event = mongoose.model('Event', eventSchema); * * Event.on('index', function (err) { * if (err) console.error(err); // error occurred during index creation * }) * * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ * * The `ensureIndex` commands are not sent in parallel. This is to avoid the `MongoError: cannot add index with a background operation in progress` error. See [this ticket](https://github.com/Automattic/mongoose/issues/1365) for more information. * * @param {Object} [options] internal options * @param {Function} [cb] optional callback * @return {Promise} * @api public */ Model.ensureIndexes = function ensureIndexes(options, callback) { if (typeof options === 'function') { callback = options; options = null; } if (options && options.__noPromise) { _ensureIndexes(this, options, callback); return; } if (callback) { callback = this.$wrapCallback(callback); } var _this = this; var Promise = PromiseProvider.get(); return new Promise.ES6(function(resolve, reject) { _ensureIndexes(_this, options || {}, function(error) { if (error) { callback && callback(error); reject(error); } callback && callback(); resolve(); }); }); }; function _ensureIndexes(model, options, callback) { var indexes = model.schema.indexes(); if (!indexes.length) { setImmediate(function() { callback && callback(); }); return; } // Indexes are created one-by-one to support how MongoDB < 2.4 deals // with background indexes. var done = function(err) { if (err && model.schema.options.emitIndexErrors) { model.emit('error', err); } model.emit('index', err); callback && callback(err); }; var indexSingleDone = function(err, fields, options, name) { model.emit('index-single-done', err, fields, options, name); }; var indexSingleStart = function(fields, options) { model.emit('index-single-start', fields, options); }; var create = function() { var index = indexes.shift(); if (!index) return done(); var indexFields = index[0]; var options = index[1]; _handleSafe(options); indexSingleStart(indexFields, options); model.collection.ensureIndex(indexFields, options, tick(function(err, name) { indexSingleDone(err, indexFields, options, name); if (err) { return done(err); } create(); })); }; setImmediate(function() { // If buffering is off, do this manually. if (options._automatic && !model.collection.collection) { model.collection.addQueue(create, []); } else { create(); } }); } function _handleSafe(options) { if (options.safe) { if (typeof options.safe === 'boolean') { options.w = options.safe; delete options.safe; } if (typeof options.safe === 'object') { options.w = options.safe.w; options.j = options.safe.j; options.wtimeout = options.safe.wtimeout; delete options.safe; } } } /** * Schema the model uses. * * @property schema * @receiver Model * @api public */ Model.schema; /*! * Connection instance the model uses. * * @property db * @receiver Model * @api public */ Model.db; /*! * Collection the model uses. * * @property collection * @receiver Model * @api public */ Model.collection; /** * Base Mongoose instance the model uses. * * @property base * @receiver Model * @api public */ Model.base; /** * Registered discriminators for this model. * * @property discriminators * @receiver Model * @api public */ Model.discriminators; /** * Removes documents from the collection. * * ####Example: * * Comment.remove({ title: 'baby born from alien father' }, function (err) { * * }); * * ####Note: * * To remove documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js): * * var query = Comment.remove({ _id: id }); * query.exec(); * * ####Note: * * This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, _no middleware (hooks) are executed_. * * @param {Object} conditions * @param {Function} [callback] * @return {Query} * @api public */ Model.remove = function remove(conditions, callback) { if (typeof conditions === 'function') { callback = conditions; conditions = {}; } // get the mongodb collection object var mq = new this.Query(conditions, {}, this, this.collection); if (callback) { callback = this.$wrapCallback(callback); } return mq.remove(callback); }; /** * Finds documents * * The `conditions` are cast to their respective SchemaTypes before the command is sent. * * ####Examples: * * // named john and at least 18 * MyModel.find({ name: 'john', age: { $gte: 18 }}); * * // executes immediately, passing results to callback * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); * * // name LIKE john and only selecting the "name" and "friends" fields, executing immediately * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) * * // passing options * MyModel.find({ name: /john/i }, null, { skip: 10 }) * * // passing options and executing immediately * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); * * // executing a query explicitly * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }) * query.exec(function (err, docs) {}); * * // using the promise returned from executing a query * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }); * var promise = query.exec(); * promise.addBack(function (err, docs) {}); * * @param {Object} conditions * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo) * @param {Object} [options] optional * @param {Function} [callback] * @return {Query} * @see field selection #query_Query-select * @see promise #promise-js * @api public */ Model.find = function find(conditions, projection, options, callback) { if (typeof conditions === 'function') { callback = conditions; conditions = {}; projection = null; options = null; } else if (typeof projection === 'function') { callback = projection; projection = null; options = null; } else if (typeof options === 'function') { callback = options; options = null; } var mq = new this.Query({}, {}, this, this.collection); mq.select(projection); mq.setOptions(options); if (this.schema.discriminatorMapping && mq.selectedInclusively()) { mq.select(this.schema.options.discriminatorKey); } if (callback) { callback = this.$wrapCallback(callback); } return mq.find(conditions, callback); }; /** * Finds a single document by its _id field. `findById(id)` is almost* * equivalent to `findOne({ _id: id })`. If you want to query by a document's * `_id`, use `findById()` instead of `findOne()`. * * The `id` is cast based on the Schema before sending the command. * * Note: `findById()` triggers `findOne` hooks. * * * Except for how it treats `undefined`. If you use `findOne()`, you'll see * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent * to `findOne({})` and return arbitrary documents. However, mongoose * translates `findById(undefined)` into `findOne({ _id: null })`. * * ####Example: * * // find adventure by id and execute immediately * Adventure.findById(id, function (err, adventure) {}); * * // same as above * Adventure.findById(id).exec(callback); * * // select only the adventures name and length * Adventure.findById(id, 'name length', function (err, adventure) {}); * * // same as above * Adventure.findById(id, 'name length').exec(callback); * * // include all properties except for `length` * Adventure.findById(id, '-length').exec(function (err, adventure) {}); * * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean` * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {}); * * // same as above * Adventure.findById(id, 'name').lean().exec(function (err, doc) {}); * * @param {Object|String|Number} id value of `_id` to query by * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo) * @param {Object} [options] optional * @param {Function} [callback] * @return {Query} * @see field selection #query_Query-select * @see lean queries #query_Query-lean * @api public */ Model.findById = function findById(id, projection, options, callback) { if (typeof id === 'undefined') { id = null; } if (callback) { callback = this.$wrapCallback(callback); } return this.findOne({_id: id}, projection, options, callback); }; /** * Finds one document. * * The `conditions` are cast to their respective SchemaTypes before the command is sent. * * *Note:* `conditions` is optional, and if `conditions` is null or undefined, * mongoose will send an empty `findOne` command to MongoDB, which will return * an arbitrary document. If you're querying by `_id`, use `findById()` instead. * * ####Example: * * // find one iphone adventures - iphone adventures?? * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {}); * * // same as above * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); * * // select only the adventures name * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); * * // same as above * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); * * // specify options, in this case lean * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback); * * // same as above * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback); * * // chaining findOne queries (same as above) * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback); * * @param {Object} [conditions] * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo) * @param {Object} [options] optional * @param {Function} [callback] * @return {Query} * @see field selection #query_Query-select * @see lean queries #query_Query-lean * @api public */ Model.findOne = function findOne(conditions, projection, options, callback) { if (typeof options === 'function') { callback = options; options = null; } else if (typeof projection === 'function') { callback = projection; projection = null; options = null; } else if (typeof conditions === 'function') { callback = conditions; conditions = {}; projection = null; options = null; } // get the mongodb collection object var mq = new this.Query({}, {}, this, this.collection); mq.select(projection); mq.setOptions(options); if (this.schema.discriminatorMapping && mq.selectedInclusively()) { mq.select(this.schema.options.discriminatorKey); } if (callback) { callback = this.$wrapCallback(callback); } return mq.findOne(conditions, callback); }; /** * Counts number of matching documents in a database collection. * * ####Example: * * Adventure.count({ type: 'jungle' }, function (err, count) { * if (err) .. * console.log('there are %d jungle adventures', count); * }); * * @param {Object} conditions * @param {Function} [callback] * @return {Query} * @api public */ Model.count = function count(conditions, callback) { if (typeof conditions === 'function') { callback = conditions; conditions = {}; } // get the mongodb collection object var mq = new this.Query({}, {}, this, this.collection); if (callback) { callback = this.$wrapCallback(callback); } return mq.count(conditions, callback); }; /** * Creates a Query for a `distinct` operation. * * Passing a `callback` immediately executes the query. * * ####Example * * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { * if (err) return handleError(err); * * assert(Array.isArray(result)); * console.log('unique urls with more than 100 clicks', result); * }) * * var query = Link.distinct('url'); * query.exec(callback); * * @param {String} field * @param {Object} [conditions] optional * @param {Function} [callback] * @return {Query} * @api public */ Model.distinct = function distinct(field, conditions, callback) { // get the mongodb collection object var mq = new this.Query({}, {}, this, this.collection); if (typeof conditions === 'function') { callback = conditions; conditions = {}; } if (callback) { callback = this.$wrapCallback(callback); } return mq.distinct(field, conditions, callback); }; /** * Creates a Query, applies the passed conditions, and returns the Query. * * For example, instead of writing: * * User.find({age: {$gte: 21, $lte: 65}}, callback); * * we can instead write: * * User.where('age').gte(21).lte(65).exec(callback); * * Since the Query class also supports `where` you can continue chaining * * User * .where('age').gte(21).lte(65) * .where('name', /^b/i) * ... etc * * @param {String} path * @param {Object} [val] optional value * @return {Query} * @api public */ Model.where = function where(path, val) { void val; // eslint // get the mongodb collection object var mq = new this.Query({}, {}, this, this.collection).find({}); return mq.where.apply(mq, arguments); }; /** * Creates a `Query` and specifies a `$where` condition. * * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. * * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {}); * * @param {String|Function} argument is a javascript string or anonymous function * @method $where * @memberOf Model * @return {Query} * @see Query.$where #query_Query-%24where * @api public */ Model.$where = function $where() { var mq = new this.Query({}, {}, this, this.collection).find({}); return mq.$where.apply(mq, arguments); }; /** * Issues a mongodb findAndModify update command. * * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned. * * ####Options: * * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) * * * ####Examples: * * A.findOneAndUpdate(conditions, update, options, callback) // executes * A.findOneAndUpdate(conditions, update, options) // returns Query * A.findOneAndUpdate(conditions, update, callback) // executes * A.findOneAndUpdate(conditions, update) // returns Query * A.findOneAndUpdate() // returns Query * * ####Note: * * All top level update keys which are not `atomic` operation names are treated as set operations: * * ####Example: * * var query = { name: 'borne' }; * Model.findOneAndUpdate(query, { name: 'jason borne' }, options, callback) * * // is sent as * Model.findOneAndUpdate(query, { $set: { name: 'jason borne' }}, options, callback) * * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`. * * ####Note: * * Values are cast to their appropriate types when using the findAndModify helpers. * However, the below are never executed. * * - defaults * - setters * * `findAndModify` helpers support limited defaults and validation. You can * enable these by setting the `setDefaultsOnInsert` and `runValidators` options, * respectively. * * If you need full-fledged validation, use the traditional approach of first * retrieving the document. * * Model.findById(id, function (err, doc) { * if (err) .. * doc.name = 'jason borne'; * doc.save(callback); * }); * * @param {Object} [conditions] * @param {Object} [update] * @param {Object} [options] * @param {Function} [callback] * @return {Query} * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command * @api public */ Model.findOneAndUpdate = function(conditions, update, options, callback) { if (typeof options === 'function') { callback = options; options = null; } else if (arguments.length === 1) { if (typeof conditions === 'function') { var msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n' + ' ' + this.modelName + '.findOneAndUpdate(update)\n' + ' ' + this.modelName + '.findOneAndUpdate()\n'; throw new TypeError(msg); } update = conditions; conditions = undefined; } if (callback) { callback = this.$wrapCallback(callback); } var fields; if (options && options.fields) { fields = options.fields; } update = utils.clone(update, {depopulate: 1, _isNested: true}); if (this.schema.options.versionKey && options && options.upsert) { if (!update.$setOnInsert) { update.$setOnInsert = {}; } update.$setOnInsert[this.schema.options.versionKey] = 0; } var mq = new this.Query({}, {}, this, this.collection); mq.select(fields); return mq.findOneAndUpdate(conditions, update, options, callback); }; /** * Issues a mongodb findAndModify update command by a document's _id field. * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`. * * Finds a matching document, updates it according to the `update` arg, * passing any `options`, and returns the found document (if any) to the * callback. The query executes immediately if `callback` is passed else a * Query object is returned. * * This function triggers `findOneAndUpdate` middleware. * * ####Options: * * - `new`: bool - true to return the modified document rather than the original. defaults to false * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * - `select`: sets the document fields to return * * ####Examples: * * A.findByIdAndUpdate(id, update, options, callback) // executes * A.findByIdAndUpdate(id, update, options) // returns Query * A.findByIdAndUpdate(id, update, callback) // executes * A.findByIdAndUpdate(id, update) // returns Query * A.findByIdAndUpdate() // returns Query * * ####Note: * * All top level update keys which are not `atomic` operation names are treated as set operations: * * ####Example: * * Model.findByIdAndUpdate(id, { name: 'jason borne' }, options, callback) * * // is sent as * Model.findByIdAndUpdate(id, { $set: { name: 'jason borne' }}, options, callback) * * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`. * * ####Note: * * Values are cast to their appropriate types when using the findAndModify helpers. * However, the below are never executed. * * - defaults * - setters * * `findAndModify` helpers support limited defaults and validation. You can * enable these by setting the `setDefaultsOnInsert` and `runValidators` options, * respectively. * * If you need full-fledged validation, use the traditional approach of first * retrieving the document. * * Model.findById(id, function (err, doc) { * if (err) .. * doc.name = 'jason borne'; * doc.save(callback); * }); * * @param {Object|Number|String} id value of `_id` to query by * @param {Object} [update] * @param {Object} [options] * @param {Function} [callback] * @return {Query} * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command * @api public */ Model.findByIdAndUpdate = function(id, update, options, callback) { if (callback) { callback = this.$wrapCallback(callback); } if (arguments.length === 1) { if (typeof id === 'function') { var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' + ' ' + this.modelName + '.findByIdAndUpdate()\n'; throw new TypeError(msg); } return this.findOneAndUpdate({_id: id}, undefined); } // if a model is passed in instead of an id if (id instanceof Document) { id = id._id; } return this.findOneAndUpdate.call(this, {_id: id}, update, options, callback); }; /** * Issue a mongodb findAndModify remove command. * * Finds a matching document, removes it, passing the found document (if any) to the callback. * * Executes immediately if `callback` is passed else a Query object is returned. * * ####Options: * * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 * - `select`: sets the document fields to return * * ####Examples: * * A.findOneAndRemove(conditions, options, callback) // executes * A.findOneAndRemove(conditions, options) // return Query * A.findOneAndRemove(conditions, callback) // executes * A.findOneAndRemove(conditions) // returns Query * A.findOneAndRemove() // returns Query * * Values are cast to their appropriate types when using the findAndModify helpers. * However, the below are never executed. * * - defaults * - setters * * `findAndModify` helpers support limited defaults and validation. You can * enable these by setting the `setDefaultsOnInsert` and `runValidators` options, * respectively. * * If you need full-fledged validation, use the traditional approach of first * retrieving the document. * * Model.findById(id, function (err, doc) { * if (err) .. * doc.name = 'jason borne'; * doc.save(callback); * }); * * @param {Object} conditions * @param {Object} [options] * @param {Function} [callback] * @return {Query} * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command * @api public */ Model.findOneAndRemove = function(conditions, options, callback) { if (arguments.length === 1 && typeof conditions === 'function') { var msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' + ' ' + this.modelName + '.findOneAndRemove()\n'; throw new TypeError(msg); } if (typeof options === 'function') { callback = options; options = undefined; } if (callback) { callback = this.$wrapCallback(callback); } var fields; if (options) { fields = options.select; options.select = undefined; } var mq = new this.Query({}, {}, this, this.collection); mq.select(fields); return mq.findOneAndRemove(conditions, options, callback); }; /** * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`. * * Finds a matching document, removes it, passing the found document (if any) to the callback. * * Executes immediately if `callback` is passed, else a `Query` object is returned. * * ####Options: * * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * - `select`: sets the document fields to return * * ####Examples: * * A.findByIdAndRemove(id, options, callback) // executes * A.findByIdAndRemove(id, options) // return Query * A.findByIdAndRemove(id, callback) // executes * A.findByIdAndRemove(id) // returns Query * A.findByIdAndRemove() // returns Query * * @param {Object|Number|String} id value of `_id` to query by * @param {Object} [options] * @param {Function} [callback] * @return {Query} * @see Model.findOneAndRemove #model_Model.findOneAndRemove * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command */ Model.findByIdAndRemove = function(id, options, callback) { if (arguments.length === 1 && typeof id === 'function') { var msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' + ' ' + this.modelName + '.findByIdAndRemove(id)\n' + ' ' + this.modelName + '.findByIdAndRemove()\n'; throw new TypeError(msg); } if (callback) { callback = this.$wrapCallback(callback); } return this.findOneAndRemove({_id: id}, options, callback); }; /** * Shortcut for saving one or more documents to the database. * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in * docs. * * Hooks Triggered: * - `save()` * * ####Example: * * // pass individual docs * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) { * if (err) // ... * }); * * // pass an array * var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; * Candy.create(array, function (err, candies) { * if (err) // ... * * var jellybean = candies[0]; * var snickers = candies[1]; * // ... * }); * * // callback is optional; use the returned promise if you like: * var promise = Candy.create({ type: 'jawbreaker' }); * promise.then(function (jawbreaker) { * // ... * }) * * @param {Array|Object|*} doc(s) * @param {Function} [callback] callback * @return {Promise} * @api public */ Model.create = function create(doc, callback) { var args; var cb; if (Array.isArray(doc)) { args = doc; cb = callback; } else { var last = arguments[arguments.length - 1]; if (typeof last === 'function') { cb = last; args = utils.args(arguments, 0, arguments.length - 1); } else { args = utils.args(arguments); } } var Promise = PromiseProvider.get(); var _this = this; if (cb) { cb = this.$wrapCallback(cb); } var promise = new Promise.ES6(function(resolve, reject) { if (args.length === 0) { setImmediate(function() { cb && cb(null); resolve(null); }); return; } var toExecute = []; args.forEach(function(doc) { toExecute.push(function(callback) { var toSave = doc instanceof _this ? doc : new _this(doc); var callbackWrapper = function(error, doc) { if (error) { return callback(error); } callback(null, doc); }; // Hack to avoid getting a promise because of // $__registerHooksFromSchema if (toSave.$__original_save) { toSave.$__original_save({ __noPromise: true }, callbackWrapper); } else { toSave.save({ __noPromise: true }, callbackWrapper); } }); }); parallel(toExecute, function(error, savedDocs) { if (error) { if (cb) { cb(error); } else { reject(error); } return; } if (doc instanceof Array) { resolve(savedDocs); cb && cb.call(_this, null, savedDocs); } else { resolve.apply(promise, savedDocs); if (cb) { savedDocs.unshift(null); cb.apply(_this, savedDocs); } } }); }); return promise; }; /** * Shortcut for validating an array of documents and inserting them into * MongoDB if they're all valid. This function is faster than `.create()` * because it only sends one operation to the server, rather than one for each * document. * * This function does **not** trigger save middleware. * * ####Example: * * var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }]; * Movies.insertMany(arr, function(error, docs) {}); * * @param {Array|Object|*} doc(s) * @param {Function} [callback] callback * @return {Promise} * @api public */ Model.insertMany = function(arr, callback) { var _this = this; if (callback) { callback = this.$wrapCallback(callback); } var toExecute = []; arr.forEach(function(doc) { toExecute.push(function(callback) { doc = new _this(doc); doc.validate({ __noPromise: true }, function(error) { if (error) { return callback(error); } callback(null, doc); }); }); }); parallel(toExecute, function(error, docs) { if (error) { callback && callback(error); return; } var docObjects = docs.map(function(doc) { if (doc.schema.options.versionKey) { doc[doc.schema.options.versionKey] = 0; } if (doc.initializeTimestamps) { return doc.initializeTimestamps().toObject(POJO_TO_OBJECT_OPTIONS); } return doc.toObject(POJO_TO_OBJECT_OPTIONS); }); _this.collection.insertMany(docObjects, function(error) { if (error) { callback && callback(error); return; } for (var i = 0; i < docs.length; ++i) { docs[i].isNew = false; docs[i].emit('isNew', false); } callback && callback(null, docs); }); }); }; /** * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. * The document returned has no paths marked as modified initially. * * ####Example: * * // hydrate previous data into a Mongoose document * var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' }); * * @param {Object} obj * @return {Document} * @api public */ Model.hydrate = function(obj) { var model = require('./queryhelpers').createModel(this, obj); model.init(obj); return model; }; /** * Updates documents in the database without returning them. * * ####Examples: * * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); * MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, raw) { * if (err) return handleError(err); * console.log('The raw response from Mongo was ', raw); * }); * * ####Valid options: * * - `safe` (boolean) safe mode (defaults to value set in schema (true)) * - `upsert` (boolean) whether to create the doc if it doesn't match (false) * - `multi` (boolean) whether multiple documents should be updated (false) * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). * - `strict` (boolean) overrides the `strict` option for this update * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false) * * All `update` values are cast to their appropriate SchemaTypes before being sent. * * The `callback` function receives `(err, rawResponse)`. * * - `err` is the error if any occurred * - `rawResponse` is the full response from Mongo * * ####Note: * * All top level keys which are not `atomic` operation names are treated as set operations: * * ####Example: * * var query = { name: 'borne' }; * Model.update(query, { name: 'jason borne' }, options, callback) * * // is sent as * Model.update(query, { $set: { name: 'jason borne' }}, options, callback) * // if overwrite option is false. If overwrite is true, sent without the $set wrapper. * * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason borne' }`. * * ####Note: * * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. * * ####Note: * * To update documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js): * * Comment.update({ _id: id }, { $set: { text: 'changed' }}).exec(); * * ####Note: * * Although values are casted to their appropriate types when using update, the following are *not* applied: * * - defaults * - setters * - validators * - middleware * * If you need those features, use the traditional approach of first retrieving the document. * * Model.findOne({ name: 'borne' }, function (err, doc) { * if (err) .. * doc.name = 'jason borne'; * doc.save(callback); * }) * * @see strict http://mongoosejs.com/docs/guide.html#strict * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output * @param {Object} conditions * @param {Object} doc * @param {Object} [options] * @param {Function} [callback] * @return {Query} * @api public */ Model.update = function update(conditions, doc, options, callback) { var mq = new this.Query({}, {}, this, this.collection); if (callback) { callback = this.$wrapCallback(callback); } // gh-2406 // make local deep copy of conditions if (conditions instanceof Document) { conditions = conditions.toObject(); } else { conditions = utils.clone(conditions, {retainKeyOrder: true}); } options = typeof options === 'function' ? options : utils.clone(options); if (this.schema.options.versionKey && options && options.upsert) { if (!doc.$setOnInsert) { doc.$setOnInsert = {}; } doc.$setOnInsert[this.schema.options.versionKey] = 0; } return mq.update(conditions, doc, options, callback); }; /** * Executes a mapReduce command. * * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options. * * ####Example: * * var o = {}; * o.map = function () { emit(this.name, 1) } * o.reduce = function (k, vals) { return vals.length } * User.mapReduce(o, function (err, results) { * console.log(results) * }) * * ####Other options: * * - `query` {Object} query filter object. * - `sort` {Object} sort input objects using this key * - `limit` {Number} max number of documents * - `keeptemp` {Boolean, default:false} keep temporary data * - `finalize` {Function} finalize function * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X * - `verbose` {Boolean, default:false} provide statistics on job execution time. * - `readPreference` {String} * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. * * ####* out options: * * - `{inline:1}` the results are returned in an array * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old * * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the `lean` option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). * * ####Example: * * var o = {}; * o.map = function () { emit(this.name, 1) } * o.reduce = function (k, vals) { return vals.length } * o.out = { replace: 'createdCollectionNameForResults' } * o.verbose = true; * * User.mapReduce(o, function (err, model, stats) { * console.log('map reduce took %d ms', stats.processtime) * model.find().where('value').gt(10).exec(function (err, docs) { * console.log(docs); * }); * }) * * // a promise is returned so you may instead write * var promise = User.mapReduce(o); * promise.then(function (model, stats) { * console.log('map reduce took %d ms', stats.processtime) * return model.find().where('value').gt(10).exec(); * }).then(function (docs) { * console.log(docs); * }).then(null, handleError).end() * * @param {Object} o an object specifying map-reduce options * @param {Function} [callback] optional callback * @see http://www.mongodb.org/display/DOCS/MapReduce * @return {Promise} * @api public */ Model.mapReduce = function mapReduce(o, callback) { var _this = this; if (callback) { callback = this.$wrapCallback(callback); } var Promise = PromiseProvider.get(); return new Promise.ES6(function(resolve, reject) { if (!Model.mapReduce.schema) { var opts = {noId: true, noVirtualId: true, strict: false}; Model.mapReduce.schema = new Schema({}, opts); } if (!o.out) o.out = {inline: 1}; if (o.verbose !== false) o.verbose = true; o.map = String(o.map); o.reduce = String(o.reduce); if (o.query) { var q = new _this.Query(o.query); q.cast(_this); o.query = q._conditions; q = undefined; } _this.collection.mapReduce(null, null, o, function(err, ret, stats) { if (err) { callback && callback(err); reject(err); return; } if (ret.findOne && ret.mapReduce) { // returned a collection, convert to Model var model = Model.compile( '_mapreduce_' + ret.collectionName , Model.mapReduce.schema , ret.collectionName , _this.db , _this.base); model._mapreduce = true; callback && callback(null, model, stats); return resolve(model, stats); } callback && callback(null, ret, stats); resolve(ret, stats); }); }); }; /** * geoNear support for Mongoose * * ####Options: * - `lean` {Boolean} return the raw object * - All options supported by the driver are also supported * * ####Example: * * // Legacy point * Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) { * console.log(results); * }); * * // geoJson * var point = { type : "Point", coordinates : [9,9] }; * Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) { * console.log(results); * }); * * @param {Object|Array} GeoJSON point or legacy coordinate pair [x,y] to search near * @param {Object} options for the qurery * @param {Function} [callback] optional callback for the query * @return {Promise} * @see http://docs.mongodb.org/manual/core/2dsphere/ * @see http://mongodb.github.io/node-mongodb-native/api-generated/collection.html?highlight=geonear#geoNear * @api public */ Model.geoNear = function(near, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } if (callback) { callback = this.$wrapCallback(callback); } var _this = this; var Promise = PromiseProvider.get(); if (!near) { return new Promise.ES6(function(resolve, reject) { var error = new Error('Must pass a near option to geoNear'); reject(error); callback && callback(error); }); } var x, y; return new Promise.ES6(function(resolve, reject) { var handler = function(err, res) { if (err) { reject(err); callback && callback(err); return; } if (options.lean) { resolve(res.results, res.stats); callback && callback(null, res.results, res.stats); return; } var count = res.results.length; // if there are no results, fulfill the promise now if (count === 0) { resolve(res.results, res.stats); callback && callback(null, res.results, res.stats); return; } var errSeen = false; function init(err) { if (err && !errSeen) { errSeen = true; reject(err); callback && callback(err); return; } if (--count <= 0) { resolve(res.results, res.stats); callback && callback(null, res.results, res.stats); } } for (var i = 0; i < res.results.length; i++) { var temp = res.results[i].obj; res.results[i].obj = new _this(); res.results[i].obj.init(temp, init); } }; if (Array.isArray(near)) { if (near.length !== 2) { var error = new Error('If using legacy coordinates, must be an array ' + 'of size 2 for geoNear'); reject(error); callback && callback(error); return; } x = near[0]; y = near[1]; _this.collection.geoNear(x, y, options, handler); } else { if (near.type !== 'Point' || !Array.isArray(near.coordinates)) { error = new Error('Must pass either a legacy coordinate array or ' + 'GeoJSON Point to geoNear'); reject(error); callback && callback(error); return; } _this.collection.geoNear(near, options, handler); } }); }; /** * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. * * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. * * ####Example: * * // Find the max balance of all accounts * Users.aggregate( * { $group: { _id: null, maxBalance: { $max: '$balance' }}} * , { $project: { _id: 0, maxBalance: 1 }} * , function (err, res) { * if (err) return handleError(err); * console.log(res); // [ { maxBalance: 98000 } ] * }); * * // Or use the aggregation pipeline builder. * Users.aggregate() * .group({ _id: null, maxBalance: { $max: '$balance' } }) * .select('-id maxBalance') * .exec(function (err, res) { * if (err) return handleError(err); * console.log(res); // [ { maxBalance: 98 } ] * }); * * ####NOTE: * * - Arguments are not cast to the model's schema because `$project` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). * - Requires MongoDB >= 2.1 * * @see Aggregate #aggregate_Aggregate * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ * @param {Object|Array} [...] aggregation pipeline operator(s) or operator array * @param {Function} [callback] * @return {Aggregate|Promise} * @api public */ Model.aggregate = function aggregate() { var args = [].slice.call(arguments), aggregate, callback; if (typeof args[args.length - 1] === 'function') { callback = args.pop(); } if (args.length === 1 && util.isArray(args[0])) { aggregate = new Aggregate(args[0]); } else { aggregate = new Aggregate(args); } aggregate.model(this); if (typeof callback === 'undefined') { return aggregate; } if (callback) { callback = this.$wrapCallback(callback); } aggregate.exec(callback); }; /** * Implements `$geoSearch` functionality for Mongoose * * ####Example: * * var options = { near: [10, 10], maxDistance: 5 }; * Locations.geoSearch({ type : "house" }, options, function(err, res) { * console.log(res); * }); * * ####Options: * - `near` {Array} x,y point to search for * - `maxDistance` {Number} the maximum distance from the point near that a result can be * - `limit` {Number} The maximum number of results to return * - `lean` {Boolean} return the raw object instead of the Mongoose Model * * @param {Object} conditions an object that specifies the match condition (required) * @param {Object} options for the geoSearch, some (near, maxDistance) are required * @param {Function} [callback] optional callback * @return {Promise} * @see http://docs.mongodb.org/manual/reference/command/geoSearch/ * @see http://docs.mongodb.org/manual/core/geohaystack/ * @api public */ Model.geoSearch = function(conditions, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } if (callback) { callback = this.$wrapCallback(callback); } var _this = this; var Promise = PromiseProvider.get(); return new Promise.ES6(function(resolve, reject) { var error; if (conditions === undefined || !utils.isObject(conditions)) { error = new Error('Must pass conditions to geoSearch'); } else if (!options.near) { error = new Error('Must specify the near option in geoSearch'); } else if (!Array.isArray(options.near)) { error = new Error('near option must be an array [x, y]'); } if (error) { callback && callback(error); reject(error); return; } // send the conditions in the options object options.search = conditions; _this.collection.geoHaystackSearch(options.near[0], options.near[1], options, function(err, res) { // have to deal with driver problem. Should be fixed in a soon-ish release // (7/8/2013) if (err) { callback && callback(err); reject(err); return; } var count = res.results.length; if (options.lean || count === 0) { callback && callback(null, res.results, res.stats); resolve(res.results, res.stats); return; } var errSeen = false; function init(err) { if (err && !errSeen) { callback && callback(err); reject(err); return; } if (!--count && !errSeen) { callback && callback(null, res.results, res.stats); resolve(res.results, res.stats); } } for (var i = 0; i < res.results.length; i++) { var temp = res.results[i]; res.results[i] = new _this(); res.results[i].init(temp, {}, init); } }); }); }; /** * Populates document references. * * ####Available options: * * - path: space delimited path(s) to populate * - select: optional fields to select * - match: optional query conditions to match * - model: optional name of the model to use for population * - options: optional query options like sort, limit, etc * * ####Examples: * * // populates a single object * User.findById(id, function (err, user) { * var opts = [ * { path: 'company', match: { x: 1 }, select: 'name' } * , { path: 'notes', options: { limit: 10 }, model: 'override' } * ] * * User.populate(user, opts, function (err, user) { * console.log(user); * }) * }) * * // populates an array of objects * User.find(match, function (err, users) { * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }] * * var promise = User.populate(users, opts); * promise.then(console.log).end(); * }) * * // imagine a Weapon model exists with two saved documents: * // { _id: 389, name: 'whip' } * // { _id: 8921, name: 'boomerang' } * * var user = { name: 'Indiana Jones', weapon: 389 } * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) { * console.log(user.weapon.name) // whip * }) * * // populate many plain objects * var users = [{ name: 'Indiana Jones', weapon: 389 }] * users.push({ name: 'Batman', weapon: 8921 }) * Weapon.populate(users, { path: 'weapon' }, function (err, users) { * users.forEach(function (user) { * console.log('%s uses a %s', users.name, user.weapon.name) * // Indiana Jones uses a whip * // Batman uses a boomerang * }) * }) * // Note that we didn't need to specify the Weapon model because * // we were already using it's populate() method. * * @param {Document|Array} docs Either a single document or array of documents to populate. * @param {Object} options A hash of key/val (path, options) used for population. * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. * @return {Promise} * @api public */ Model.populate = function(docs, paths, callback) { var _this = this; if (callback) { callback = this.$wrapCallback(callback); } // normalized paths var noPromise = paths && !!paths.__noPromise; paths = utils.populate(paths); // data that should persist across subPopulate calls var cache = {}; if (noPromise) { _populate(this, docs, paths, cache, callback); } else { var Promise = PromiseProvider.get(); return new Promise.ES6(function(resolve, reject) { _populate(_this, docs, paths, cache, function(error, docs) { if (error) { callback && callback(error); reject(error); } else { callback && callback(null, docs); resolve(docs); } }); }); } }; /*! * Populate helper * * @param {Model} model the model to use * @param {Document|Array} docs Either a single document or array of documents to populate. * @param {Object} paths * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. * @return {Function} * @api private */ function _populate(model, docs, paths, cache, callback) { var pending = paths.length; if (pending === 0) { return callback(null, docs); } // each path has its own query options and must be executed separately var i = pending; var path; while (i--) { path = paths[i]; populate(model, docs, path, next); } function next(err) { if (err) { return callback(err); } if (--pending) { return; } callback(null, docs); } } /*! * Populates `docs` */ var excludeIdReg = /\s?-_id\s?/, excludeIdRegGlobal = /\s?-_id\s?/g; function populate(model, docs, options, callback) { var modelsMap; // normalize single / multiple docs passed if (!Array.isArray(docs)) { docs = [docs]; } if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) { return callback(); } modelsMap = getModelsMapForPopulate(model, docs, options); var i, len = modelsMap.length, mod, match, select, vals = []; function flatten(item) { // no need to include undefined values in our query return undefined !== item; } var _remaining = len; var hasOne = false; for (i = 0; i < len; i++) { mod = modelsMap[i]; select = mod.options.select; if (mod.options.match) { match = utils.object.shallowCopy(mod.options.match); } else { match = {}; } var ids = utils.array.flatten(mod.ids, flatten); ids = utils.array.unique(ids); if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) { --_remaining; continue; } hasOne = true; if (mod.foreignField !== '_id' || !match['_id']) { match[mod.foreignField] = { $in: ids }; } var assignmentOpts = {}; assignmentOpts.sort = mod.options.options && mod.options.options.sort || undefined; assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0); if (assignmentOpts.excludeId) { // override the exclusion from the query so we can use the _id // for document matching during assignment. we'll delete the // _id back off before returning the result. if (typeof select === 'string') { select = select.replace(excludeIdRegGlobal, ' '); } else { // preserve original select conditions by copying select = utils.object.shallowCopy(select); delete select._id; } } if (mod.options.options && mod.options.options.limit) { assignmentOpts.originalLimit = mod.options.options.limit; mod.options.options.limit = mod.options.options.limit * ids.length; } var subPopulate = mod.options.populate; var query = mod.Model.find(match, select, mod.options.options); if (subPopulate) { query.populate(subPopulate); } query.exec(next.bind(this, mod, assignmentOpts)); } if (!hasOne) { return callback(); } function next(options, assignmentOpts, err, valsFromDb) { if (err) return callback(err); vals = vals.concat(valsFromDb); _assign(null, vals, options, assignmentOpts); if (--_remaining === 0) { callback(); } } function _assign(err, vals, mod, assignmentOpts) { if (err) return callback(err); var options = mod.options; var _val; var lean = options.options && options.options.lean, len = vals.length, rawOrder = {}, rawDocs = {}, key, val; // optimization: // record the document positions as returned by // the query result. for (var i = 0; i < len; i++) { val = vals[i]; if (val) { _val = utils.getValue(mod.foreignField, val); if (Array.isArray(_val)) { var _valLength = _val.length; for (var j = 0; j < _valLength; ++j) { if (_val[j] instanceof Document) { _val[j] = _val[j]._id; } key = String(_val[j]); if (rawDocs[key]) { if (Array.isArray(rawDocs[key])) { rawDocs[key].push(val); rawOrder[key].push(i); } else { rawDocs[key] = [rawDocs[key], val]; rawOrder[key] = [rawOrder[key], i]; } } else { rawDocs[key] = val; rawOrder[key] = i; } } } else { if (_val instanceof Document) { _val = _val._id; } key = String(_val); if (rawDocs[key]) { if (Array.isArray(rawDocs[key])) { rawDocs[key].push(val); rawOrder[key].push(i); } else { rawDocs[key] = [rawDocs[key], val]; rawOrder[key] = [rawOrder[key], i]; } } else { rawDocs[key] = val; rawOrder[key] = i; } } // flag each as result of population if (!lean) { val.$__.wasPopulated = true; } } } assignVals({ originalModel: model, rawIds: mod.ids, localField: mod.localField, foreignField: mod.foreignField, rawDocs: rawDocs, rawOrder: rawOrder, docs: mod.docs, path: options.path, options: assignmentOpts, justOne: mod.justOne, isVirtual: mod.isVirtual }); } } /*! * Assigns documents returned from a population query back * to the original document path. */ function assignVals(o) { // replace the original ids in our intermediate _ids structure // with the documents found by query assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, o.options, o.localField, o.foreignField); // now update the original documents being populated using the // result structure that contains real documents. var docs = o.docs; var rawIds = o.rawIds; var options = o.options; function setValue(val) { return valueFilter(val, options); } for (var i = 0; i < docs.length; ++i) { if (utils.getValue(o.path, docs[i]) == null && !o.originalModel.schema.virtuals[o.path]) { continue; } if (o.isVirtual && !o.justOne && !Array.isArray(rawIds[i])) { rawIds[i] = [rawIds[i]]; } utils.setValue(o.path, rawIds[i], docs[i], setValue); } } /*! * Assign `vals` returned by mongo query to the `rawIds` * structure returned from utils.getVals() honoring * query sort order if specified by user. * * This can be optimized. * * Rules: * * if the value of the path is not an array, use findOne rules, else find. * for findOne the results are assigned directly to doc path (including null results). * for find, if user specified sort order, results are assigned directly * else documents are put back in original order of array if found in results * * @param {Array} rawIds * @param {Array} vals * @param {Boolean} sort * @api private */ function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, localFields, foreignFields, recursed) { // honor user specified sort order var newOrder = []; var sorting = options.sort && rawIds.length > 1; var doc; var sid; var id; for (var i = 0; i < rawIds.length; ++i) { id = rawIds[i]; if (Array.isArray(id)) { // handle [ [id0, id2], [id3] ] assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, localFields, foreignFields, true); newOrder.push(id); continue; } if (id === null && !sorting) { // keep nulls for findOne unless sorting, which always // removes them (backward compat) newOrder.push(id); continue; } sid = String(id); if (recursed) { // apply find behavior // assign matching documents in original order unless sorting doc = resultDocs[sid]; if (doc) { if (sorting) { newOrder[resultOrder[sid]] = doc; } else { newOrder.push(doc); } } else { newOrder.push(id); } } else { // apply findOne behavior - if document in results, assign, else assign null newOrder[i] = doc = resultDocs[sid] || null; } } rawIds.length = 0; if (newOrder.length) { // reassign the documents based on corrected order // forEach skips over sparse entries in arrays so we // can safely use this to our advantage dealing with sorted // result sets too. newOrder.forEach(function(doc, i) { if (!doc) { return; } rawIds[i] = doc; }); } } function getModelsMapForPopulate(model, docs, options) { var i, doc, len = docs.length, available = {}, map = [], modelNameFromQuery = options.model && options.model.modelName || options.model, schema, refPath, Model, currentOptions, modelNames, modelName, discriminatorKey, modelForFindSchema; var originalOptions = utils.clone(options); var isVirtual = false; schema = model._getSchema(options.path); if (schema && schema.caster) { schema = schema.caster; } if (!schema && model.discriminators) { discriminatorKey = model.schema.discriminatorMapping.key; } refPath = schema && schema.options && schema.options.refPath; for (i = 0; i < len; i++) { doc = docs[i]; if (refPath) { modelNames = utils.getValue(refPath, doc); if (Array.isArray(modelNames)) { modelNames = modelNames.filter(function(v) { return v != null; }); } } else { if (!modelNameFromQuery) { var modelForCurrentDoc = model; var schemaForCurrentDoc; if (!schema && discriminatorKey) { modelForFindSchema = utils.getValue(discriminatorKey, doc); if (modelForFindSchema) { modelForCurrentDoc = model.db.model(modelForFindSchema); schemaForCurrentDoc = modelForCurrentDoc._getSchema(options.path); if (schemaForCurrentDoc && schemaForCurrentDoc.caster) { schemaForCurrentDoc = schemaForCurrentDoc.caster; } } } else { schemaForCurrentDoc = schema; } var virtual = modelForCurrentDoc.schema.virtuals[options.path]; if (schemaForCurrentDoc && schemaForCurrentDoc.options && schemaForCurrentDoc.options.ref) { modelNames = [schemaForCurrentDoc.options.ref]; } else if (virtual && virtual.options && virtual.options.ref) { modelNames = [virtual && virtual.options && virtual.options.ref]; isVirtual = true; } else { modelNames = [model.modelName]; } } else { modelNames = [modelNameFromQuery]; // query options } } if (!modelNames) { continue; } if (!Array.isArray(modelNames)) { modelNames = [modelNames]; } virtual = model.schema.virtuals[options.path]; var localField = virtual && virtual.options ? virtual.options.localField : options.path; var foreignField = virtual && virtual.options ? virtual.options.foreignField : '_id'; if (!localField || !foreignField) { throw new Error('If you are populating a virtual, you must set the ' + 'localField and foreignField options'); } var justOne = virtual && virtual.options && virtual.options.justOne; if (virtual && virtual.options && virtual.options.ref) { isVirtual = true; } options.isVirtual = isVirtual; var ret = convertTo_id(utils.getValue(localField, doc)); var id = String(utils.getValue(foreignField, doc)); options._docs[id] = Array.isArray(ret) ? ret.slice() : ret; if (doc.$__) { doc.populated(options.path, options._docs[id], options); } var k = modelNames.length; while (k--) { modelName = modelNames[k]; Model = originalOptions.model && originalOptions.model.modelName ? originalOptions.model : model.db.model(modelName); if (!available[modelName]) { currentOptions = { model: Model }; utils.merge(currentOptions, options); if (schema && !discriminatorKey) { currentOptions.model = Model; } options.model = Model; available[modelName] = { Model: Model, options: currentOptions, docs: [doc], ids: [ret], // Assume only 1 localField + foreignField localField: localField, foreignField: foreignField, justOne: justOne, isVirtual: isVirtual }; map.push(available[modelName]); } else { available[modelName].docs.push(doc); available[modelName].ids.push(ret); } } } return map; } /*! * Retrieve the _id of `val` if a Document or Array of Documents. * * @param {Array|Document|Any} val * @return {Array|Document|Any} */ function convertTo_id(val) { if (val instanceof Model) return val._id; if (Array.isArray(val)) { for (var i = 0; i < val.length; ++i) { if (val[i] instanceof Model) { val[i] = val[i]._id; } } if (val.isMongooseArray) { return new MongooseArray(val, val._path, val._parent); } return [].concat(val); } return val; } /*! * 1) Apply backwards compatible find/findOne behavior to sub documents * * find logic: * a) filter out non-documents * b) remove _id from sub docs when user specified * * findOne * a) if no doc found, set to null * b) remove _id from sub docs when user specified * * 2) Remove _ids when specified by users query. * * background: * _ids are left in the query even when user excludes them so * that population mapping can occur. */ function valueFilter(val, assignmentOpts) { if (Array.isArray(val)) { // find logic var ret = []; var numValues = val.length; for (var i = 0; i < numValues; ++i) { var subdoc = val[i]; if (!isDoc(subdoc)) continue; maybeRemoveId(subdoc, assignmentOpts); ret.push(subdoc); if (assignmentOpts.originalLimit && ret.length >= assignmentOpts.originalLimit) { break; } } // Since we don't want to have to create a new mongoosearray, make sure to // modify the array in place while (val.length > ret.length) { Array.prototype.pop.apply(val, []); } for (i = 0; i < ret.length; ++i) { val[i] = ret[i]; } return val; } // findOne if (isDoc(val)) { maybeRemoveId(val, assignmentOpts); return val; } return null; } /*! * Remove _id from `subdoc` if user specified "lean" query option */ function maybeRemoveId(subdoc, assignmentOpts) { if (assignmentOpts.excludeId) { if (typeof subdoc.setValue === 'function') { delete subdoc._doc._id; } else { delete subdoc._id; } } } /*! * Determine if `doc` is a document returned * by a populate query. */ function isDoc(doc) { if (doc == null) { return false; } var type = typeof doc; if (type === 'string') { return false; } if (type === 'number') { return false; } if (Buffer.isBuffer(doc)) { return false; } if (doc.constructor.name === 'ObjectID') { return false; } // only docs return true; } /** * Finds the schema for `path`. This is different than * calling `schema.path` as it also resolves paths with * positional selectors (something.$.another.$.path). * * @param {String} path * @return {Schema} * @api private */ Model._getSchema = function _getSchema(path) { return this.schema._getSchema(path); }; /*! * Compiler utility. * * @param {String} name model name * @param {Schema} schema * @param {String} collectionName * @param {Connection} connection * @param {Mongoose} base mongoose instance */ Model.compile = function compile(name, schema, collectionName, connection, base) { var versioningEnabled = schema.options.versionKey !== false; if (versioningEnabled && !schema.paths[schema.options.versionKey]) { // add versioning to top level documents only var o = {}; o[schema.options.versionKey] = Number; schema.add(o); } // generate new class function model(doc, fields, skipId) { if (!(this instanceof model)) { return new model(doc, fields, skipId); } Model.call(this, doc, fields, skipId); } model.hooks = schema.s.hooks.clone(); model.base = base; model.modelName = name; model.__proto__ = Model; model.prototype.__proto__ = Model.prototype; model.model = Model.prototype.model; model.db = model.prototype.db = connection; model.discriminators = model.prototype.discriminators = undefined; model.prototype.$__setSchema(schema); var collectionOptions = { bufferCommands: schema.options.bufferCommands, capped: schema.options.capped }; model.prototype.collection = connection.collection( collectionName , collectionOptions ); // apply methods and statics applyMethods(model, schema); applyStatics(model, schema); model.schema = model.prototype.schema; model.collection = model.prototype.collection; // Create custom query constructor model.Query = function() { Query.apply(this, arguments); this.options.retainKeyOrder = model.schema.options.retainKeyOrder; }; model.Query.prototype = Object.create(Query.prototype); model.Query.base = Query.base; applyQueryMethods(model, schema.query); var kareemOptions = { useErrorHandlers: true }; model.$__insertMany = model.hooks.createWrapper('insertMany', model.insertMany, model, kareemOptions); model.insertMany = function(arr, callback) { var Promise = PromiseProvider.get(); return new Promise.ES6(function(resolve, reject) { model.$__insertMany(arr, function(error, result) { if (error) { callback && callback(error); return reject(error); } callback && callback(null, result); resolve(result); }); }); }; return model; }; /*! * Register methods for this model * * @param {Model} model * @param {Schema} schema */ var applyMethods = function(model, schema) { function apply(method, schema) { Object.defineProperty(model.prototype, method, { get: function() { var h = {}; for (var k in schema.methods[method]) { h[k] = schema.methods[method][k].bind(this); } return h; }, configurable: true }); } for (var method in schema.methods) { if (schema.tree.hasOwnProperty(method)) { throw new Error('You have a method and a property in your schema both ' + 'named "' + method + '"'); } if (typeof schema.methods[method] === 'function') { model.prototype[method] = schema.methods[method]; } else { apply(method, schema); } } }; /*! * Register statics for this model * @param {Model} model * @param {Schema} schema */ var applyStatics = function(model, schema) { for (var i in schema.statics) { model[i] = schema.statics[i]; } }; /*! * Register custom query methods for this model * * @param {Model} model * @param {Schema} schema */ function applyQueryMethods(model, methods) { for (var i in methods) { model.Query.prototype[i] = methods[i]; } } /*! * Subclass this model with `conn`, `schema`, and `collection` settings. * * @param {Connection} conn * @param {Schema} [schema] * @param {String} [collection] * @return {Model} */ Model.__subclass = function subclass(conn, schema, collection) { // subclass model using this connection and collection name var _this = this; var Model = function Model(doc, fields, skipId) { if (!(this instanceof Model)) { return new Model(doc, fields, skipId); } _this.call(this, doc, fields, skipId); }; Model.__proto__ = _this; Model.prototype.__proto__ = _this.prototype; Model.db = Model.prototype.db = conn; var s = schema && typeof schema !== 'string' ? schema : _this.prototype.schema; var options = s.options || {}; if (!collection) { collection = _this.prototype.schema.get('collection') || utils.toCollectionName(_this.modelName, options); } var collectionOptions = { bufferCommands: s ? options.bufferCommands : true, capped: s && options.capped }; Model.prototype.collection = conn.collection(collection, collectionOptions); Model.collection = Model.prototype.collection; Model.init(); return Model; }; Model.$wrapCallback = function(callback) { var _this = this; return function() { try { callback.apply(null, arguments); } catch (error) { _this.emit('error', error); } }; }; /*! * Module exports. */ module.exports = exports = Model;
mit
iprnq9/give-back
institution_profile.php
5136
<!DOCTYPE html> <html> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/> <meta name="theme-color" content="#2196F3" /> <title>Institution Profile - Give Back</title> <?php include('session.php'); include 'includes.php'; ?> <body> <header> <?php //error_reporting(E_ALL); //ini_set('display_errors', 'On'); //ini_set('html_errors', 'On'); include 'header.php'; ?> </header> <main> <div class="section container"> <div class="row"> <div class="col s12"> <div class="row"> <div class="col s6 offset-s3 l2 profile-picture valign-wrapper"><img src="images/institution_profile.png" class="responsive-img materialboxed valign" data-caption="West Lane Elementary's Profile Picture"/></div> <div class="col s12 l6 profile-details"> <span class="profile-name">West Lane Elementary</span> <span class="profile-sub-name chip"><i class="material-icons">school</i>Jackson R-2 School District</span> <span class="profile-location chip"><i class="material-icons">place</i>Jackson, MO</span> <span class="profile-grade-level chip">Elementary School</span> <span class="profile-skills"> <div class="chip">Programming</div> <div class="chip">Science</div> <div class="chip">Electronics</div> </span> </div> <div class="col s12 l4 profile-score-box hide"> <div class="card-panel light-blue"> Give Back Points <span class="profile-score-points">52</span> </div> </div> </div> <div class="row"> <div class="col s12 l8"> <div class="profile-ideas"> Workshops That Need Hosting <div class="row object-card card"> <div class="topcorner deep-orange lighten-4 grey-text">July 7, 2016</div> <div class="col s12"> <span class="object-title">Raspbery Pi Workshop&nbsp;<span class="object-details">Jackson, MO</span></span> <span class="object-author">Grade Level: Elementary - Middle</span> </div> <div class="col s12 object-description">We know that the Raspberry Pi is getting very popular and is a great tool for learning. We'd love to have a workshop to truly show kids how cool technology is!</div> <div class="col s8 valign-wrapper object-tags"> <div class="chip"><i class="material-icons">code</i>Programming</div> <div class="chip"><i class="material-icons">public</i>Science</div> <div class="chip"><i class="material-icons">memory</i>Electronics</div> </div> <div class="col s4 object-button right-align"> <a class="waves-effect btn-flat white-text deep-orange darken-2" href="workshop.php" target=""><i class="material-icons left">exit_to_app</i>Full Details</a> <a class="waves-effect btn-flat white-text deep-orange darken-2 hide" href="#" target="_blank"><i class="material-icons left">email</i>Contact Ian</a> </div> </div> </div> </div> <div class="col s12 l4"> <div class="profile-history"> Fulfilled <div class="row object-card card"> <div class="col s12"> <div class="col s12"> <span class="object-title">Math Workshop&nbsp;<span class="object-details">Rolla, MO &middot; 4/2/2015</span></span> <span class="object-author">Volunteer: Ian Roberts</span> </div> <div class="col s12 object-button"> <a class="waves-effect btn-flat white-text deep-orange darken-2" href="#" target="_blank"><i class="material-icons left">exit_to_app</i>Full Details</a> </div> </div> </div> </div> </div> </div> </div> </div> </div> </main> <?php include 'footer.php'; ?> <?php include 'bottom-script.php'; ?> </body> </html>
mit
paulcbetts/audio-switcher
src/AudioSwitcher/Presentation/UI/ToolStripExtensions.cs
3097
// ----------------------------------------------------------------------- // Copyright (c) David Kean. // ----------------------------------------------------------------------- using System; using System.Linq; using System.ComponentModel; using System.Windows.Forms; using AudioSwitcher.ComponentModel; using AudioSwitcher.Presentation.CommandModel; namespace AudioSwitcher.Presentation.UI { internal static partial class ToolStripExtensions { public static void RefreshCommands(this ToolStrip strip) { if (strip == null) throw new ArgumentNullException("strip"); // If the strip itself is not visible, don't update the items if (!strip.Visible) return; foreach (ToolStripMenuItem item in strip.Items.OfType<ToolStripMenuItem>()) { item.RefreshCommand(true); } } public static void RefreshCommand(this ToolStripMenuItem item, bool refreshChildren = false) { if (item == null) throw new ArgumentNullException("item"); MenuItemCommandBinding binding = (MenuItemCommandBinding)item.Tag; if (binding != null) binding.Refresh(); if (refreshChildren) { RefreshCommands(item.DropDown); } } public static ToolStripMenuItem BindCommand(this ToolStripDropDown dropDown, CommandManager commandManager, string commandId) { return dropDown.BindCommand(commandManager, commandId, (object)null); } public static ToolStripMenuItem BindCommand(this ToolStripDropDown dropDown, CommandManager commandManager, string commandId, object argument) { Lifetime<ICommand> command = commandManager.FindCommand(commandId); if (command == null) throw new ArgumentException(); return dropDown.BindCommand(command, argument); } private static ToolStripMenuItem BindCommand(this ToolStripDropDown dropDown, Lifetime<ICommand> command, object argument) { ToolStripMenuItem item = dropDown.Add(string.Empty); item.Tag = new MenuItemCommandBinding(dropDown, item, command, argument); return item; } public static ToolStripMenuItem Add(this ToolStripDropDown dropDown, string text) { return (ToolStripMenuItem)dropDown.Items.Add(text); } public static ToolStripMenuItem AddDisabled(this ToolStripDropDown dropDown, string text) { ToolStripMenuItem item = dropDown.Add(text); item.Enabled = false; return item; } public static void AddSeparator(this ToolStripDropDown dropDown) { dropDown.Items.Add("-"); } public static void AddSeparatorIfNeeded(this ToolStripDropDown dropDown) { if (dropDown.Items.Count != 0) dropDown.AddSeparator(); } } }
mit
vikerman/angular
packages/zone.js/test/common/Promise.spec.ts
23653
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {isNode, zoneSymbol} from '../../lib/common/utils'; import {ifEnvSupports} from '../test-util'; declare const global: any; class MicroTaskQueueZoneSpec implements ZoneSpec { name: string = 'MicroTaskQueue'; queue: MicroTask[] = []; properties = {queue: this.queue, flush: this.flush.bind(this)}; flush() { while (this.queue.length) { const task = this.queue.shift(); task !.invoke(); } } onScheduleTask(delegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task): any { this.queue.push(task as MicroTask); } } function flushMicrotasks() { Zone.current.get('flush')(); } class TestRejection { prop1?: string; prop2?: string; } describe( 'Promise', ifEnvSupports('Promise', function() { if (!global.Promise) return; let log: string[]; let queueZone: Zone; let testZone: Zone; let pZone: Zone; beforeEach(() => { testZone = Zone.current.fork({name: 'TestZone'}); pZone = Zone.current.fork({ name: 'promise-zone', onScheduleTask: (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task): any => { log.push('scheduleTask'); parentZoneDelegate.scheduleTask(targetZone, task); } }); queueZone = Zone.current.fork(new MicroTaskQueueZoneSpec()); log = []; }); xit('should allow set es6 Promise after load ZoneAwarePromise', (done) => { const ES6Promise = require('es6-promise').Promise; const NativePromise = global[zoneSymbol('Promise')]; try { global['Promise'] = ES6Promise; Zone.assertZonePatched(); expect(global[zoneSymbol('Promise')]).toBe(ES6Promise); const promise = Promise.resolve(0); console.log('promise', promise); promise .then(value => { expect(value).toBe(0); done(); }) .catch(error => { fail(error); }); } finally { global['Promise'] = NativePromise; Zone.assertZonePatched(); expect(global[zoneSymbol('Promise')]).toBe(NativePromise); } }); it('should pretend to be a native code', () => { expect(String(Promise).indexOf('[native code]') >= 0).toBe(true); }); it('should use native toString for promise instance', () => { expect(Object.prototype.toString.call(Promise.resolve())).toEqual('[object Promise]'); }); it('should make sure that new Promise is instance of Promise', () => { expect(Promise.resolve(123) instanceof Promise).toBe(true); expect(new Promise(() => null) instanceof Promise).toBe(true); }); xit('should ensure that Promise this is instanceof Promise', () => { expect(() => { Promise.call({} as any, () => null); }).toThrowError('Must be an instanceof Promise.'); }); it('should allow subclassing with Promise.specices', () => { class MyPromise extends Promise<any> { constructor(fn: any) { super(fn); } static get[Symbol.species]() { return MyPromise; } } expect(new MyPromise(() => {}).then(() => null) instanceof MyPromise).toBe(true); }); it('Promise.specices should return ZoneAwarePromise', () => { const empty = function() {}; const promise = Promise.resolve(1); const FakePromise = ((promise.constructor = {} as any) as any)[Symbol.species] = function( exec: any) { exec(empty, empty); }; expect(promise.then(empty) instanceof FakePromise).toBe(true); }); it('should intercept scheduling of resolution and then', (done) => { pZone.run(() => { let p: Promise<any> = new Promise(function(resolve, reject) { expect(resolve('RValue')).toBe(undefined); }); expect(log).toEqual([]); expect(p instanceof Promise).toBe(true); p = p.then((v) => { log.push(v); expect(v).toBe('RValue'); expect(log).toEqual(['scheduleTask', 'RValue']); return 'second value'; }); expect(p instanceof Promise).toBe(true); expect(log).toEqual(['scheduleTask']); p = p.then((v) => { log.push(v); expect(log).toEqual(['scheduleTask', 'RValue', 'scheduleTask', 'second value']); done(); }); expect(p instanceof Promise).toBe(true); expect(log).toEqual(['scheduleTask']); }); }); it('should allow sync resolution of promises', () => { queueZone.run(() => { const flush = Zone.current.get('flush'); const queue = Zone.current.get('queue'); const p = new Promise<string>(function(resolve, reject) { resolve('RValue'); }) .then((v: string) => { log.push(v); return 'second value'; }) .then((v: string) => { log.push(v); }); expect(queue.length).toEqual(1); expect(log).toEqual([]); flush(); expect(log).toEqual(['RValue', 'second value']); }); }); it('should allow sync resolution of promises returning promises', () => { queueZone.run(() => { const flush = Zone.current.get('flush'); const queue = Zone.current.get('queue'); const p = new Promise<string>(function(resolve, reject) { resolve(Promise.resolve('RValue')); }) .then((v: string) => { log.push(v); return Promise.resolve('second value'); }) .then((v: string) => { log.push(v); }); expect(queue.length).toEqual(1); expect(log).toEqual([]); flush(); expect(log).toEqual(['RValue', 'second value']); }); }); describe('Promise API', function() { it('should work with .then', function(done) { let resolve: Function|null = null; testZone.run(function() { new Promise(function(resolveFn) { resolve = resolveFn; }).then(function() { expect(Zone.current).toBe(testZone); done(); }); }); resolve !(); }); it('should work with .catch', function(done) { let reject: (() => void)|null = null; testZone.run(function() { new Promise(function(resolveFn, rejectFn) { reject = rejectFn; })['catch'](function() { expect(Zone.current).toBe(testZone); done(); }); }); expect(reject !()).toBe(undefined); }); it('should work with .finally with resolved promise', function(done) { let resolve: Function|null = null; testZone.run(function() { (new Promise(function(resolveFn) { resolve = resolveFn; }) as any).finally(function() { expect(arguments.length).toBe(0); expect(Zone.current).toBe(testZone); done(); }); }); resolve !('value'); }); it('should work with .finally with rejected promise', function(done) { let reject: Function|null = null; testZone.run(function() { (new Promise(function(_, rejectFn) { reject = rejectFn; }) as any).finally(function() { expect(arguments.length).toBe(0); expect(Zone.current).toBe(testZone); done(); }); }); reject !('error'); }); it('should work with Promise.resolve', () => { queueZone.run(() => { let value: any = null; Promise.resolve('resolveValue').then((v) => value = v); expect(Zone.current.get('queue').length).toEqual(1); flushMicrotasks(); expect(value).toEqual('resolveValue'); }); }); it('should work with Promise.reject', () => { queueZone.run(() => { let value: any = null; Promise.reject('rejectReason')['catch']((v) => value = v); expect(Zone.current.get('queue').length).toEqual(1); flushMicrotasks(); expect(value).toEqual('rejectReason'); }); }); describe('reject', () => { it('should reject promise', () => { queueZone.run(() => { let value: any = null; Promise.reject('rejectReason')['catch']((v) => value = v); flushMicrotasks(); expect(value).toEqual('rejectReason'); }); }); it('should re-reject promise', () => { queueZone.run(() => { let value: any = null; Promise.reject('rejectReason')['catch']((v) => { throw v; })['catch']( (v) => value = v); flushMicrotasks(); expect(value).toEqual('rejectReason'); }); }); it('should reject and recover promise', () => { queueZone.run(() => { let value: any = null; Promise.reject('rejectReason')['catch']((v) => v).then((v) => value = v); flushMicrotasks(); expect(value).toEqual('rejectReason'); }); }); it('should reject if chained promise does not catch promise', () => { queueZone.run(() => { let value: any = null; Promise.reject('rejectReason') .then((v) => fail('should not get here')) .then(null, (v) => value = v); flushMicrotasks(); expect(value).toEqual('rejectReason'); }); }); it('should output error to console if ignoreConsoleErrorUncaughtError is false', (done) => { Zone.current.fork({name: 'promise-error'}).run(() => { (Zone as any)[Zone.__symbol__('ignoreConsoleErrorUncaughtError')] = false; const originalConsoleError = console.error; console.error = jasmine.createSpy('consoleErr'); const p = new Promise((resolve, reject) => { throw new Error('promise error'); }); setTimeout(() => { expect(console.error).toHaveBeenCalled(); console.error = originalConsoleError; done(); }, 10); }); }); it('should not output error to console if ignoreConsoleErrorUncaughtError is true', (done) => { Zone.current.fork({name: 'promise-error'}).run(() => { (Zone as any)[Zone.__symbol__('ignoreConsoleErrorUncaughtError')] = true; const originalConsoleError = console.error; console.error = jasmine.createSpy('consoleErr'); const p = new Promise((resolve, reject) => { throw new Error('promise error'); }); setTimeout(() => { expect(console.error).not.toHaveBeenCalled(); console.error = originalConsoleError; (Zone as any)[Zone.__symbol__('ignoreConsoleErrorUncaughtError')] = false; done(); }, 10); }); }); it('should notify Zone.onHandleError if no one catches promise', (done) => { let promiseError: Error|null = null; let zone: Zone|null = null; let task: Task|null = null; let error: Error|null = null; queueZone .fork({ name: 'promise-error', onHandleError: (delegate: ZoneDelegate, current: Zone, target: Zone, error: any): boolean => { promiseError = error; delegate.handleError(target, error); return false; } }) .run(() => { zone = Zone.current; task = Zone.currentTask; error = new Error('rejectedErrorShouldBeHandled'); try { // throw so that the stack trace is captured throw error; } catch (e) { } Promise.reject(error); expect(promiseError).toBe(null); }); setTimeout((): any => null); setTimeout(() => { expect(promiseError !.message) .toBe( 'Uncaught (in promise): ' + error + (error !.stack ? '\n' + error !.stack : '')); expect((promiseError as any)['rejection']).toBe(error); expect((promiseError as any)['zone']).toBe(zone); expect((promiseError as any)['task']).toBe(task); done(); }); }); it('should print readable information when throw a not error object', (done) => { let promiseError: Error|null = null; let zone: Zone|null = null; let task: Task|null = null; let rejectObj: TestRejection; queueZone .fork({ name: 'promise-error', onHandleError: (delegate: ZoneDelegate, current: Zone, target: Zone, error: any): boolean => { promiseError = error; delegate.handleError(target, error); return false; } }) .run(() => { zone = Zone.current; task = Zone.currentTask; rejectObj = new TestRejection(); rejectObj.prop1 = 'value1'; rejectObj.prop2 = 'value2'; Promise.reject(rejectObj); expect(promiseError).toBe(null); }); setTimeout((): any => null); setTimeout(() => { expect(promiseError !.message) .toMatch(/Uncaught \(in promise\):.*: {"prop1":"value1","prop2":"value2"}/); done(); }); }); }); describe('Promise.race', () => { it('should reject the value', () => { queueZone.run(() => { let value: any = null; (Promise as any).race([ Promise.reject('rejection1'), 'v1' ])['catch']((v: any) => value = v); // expect(Zone.current.get('queue').length).toEqual(2); flushMicrotasks(); expect(value).toEqual('rejection1'); }); }); it('should resolve the value', () => { queueZone.run(() => { let value: any = null; (Promise as any) .race([Promise.resolve('resolution'), 'v1']) .then((v: any) => value = v); // expect(Zone.current.get('queue').length).toEqual(2); flushMicrotasks(); expect(value).toEqual('resolution'); }); }); }); describe('Promise.all', () => { it('should reject the value', () => { queueZone.run(() => { let value: any = null; Promise.all([Promise.reject('rejection'), 'v1'])['catch']((v: any) => value = v); // expect(Zone.current.get('queue').length).toEqual(2); flushMicrotasks(); expect(value).toEqual('rejection'); }); }); it('should resolve the value', () => { queueZone.run(() => { let value: any = null; Promise.all([Promise.resolve('resolution'), 'v1']).then((v: any) => value = v); // expect(Zone.current.get('queue').length).toEqual(2); flushMicrotasks(); expect(value).toEqual(['resolution', 'v1']); }); }); it('should resolve with the sync then operation', () => { queueZone.run(() => { let value: any = null; const p1 = {then: function(thenCallback: Function) { return thenCallback('p1'); }}; const p2 = {then: function(thenCallback: Function) { return thenCallback('p2'); }}; Promise.all([p1, 'v1', p2]).then((v: any) => value = v); // expect(Zone.current.get('queue').length).toEqual(2); flushMicrotasks(); expect(value).toEqual(['p1', 'v1', 'p2']); }); }); it('should resolve generators', ifEnvSupports( () => { return isNode; }, () => { const generators: any = function* () { yield Promise.resolve(1); yield Promise.resolve(2); return; }; queueZone.run(() => { let value: any = null; Promise.all(generators()).then(val => { value = val; }); // expect(Zone.current.get('queue').length).toEqual(2); flushMicrotasks(); expect(value).toEqual([1, 2]); }); })); }); }); describe('Promise subclasses', function() { class MyPromise<T> { private _promise: Promise<any>; constructor(init: any) { this._promise = new Promise(init); } catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>)| undefined|null): Promise<T|TResult> { return this._promise.catch.call(this._promise, onrejected); }; then<TResult1 = T, TResult2 = never>( onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>)|undefined|null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>)|undefined| null): Promise<any> { return this._promise.then.call(this._promise, onfulfilled, onrejected); }; } const setPrototypeOf = (Object as any).setPrototypeOf || function(obj: any, proto: any) { obj.__proto__ = proto; return obj; }; setPrototypeOf(MyPromise.prototype, Promise.prototype); it('should reject if the Promise subclass rejects', function() { const myPromise = new MyPromise(function(resolve: any, reject: any): void { reject('foo'); }); return Promise.resolve() .then(function() { return myPromise; }) .then( function() { throw new Error('Unexpected resolution'); }, function(result) { expect(result).toBe('foo'); }); }); function testPromiseSubClass(done?: Function) { const myPromise = new MyPromise(function(resolve: any, reject: Function) { resolve('foo'); }); return Promise.resolve().then(function() { return myPromise; }).then(function(result) { expect(result).toBe('foo'); done && done(); }); } it('should resolve if the Promise subclass resolves', jasmine ? function(done) { testPromiseSubClass(done); } : function() { testPromiseSubClass(); }); }); describe('Promise.allSettled', () => { const yes = function makeFulfilledResult(value: any) { return {status: 'fulfilled', value: value}; }; const no = function makeRejectedResult(reason: any) { return {status: 'rejected', reason: reason}; }; const a = {}; const b = {}; const c = {}; const allSettled = (Promise as any).allSettled; it('no promise values', (done: DoneFn) => { allSettled([a, b, c]).then((results: any[]) => { expect(results).toEqual([yes(a), yes(b), yes(c)]); done(); }); }); it('all fulfilled', (done: DoneFn) => { allSettled([ Promise.resolve(a), Promise.resolve(b), Promise.resolve(c) ]).then((results: any[]) => { expect(results).toEqual([yes(a), yes(b), yes(c)]); done(); }); }); it('all rejected', (done: DoneFn) => { allSettled([ Promise.reject(a), Promise.reject(b), Promise.reject(c) ]).then((results: any[]) => { expect(results).toEqual([no(a), no(b), no(c)]); done(); }); }); it('mixed', (done: DoneFn) => { allSettled([a, Promise.resolve(b), Promise.reject(c)]).then((results: any[]) => { expect(results).toEqual([yes(a), yes(b), no(c)]); done(); }); }); it('mixed should in zone', (done: DoneFn) => { const zone = Zone.current.fork({name: 'settled'}); const bPromise = Promise.resolve(b); const cPromise = Promise.reject(c); zone.run(() => { allSettled([a, bPromise, cPromise]).then((results: any[]) => { expect(results).toEqual([yes(a), yes(b), no(c)]); expect(Zone.current.name).toEqual(zone.name); done(); }); }); }); it('poisoned .then', (done: DoneFn) => { const promise = new Promise(function() {}); promise.then = function() { throw new EvalError(); }; allSettled([promise]).then( () => { fail('should not reach here'); }, (reason: any) => { expect(reason instanceof EvalError).toBe(true); done(); }); }); const Subclass = (function() { try { // eslint-disable-next-line no-new-func return Function( 'class Subclass extends Promise { constructor(...args) { super(...args); this.thenArgs = []; } then(...args) { Subclass.thenArgs.push(args); this.thenArgs.push(args); return super.then(...args); } } Subclass.thenArgs = []; return Subclass;')(); } catch (e) { /**/ } return false; }()); describe('inheritance', () => { it('preserves correct subclass', () => { const promise = allSettled.call(Subclass, [1]); expect(promise instanceof Subclass).toBe(true); expect(promise.constructor).toEqual(Subclass); }); it('invoke the subclass', () => { Subclass.thenArgs.length = 0; const original = Subclass.resolve(); expect(Subclass.thenArgs.length).toBe(0); expect(original.thenArgs.length).toBe(0); allSettled.call(Subclass, [original]); expect(original.thenArgs.length).toBe(1); expect(Subclass.thenArgs.length).toBe(1); }); }); }); }));
mit
boldr/boldr-ui
src/util/TouchRipple.js
3309
/* @flow weak */ /* eslint-disable */ import * as React from 'react'; import ReactDOM from 'react-dom'; import TransitionGroup from 'react-transition-group/TransitionGroup'; import Ripple from './Ripple'; type Props = { className: ?string, style: ?Object, displayCenter: ?boolean, }; export default class TouchRipple extends React.Component<Props, *> { static defaultProps = { className: null, style: null, displayCenter: false, }; constructor(props) { super(props); // $FlowIssue this.ignoreNextMouseDown = false; // $FlowIssue this.nextKey = 0; // $FlowIssue this.timeoutIds = []; this.state = { ripples: [], }; } componentWillUnmount() { this.clearRippleTimeout(); } props: Props; getDiag(a, b) { return Math.sqrt(a * a + b * b); } getOffset(el) { const rect = el.getBoundingClientRect(); return { // $FlowIssue offsetTop: rect.top + document.body.scrollTop, // $FlowIssue offsetLeft: rect.left + document.body.scrollLeft, }; } getRippleStyle = e => { const { displayCenter } = this.props; const el = ReactDOM.findDOMNode(this); const elWidth = el.offsetWidth; const elHeight = el.offsetHeight; let pointerX, pointerY; if (displayCenter) { pointerX = elWidth / 2; pointerY = elHeight / 2; } else { const { offsetTop, offsetLeft } = this.getOffset(el); pointerX = e.pageX - offsetLeft; pointerY = e.pageY - offsetTop; } const rippleRadius = Math.max( this.getDiag(pointerX, pointerY), this.getDiag(elWidth - pointerX, pointerY), this.getDiag(elWidth - pointerX, elHeight - pointerY), this.getDiag(pointerX, elHeight - pointerY), ); const rippleSize = rippleRadius * 2; const left = pointerX - rippleRadius; const top = pointerY - rippleRadius; return { height: rippleSize, width: rippleSize, top, left, }; }; addRipple(e: Event) { if (this.ignoreNextMouseDown) { return; } // $FlowIssue this.ignoreNextMouseDown = true; const { ripples } = this.state; ripples.push(<Ripple key={this.nextKey++} style={this.getRippleStyle(e)} />); this.setState( { ripples, }, () => { // $FlowIssue this.ignoreNextMouseDown = false; }, ); } removeRipple() { this.clearRippleTimeout(); this.setState({ ripples: [], }); } clearRippleTimeout = () => { if (!this.timeoutIds || this.timeoutIds.length < 1) { return; } this.timeoutIds.forEach(item => clearTimeout(item)); this.timeoutIds = []; }; mouseDownHandle = e => { this.timeoutIds[this.nextKey] = setTimeout(() => { this.removeRipple(); }, 1000 / 60); this.addRipple(e); }; mouseUpHandle = () => { this.removeRipple(); }; render() { const { className, style } = this.props; const { ripples } = this.state; return ( <TransitionGroup component="div" className="touch-ripple" style={style} onMouseDown={this.mouseDownHandle} onMouseUp={this.mouseUpHandle} > {ripples && ripples.length > 0 ? ripples : null} </TransitionGroup> ); } }
mit
potherca-contrib/GitVersion
GitVersionCore/AssemblyMetaData.cs
341
namespace GitVersion { public class AssemblyMetaData { public AssemblyMetaData(string version, string fileVersion) { Version = version; FileVersion = fileVersion; } public string Version { get; private set; } public string FileVersion { get; private set; } } }
mit
pcclarke/civ-techs
node_modules/@material-ui/core/esm/Modal/TrapFocus.js
5863
/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex */ import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import warning from 'warning'; import ownerDocument from '../utils/ownerDocument'; import { useForkRef } from '../utils/reactHelpers'; function TrapFocus(props) { var children = props.children, _props$disableAutoFoc = props.disableAutoFocus, disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc, _props$disableEnforce = props.disableEnforceFocus, disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce, _props$disableRestore = props.disableRestoreFocus, disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore, getDoc = props.getDoc, isEnabled = props.isEnabled, open = props.open; var ignoreNextEnforceFocus = React.useRef(); var sentinelStart = React.useRef(null); var sentinelEnd = React.useRef(null); var lastFocus = React.useRef(); var rootRef = React.useRef(null); // can be removed once we drop support for non ref forwarding class components var handleOwnRef = React.useCallback(function (instance) { // #StrictMode ready rootRef.current = ReactDOM.findDOMNode(instance); }, []); var handleRef = useForkRef(children.ref, handleOwnRef); // ⚠️ You may rely on React.useMemo as a performance optimization, not as a semantic guarantee. // https://reactjs.org/docs/hooks-reference.html#usememo React.useMemo(function () { if (!open) { return; } lastFocus.current = getDoc().activeElement; }, [open]); // eslint-disable-line react-hooks/exhaustive-deps React.useEffect(function () { if (!open) { return; } var doc = ownerDocument(rootRef.current); // We might render an empty child. if (!disableAutoFocus && rootRef.current && !rootRef.current.contains(doc.activeElement)) { if (!rootRef.current.hasAttribute('tabIndex')) { process.env.NODE_ENV !== "production" ? warning(false, ['Material-UI: the modal content node does not accept focus.', 'For the benefit of assistive technologies, ' + 'the tabIndex of the node is being set to "-1".'].join('\n')) : void 0; rootRef.current.setAttribute('tabIndex', -1); } rootRef.current.focus(); } var enforceFocus = function enforceFocus() { if (disableEnforceFocus || !isEnabled() || ignoreNextEnforceFocus.current) { ignoreNextEnforceFocus.current = false; return; } if (rootRef.current && !rootRef.current.contains(doc.activeElement)) { rootRef.current.focus(); } }; var loopFocus = function loopFocus(event) { // 9 = Tab if (disableEnforceFocus || !isEnabled() || event.keyCode !== 9) { return; } // Make sure the next tab starts from the right place. if (doc.activeElement === rootRef.current) { // We need to ignore the next enforceFocus as // it will try to move the focus back to the rootRef element. ignoreNextEnforceFocus.current = true; if (event.shiftKey) { sentinelEnd.current.focus(); } else { sentinelStart.current.focus(); } } }; doc.addEventListener('focus', enforceFocus, true); doc.addEventListener('keydown', loopFocus, true); return function () { doc.removeEventListener('focus', enforceFocus, true); doc.removeEventListener('keydown', loopFocus, true); // restoreLastFocus() if (!disableRestoreFocus) { // Not all elements in IE 11 have a focus method. // Because IE 11 market share is low, we accept the restore focus being broken // and we silent the issue. if (lastFocus.current.focus) { lastFocus.current.focus(); } lastFocus.current = null; } }; }, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open]); return React.createElement(React.Fragment, null, React.createElement("div", { tabIndex: 0, ref: sentinelStart, "data-test": "sentinelStart" }), React.cloneElement(children, { ref: handleRef }), React.createElement("div", { tabIndex: 0, ref: sentinelEnd, "data-test": "sentinelEnd" })); } /** * @ignore - internal component. */ process.env.NODE_ENV !== "production" ? TrapFocus.propTypes = { /** * A single child content element. */ children: PropTypes.element.isRequired, /** * If `true`, the modal will not automatically shift focus to itself when it opens, and * replace it to the last focused element when it closes. * This also works correctly with any modal children that have the `disableAutoFocus` prop. * * Generally this should never be set to `true` as it makes the modal less * accessible to assistive technologies, like screen readers. */ disableAutoFocus: PropTypes.bool, /** * If `true`, the modal will not prevent focus from leaving the modal while open. * * Generally this should never be set to `true` as it makes the modal less * accessible to assistive technologies, like screen readers. */ disableEnforceFocus: PropTypes.bool, /** * If `true`, the modal will not restore focus to previously focused element once * modal is hidden. */ disableRestoreFocus: PropTypes.bool, /** * Return the document to consider. * We use it to implement the restore focus between different browser documents. */ getDoc: PropTypes.func.isRequired, /** * Do we still want to enforce the focus? * This property helps nesting TrapFocus elements. */ isEnabled: PropTypes.func.isRequired, /** * If `true`, the modal is open. */ open: PropTypes.bool.isRequired } : void 0; export default TrapFocus;
mit
hisland/hdl-assets
js/misc/req-mod-tmpl/req-mod-tmpl.js
364
/** * */ define(['jquery', 'kissy'], function($, S){ /** * @class * @memberOf sf */ function Compare(){ this.__init().__initEvent(); } /** * @lends sf.Compare# */ S.augment(Compare, { /** * @return this */ __init: function(){ return this; }, /** * @return this */ __initEvent: function(){ return this; } }); });
mit
brain-research/mirage-rl-qprop
rllab/exploration_strategies/base.py
203
class ExplorationStrategy(object): def get_action(self, t, observation, policy, **kwargs): action, _ = policy.get_action(observation) return action def reset(self): pass
mit
IcecaveStudios/pasta-ast
test/suite/ContentBlockTest.php
499
<?php namespace Icecave\Pasta\AST; use PHPUnit_Framework_TestCase; class ContentBlockTest extends PHPUnit_Framework_TestCase { public function setUp() { $this->node = new ContentBlock('<html></html>'); } public function testContent() { $this->assertSame('<html></html>', $this->node->content()); } public function testSetContent() { $this->node->setContent('<xml />'); $this->assertSame('<xml />', $this->node->content()); } }
mit
goppii/GBackup
src/com/gbackup/components/SubjectI.java
175
package com.gbackup.components; public interface SubjectI { void add(ObserverI observer); void notify(String name, int value); void remove(ObserverI observer); }
mit
HAG87/vscode-maxscript
.eslintrc.js
1166
/* 👋 Hi! This file was autogenerated by tslint-to-eslint-config. https://github.com/typescript-eslint/tslint-to-eslint-config It represents the closest reasonable ESLint configuration to this project's original TSLint configuration. We recommend eventually switching this configuration to extend from the recommended rulesets in typescript-eslint. https://github.com/typescript-eslint/tslint-to-eslint-config/blob/master/docs/FAQs.md Happy linting! 💖 */ module.exports = { "env": { "browser": true, "es6": true, "node": true }, "extends": [ "prettier", "prettier/@typescript-eslint" ], "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": 6, "sourceType": "module", "ecmaFeatures": { "jsx": true } }, "plugins": [ "@typescript-eslint" ], "rules": { "@typescript-eslint/indent": [ "error", "tab" ], "@typescript-eslint/member-delimiter-style": [ "error", { "multiline": { "delimiter": "semi", "requireLast": true }, "singleline": { "delimiter": "semi", "requireLast": false } } ], "@typescript-eslint/semi": [ "error", "always" ] } };
mit
WILLYTV/react
cdc-admin/src/componentes/InputCustomizado.js
1090
import React, { Component } from 'react'; import PubSub from 'pubsub-js'; export default class InputCustomizado extends Component{ constructor(){ super(); this.state = {msgErro:''}; } render() { return ( <div className="pure-control-group"> <label htmlFor={this.props.id}>{this.props.label}</label> <input id={this.props.id} type={this.props.type} name={this.props.name} value={this.props.value} onChange={this.props.onChange}/> <span className="error">{this.state.msgErro}</span> </div> ); } componentDidMount() { PubSub.subscribe("erro-validacao",function(topico,erro){ if(erro.field === this.props.name){ this.setState({msgErro:erro.defaultMessage}); } }.bind(this)); PubSub.subscribe("limpa-erros",function(topico){ this.setState({msgErro:''}); }.bind(this)); } }
mit
vkku/cppWorkspace
stringPrograms/subArrGivenSum.cpp
700
#include<iostream> #include<string> #include<stdlib.h> using namespace std; int main() { int num[50], sum = 0, i =0; int flag = 0; cout<<"\nEnter array\n"; for(i = 0 ; i < 5 ; i++) { cout<<"\nElement"<<i+1<<" : "; cin>>num[i]; } cout<<"\nEnter Sum\n"; cin>>sum; int temp = 0; for(i = 0 ; i < 5 ; i++) { int del = 0; temp += num[i]; if(temp > sum) temp -= num[del++]; if(temp == sum) { cout<<"\nSubstring : [ "<<del+1<<": "<<i+1<<" ]"; flag = 1; break; } } if(flag == 0) cout<<"\nNo Substr found\n"; return 0; }
mit
Microsoft/WPF-Samples
Threading/UsingDispatcher/MainWindow.cs
3801
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading; using System.Windows; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Threading; namespace UsingDispatcher { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private Storyboard _hideClockFaceStoryboard; private Storyboard _hideWeatherImageStoryboard; // Storyboards for the animations. private Storyboard _showClockFaceStoryboard; private Storyboard _showWeatherImageStoryboard; public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { // Load the storyboard resources. _showClockFaceStoryboard = (Storyboard) Resources["ShowClockFaceStoryboard"]; _hideClockFaceStoryboard = (Storyboard) Resources["HideClockFaceStoryboard"]; _showWeatherImageStoryboard = (Storyboard) Resources["ShowWeatherImageStoryboard"]; _hideWeatherImageStoryboard = (Storyboard) Resources["HideWeatherImageStoryboard"]; } private void ForecastButtonHandler(object sender, RoutedEventArgs e) { // Change the status image and start the rotation animation. fetchButton.IsEnabled = false; fetchButton.Content = "Contacting Server"; weatherText.Text = ""; _hideWeatherImageStoryboard.Begin(this); // Start fetching the weather forecast asynchronously. var fetcher = new NoArgDelegate( FetchWeatherFromServer); fetcher.BeginInvoke(null, null); } private void FetchWeatherFromServer() { // Simulate the delay from network access. Thread.Sleep(4000); // Tried and true method for weather forecasting - random numbers. var rand = new Random(); string weather; weather = rand.Next(2) == 0 ? "rainy" : "sunny"; // Schedule the update function in the UI thread. tomorrowsWeather.Dispatcher.BeginInvoke( DispatcherPriority.Normal, new OneArgDelegate(UpdateUserInterface), weather); } private void UpdateUserInterface(string weather) { //Set the weather image if (weather == "sunny") { weatherIndicatorImage.Source = (ImageSource) Resources[ "SunnyImageSource"]; } else if (weather == "rainy") { weatherIndicatorImage.Source = (ImageSource) Resources[ "RainingImageSource"]; } //Stop clock animation _showClockFaceStoryboard.Stop(this); _hideClockFaceStoryboard.Begin(this); //Update UI text fetchButton.IsEnabled = true; fetchButton.Content = "Fetch Forecast"; weatherText.Text = weather; } private void HideClockFaceStoryboard_Completed(object sender, EventArgs args) { _showWeatherImageStoryboard.Begin(this); } private void HideWeatherImageStoryboard_Completed(object sender, EventArgs args) { _showClockFaceStoryboard.Begin(this, true); } private delegate void NoArgDelegate(); private delegate void OneArgDelegate(string arg); } }
mit
toni-moreno/snmpcollector
src/core/default-request.options.ts
229
import { BaseRequestOptions } from '@angular/http'; export class DefaultRequestOptions extends BaseRequestOptions { constructor () { super(); this.headers.append('Content-Type', 'application/json'); } }
mit
czim/laravel-cms-models
src/ModelInformation/Data/Form/Layout/ModelFormFieldLabelData.php
1099
<?php namespace Czim\CmsModels\ModelInformation\Data\Form\Layout; use Czim\CmsModels\Support\Enums\LayoutNodeType; /** * Class ModelFormFieldLabelData * * Data container for label in layout. Useful for field group, to add * in-row labels. * * @property string $type * @property string $label * @property string $label_translated * @property string $label_for * @property bool $required */ class ModelFormFieldLabelData extends AbstractModelFormLayoutNodeData { protected $attributes = [ 'type' => LayoutNodeType::LABEL, // Field label (or translation key) to show 'label' => null, 'label_translated' => null, // The ID of the field label 'label_for' => null, // Whether the fields belonging to this are required (affects display only) 'required' => null, // This layout type should not have children 'children' => [], ]; protected $known = [ 'type', 'label', 'label_translated', 'label_for', 'required', 'children', ]; }
mit
FacticiusVir/Warm
Keeper.Warm.Core/Properties/AssemblyInfo.cs
1477
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Keeper.Warm.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Keeper.Warm.Core")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cf73af0b-de7e-4deb-a48b-13368dbf4f4f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Keeper.Warm.Test")]
mit
redkyo017/LaraParse
src/ParseServiceProvider.php
3063
<?php namespace LaraParse; use Illuminate\Support\ServiceProvider; use LaraParse\Auth\ParseUserProvider; use LaraParse\Subclasses\User; use Parse\ParseClient; use LaraParse\Session\ParseSessionStorage; class ParseServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $this->registerConfig(); $this->registerAuthProvider(); $this->registerCustomValidation(); $this->registerSubclasses(); $this->registerRepositoryImplementations(); $this->bootParseClient(); } /** * Register the application services. * * @return void */ public function register() { // Register our user registrar service $this->app->bind( 'Illuminate\Contracts\Auth\Registrar', 'LaraParse\Auth\Registrar' ); // Register our custom commands $this->app['command.parse.subclass.make'] = $this->app->share(function ($app) { return $app->make('LaraParse\Console\SubclassMakeCommand'); }); $this->app['command.parse.repository.make'] = $this->app->share(function ($app) { return $app->make('LaraParse\Console\RepositoryMakeCommand'); }); $this->commands('command.parse.subclass.make', 'command.parse.repository.make'); } private function registerConfig() { $configPath = __DIR__ . '/../config/parse.php'; $this->publishes([$configPath => config_path('parse.php')], 'config'); $this->mergeConfigFrom($configPath, 'parse'); } private function registerAuthProvider() { $this->app['auth']->extend('parse', function () { return new ParseUserProvider; }); } private function registerSubclasses() { $subclasses = $this->app['config']->get('parse.subclasses'); $foundUserSubclass = false; foreach ($subclasses as $subclass) { call_user_func("$subclass::registerSubclass"); if ((new $subclass)->getClassName() == '_User') { $foundUserSubclass = true; } } if (! $foundUserSubclass) { User::registerSubclass(); } } private function registerCustomValidation() { $this->app['validator']->extend('parse_user_unique', 'LaraParse\Validation\Validator@parseUserUnique'); } public function registerRepositoryImplementations() { $repositories = $this->app['config']->get('parse.repositories'); foreach ($repositories as $contract => $implementation) { $this->app->bind($implementation, $contract); } } private function bootParseClient() { $config = $this->app['config']->get('parse'); // Init the parse client ParseClient::initialize($config['app_id'], $config['rest_key'], $config['master_key']); ParseClient::setStorage(new ParseSessionStorage($this->app['session'])); } }
mit
buenadigital/SaaSPro
src/SaaSPro.Web.Management/App_Start/AutoMapperConfig.cs
1140
using AutoMapper; using SaaSPro.Domain; using SaaSPro.Services.ViewModels; using SaaSPro.Web.Common.Scheduling; using SaaSPro.Web.Management.ViewModels; namespace SaaSPro.Web.Management { public class AutoMapperConfig { public static void Register() { Mapper.CreateMap<Plan, PlansListModel.PlanSummary>(); Mapper.CreateMap<Plan, PlansUpdateModel>(); Mapper.CreateMap<Customer, CustomersListModel.CustomerSummary>() .ForMember(model => model.AdminEmail, opt => opt.MapFrom(j => j.AdminUser.Email)); Mapper.CreateMap<Customer, CustomersDetailsModel>(); Mapper.CreateMap<EmailTemplate, EmailTemplateListModel.EmailTemplateSummary>(); Mapper.CreateMap<SchedulerJob, SchedulerUpdateModel>() .ForMember(model => model.RepeatInterval, opt => opt.MapFrom(j => j.RepeatInterval.TotalMinutes)); Mapper.CreateMap<SchedulerJobSummary, SchedulerListModel.JobSummary>(); Mapper.CreateMap<Note, NotesViewModel.Note>(); Mapper.CreateMap<NotesViewModel.Note, Note>(); } } }
mit
fcrespo82/atom-markdown-table-formatter
src/atom.d.ts
1076
export {} declare module 'atom' { interface ConfigValues { 'markdown-table-formatter': { autoSelectEntireDocument: boolean spacePadding: number keepFirstAndLastPipes: boolean formatOnSave: boolean defaultTableJustification: 'Left' | 'Right' | 'Center' markdownGrammarScopes: string[] limitLastColumnPadding: boolean } 'markdown-table-formatter.autoSelectEntireDocument': boolean 'markdown-table-formatter.spacePadding': number 'markdown-table-formatter.keepFirstAndLastPipes': boolean 'markdown-table-formatter.formatOnSave': boolean 'markdown-table-formatter.defaultTableJustification': | 'Left' | 'Right' | 'Center' 'markdown-table-formatter.markdownGrammarScopes': string[] 'markdown-table-formatter.limitLastColumnPadding': boolean } interface Config { get<T extends keyof ConfigValues>( keyPath: T, options?: { sources?: string[] excludeSources?: string[] scope?: string[] | ScopeDescriptor }, ): ConfigValues[T] } }
mit
ronawilliamsoso/eos
eos-parent/eos-service/src/main/java/com/vcg/uc/entity/AddPriceSpy.java
895
package com.vcg.uc.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel public class AddPriceSpy { @ApiModelProperty(value = "手机号") private String mobile; @ApiModelProperty(value = "新用户的时候一定必填") private String name; @ApiModelProperty(value = "时间期限 1:一年 2:一天") private Integer periodType; public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPeriodType() { return periodType; } public void setPeriodType(Integer periodType) { this.periodType = periodType; } }
mit
imdanshraaj/screeenly
resources/views/app/dashboard.blade.php
1472
@extends ('layouts.master') @section('meta_title') Dashboard @stop @section('content') <div class="p2 bg-white border border-black rounded mb2"> <p><b>Hi there! Thanks for using Screeenly.</b></p> You find instructions to use the API in our <a href="https://github.com/stefanzweifel/screeenly/wiki/Use-the-API" target="blank">Wiki on Github</a>. <br>PHP Developer? Checkout <a href="https://github.com/stefanzweifel/ScreeenlyClient">wnx/screeenly-client</a> </div> <h2>API Keys</h2> <p>Screeenly supports multiple API keys. Create and manage your keys here.</p> @if ($apikeys->count() < 25) {!! Form::open(['route' => 'apikeys.store']) !!} @include('app.apikeys._form', ['buttonText' => 'Create key']) {!! Form::close() !!} @else <div class="p2 bg-orange white rounded mb2"> Sorry, but you can only create up to 25 different API keys. </div> @endif @if ($apikeys->count() > 0) @include('app.apikeys._table', ['apikeys' => $apikeys]) <div class="center mt1"> <span class="gray">{{ $apikeys->count() }} / 25 keys</span> </div> @else <div class="flash flash-info"> <p>You dont have any active API keys. Create one now.</p> </div> @endif @stop
mit
CGX-GROUP/DotSpatial
Source/DotSpatial.Controls/LayoutPropertyGrid.cs
3197
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.Windows.Forms; namespace DotSpatial.Controls { /// <summary> /// This is a control that allows users to easilly modify the various aspects of many different layout components /// </summary> // This control will no longer be visible [ToolboxItem(false)] public partial class LayoutPropertyGrid : UserControl { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="LayoutPropertyGrid"/> class. /// </summary> public LayoutPropertyGrid() { InitializeComponent(); } #endregion #region Properties /// <summary> /// Gets or sets the layout control associated with this property grid /// </summary> [Browsable(false)] public LayoutControl LayoutControl { get { return _layoutControl; } set { _layoutControl = value; if (_layoutControl == null) return; _layoutControl.SelectionChanged += LayoutControlSelectionChanged; } } #endregion #region Methods /// <summary> /// If the selection changes this event is called /// </summary> /// <param name="sender">Sender that raised the event.</param> /// <param name="e">The event args.</param> private void LayoutControlSelectionChanged(object sender, EventArgs e) { // This code is so that the property grid gets updates if one of the properties changes foreach (LayoutElement selecteElement in _layoutControl.LayoutElements) selecteElement.Invalidated -= SelecteElementInvalidated; foreach (LayoutElement selecteElement in _layoutControl.SelectedLayoutElements) selecteElement.Invalidated += SelecteElementInvalidated; // If there is no selection get the layoutControls properties otherwise show the selected elements properties _propertyGrid.SelectedObjects = _layoutControl.SelectedLayoutElements.Count > 0 ? _layoutControl.SelectedLayoutElements.ToArray() : null; } private void LayoutPropertyGridKeyUp(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Delete: _layoutControl.DeleteSelected(); break; case Keys.F5: _layoutControl.RefreshElements(); break; } } private void SelecteElementInvalidated(object sender, EventArgs e) { // If there is no selection get the layoutControls properties otherwise show the selected elements properties _propertyGrid.Refresh(); } #endregion } }
mit
dakingha69/readable
frontend/src/index.js
947
import React from 'react' import ReactDOM from 'react-dom' import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import { Provider } from 'react-redux' import { BrowserRouter as Router, Route } from 'react-router-dom' import App from './components/App' import PostDetail from './components/PostDetail' import registerServiceWorker from './registerServiceWorker' import rootReducer from './reducers' import 'semantic-ui-css/semantic.min.css' import './index.css' const store = createStore( rootReducer, applyMiddleware(thunk) ) ReactDOM.render( <Provider store={store}> <Router> <div> <Route exact path='/' component={App} /> <Route exact path='/:category' render={({match}) => (<App match={match} />)} /> <Route path='/:category/:id' component={PostDetail} /> </div> </Router> </Provider>, document.getElementById('root') ) registerServiceWorker()
mit
szymach/talesweaver
src/Domain/ValueObject/Email.php
451
<?php declare(strict_types=1); namespace Talesweaver\Domain\ValueObject; use Assert\Assertion; class Email { /** * @var string */ private $value; public function __construct(string $value) { Assertion::email($value); $this->value = $value; } public function __toString() { return $this->value; } public function getValue(): string { return $this->value; } }
mit
Viktor-s/f
src/Furniture/FactoryBundle/Entity/FactoryContact.php
3787
<?php namespace Furniture\FactoryBundle\Entity; use Sylius\Component\Translation\Model\AbstractTranslatable; use Symfony\Component\Validator\Constraints as Assert; class FactoryContact extends AbstractTranslatable { /** * @var int */ private $id; /** * @var Factory */ private $factory; /** * @var \Doctrine\Common\Collections\Collection|FactoryContactTranslation[] * * @Assert\Valid() */ protected $translations; /** * The department name (Example: Selva s.p.a., W.W.T.S. Italia srl) * @var string * * @Assert\NotBlank() * @Assert\Length(max=255) */ private $departmentName; /** * @var string * * @Assert\Length(max=255) */ private $address; /** * @var array */ private $emails = []; /** * @var array */ private $phones = []; /** * @var array */ private $sites = []; /** * * @var int */ private $position; /** * Construct */ public function __construct() { parent::__construct(); } /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Get factory * * @return Factory */ public function getFactory() { return $this->factory; } /** * Get factory * * @param Factory $factory * * @return FactoryContact */ public function setFactory($factory) { $this->factory = $factory; return $this; } /** * Get department name * * @return string */ public function getDepartmentName() { return $this->departmentName; } /** * Set department name * * @param string $departmentName * * @return FactoryContact */ public function setDepartmentName($departmentName) { $this->departmentName = $departmentName; } /** * Get address * * @return string */ public function getAddress() { return $this->address; } /** * Set address * * @param string $address * * @return FactoryContact */ public function setAddress($address) { $this->address = $address; return $this; } /** * Get emails * * @return array */ public function getEmails() { return $this->emails; } /** * Set emails * * @param array $emails * * @return FactoryContact */ public function setEmails(array $emails) { $this->emails = $emails; return $this; } /** * Get phones * * @return array */ public function getPhones() { return $this->phones; } /** * Set phones * * @param array $phones * * @return FactoryContact */ public function setPhones($phones) { $this->phones = $phones; return $this; } /** * Get sites * * @return array */ public function getSites() { return $this->sites; } /** * Set sites * * @param array $sites * * @return FactoryContact */ public function setSites(array $sites) { $this->sites = $sites; } /** * * @return int */ public function getPosition() { return $this->position; } /** * * @param int $position * @return \Furniture\FactoryBundle\Entity\FactoryContact */ public function setPosition($position) { $this->position = $position; return $this; } }
mit
sehgalvibhor/Whatsapp-ening
flaskr.py
2428
import os import sqlite3 import re import csv from nltk import FreqDist from flask import Flask, request, session, g, redirect, url_for, abort,render_template, flash from werkzeug.utils import secure_filename from flask import send_from_directory app = Flask(__name__) app.config.from_object(__name__) UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['txt']) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def create_csv(filename,data): with open(os.path.join('static/',filename),'wb') as myfile : wr = csv.writer(myfile) wr.writerow(['word','weight']) for i in data : a,b = i wr.writerow([str(a),int(b)]) def cleaner(filename): textfile = open(os.path.join(app.config['UPLOAD_FOLDER'], filename),'r') text = [] all_dates = [] complete_text = [] words_list = [] nodes = [] for line in textfile: datetime,chat = line.split('-') date, time = datetime.split(',') loc = chat.find(':') #if len(chat.split(':'))==3: # print chat user,text = chat[:loc],chat[loc+2:] text = text.replace("\n",'') words = text.split(' ') for i in words: words_list.append(i) complete_text.append(text) nodes.append(user) all_dates.append(date) #print set(nodes) #print set(all_dates) fdist = FreqDist(words_list) f1 = fdist.most_common(100) create_csv('wordcloud.csv',f1) textfile.close() def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit a empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) cleaner(filename) return render_template('dashboard.html') return render_template('index.html')
mit
kangmin2z/dev_ci4
system/View/Parser.php
19564
<?php namespace CodeIgniter\View; /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014-2017 British Columbia Institute of Technology * * 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 CodeIgniter * @author CodeIgniter Dev Team * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) * @license https://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 3.0.0 * @filesource */ use CodeIgniter\Log\Logger; /** * Class Parser * * ClassFormerlyKnownAsTemplateParser * * @todo Views\Parser_Test * @tofo Common::parse * @todo user guide * @todo options -> delimiters * * @package CodeIgniter\View */ class Parser extends View { /** * Left delimiter character for pseudo vars * * @var string */ public $leftDelimiter = '{'; /** * Right delimiter character for pseudo vars * * @var string */ public $rightDelimiter = '}'; /** * Stores extracted noparse blocks. * * @var array */ protected $noparseBlocks = []; /** * Stores any plugins registered at run-time. * @var array */ protected $plugins = []; //-------------------------------------------------------------------- /** * Constructor * * @param \Config\View $config * @param string $viewPath * @param mixed $loader * @param bool $debug * @param Logger $logger */ public function __construct($config, string $viewPath = null, $loader = null, bool $debug = null, Logger $logger = null) { // Ensure user plugins override core plugins. $this->plugins = $config->plugins ?? []; parent::__construct($config, $viewPath, $loader, $debug, $logger); } //-------------------------------------------------------------------- /** * Parse a template * * Parses pseudo-variables contained in the specified template view, * replacing them with any data that has already been set. * * @param string $view * @param array $options * @param bool $saveData * * @return string */ public function render(string $view, array $options = null, $saveData = null): string { $start = microtime(true); if (is_null($saveData)) { $saveData = $this->config->saveData; } $view = str_replace('.php', '', $view) . '.php'; // Was it cached? if (isset($options['cache'])) { $cacheName = $options['cache_name'] ?: str_replace('.php', '', $view); if ($output = cache($cacheName)) { $this->logPerformance($start, microtime(true), $view); return $output; } } $file = $this->viewPath . $view; if ( ! file_exists($file)) { $file = $this->loader->locateFile($view, 'Views'); } // locateFile will return an empty string if the file cannot be found. if (empty($file)) { throw new \InvalidArgumentException('View file not found: ' . $file); } $template = file_get_contents($file); $output = $this->parse($template, $this->data, $options); $this->logPerformance($start, microtime(true), $view); if ( ! $saveData) { $this->data = []; } // Should we cache? if (isset($options['cache'])) { cache()->save($cacheName, $output, (int) $options['cache']); } return $output; } //-------------------------------------------------------------------- /** * Parse a String * * Parses pseudo-variables contained in the specified string, * replacing them with any data that has already been set. * * @param string $template * @param array $options * @param bool $saveData * * @return string */ public function renderString(string $template, array $options = null, $saveData = null): string { $start = microtime(true); if (is_null($saveData)) { $saveData = $this->config->saveData; } $output = $this->parse($template, $this->data, $options); $this->logPerformance($start, microtime(true), $this->excerpt($template)); if ( ! $saveData) { $this->data = []; } return $output; } //-------------------------------------------------------------------- /** * Parse a template * * Parses pseudo-variables contained in the specified template, * replacing them with the data in the second param * * @param string $template * @param array $data * @param array $options Future options * @return string */ protected function parse(string $template, array $data = [], array $options = null): string { if ($template === '') { return ''; } // Remove any possible PHP tags since we don't support it // and parseConditionals needs it clean anyway... $template = str_replace(['<?', '?>'], ['&lt;?', '?&gt;'], $template); $template = $this->parseComments($template); $template = $this->extractNoparse($template); // Replace any conditional code here so we don't have to parse as much $template = $this->parseConditionals($template); // Handle any plugins before normal data, so that // it can potentially modify any template between its tags. $template = $this->parsePlugins($template); // loop over the data variables, replacing // the content as we go. foreach ($data as $key => $val) { $escape = true; if (is_array($val)) { $escape = false; $replace = $this->parsePair($key, $val, $template); } else { $replace = $this->parseSingle($key, (string) $val); } foreach ($replace as $pattern => $content) { $template = $this->replaceSingle($pattern, $content, $template, $escape); } } $template = $this->insertNoparse($template); return $template; } //-------------------------------------------------------------------- protected function is_assoc($arr) { return array_keys($arr) !== range(0, count($arr) - 1); } //-------------------------------------------------------------------- function strpos_all($haystack, $needle) { $offset = 0; $allpos = []; while (($pos = strpos($haystack, $needle, $offset)) !== FALSE) { $offset = $pos + 1; $allpos[] = $pos; } return $allpos; } //-------------------------------------------------------------------- /** * Parse a single key/value, extracting it * * @param string $key * @param string $val * @return array */ protected function parseSingle(string $key, string $val): array { $pattern = '#' . $this->leftDelimiter . '!?\s*' . preg_quote($key) . '\s*\|*\s*([|a-zA-Z0-9<>=\(\),:_\-\s\+]+)*\s*!?' . $this->rightDelimiter . '#ms'; return [$pattern => (string) $val]; } //-------------------------------------------------------------------- /** * Parse a tag pair * * Parses tag pairs: {some_tag} string... {/some_tag} * * @param string $variable * @param array $data * @param string $template * @return array */ protected function parsePair(string $variable, array $data, string $template): array { // Holds the replacement patterns and contents // that will be used within a preg_replace in parse() $replace = []; // Find all matches of space-flexible versions of {tag}{/tag} so we // have something to loop over. preg_match_all( '#' . $this->leftDelimiter . '\s*' . preg_quote($variable) . '\s*' . $this->rightDelimiter . '(.+?)' . $this->leftDelimiter . '\s*' . '/' . preg_quote($variable) . '\s*' . $this->rightDelimiter . '#s', $template, $matches, PREG_SET_ORDER ); /* * Each match looks like: * * $match[0] {tag}...{/tag} * $match[1] Contents inside the tag */ foreach ($matches as $match) { // Loop over each piece of $data, replacing // it's contents so that we know what to replace in parse() $str = ''; // holds the new contents for this tag pair. foreach ($data as $row) { $temp = []; $out = $match[1]; foreach ($row as $key => $val) { // For nested data, send us back through this method... if (is_array($val)) { $pair = $this->parsePair($key, $val, $match[1]); if ( ! empty($pair)) { $temp = array_merge($temp, $pair); } continue; } else if (is_object($val)) { $val = 'Class: ' . get_class($val); } else if (is_resource($val)) { $val = 'Resource'; } $temp['#' . $this->leftDelimiter . '!?\s*' . preg_quote($key) . '\s*\|*\s*([|\w<>=\(\),:_\-\s\+]+)*\s*!?' . $this->rightDelimiter . '#s'] = $val; } // Now replace our placeholders with the new content. foreach ($temp as $pattern => $content) { $out = $this->replaceSingle($pattern, $content, $out, true); } $str .= $out; } $replace['#' . $match[0] . '#s'] = $str; } return $replace; } //-------------------------------------------------------------------- /** * Removes any comments from the file. Comments are wrapped in {# #} symbols: * * {# This is a comment #} * * @param string $template * * @return string */ protected function parseComments(string $template): string { return preg_replace('/\{#.*?#\}/s', '', $template); } //-------------------------------------------------------------------- /** * Extracts noparse blocks, inserting a hash in its place so that * those blocks of the page are not touched by parsing. * * @param string $template * * @return string */ protected function extractNoparse(string $template): string { $pattern = '/\{\s*noparse\s*\}(.*?)\{\s*\/noparse\s*\}/ms'; /* * $matches[][0] is the raw match * $matches[][1] is the contents */ if (preg_match_all($pattern, $template, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { // Create a hash of the contents to insert in its place. $hash = md5($match[1]); $this->noparseBlocks[$hash] = $match[1]; $template = str_replace($match[0], "noparse_{$hash}", $template); } } return $template; } //-------------------------------------------------------------------- /** * Re-inserts the noparsed contents back into the template. * * @param string $template * * @return string */ public function insertNoparse(string $template): string { foreach ($this->noparseBlocks as $hash => $replace) { $template = str_replace("noparse_{$hash}", $replace, $template); unset($this->noparseBlocks[$hash]); } return $template; } //-------------------------------------------------------------------- /** * Parses any conditionals in the code, removing blocks that don't * pass so we don't try to parse it later. * * Valid conditionals: * - if * - elseif * - else * * @param string $template * * @return string */ protected function parseConditionals(string $template): string { $pattern = '/\{\s*(if|elseif)\s*((?:\()?(.*?)(?:\))?)\s*\}/ms'; /** * For each match: * [0] = raw match `{if var}` * [1] = conditional `if` * [2] = condition `do === true` * [3] = same as [2] */ preg_match_all($pattern, $template, $matches, PREG_SET_ORDER); foreach ($matches as $match) { // Build the string to replace the `if` statement with. $condition = $match[2]; $statement = $match[1] == 'elseif' ? '<?php elseif ($' . $condition . '): ?>' : '<?php if ($' . $condition . '): ?>'; $template = str_replace($match[0], $statement, $template); } $template = preg_replace('/\{\s*else\s*\}/ms', '<?php else: ?>', $template); $template = preg_replace('/\{\s*endif\s*\}/ms', '<?php endif; ?>', $template); // Parse the PHP itself, or insert an error so they can debug ob_start(); extract($this->data); $result = eval('?>' . $template . '<?php '); if ($result === false) { $output = 'You have a syntax error in your Parser tags: '; throw new \RuntimeException($output . str_replace(['?>', '<?php '], '', $template)); } return ob_get_clean(); } //-------------------------------------------------------------------- /** * Over-ride the substitution field delimiters. * * @param string $leftDelimiter * @param string $rightDelimiter * @return RendererInterface */ public function setDelimiters($leftDelimiter = '{', $rightDelimiter = '}'): RendererInterface { $this->leftDelimiter = $leftDelimiter; $this->rightDelimiter = $rightDelimiter; return $this; } //-------------------------------------------------------------------- /** * Handles replacing a pseudo-variable with the actual content. Will double-check * for escaping brackets. * * @param $pattern * @param $content * @param $template * @param bool $escape * * @return string */ protected function replaceSingle($pattern, $content, $template, bool $escape = false): string { // Any dollar signs in the pattern will be mis-interpreted, so slash them $pattern = addcslashes($pattern, '$'); // Replace the content in the template $template = preg_replace_callback($pattern, function ($matches) use ($content, $escape) { // Check for {! !} syntax to not-escape this one. if (substr($matches[0], 0, 2) == '{!' && substr($matches[0], -2) == '!}') { $escape = false; } return $this->prepareReplacement($matches, $content, $escape); }, $template); return $template; } //-------------------------------------------------------------------- /** * Callback used during parse() to apply any filters to the value. * * @param array $matches * @param string $replace * * @return mixed|string */ protected function prepareReplacement(array $matches, string $replace, bool $escape = true) { $orig = array_shift($matches); // Our regex earlier will leave all chained values on a single line // so we need to break them apart so we can apply them all. $filters = isset($matches[0]) ? explode('|', $matches[0]) : []; if ($escape && ( ! isset($matches[0]) || $this->shouldAddEscaping($orig))) { $filters[] = 'esc(html)'; } $replace = $this->applyFilters($replace, $filters); return $replace; } //-------------------------------------------------------------------- /** * Checks the placeholder the view provided to see if we need to provide any autoescaping. * * @param string $key * * @return bool */ public function shouldAddEscaping(string $key) { $escape = false; // No pipes, then we know we need to escape if (strpos($key, '|') === false) { $escape = true; } // If there's a `noescape` then we're definitely false. elseif (strpos($key, 'noescape') !== false) { $escape = false; } // If no `esc` filter is found, then we'll need to add one. elseif ( ! preg_match('/^|\s+esc/', $key)) { $escape = true; } return $escape; } //-------------------------------------------------------------------- /** * Given a set of filters, will apply each of the filters in turn * to $replace, and return the modified string. * * @param string $replace * @param array $filters * * @return string */ protected function applyFilters(string $replace, array $filters): string { // Determine the requested filters foreach ($filters as $filter) { // Grab any parameter we might need to send preg_match('/\([a-zA-Z0-9\-:_ +,<>=]+\)/', $filter, $param); // Remove the () and spaces to we have just the parameter left $param = ! empty($param) ? trim($param[0], '() ') : null; // Params can be separated by commas to allow multiple parameters for the filter if ( ! empty($param)) { $param = explode(',', $param); // Clean it up foreach ($param as &$p) { $p = trim($p, ' "'); } } else { $param = []; } // Get our filter name $filter = ! empty($param) ? trim(strtolower(substr($filter, 0, strpos($filter, '(')))) : trim($filter); if ( ! array_key_exists($filter, $this->config->filters)) continue; // Filter it.... $replace = call_user_func($this->config->filters[$filter], $replace, ...$param); } return $replace; } //-------------------------------------------------------------------- // Plugins //-------------------------------------------------------------------- /** * Scans the template for any parser plugins, and attempts to execute them. * Plugins are notated based on {+ +} opening and closing braces. * * When encountered, * * @param string $template * * @return string */ protected function parsePlugins(string $template) { foreach ($this->plugins as $plugin => $callable) { // Paired tags are enclosed in an array in the config array. $isPair = is_array($callable); $callable = $isPair ? array_shift($callable) : $callable; $pattern = $isPair ? '#{\+\s*' . $plugin . '([\w\d=-_:\+\s()\"@.]*)?\s*\+}(.+?){\+\s*/' . $plugin . '\s*\+}#ims' : '#{\+\s*' . $plugin . '([\w\d=-_:\+\s()\"@.]*)?\s*\+}#ims'; /** * Match tag pairs * * Each match is an array: * $matches[0] = entire matched string * $matches[1] = all parameters string in opening tag * $matches[2] = content between the tags to send to the plugin. */ preg_match_all($pattern, $template, $matches, PREG_SET_ORDER); if (empty($matches)) { continue; } foreach ($matches as $match) { $params = []; // Split on "words", but keep quoted groups together, accounting for escaped quotes. // Note: requires double quotes, not single quotes. $parts = str_getcsv($match[1], ' '); foreach ($parts as $part) { if (empty($part)) continue; if (strpos($part, '=') !== false) { list($a, $b) = explode('=', $part); $params[$a] = $b; } else { $params[] = $part; } } unset($parts); $template = $isPair ? str_replace($match[0], $callable($match[2], $params), $template) : str_replace($match[0], $callable($params), $template); } } return $template; } /** * Makes a new plugin available during the parsing of the template. * * @param string $alias * @param callable $callback * * @param bool $isPair * * @return $this */ public function addPlugin(string $alias, callable $callback, bool $isPair = false) { $this->plugins[$alias] = $isPair ? [$callback] : $callback; return $this; } //-------------------------------------------------------------------- /** * Removes a plugin from the available plugins. * * @param string $alias * * @return $this */ public function removePlugin(string $alias) { unset($this->plugins[$alias]); return $this; } //-------------------------------------------------------------------- }
mit
fweber1/Annies-Ancestors
webtrees/app/Census/CensusColumnBirthPlaceSimple.php
1297
<?php /** * webtrees: online genealogy * Copyright (C) 2016 webtrees development team * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace Fisharebest\Webtrees\Census; use Fisharebest\Webtrees\Individual; /** * The individual's birth place. */ class CensusColumnBirthPlaceSimple extends CensusColumnBirthPlace implements CensusColumnInterface { /** * Generate the likely value of this census column, based on available information. * * @param Individual $individual * @param Individual|null $head * * @return string */ public function generate(Individual $individual, Individual $head = null) { return $this->lastPartOfPlace(parent::generate($individual, $head)); } }
mit
caioariede/pyq
sizzle/match.py
3323
from .selector import Selector class MatchEngine(object): pseudo_fns = {} selector_class = Selector def __init__(self): self.register_pseudo('not', self.pseudo_not) self.register_pseudo('has', self.pseudo_has) def register_pseudo(self, name, fn): self.pseudo_fns[name] = fn @staticmethod def pseudo_not(matcher, node, value): return not matcher.match_node(matcher.parse_selector(value)[0], node) @staticmethod def pseudo_has(matcher, node, value): for node, body in matcher.iter_data([node]): if body: return any( matcher.match_data(matcher.parse_selector(value)[0], body)) def parse_selector(self, selector): return self.selector_class.parse(selector) def match(self, selector, data): selectors = self.parse_selector(selector) nodeids = {} for selector in selectors: for node in self.match_data(selector, data): nodeid = id(node) if nodeid not in nodeids: nodeids[nodeid] = None yield node def match_data(self, selector, data): for node, body in self._iter_data(data): match = self.match_node(selector, node) if match: next_selector = selector.next_selector if next_selector: if body: for node in self.match_data(next_selector, body): yield node else: yield node if body and not selector.combinator == self.selector_class.CHILD: for node in self.match_data(selector, body): yield node def match_node(self, selector, node): match = all(self.match_rules(selector, node)) if match and selector.attrs: match &= all(self.match_attrs(selector, node)) if match and selector.pseudos: match &= all(self.match_pseudos(selector, node)) return match def match_rules(self, selector, node): if selector.typ: yield self.match_type(selector.typ, node) if selector.id_: yield self.match_id(selector.id_, node) def match_attrs(self, selector, node): for a in selector.attrs: lft, op, rgt = a yield self.match_attr(lft, op, rgt, node) def match_pseudos(self, selector, d): for p in selector.pseudos: name, value = p if name not in self.pseudo_fns: raise Exception('Selector not implemented: {}'.format(name)) yield self.pseudo_fns[name](self, d, value) def _iter_data(self, data): for tupl in self.iter_data(data): if len(tupl) != 2: raise Exception( 'The iter_data method must yield pair tuples containing ' 'the node and its body (empty if not available)') yield tupl def match_type(self, typ, node): raise NotImplementedError def match_id(self, id_, node): raise NotImplementedError def match_attr(self, lft, op, rgt, no): raise NotImplementedError def iter_data(self, data): raise NotImplementedError
mit
andyfurniss4/DynamicsDataSearch
src/DynamicsDataSearch/angularApp/app/dynamics-search/models/dynamics-contact.ts
153
export class DynamicsContact { contactid: string = undefined; fullname: string = undefined; gbp_legacycontactid: string = undefined; }
mit
Mysterypancake1/Source-Fun
js/crawly.js
547
"use strict"; const request = require("request"); const cheerio = require("cheerio"); function isFile(path) { return path.split("/").pop().indexOf(".") !== -1; } function findFiles(dir) { request(dir, function(error, response, body) { if (body) { const $ = cheerio.load(body); $("a").each(function() { const url = $(this).attr("href"); if (url && url !== "../") { if (isFile(url)) { console.log(dir + url); } else { findFiles(dir + url); } } }); } }); } findFiles("http://example.com/");
mit
kaoscript/coverage-istanbul
test/fixtures/compile/unless.decl.js
1022
var __ks_coverage = (function(_export) { return typeof _export.__ks_coverage === 'undefined' ? _export.__ks_coverage = {} : _export.__ks_coverage; })(typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this); if(!__ks_coverage["/fixtures/compile/unless.decl.ks"]) { __ks_coverage["/fixtures/compile/unless.decl.ks"] = {"path":"/fixtures/compile/unless.decl.ks","s":{"1":0,"2":0},"b":{"1":[0,0]},"f":{},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":1,"column":8}},"2":{"start":{"line":3,"column":0},"end":{"line":3,"column":23}}},"branchMap":{"1":{"type":"cond-expr","line":3,"locations":[{"start":{"line":3,"column":8},"end":{"line":3,"column":8}},{"start":{"line":3,"column":8},"end":{"line":3,"column":8}}]}},"fnMap":{}}; }; module.exports = function() { __ks_coverage["/fixtures/compile/unless.decl.ks"].s[1]++; __ks_coverage["/fixtures/compile/unless.decl.ks"].s[2]++; let x = (y === 0) ? null : (__ks_coverage["/fixtures/compile/unless.decl.ks"].b[1][0]++, 1); };
mit
h4ck3r01/libania
app/helpers.php
4778
<?php /** * Global helpers file with misc functions. */ if (!function_exists('gravatar')) { /** * Access the gravatar helper. * * @return \Creativeorange\Gravatar\Gravatar|\Illuminate\Foundation\Application|mixed */ function gravatar() { return app('gravatar'); } } if (!function_exists('to_js')) { /** * Access the javascript helper. */ function to_js($key = null, $default = null) { if (is_null($key)) { return app('tojs'); } if (is_array($key)) { return app('tojs')->put($key); } return app('tojs')->get($key, $default); } } if (!function_exists('meta')) { /** * Access the meta helper. */ function meta() { return app('meta'); } } if (!function_exists('meta_tag')) { /** * Access the meta tags helper. */ function meta_tag($name = null, $content = null, $attributes = []) { return app('meta')->tag($name, $content, $attributes); } } if (!function_exists('meta_property')) { /** * Access the meta tags helper. */ function meta_property($name = null, $content = null, $attributes = []) { return app('meta')->property($name, $content, $attributes); } } if (!function_exists('protection_context')) { /** * @return \NetLicensing\Context */ function protection_context() { return app('netlicensing')->context(); } } if (!function_exists('protection_context_basic_auth')) { /** * @return \NetLicensing\Context */ function protection_context_basic_auth() { return app('netlicensing')->context(\NetLicensing\Context::BASIC_AUTHENTICATION); } } if (!function_exists('protection_context_api_key')) { /** * @return \NetLicensing\Context */ function protection_context_api_key() { return app('netlicensing')->context(\NetLicensing\Context::APIKEY_IDENTIFICATION); } } if (!function_exists('protection_shop_token')) { /** * @param \App\Models\Auth\User\User $user * @param null $successUrl * @param null $cancelUrl * @param null $successUrlTitle * @param null $cancelUrlTitle * @return \App\Models\Protection\ProtectionShopToken */ function protection_shop_token(\App\Models\Auth\User\User $user, $successUrl = null, $cancelUrl = null, $successUrlTitle = null, $cancelUrlTitle = null) { return app('netlicensing')->createShopToken($user, $successUrl, $cancelUrl, $successUrlTitle, $cancelUrlTitle); } } if (!function_exists('protection_validate')) { /** * @param \App\Models\Auth\User\User $user * @return \App\Models\Protection\ProtectionValidation */ function protection_validate(\App\Models\Auth\User\User $user) { return app('netlicensing')->validate($user); } } if (!function_exists('activeMenu')) { function activeMenu(Array $routes, $output = 'active') { foreach ($routes as $route) { if (Request::is(Request::segment(1) . '/' . $route . '/*') || Request::is(Request::segment(1) . '/' . $route) || Request::is($route)) { return $output; } } } } if (!function_exists('blockMenu')) { function blockMenu(Array $routes, $output = 'display: block') { foreach ($routes as $route) { if (Request::is(Request::segment(1) . '/' . $route . '/*') || Request::is(Request::segment(1) . '/' . $route) || Request::is($route)) { return $output; } } } } if (!function_exists('currentMenu')) { function currentMenu(Array $routes, $output = 'current-page') { foreach ($routes as $route) { if (Request::is(Request::segment(1) . '/' . $route . '/*') || Request::is(Request::segment(1) . '/' . $route) || Request::is($route)) { return $output; } } } } if (!function_exists('parseMoney')) { function parseMoney($val) { return number_format($val, 2, ',', '.'); } } if (!function_exists('formatMoney')) { function formatMoney($val) { return str_replace(',', '.', str_replace('.', '', $val)); } } if (!function_exists('capitalizeName')) { function capitalizeName($val) { $exceptions = array("e", "da", "de", "do", "dos", "das", "com", "sem", "no", "na"); $words = explode(' ', $val); $new_val = array(); foreach ($words as $word) { if (!in_array($word, $exceptions)) { $word = ucfirst($word); } array_push($new_val, $word); } $val = join(' ', $new_val); return $val; } }
mit
Jason-lee-c/magical-engine
source/magical-engine/src/renderer/gl/VertexBufferObject.cpp
16049
/****************************************************************************** The MIT License (MIT) Copyright (c) 2014 Jason.lee Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************/ #include "VertexBufferObject.h" NAMESPACE_MAGICAL VertexBufferObject::VertexBufferObject( void ) { /* // init VertexBufferObject* vbo = Renderer::createVertexBufferObject(); vbo->alloc( 4, VertexBufferObject::Combine ); vbo->enable( Shader::Attribute::iVertex, 3, Shader::TFloat, false ); vbo->enable( Shader::Attribute::iColor, 4, Shader::TUbyte, true ); vbo->enable( Shader::Attribute::iTexCoord, 2, Shader::TFloat, false ); vbo->combine(); vbo->commit( data ); vbo->edit(); vbo->vertex3f( 1, 1, 1 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex2f( 0, 1 ); vbo->vertex3f( 1, 1, 1 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex2f( 0, 1 ); vbo->vertex3f( 1, 1, 1 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex2f( 0, 1 ); vbo->vertex3f( 1, 1, 1 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex2f( 0, 1 ); vbo->commit(); // update vbo->clear(); vbo->edit(); vbo->vertex3f( 1, 1, 1 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex2f( 0, 1 ); vbo->vertex3f( 1, 1, 1 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex2f( 0, 1 ); vbo->vertex3f( 1, 1, 1 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex2f( 0, 1 ); vbo->vertex3f( 1, 1, 1 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex2f( 0, 1 ); vbo->commit(); // delete vbo->free(); */ /* VertexBufferObject* vbo = Renderer::createVertexBufferObject(); vbo->alloc( 4, VertexBufferObject::Separate ); vbo->enable( Shader::Attribute::iVertex, 3, Shader::TFloat, false ); vbo->enable( Shader::Attribute::iColor, 4, Shader::TUbyte, true ); vbo->enable( Shader::Attribute::iTexCoord, 2, Shader::TFloat, false ); vbo->bind( Shader::Attribute::iVertex ); vbo->edit(); vbo->vertex3f( 1, 1, 1 ); vbo->vertex3f( 1, 1, 1 ); vbo->vertex3f( 1, 1, 1 ); vbo->vertex3f( 1, 1, 1 ); vbo->commit(); vbo->bind( Shader::Attribute::iColor ); vbo->edit(); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->vertex4ub( 255, 255, 255, 255 ); vbo->commit(); vbo->bind( Shader::Attribute::iTexCoord ); vbo->commit( data ); // update vbo->bind( Shader::Attribute::iVertex ); vbo->disable(); vbo->enable( Shader::Attribute::iVertex, 3, Shader::TFloat, false ); vbo->commit( data ); or vbo->bind( Shader::Attribute::iVertex ); vbo->commit( nullptr ); // delete vbo->free(); */ } VertexBufferObject::~VertexBufferObject( void ) { for( auto& itr : m_vertex_bufs ) { if( itr.second->vbo ) glDeleteBuffers( 1, &itr.second->vbo ); delete itr.second; } if( m_combine_vertex_buf ) { if( m_combine_vertex_buf->vbo ) glDeleteBuffers( 1, &m_combine_vertex_buf->vbo ); delete m_combine_vertex_buf; } } Ptr<VertexBufferObject> VertexBufferObject::create( void ) { VertexBufferObject* ret = new VertexBufferObject(); MAGICAL_ASSERT( ret, "new VertexBufferObject() failed" ); return Ptr<VertexBufferObject>( Ptrctor<VertexBufferObject>( ret ) ); } void VertexBufferObject::alloc( size_t count, int structure ) { MAGICAL_ASSERT( count > 0, "Invalid count!" ); MAGICAL_ASSERT( structure != VertexBufferObject::None, "Invalid structure!" ); switch( m_structure ) { case None: default: m_vertex_count = count; m_structure = structure; break; case Separate: for( auto& itr : m_vertex_bufs ) { if( itr.second->vbo ) glDeleteBuffers( 1, &itr.second->vbo ); delete itr.second; } m_vertex_bufs.clear(); m_bound_vertex_buf = nullptr; break; case Combine: if( m_combine_vertex_buf ) { if( m_combine_vertex_buf->vbo ) glDeleteBuffers( 1, &m_combine_vertex_buf->vbo ); delete m_combine_vertex_buf; } for( auto& itr : m_vertex_bufs ) delete itr.second; m_vertex_bufs.clear(); m_combine_vertex_buf = nullptr; break; } } void VertexBufferObject::enable( unsigned int index, size_t size, int type, bool normalized, void* data, VboUsage usage ) { MAGICAL_ASSERT( m_vertex_count > 0, "Invalid count!" ); MAGICAL_ASSERT( size > 0, "Invalid size!" ); switch( m_structure ) { case Separate: { GLuint vbo = 0; glGenBuffers( 1, &vbo ); glBindBuffer( GL_ARRAY_BUFFER, vbo ); size_t sizeof_type = Shader::sizeof_id( type ); size_t bytesize = sizeof_type * size; size_t total_bytesize = bytesize * m_vertex_count; glBufferData( GL_ARRAY_BUFFER, total_bytesize, data, (GLenum) usage ); VertexBuffer* buf = new VertexBuffer(); buf->vbo = vbo; buf->index = index; buf->usage = usage; buf->size = size; buf->total_size = m_vertex_count * size; buf->bytesize = bytesize; buf->total_bytesize = total_bytesize; buf->type = type; buf->sizeof_type = sizeof_type; buf->normalized = normalized; buf->offset = 0; buf->data = nullptr; buf->cursor = 0; buf->bytecursor = 0; buf->edit = false; buf->finish = data ? true : false; m_vertex_bufs.push_back_unique( std::make_pair( index, buf ) ); m_bound_vertex_buf = buf; } break; case Combine: { MAGICAL_ASSERT( m_combine_vertex_buf == nullptr, "Invalid!" ); MAGICAL_ASSERT( data == nullptr, "Invalid!" ); size_t offset = 0; for( auto& itr : m_vertex_bufs ) { offset += itr.second->bytesize; } size_t sizeof_type = Shader::sizeof_id( type ); size_t bytesize = sizeof_type * size; size_t total_bytesize = bytesize * m_vertex_count; VertexBuffer* buf = new VertexBuffer(); buf->vbo = 0; buf->index = index; buf->usage = usage; buf->size = size; buf->total_size = m_vertex_count * size; buf->bytesize = bytesize; buf->total_bytesize = total_bytesize; buf->type = type; buf->sizeof_type = sizeof_type; buf->normalized = normalized; buf->offset = offset; buf->data = nullptr; buf->cursor = 0; buf->bytecursor = 0; buf->edit = false; buf->finish = false; m_vertex_bufs.push_back_unique( std::make_pair( index, buf ) ); } break; default: MAGICAL_ASSERT( false, "Invalid!" ); break; } } void VertexBufferObject::bind( unsigned int index ) { MAGICAL_ASSERT( m_structure == Separate, "Invalid!" ); auto itr = m_vertex_bufs.find( index ); MAGICAL_ASSERT( itr != m_vertex_bufs.end(), "Invalid bind!" ); m_bound_vertex_buf = itr->second; } void VertexBufferObject::edit( void ) { switch( m_structure ) { case Separate: { MAGICAL_ASSERT( m_bound_vertex_buf, "Invalid bind!" ); MAGICAL_ASSERT( m_bound_vertex_buf->edit == false, "Invalid!" ); glBindBuffer( GL_ARRAY_BUFFER, m_bound_vertex_buf->vbo ); m_bound_vertex_buf->data = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY ); m_bound_vertex_buf->cursor = 0; m_bound_vertex_buf->edit = true; m_bound_vertex_buf->finish = false; } break; case Combine: { MAGICAL_ASSERT( m_combine_vertex_buf, "Invalid bind!" ); MAGICAL_ASSERT( m_combine_vertex_buf->edit == false, "Invalid!" ); glBindBuffer( GL_ARRAY_BUFFER, m_combine_vertex_buf->vbo ); m_combine_vertex_buf->data = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY ); m_combine_vertex_buf->bytecursor = 0; m_combine_vertex_buf->edit = true; m_combine_vertex_buf->finish = false; } break; default: MAGICAL_ASSERT( false, "Invalid!" ); break; } } void VertexBufferObject::commit( void ) { switch( m_structure ) { case Separate: { MAGICAL_ASSERT( m_bound_vertex_buf, "Invalid bind!" ); MAGICAL_ASSERT( m_bound_vertex_buf->edit, "Invalid!" ); MAGICAL_ASSERT( m_bound_vertex_buf->cursor == m_bound_vertex_buf->total_size, "Invalid! not finish" ); glBindBuffer( GL_ARRAY_BUFFER, m_bound_vertex_buf->vbo ); glUnmapBuffer( GL_ARRAY_BUFFER ); m_bound_vertex_buf->data = nullptr; m_bound_vertex_buf->cursor = 0; m_bound_vertex_buf->edit = false; m_bound_vertex_buf->finish = true; } break; case Combine: { MAGICAL_ASSERT( m_combine_vertex_buf, "Invalid bind!" ); MAGICAL_ASSERT( m_combine_vertex_buf->edit, "Invalid!" ); MAGICAL_ASSERT( m_combine_vertex_buf->bytecursor == m_combine_vertex_buf->total_bytesize, "Invalid! not finish" ); glBindBuffer( GL_ARRAY_BUFFER, m_combine_vertex_buf->vbo ); glUnmapBuffer( GL_ARRAY_BUFFER ); m_combine_vertex_buf->data = nullptr; m_combine_vertex_buf->bytecursor = 0; m_combine_vertex_buf->edit = false; m_combine_vertex_buf->finish = true; } break; default: MAGICAL_ASSERT( false, "Invalid!" ); break; } } void VertexBufferObject::commit( void* data ) { switch( m_structure ) { case Separate: { MAGICAL_ASSERT( m_bound_vertex_buf, "Invalid bind!" ); MAGICAL_ASSERT( m_bound_vertex_buf->edit == false, "Invalid!" ); glBindBuffer( GL_ARRAY_BUFFER, m_bound_vertex_buf->vbo ); glBufferSubData( GL_ARRAY_BUFFER, 0, m_bound_vertex_buf->total_bytesize, data ); m_bound_vertex_buf->finish = data ? true : false; } break; case Combine: { MAGICAL_ASSERT( m_combine_vertex_buf, "Invalid bind!" ); MAGICAL_ASSERT( m_combine_vertex_buf->edit == false, "Invalid!" ); glBindBuffer( GL_ARRAY_BUFFER, m_combine_vertex_buf->vbo ); glBufferSubData( GL_ARRAY_BUFFER, 0, m_combine_vertex_buf->total_bytesize, data ); m_combine_vertex_buf->finish = data ? true : false; } break; default: MAGICAL_ASSERT( false, "Invalid!" ); break; } } void VertexBufferObject::disable( void ) { switch( m_structure ) { case Separate: { MAGICAL_ASSERT( m_bound_vertex_buf, "Invalid bind!" ); MAGICAL_ASSERT( m_bound_vertex_buf->edit == false, "Invalid!" ); auto itr = m_vertex_bufs.find( m_bound_vertex_buf->index ); m_vertex_bufs.erase( itr ); glDeleteBuffers( 1, &m_bound_vertex_buf->vbo ); delete m_bound_vertex_buf; m_bound_vertex_buf = nullptr; } break; case Combine: { MAGICAL_ASSERT( m_combine_vertex_buf, "Invalid bind!" ); MAGICAL_ASSERT( m_combine_vertex_buf->edit == false, "Invalid!" ); glDeleteBuffers( 1, &m_combine_vertex_buf->vbo ); delete m_combine_vertex_buf; m_combine_vertex_buf = nullptr; for( auto& itr : m_vertex_bufs ) delete itr.second; m_vertex_bufs.clear(); } break; default: MAGICAL_ASSERT( false, "Invalid!" ); break; } } void VertexBufferObject::clear( void ) { commit( nullptr ); } void VertexBufferObject::combine( void ) { MAGICAL_ASSERT( m_structure == Combine, "Invalid!" ); MAGICAL_ASSERT( m_vertex_bufs.size() > 1, "Invalid! size should > 1" ); MAGICAL_ASSERT( m_combine_vertex_buf == nullptr, "Invalid!" ); GLuint vbo = 0; glGenBuffers( 1, &vbo ); m_combine_vertex_buf = new VertexBuffer(); m_combine_vertex_buf->vbo = vbo; m_combine_vertex_buf->data = nullptr; m_combine_vertex_buf->bytecursor = 0; m_combine_vertex_buf->edit = false; m_combine_vertex_buf->finish = false; m_combine_vertex_buf->usage = m_vertex_bufs[0].second->usage; m_combine_vertex_buf->size = 0; m_combine_vertex_buf->total_size = 0; m_combine_vertex_buf->bytesize = 0; m_combine_vertex_buf->total_bytesize = 0; for( auto& itr : m_vertex_bufs ) { MAGICAL_ASSERT( m_combine_vertex_buf->usage == itr.second->usage, "Invalid! usage are not equal" ); m_combine_vertex_buf->size += itr.second->size; m_combine_vertex_buf->total_size += itr.second->total_size; m_combine_vertex_buf->bytesize += itr.second->bytesize; m_combine_vertex_buf->total_bytesize += itr.second->total_bytesize; } glBindBuffer( GL_ARRAY_BUFFER, vbo ); glBufferData( GL_ARRAY_BUFFER, m_combine_vertex_buf->total_bytesize, nullptr, (GLenum) m_combine_vertex_buf->usage ); } void VertexBufferObject::combine( void* data ) { MAGICAL_ASSERT( m_structure == Combine, "Invalid!" ); MAGICAL_ASSERT( m_vertex_bufs.size() > 1, "Invalid! size should > 1" ); MAGICAL_ASSERT( m_combine_vertex_buf == nullptr, "Invalid!" ); GLuint vbo = 0; glGenBuffers( 1, &vbo ); m_combine_vertex_buf = new VertexBuffer(); m_combine_vertex_buf->vbo = vbo; m_combine_vertex_buf->data = nullptr; m_combine_vertex_buf->bytecursor = 0; m_combine_vertex_buf->edit = false; m_combine_vertex_buf->finish = data ? true : false; m_combine_vertex_buf->usage = m_vertex_bufs[0].second->usage; m_combine_vertex_buf->size = 0; m_combine_vertex_buf->total_size = 0; m_combine_vertex_buf->bytesize = 0; m_combine_vertex_buf->total_bytesize = 0; for( auto& itr : m_vertex_bufs ) { MAGICAL_ASSERT( m_combine_vertex_buf->usage == itr.second->usage, "Invalid! usage are not equal" ); m_combine_vertex_buf->size += itr.second->size; m_combine_vertex_buf->total_size += itr.second->total_size; m_combine_vertex_buf->bytesize += itr.second->bytesize; m_combine_vertex_buf->total_bytesize += itr.second->total_bytesize; } glBindBuffer( GL_ARRAY_BUFFER, vbo ); glBufferData( GL_ARRAY_BUFFER, m_combine_vertex_buf->total_bytesize, data, (GLenum) m_combine_vertex_buf->usage ); } void VertexBufferObject::use( void ) { switch( m_structure ) { case Separate: { MAGICAL_ASSERT( !m_vertex_bufs.empty(), "Invalid! not enable any buffer yet!" ); for( auto& itr : m_vertex_bufs ) { MAGICAL_ASSERT( itr.second->finish, "Invalid! not finish" ); glBindBuffer( GL_ARRAY_BUFFER, itr.second->vbo ); glEnableVertexAttribArray( itr.second->index ); glVertexAttribPointer( (GLuint)itr.second->index, (GLint)itr.second->size, (GLenum)itr.second->type, (GLboolean)itr.second->normalized, 0, 0 ); } } break; case Combine: { MAGICAL_ASSERT( !m_vertex_bufs.empty(), "Invalid! not enable any buffer yet!" ); MAGICAL_ASSERT( m_combine_vertex_buf, "Invalid!" ); MAGICAL_ASSERT( m_combine_vertex_buf->finish, "Invalid! not finish" ); glBindBuffer( GL_ARRAY_BUFFER, m_combine_vertex_buf->vbo ); for( auto& itr : m_vertex_bufs ) { glEnableVertexAttribArray( itr.second->index ); glVertexAttribPointer( (GLuint)itr.second->index, (GLint)itr.second->size, (GLenum)itr.second->type, (GLboolean)itr.second->normalized, (GLsizei)m_combine_vertex_buf->bytesize, (GLvoid*)itr.second->offset ); } } break; default: MAGICAL_ASSERT( false, "Invalid!" ); break; } } void VertexBufferObject::unuse( void ) { switch( m_structure ) { case Separate: { MAGICAL_ASSERT( !m_vertex_bufs.empty(), "Invalid! not enable any buffer yet!" ); for( auto& itr : m_vertex_bufs ) { glDisableVertexAttribArray( itr.second->index ); } } break; case Combine: { MAGICAL_ASSERT( !m_vertex_bufs.empty(), "Invalid! not enable any buffer yet!" ); for( auto& itr : m_vertex_bufs ) { glDisableVertexAttribArray( itr.second->index ); } } break; default: MAGICAL_ASSERT( false, "Invalid!" ); break; } } NAMESPACE_END
mit
david-risney/CrashProcess
CrashProcess/CrashProcess.cpp
963
#include <Windows.h> #include <ProcessThreadsApi.h> #include <iostream> using namespace std; int wmain(const int argc, const WCHAR* argv[]) { if (argc == 2) { const DWORD pid = static_cast<DWORD>(_wtoi(argv[1])); const HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); if (process != NULL) { // Create a thread in the target process with a NULL start address. The new // thread is created and immediately AVs. // Incidentally, it is much easier to use CreateRemoteThread to cause a crash // than it is to actually serve its intended purpose. A sign of possible bad API design. const HANDLE thread = CreateRemoteThread(process, NULL, 0, NULL, NULL, 0, NULL); if (thread == NULL) { wcerr << L"Unable to inject thread because " << GetLastError() << endl; } } else { wcerr << L"Unable to open pid " << pid << L" because " << GetLastError() << endl; } } else { wcerr << L"CrashProcess [pid]" << endl; } }
mit
stellaval/CSharp
ConsoleInputOutput/CirclePerimeterArea/CirclePS.cs
604
//Problem 3. Circle Perimeter and Area //Write a program that reads the radius r of a circle and prints its perimeter and area formatted with 2 digits after the decimal point. using System; class CirclePS { static void Main() { Console.WriteLine("Please enter the radius of the circle:"); double r = double.Parse(Console.ReadLine()); double pi = Math.PI; double perimeter = 2*pi*r; double area = pi*(Math.Pow(r,2)); Console.WriteLine("The perimeter of the circle is {0:0.00} and the area is {1:0.00}",perimeter,area); } }
mit
Koceto/SoftUni
Old Code/Programming Basics/Drawing with loops/Square Frame/Program.cs
698
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Square_Frame { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); string dash = new string('-', 1) + new string(' ', 1); Console.WriteLine("+ {0}+", string.Concat(Enumerable.Repeat(dash, n - 2))); for (int i = 0; i < n - 2; i++) { Console.WriteLine("| {0}|", string.Concat(Enumerable.Repeat(dash, n - 2))); } Console.WriteLine("+ {0}+", string.Concat(Enumerable.Repeat(dash, n - 2))); } } }
mit
Mykees/Blog-Bundle
Entity/User.php
407
<?php namespace Mvc\BlogBundle\Entity; use Doctrine\ORM\Mapping as ORM; use FOS\UserBundle\Model\User as BaseUser; /** * User * * @ORM\Table() * @ORM\Entity */ class User extends BaseUser { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; public function __construct() { parent::__construct(); } }
mit
micahhahn/Hiscross
src/Winterim/Properties/AssemblyInfo.cs
1392
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Winterim")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Winterim")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5722effc-e42e-4d6c-b1e5-c1424fdf8f99")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
cubistcastle/infl-form
javascripts/foundation/jquery.foundation.navigation.js
2062
/*;(function ($, window, undefined) { 'use strict'; $.fn.foundationNavigation = function (options) { var lockNavBar = false; // Windows Phone, sadly, does not register touch events :( if (Modernizr.touch || navigator.userAgent.match(/Windows Phone/i)) { $(document).on('click.fndtn touchstart.fndtn', '.nav-bar a.flyout-toggle', function (e) { e.preventDefault(); var flyout = $(this).siblings('.flyout').first(); if (lockNavBar === false) { $('.nav-bar .flyout').not(flyout).slideUp(500); flyout.slideToggle(500, function () { lockNavBar = false; }); } lockNavBar = true; }); $('.nav-bar>li.has-flyout', this).addClass('is-touch'); } else { $('.nav-bar>li.has-flyout', this).hover(function () { $(this).children('.flyout').show(); }, function () { $(this).children('.flyout').hide(); }); } }; })( jQuery, this );*/ ;(function ($, window, undefined) { 'use strict'; $.fn.foundationNavigation = function (options) { var lockNavBar = false; // Windows Phone, sadly, does not register touch events :( if (Modernizr.touch || navigator.userAgent.match(/Windows Phone/i)) { // changing the standard functionality to increase the size of the touch target to the entire list item $(document).on('click.fndtn touchstart.fndtn', '.nav-bar .has-flyout', function (e) { e.preventDefault(); var flyout = $(this).children('.flyout'); if (lockNavBar === false) { $('.nav-bar .flyout').not(flyout).slideUp(500); flyout.slideToggle(500, function () { lockNavBar = false; }); } lockNavBar = true; }); $('.nav-bar>li.has-flyout', this).addClass('is-touch'); } else { $('.nav-bar>li.has-flyout', this).hoverIntent(function () { $(this).children('.flyout').show(); }, function () { $(this).children('.flyout').hide(); }); } }; })( jQuery, this );
mit
bostrt/gcparse
src/main/java/com/redhat/gcparser/model/space/OldGeneration.java
252
package com.redhat.gcparser.model.space; import com.redhat.gcparser.model.Size; /** * Created by rbost on 6/28/15. */ public class OldGeneration extends SpaceSize { public OldGeneration(Size size) { super(Space.PSOldGen, size); } }
mit
BlueManiac/PoESkillTreeSource
WPFSKillTree/TreeGenerator/ViewModels/AdvancedTabViewModel.cs
28836
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Windows.Data; using System.Windows.Input; using POESKillTree.Localization; using POESKillTree.Model; using POESKillTree.SkillTreeFiles; using POESKillTree.TreeGenerator.Model; using POESKillTree.TreeGenerator.Model.PseudoAttributes; using POESKillTree.TreeGenerator.Settings; using POESKillTree.TreeGenerator.Solver; using POESKillTree.Utils.Converter; namespace POESKillTree.TreeGenerator.ViewModels { // Some aliases to make things clearer without the need of extra classes. using AttributeConstraint = TargetWeightConstraint<string>; using PseudoAttributeConstraint = TargetWeightConstraint<PseudoAttribute>; /// <summary> /// GeneratorTabViewModel that uses user specified constraints based /// on attributes to generate skill trees. /// </summary> public sealed class AdvancedTabViewModel : GeneratorTabViewModel { /// <summary> /// Converts attributes to their groups. Similar to <see cref="GroupStringConverter"/> /// except that it additionally groups attributes in <see cref="PopularAttributes"/> together /// and caches the calculations to a dictionary. /// </summary> private class AttributeToGroupConverter : IValueConverter { private static readonly GroupStringConverter GroupStringConverter = new GroupStringConverter(); private readonly Dictionary<string, string> _attributeToGroupDictionary = new Dictionary<string, string>(); public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return Convert(value.ToString()); } public string Convert(string attrName) { string groupName; if (!_attributeToGroupDictionary.TryGetValue(attrName, out groupName)) { groupName = PopularAttributes.Contains(attrName) ? PopularGroupName : GroupStringConverter.Convert(attrName).GroupName; _attributeToGroupDictionary[attrName] = groupName; } return groupName; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } #region Attribute constants /// <summary> /// Converts attribute strings to their group names. /// </summary> private static readonly AttributeToGroupConverter AttrToGroupConverter = new AttributeToGroupConverter(); private static readonly string PopularGroupName = L10n.Message("Popular"); /// <summary> /// Order in which the attribute groups are shown. /// </summary> private static readonly Dictionary<string, int> AttrGroupOrder = new Dictionary<string, int>() { {PopularGroupName, -1}, // General {L10n.Message("Core Attributes"), 0}, {L10n.Message("General"), 1}, {L10n.Message("Keystone"), 2}, {L10n.Message("Charges"), 3}, // Defense {L10n.Message("Defense"), 4}, {L10n.Message("Block"), 5}, {L10n.Message("Shield"), 6}, // Offense {L10n.Message("Weapon"), 7}, {L10n.Message("Spell"), 8}, {L10n.Message("Critical Strike"), 9}, // Alternate Spell groups {L10n.Message("Aura"), 10}, {L10n.Message("Curse"), 11}, {L10n.Message("Minion"), 12}, {L10n.Message("Trap"), 13}, {L10n.Message("Totem"), 14}, {L10n.Message("Flasks"), 15 }, {L10n.Message("Everything Else"), 16} }; /// <summary> /// List of attributes that should be displayed before others. /// </summary> private static readonly HashSet<string> PopularAttributes = new HashSet<string>() { "+# to Dexterity", "+# to Intelligence", "+# to Strength", "#% increased Movement Speed", "#% increased maximum Life", "#% of Life Regenerated per Second", "#% of Physical Attack Damage Leeched as Mana", "#% increased effect of Auras you Cast", "#% reduced Mana Reserved", "+# to Jewel Socket" }; /// <summary> /// Dictionary of attributes influenced by character level with the ratio per level. /// </summary> private static readonly Dictionary<string, float> AttributesPerLevel = new Dictionary<string, float>() { {"+# to maximum Mana", Constants.ManaPerLevel}, {"+# to maximum Life", Constants.LifePerLevel}, {"+# Accuracy Rating", Constants.AccPerLevel}, {"Evasion Rating: #", Constants.EvasPerLevel} }; /// <summary> /// List of not selectable attributes. /// </summary> private static readonly HashSet<string> AttributeBlackList = new HashSet<string>() { "+# to maximum Mana", "+# to maximum Life", "+# Accuracy Rating", "+# to maximum Energy Shield" }; #endregion /// <summary> /// Gets all values of the WeaponClass Enum. /// </summary> public static IEnumerable<WeaponClass> WeaponClassValues { get { return Enum.GetValues(typeof(WeaponClass)).Cast<WeaponClass>(); } } #region Presentation private readonly HashSet<string> _addedAttributes = new HashSet<string>(); /// <summary> /// The collection of attributes that can be used in AttributeConstraints. /// </summary> private readonly List<string> _attributes; /// <summary> /// Gets the CollectionView to the attribute names the user can use. /// </summary> public ICollectionView AttributesView { get; private set; } /// <summary> /// Gets the collection of AttributeConstraints the user specified. /// </summary> public ObservableCollection<AttributeConstraint> AttributeConstraints { get; private set; } private AttributeConstraint _newAttributeConstraint; /// <summary> /// Gets the AttributeConstraint used for creating new AttributeConstraints by the user. /// </summary> public AttributeConstraint NewAttributeConstraint { get { return _newAttributeConstraint; } private set { SetProperty(ref _newAttributeConstraint, value); } } /// <summary> /// HashSet of PseudoAttributes already added as PseudoAttributeConstraint. /// </summary> private readonly HashSet<PseudoAttribute> _addedPseudoAttributes = new HashSet<PseudoAttribute>(); /// <summary> /// Collection of pseudo attributes that can be used in PseudoAttributeConstraints. /// </summary> private readonly ObservableCollection<PseudoAttribute> _pseudoAttributes = new ObservableCollection<PseudoAttribute>(); /// <summary> /// Gets the CollectionView to the PseudoAttributes the user can use. /// </summary> public ICollectionView PseudoAttributesView { get; private set; } /// <summary> /// Gets the collection of PseudoAttributeConstraints the user specified. /// </summary> public ObservableCollection<PseudoAttributeConstraint> PseudoAttributeConstraints { get; private set; } /// <summary> /// Placeholder for the PseudoAttributeConstraint the user is editing that can be added. /// </summary> private PseudoAttributeConstraint _newPseudoAttributeConstraint; /// <summary> /// Gets the PseudoAttributeConstraint used for creating new ones by the user. /// </summary> public PseudoAttributeConstraint NewPseudoAttributeConstraint { get { return _newPseudoAttributeConstraint; } private set { SetProperty(ref _newPseudoAttributeConstraint, value); } } private const bool TreePlusItemsModeDefaultValue = false; private bool _treePlusItemsMode = TreePlusItemsModeDefaultValue; /// <summary> /// Gets or sets if the Tab should use 'Tree + Items' or 'Tree only' mode. /// (has no effect at the moment) /// </summary> public bool TreePlusItemsMode { get { return _treePlusItemsMode; } set { SetProperty(ref _treePlusItemsMode, value); } } private const WeaponClass WeaponClassDefaultValue = WeaponClass.Unarmed; private WeaponClass _weaponClass = WeaponClassDefaultValue; /// <summary> /// Gets or sets the WeaponClass used for pseudo attribute calculations. /// </summary> public WeaponClass WeaponClass { get { return _weaponClass; } set { SetProperty(ref _weaponClass, value, () => WeaponClassIsTwoHanded = _weaponClass.IsTwoHanded()); } } private bool _weaponClassIsTwoHanded; /// <summary> /// Gets whether the currently selected WeaponClass is a two handed class. /// </summary> public bool WeaponClassIsTwoHanded { get { return _weaponClassIsTwoHanded; } private set { SetProperty(ref _weaponClassIsTwoHanded, value, () => OffHand = _weaponClassIsTwoHanded ? OffHand.TwoHanded : OffHand.Shield); } } private const OffHand OffHandDefaultValue = OffHand.Shield; private OffHand _offHand = OffHandDefaultValue; /// <summary> /// Gets or sets the OffHand used for pseudo attribute calculations. /// </summary> public OffHand OffHand { get { return _offHand; } set { SetProperty(ref _offHand, value); } } private const Tags TagsDefaultValue = Tags.None; private Tags _tags = TagsDefaultValue; /// <summary> /// Gets or sets the Tags used for pseudo attribute calculations. /// </summary> public Tags Tags { get { return _tags; } set { SetProperty(ref _tags, value); } } #endregion #region Commands private RelayCommand _addAttributeConstraintCommand; /// <summary> /// Gets the command to add an AttributeConstraint to the collection. /// </summary> public ICommand AddAttributeConstraintCommand { get { return _addAttributeConstraintCommand ?? (_addAttributeConstraintCommand = new RelayCommand( param => { var newConstraint = (AttributeConstraint)NewAttributeConstraint.Clone(); _addedAttributes.Add(newConstraint.Data); AttributesView.Refresh(); AttributesView.MoveCurrentToFirst(); NewAttributeConstraint.Data = AttributesView.CurrentItem as string; AttributeConstraints.Add(newConstraint); }, param => _addedAttributes.Count < _attributes.Count)); } } private RelayCommand _removeAttributeConstraintCommand; /// <summary> /// Gets the command to remove an AttributeConstraint from the collection. /// </summary> public ICommand RemoveAttributeConstraintCommand { get { return _removeAttributeConstraintCommand ?? (_removeAttributeConstraintCommand = new RelayCommand( param => { var oldConstraint = (AttributeConstraint) param; _addedAttributes.Remove(oldConstraint.Data); AttributesView.Refresh(); NewAttributeConstraint = oldConstraint; AttributeConstraints.Remove(oldConstraint); }, param => param is AttributeConstraint)); } } private RelayCommand _loadAttributesFromTreeCommand; /// <summary> /// Gets the command to load the attributes from the current tree as AttributeConstraints. /// </summary> public ICommand LoadAttributesFromTreeCommand { get { return _loadAttributesFromTreeCommand ?? (_loadAttributesFromTreeCommand = new RelayCommand(param => LoadAttributesFromTree())); } } private RelayCommand _addPseudoConstraintCommand; /// <summary> /// Gets the command to add a PseudoAttributeConstraint to the collection. /// </summary> public ICommand AddPseudoConstraintCommand { get { return _addPseudoConstraintCommand ?? (_addPseudoConstraintCommand = new RelayCommand( param => { var newConstraint = (PseudoAttributeConstraint) NewPseudoAttributeConstraint.Clone(); _addedPseudoAttributes.Add(newConstraint.Data); PseudoAttributesView.Refresh(); PseudoAttributesView.MoveCurrentToFirst(); NewPseudoAttributeConstraint.Data = PseudoAttributesView.CurrentItem as PseudoAttribute; PseudoAttributeConstraints.Add(newConstraint); }, param => _addedPseudoAttributes.Count < _pseudoAttributes.Count)); } } private RelayCommand _removePseudoConstraintCommand; /// <summary> /// Gets the command to remove a PseudoAttributeConstraint from the collection. /// </summary> public ICommand RemovePseudoConstraintCommand { get { return _removePseudoConstraintCommand ?? (_removePseudoConstraintCommand = new RelayCommand( param => { var oldConstraint = (PseudoAttributeConstraint) param; _addedPseudoAttributes.Remove(oldConstraint.Data); PseudoAttributesView.Refresh(); NewPseudoAttributeConstraint = oldConstraint; PseudoAttributeConstraints.Remove(oldConstraint); }, param => param is PseudoAttributeConstraint)); } } private RelayCommand _reloadPseudoAttributesCommand; /// <summary> /// Gets the command to reload the possible PseudoAttributes from the filesystem. /// Removes all user specified PseudoAttributeConstraints. /// </summary> public ICommand ReloadPseudoAttributesCommand { get { return _reloadPseudoAttributesCommand ?? (_reloadPseudoAttributesCommand = new RelayCommand( o => ReloadPseudoAttributes())); } } private RelayCommand _convertAttributeToPseudoConstraintsCommand; /// <summary> /// Gets the command to converts attribute constraints to pseudo attribute constraints where possible. /// </summary> public ICommand ConvertAttributeToPseudoConstraintsCommand { get { return _convertAttributeToPseudoConstraintsCommand ?? (_convertAttributeToPseudoConstraintsCommand = new RelayCommand( param => ConverteAttributeToPseudoAttributeConstraints(), param => AttributeConstraints.Count > 0)); } } #endregion private readonly PseudoAttributeLoader _pseudoAttributeLoader = new PseudoAttributeLoader(); /// <summary> /// Instantiates a new AdvancedTabViewModel. /// </summary> /// <param name="tree">The (not null) SkillTree instance to operate on.</param> public AdvancedTabViewModel(SkillTree tree) : base(tree) { _attributes = CreatePossibleAttributes().ToList(); AttributesView = new ListCollectionView(_attributes) { Filter = item => !_addedAttributes.Contains(item), CustomSort = Comparer<string>.Create((s1, s2) => { // Sort by group as in AttrGroupOrder first and then by name. var groupCompare = AttrGroupOrder[AttrToGroupConverter.Convert(s1)].CompareTo( AttrGroupOrder[AttrToGroupConverter.Convert(s2)]); return groupCompare != 0 ? groupCompare : string.CompareOrdinal(s1, s2); }) }; AttributesView.GroupDescriptions.Add(new PropertyGroupDescription(".", AttrToGroupConverter)); AttributesView.MoveCurrentToFirst(); AttributeConstraints = new ObservableCollection<AttributeConstraint>(); NewAttributeConstraint = new AttributeConstraint(AttributesView.CurrentItem as string); PseudoAttributesView = new ListCollectionView(_pseudoAttributes) { Filter = item => !_addedPseudoAttributes.Contains((PseudoAttribute) item) }; PseudoAttributesView.SortDescriptions.Add(new SortDescription("Group", ListSortDirection.Ascending)); PseudoAttributesView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending)); PseudoAttributesView.GroupDescriptions.Add(new PropertyGroupDescription("Group")); PseudoAttributeConstraints = new ObservableCollection<PseudoAttributeConstraint>(); ReloadPseudoAttributes(); DisplayName = L10n.Message("Advanced"); } public override void Reset() { _addedAttributes.Clear(); AttributeConstraints.Clear(); AttributesView.Refresh(); AttributesView.MoveCurrentToFirst(); NewAttributeConstraint = new AttributeConstraint(AttributesView.CurrentItem as string); _addedPseudoAttributes.Clear(); PseudoAttributeConstraints.Clear(); PseudoAttributesView.Refresh(); PseudoAttributesView.MoveCurrentToFirst(); NewPseudoAttributeConstraint = new PseudoAttributeConstraint(PseudoAttributesView.CurrentItem as PseudoAttribute); TreePlusItemsMode = TreePlusItemsModeDefaultValue; WeaponClass = WeaponClassDefaultValue; OffHand = OffHandDefaultValue; Tags = TagsDefaultValue; } /// <summary> /// Creates possible attributes from the SkillTree nodes. /// Unique and blacklisted attributes are not taken. /// Attributes of ascendancy nodes are ignored. /// Attributes must have at least one '#' in their name (which means they have a value). /// </summary> private static IEnumerable<string> CreatePossibleAttributes() { return from node in SkillTree.Skillnodes.Values where node.ascendancyName == null from attr in SkillTree.ExpandHybridAttributes(node.Attributes) where !AttributeBlackList.Contains(attr.Key) && attr.Key.Contains("#") group attr by attr.Key into attrGroup where attrGroup.Count() > 1 select attrGroup.First().Key; } /// <summary> /// Reloads the possible PseudoAttributes from the filesystem. /// Resets PseudoAttributeConstraints entered by the user. /// </summary> private void ReloadPseudoAttributes() { _addedPseudoAttributes.Clear(); _pseudoAttributes.Clear(); foreach (var pseudo in _pseudoAttributeLoader.LoadPseudoAttributes()) { _pseudoAttributes.Add(pseudo); } PseudoAttributeConstraints.Clear(); PseudoAttributesView.MoveCurrentToFirst(); NewPseudoAttributeConstraint = new PseudoAttributeConstraint(PseudoAttributesView.CurrentItem as PseudoAttribute); } /// <summary> /// Loads the attributes from the current tree as AttributeConstraints /// and Check-tags nodes that have unique attributes. /// </summary> /// <remarks> /// Character class changes after calling this method will not influence the attributes /// (which have the old character class calculated into them) /// </remarks> private void LoadAttributesFromTree() { Tree.UntagAllNodes(); var attributes = new Dictionary<string, float>(); foreach (var node in Tree.SkilledNodes) { var hasUniqueAttribute = false; foreach (var attribute in SkillTree.ExpandHybridAttributes(node.Attributes)) { var attr = attribute.Key; if (_attributes.Contains(attr)) { if (attribute.Value.Count == 0) { continue; } if (attributes.ContainsKey(attr)) { attributes[attr] += attribute.Value[0]; } else { attributes[attr] = attribute.Value[0]; } } else if (!AttributeBlackList.Contains(attr)) { hasUniqueAttribute = true; } } if (hasUniqueAttribute) { Tree.CycleNodeTagForward(node); } } foreach (var attr in CreateInitialAttributes()) { if (attributes.ContainsKey(attr.Key)) { attributes[attr.Key] += attr.Value; } } AttributeConstraints.Clear(); foreach (var attribute in attributes) { AttributeConstraints.Add(new AttributeConstraint(attribute.Key) {TargetValue = attribute.Value}); } } /// <summary> /// Converts attribute constraints to pseudo attribute constraints with the set Tags, WeaponClass, /// OffHand and check-tagged keystones where possible. /// Str, Int and Dex are not removed from the attribute constraint list but still converted. /// </summary> private void ConverteAttributeToPseudoAttributeConstraints() { var keystones = from node in Tree.GetCheckedNodes() where node.Type == NodeType.Keystone select node.Name; var conditionSettings = new ConditionSettings(Tags, OffHand, keystones.ToArray(), WeaponClass); var convertedConstraints = new List<AttributeConstraint>(); foreach (var attributeConstraint in AttributeConstraints) { var attrName = attributeConstraint.Data; // Select the pseudo attributes and the multiplier for attributes which match the given one and evaluate to true. var pseudos = from pseudo in _pseudoAttributes let matches = (from attr in pseudo.Attributes where attr.MatchesAndEvaluates(conditionSettings, attrName) select attr) where matches.Any() select new { PseudoAttribute = pseudo, Multiplier = matches.First().ConversionMultiplier }; // Add attribute target and weight to the pseudo attributes. var converted = false; foreach (var pseudo in pseudos) { var pseudoAttribute = pseudo.PseudoAttribute; converted = true; if (_addedPseudoAttributes.Contains(pseudoAttribute)) { foreach (var pseudoAttributeConstraint in PseudoAttributeConstraints) { if (pseudoAttributeConstraint.Data == pseudoAttribute) { pseudoAttributeConstraint.TargetValue += attributeConstraint.TargetValue * pseudo.Multiplier; } } } else { _addedPseudoAttributes.Add(pseudoAttribute); PseudoAttributeConstraints.Add(new PseudoAttributeConstraint(pseudoAttribute) { TargetValue = attributeConstraint.TargetValue * pseudo.Multiplier }); } } if (converted && attrName != "+# to Intelligence" && attrName != "+# to Dexterity" && attrName != "+# to Strength") { convertedConstraints.Add(attributeConstraint); } } // Update the attribute constraint related collections. foreach (var convertedConstraint in convertedConstraints) { _addedAttributes.Remove(convertedConstraint.Data); AttributeConstraints.Remove(convertedConstraint); } if (convertedConstraints.Count > 0) { AttributesView.Refresh(); NewAttributeConstraint = convertedConstraints[0]; PseudoAttributesView.Refresh(); PseudoAttributesView.MoveCurrentToFirst(); NewPseudoAttributeConstraint.Data = PseudoAttributesView.CurrentItem as PseudoAttribute; } } public override ISolver CreateSolver(SolverSettings settings) { var attributeConstraints = AttributeConstraints.ToDictionary( constraint => constraint.Data, constraint => new Tuple<float, double>(constraint.TargetValue, constraint.Weight / 100.0)); var pseudoConstraints = PseudoAttributeConstraints.ToDictionary( constraint => constraint.Data, constraint => new Tuple<float, double>(constraint.TargetValue, constraint.Weight / 100.0)); return new AdvancedSolver(Tree, new AdvancedSolverSettings(settings, CreateInitialAttributes(), attributeConstraints, pseudoConstraints, WeaponClass, Tags, OffHand)); } /// <summary> /// Creates the attributes the skill tree has with these settings initially /// (without any tree generating done). /// </summary> private Dictionary<string, float> CreateInitialAttributes() { // base attributes: SkillTree.BaseAttributes, SkillTree.CharBaseAttributes var stats = new Dictionary<string, float>(SkillTree.BaseAttributes); foreach (var attr in SkillTree.CharBaseAttributes[Tree.Chartype]) { stats[attr.Key] = attr.Value; } // Level attributes (flat mana, life, evasion and accuracy) are blacklisted, because they are also dependent // on core attributes, which are dependent on the actual tree and are pretty pointless as basic attributes anyway. // For the calculation of pseudo attributes, they need to be included however. foreach (var attr in AttributesPerLevel) { if (stats.ContainsKey(attr.Key)) { stats[attr.Key] += Tree.Level*attr.Value; } else { stats[attr.Key] = Tree.Level*attr.Value; } } if (_treePlusItemsMode) { // TODO add attributes from items (tree+gear mode) } return stats; } } }
mit
briljant/mimir
examples/src/main/java/org/briljantframework/examples/RandomShapeletForestExamples.java
4835
/** * The MIT License (MIT) * * Copyright (c) 2016 Isak Karlsson * * 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. */ /** * This copy of Woodstox XML processor is licensed under the * Apache (Software) License, version 2.0 ("the License"). * See the License for details about distribution rights, and the * specific rights regarding derivate works. * * You may obtain a copy of the License at: * * http://www.apache.org/licenses/ * * A copy is also included in the downloadable source code package * containing Woodstox, in file "ASL2.0", under the same directory * as this file. */ package org.briljantframework.examples; import java.io.FileInputStream; import java.io.IOException; import org.briljantframework.data.dataframe.DataFrame; import org.briljantframework.data.dataframe.DataFrames; import org.briljantframework.data.dataseries.DataSeriesCollection; import org.briljantframework.data.vector.Vector; import org.briljantframework.dataset.io.DatasetReader; import org.briljantframework.dataset.io.Datasets; import org.briljantframework.dataset.io.MatlabDatasetReader; import org.briljantframework.mimir.classification.ClassifierValidator; import org.briljantframework.mimir.classification.EnsembleEvaluator; import org.briljantframework.mimir.classification.RandomShapeletForest; import org.briljantframework.mimir.classification.ShapeletTree; import org.briljantframework.mimir.evaluation.Evaluator; import org.briljantframework.mimir.evaluation.Result; import org.briljantframework.mimir.evaluation.Validator; /** * Created by isak on 11/13/15. */ public class RandomShapeletForestExamples { public static void main(String[] args) throws IOException { // This is a dataset which we load DataFrame data = DataFrames.permuteRecords(Datasets.loadSyntheticControl()); // See: loadDatasetExample() for an example of how to load a dataset // DataFrame data = DataFrames.permuteRecords(loadDatasetExample()); // The first column of the dataset contains the class, so we drop it and then extract it DataFrame x = data.drop(0); Vector y = data.get(0); Validator<RandomShapeletForest> cv = ClassifierValidator.crossValidator(10); cv.add(Evaluator.foldOutput(i -> System.out.printf("Fold: %d\n", i))); cv.add(EnsembleEvaluator.INSTANCE); // Initialize a random shapelet forest configurator; 100 trees RandomShapeletForest.Configurator config = new RandomShapeletForest.Configurator(100); // Use information gain config.setAssessment(ShapeletTree.Learner.Assessment.IG); // The minimum shapelet length is 2.5% of the time series length config.setLowerLength(0.025); config.setUpperLength(1.0); // Sample 10 shapelets at each node config.setMaximumShapelets(10); RandomShapeletForest.Learner forest = config.configure(); // Evaluate the classifier Result result = cv.test(forest, x, y); // Note that precision and recall is not implemented yet System.out.println("Results averaged over 10-fold cross-validation"); DataFrame measures = result.getMeasures(); System.out.println(measures.mean()); } public static DataFrame loadDatasetExample() throws IOException { // Dataset can be found here: http://www.cs.ucr.edu/~eamonn/time_series_data/ String trainFile = "/home/isak/Projects/datasets/dataset/Gun_Point/Gun_Point_TRAIN"; String testFile = "/home/isak/Projects/datasets/dataset/Gun_Point/Gun_Point_TEST"; try (DatasetReader train = new MatlabDatasetReader(new FileInputStream(trainFile)); DatasetReader test = new MatlabDatasetReader(new FileInputStream(testFile))) { DataFrame.Builder dataset = new DataSeriesCollection.Builder(double.class); dataset.readAll(train); dataset.readAll(test); return dataset.build(); } } }
mit
jtpaasch/armyguys
armyguys/aws/iam/policy.py
2140
# -*- coding: utf-8 -*- """Utilities for working with IAM policies.""" import json from os import path from .. import client as boto3client def create(profile, name, contents=None, filepath=None): """Create an IAM policy (from a file). Args: profile A profile to connect to AWS with. name A name to give to the policy. contents The contents of the policy (as a Python dict or list). You must specify this OR a filepath. filepath The path to the policy you want to upload. You must specify this OR a filepath. Returns: The response returned by boto3. """ if filepath: norm_path = path.normpath(filepath) norm_path = norm_path.rstrip(path.sep) with open(norm_path, "rb") as f: data = f.read().decode("utf-8") elif contents: data = json.dumps(contents) client = boto3client.get("iam", profile) params = {} params["PolicyName"] = name params["PolicyDocument"] = data return client.create_policy(**params) def delete(profile, policy): """Delete an IAM policy. Args: profile A profile to connect to AWS with. policy The full ARN of the policy you want to delete. """ client = boto3client.get("iam", profile) params = {} params["PolicyArn"] = policy return client.delete_policy(**params) def get(profile): """Get a list of all IAM policies. Args: profile A profile to connect to AWS with. Returns: The response returned by boto3. """ client = boto3client.get("iam", profile) return client.list_policies() def details(profile, policy): """Get one IAM policy. Args: profile A profile to connect to AWS with. policy The ARN of the policy you want to fetch. Returns: The response returned by boto3. """ client = boto3client.get("iam", profile) params = {} params["PolicyArn"] = policy return client.get_policy(**params)
mit
alexwyett/norfolkbadminton_drupal
nbatheme/templates/html.tpl.php
1404
<?php global $base_path; global $theme; $themePath = $base_path . drupal_get_path('theme', 'nbatheme'); $localThemePath = $base_path . drupal_get_path('theme', $theme); ?><!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><?php echo $head_title; ?></title> <?php echo $head; ?> <?php echo $styles; ?> <?php echo $scripts; ?> <!-- CSS --> <link rel="icon" href="<?php echo $localThemePath; ?>/favicon.ico" type="image/x-icon" /> </head> <body> <?php global $user; if (!empty($tabs) && user_is_logged_in()) { echo sprintf( '<nav class="main-header_tabs">%s</div>', render($tabs) ); } ?> <div class="main-window"> <div class="main-wrapper"> <?php echo $page_top; echo $page; echo $page_bottom; ?> </div> </div> </body> </html>
mit
NetOfficeFw/NetOffice
Source/OWC10/DispatchInterfaces/SchemaRelationship.cs
5497
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.OWC10Api { /// <summary> /// DispatchInterface SchemaRelationship /// SupportByVersion OWC10, 1 /// </summary> [SupportByVersion("OWC10", 1)] [EntityType(EntityType.IsDispatchInterface)] public class SchemaRelationship : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(SchemaRelationship); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public SchemaRelationship(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public SchemaRelationship(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public SchemaRelationship(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public SchemaRelationship(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public SchemaRelationship(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public SchemaRelationship(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public SchemaRelationship() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public SchemaRelationship(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public string Name { get { return Factory.ExecuteStringPropertyGet(this, "Name"); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public string ManySide { get { return Factory.ExecuteStringPropertyGet(this, "ManySide"); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public string OneSide { get { return Factory.ExecuteStringPropertyGet(this, "OneSide"); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.SchemaRelatedFields SchemaRelatedFields { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OWC10Api.SchemaRelatedFields>(this, "SchemaRelatedFields", NetOffice.OWC10Api.SchemaRelatedFields.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public NetOffice.OWC10Api.Enums.DscLocationEnum Location { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.DscLocationEnum>(this, "Location"); } set { Factory.ExecuteEnumPropertySet(this, "Location", value); } } #endregion #region Methods /// <summary> /// SupportByVersion OWC10 1 /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersion("OWC10", 1)] public void Delete() { Factory.ExecuteMethod(this, "Delete"); } #endregion #pragma warning restore } }
mit
kgryte/node-metrics-os
test/test.js
952
// MODULES // var // Expectation library: chai = require( 'chai' ), // Module to be tested: lib = require( './../lib' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'metrics-os', function tests() { 'use strict'; // SETUP // var metrics = lib(); // TESTS // it( 'should export a function', function test() { expect( lib ).to.be.a( 'function' ); }); it( 'should return an object with metrics', function test() { expect( metrics ).to.be.an( 'object' ); }); it( 'should return the CPU load', function test() { expect( metrics.load ).to.be.an( 'object' ); }); it( 'should return the uptime', function test() { expect( metrics.uptime ).to.be.a( 'number' ); }); it( 'should return memory metrics', function test() { expect( metrics.mem ).to.be.an( 'object' ); }); it( 'should return cpu metrics', function test() { expect( metrics.cpu ).to.be.an( 'array' ); }); });
mit
Gnail-nehc/testclient
src/com/testclient/httpmodel/IdValue.java
280
package com.testclient.httpmodel; public class IdValue { int id; String value; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
mit
svens/sal
sal/crypto/hmac.hpp
5914
#pragma once /** * \file sal/crypto/hmac.hpp * Cryptographic HMAC functions */ #include <sal/config.hpp> #include <sal/crypto/hash.hpp> #include <sal/error.hpp> #include <sal/memory.hpp> __sal_begin namespace crypto { /** * Keyed-hash message authentication code * (<a href="https://en.wikipedia.org/wiki/Cryptographic_hash_function">HMAC</a>) * using \a Algorithm. * * Usage of this class is similar to hash_t. */ template <typename Algorithm> class hmac_t { public: /** * Number of bytes in hash digest result. */ static constexpr size_t digest_size = __bits::digest_size_v<Algorithm>; /** * Initialize HMAC object using empty key. */ hmac_t () : hmac_t(nullptr, 0U) {} /** * Initialize HMAC object using key in range [\a first, \a last). */ template <typename It> hmac_t (It first, It last) : hmac_t(to_ptr(first), range_size(first, last)) {} /** * Initialize HMAC object using \a key. */ template <typename Data> hmac_t (const Data &key) : hmac_t(std::cbegin(key), std::cend(key)) {} /** * Create this as copy of \a that */ hmac_t (const hmac_t &that) = default; /** * Copy state of \a that into this, overriding current state. */ hmac_t &operator= (const hmac_t &that) = default; /** * Create this from \a that by moving it's state into this. * It is undefined behaviour to use \a that without re-initializing it * after move. */ hmac_t (hmac_t &&that) = default; /** * Drop current state of this and move state of \a that into this. * It is undefined behaviour to use \a that without re-initializing it * after move. */ hmac_t &operator= (hmac_t &&that) = default; /** * Add region [\a first, \a last) into hasher. */ template <typename It> hmac_t &update (It first, It last) { if (first != last) { update(to_ptr(first), range_size(first, last)); } return *this; } /** * Add more \a data into hasher. */ template <typename Data> hmac_t &update (const Data &data) { using std::cbegin; using std::cend; return update(cbegin(data), cend(data)); } /** * Calculate HMAC of previously added data and store into region starting at * \a first. If size of region [\a first, \a last) is less than * digest_size, throw std::logic_error */ template <typename It> void finish (It first, It last) { auto result_size = range_size(first, last); sal_throw_if(result_size < digest_size); finish(to_ptr(first), result_size); } /** * Calculate HMAC of previously added data and return result as array. */ std::array<uint8_t, digest_size> finish () { std::array<uint8_t, digest_size> result; finish(result.begin(), result.end()); return result; } /** * Calculate HMAC over [\a data_first, \a data_last) without key and write * result into [\a digest_first, \a digest_last). * * \throws std::logic_error if area [\a digest_first, \a digest_last) is * less than digest_size */ template <typename DataIt, typename DigestIt> static void one_shot (DataIt data_first, DataIt data_last, DigestIt digest_first, DigestIt digest_last) { auto result_size = range_size(digest_first, digest_last); sal_throw_if(result_size < digest_size); auto result = to_ptr(digest_first); if (data_first != data_last) { auto data = to_ptr(data_first); auto data_size = range_size(data_first, data_last); one_shot(nullptr, 0, data, data_size, result, result_size); } else { one_shot(nullptr, 0, nullptr, 0, result, result_size); } } /** * Calculate HMAC over [\a data_first, \a data_last) using key in * [\a key_first, \a key_last) and write result into [\a digest_first, * \a digest_last). * * \throws std::logic_error if area [\a digest_first, \a digest_last) is * less than digest_size */ template <typename KeyIt, typename DataIt, typename DigestIt> static void one_shot (KeyIt key_first, KeyIt key_last, DataIt data_first, DataIt data_last, DigestIt digest_first, DigestIt digest_last) { auto result_size = range_size(digest_first, digest_last); sal_throw_if(result_size < digest_size); auto result = to_ptr(digest_first); auto key = to_ptr(key_first); auto key_size = range_size(key_first, key_last); if (data_first != data_last) { auto data = to_ptr(data_first); auto data_size = range_size(data_first, data_last); one_shot(key, key_size, data, data_size, result, result_size); } else { one_shot(key, key_size, nullptr, 0, result, result_size); } } /** * Calculate HMAC over \a data without key and return result as std::array */ template <typename Data> static std::array<uint8_t, digest_size> one_shot (const Data &data) { std::array<uint8_t, digest_size> result; using std::cbegin; using std::cend; one_shot(cbegin(data), cend(data), result.begin(), result.end()); return result; } /** * Calculate HMAC over \a data with \a key and return result as std::array */ template <typename Key, typename Data> static std::array<uint8_t, digest_size> one_shot (const Key &key, const Data &data) { std::array<uint8_t, digest_size> result; using std::cbegin; using std::cend; one_shot( cbegin(key), cend(key), cbegin(data), cend(data), result.begin(), result.end() ); return result; } private: typename Algorithm::hmac_t ctx_; hmac_t (const void *key, size_t size); void update (const void *data, size_t size); void finish (void *digest, size_t size); static void one_shot ( const void *key, size_t key_size, const void *data, size_t data_size, void *digest, size_t digest_length ); }; } // namespace crypto __sal_end
mit
vietjtnguyen/AnimatSim
Gruntfile.js
2316
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-jsdoc'); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), copy: { main: { files: [ { expand: true, cwd: 'src/css', src: '*.css', dest: 'dist/css/' }, { expand: true, cwd: 'src', src: '*.html', dest: 'dist/' } ] } }, // concat: { // options: { // separator: ';' // }, // dist: { // src: ['src/js/.js'], // dest: 'dist/<%= pkg.name %>.js' // } // }, browserify: { dist: { files: {"dist/js/AnimatSim.js": ["src/js/AnimatSim.js"]} } }, uglify: { // options: { // banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n' // }, dist: { files: { 'dist/js/AnimatSim.min.js': ['dist/js/AnimatSim.js'] } } }, jsdoc: { dist: { src: ['src/**/*.js', 'README.md'], options: { destination: './dist/docs' } } }, jshint: { files: ['Gruntfile.js', 'src/js/*.js', 'test/**/*.js'], options: { // options here to override JSHint defaults // globals: { // jQuery: true, // console: true, // module: true, // document: true // } } }, mochaTest: { test: { options: { reporter: 'spec' }, src: ['test/**/*.js'] } }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint', 'mochaTest', 'jsdoc', 'browserify', 'uglify', 'copy'] } }); grunt.registerTask('build', ['browserify', 'uglify']);//, 'concat', 'uglify']); grunt.registerTask('docs', ['jsdoc']); grunt.registerTask('test', ['jshint', 'mochaTest']); grunt.registerTask('default', ['jsdoc', 'jshint', 'mochaTest', 'browserify', 'uglify', 'copy']); // TODO: Add a documentation task. };
mit
zhangqiang110/my4j
pms/src/main/java/com/swfarm/biz/ebay/dao/EbayOrderIndexDao.java
216
package com.swfarm.biz.ebay.dao; import com.swfarm.biz.ebay.bo.EbayOrderIndex; import com.swfarm.pub.framework.dao.GenericDao; public interface EbayOrderIndexDao extends GenericDao<EbayOrderIndex, Long> { }
mit
nickvdyck/gulp-jspm-assets
test/jspm.spec.ts
716
import { Jspm } from '../src/jspm'; describe('jspm facade', () => { beforeEach(() => Jspm.mock()); it('should be possible to swap the jspm implementation', (done: Function) => { Jspm.mock({ normalize: function(msg: string): Promise<string> { return new Promise((resolve: Function, reject: Function) => { resolve(msg); }); } }); let jspm: Jspm = new Jspm(); jspm.normalize('mocked normalize').then((response: string) => { expect(response).to.equal('mocked normalize'); done(); }); }); it('should pass on module loading to node when no mock is provided', () => { let jspm: Jspm = new Jspm(); expect(jspm).to.exist; }); });
mit
BernardTatin/bblog
btat1-libs/src/test/java/com/btat1/sax/SimpleParserTest.java
2130
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.btat1.sax; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.xml.sax.SAXException; /** * * @author bernard */ public class SimpleParserTest { private SAXParser saxParser; public SimpleParserTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { try { saxParser = ParserMaker.getParser(); } catch(Exception e) { saxParser = null; } } @Test public void parserNotNull() { assertTrue(saxParser != null); } @Test public void simpleParserOK() { boolean itsOk = true; try { SimpleParser parser = new SimpleParser(); //TODO : I don't want that absolute path but I can't do anything else !!! parser.parse("/home/bernard/git/bblog/btat1-libs/src/test/java/com/btat1/sax/menu.xml"); } catch(ParserConfigurationException | SAXException | IOException e) { itsOk = false; System.out.println("ERROR : " + e.getMessage()); } assertTrue(itsOk); } @Test public void simpleParserFailure() { boolean itsOk = true; try { SimpleParser parser = new SimpleParser(); parser.parse("nomenu.xml"); } catch(ParserConfigurationException | SAXException | IOException e) { itsOk = false; System.out.println("ERROR : " + e.getMessage()); } assertFalse(itsOk); } @After public void tearDown() { saxParser = null; } }
mit
pegurnee/2013-01-111
complete/src/intro/proj/p1/v3/MainClass.java
1144
package intro.proj.p1.v3; /* It's a game. * All coding provided by Eddie Gurnee * * This class allows the user to decide what mode to play * * version 0.2.14 * */ public class MainClass { public static void main(String [ ] args) { for (int k = 0; k < 5; k++) { // Box that displays a set of choice buttons // create array of options to present in dialog box String[] gameMode = {"Single Player", "Multiplayer", "LAN", "Online", "Quit"}; String modeSelect = "What mode would you like to play?"; int n = CommonChecks.checkOptionsOOC(modeSelect, gameMode); if (n == 0) { SinglePlayer.run(); } else if (n == 1 || n == 2 || n == 3) { CommonChecks.notImplementedOOC(); } else if (n == 4) { System.exit(0); } } CommonChecks.messageOOC("If you're having that much trouble with starting the game, \nyou probably shouldn't even attempt this game."); } }
mit
stevemu/fake-music-album-api
src/server/api/index.js
1465
'use strict'; var express = require('express'); var router = express.Router(); router.get('/music_albums', function(req, res) { const albums = [ { title: 'Abbey Road', artist: 'The Beatles', url: 'https://www.amazon.com/Abbey-Road-Beatles/dp/B01929HGH4/ref=sr_1_2?ie=UTF8&qid=1486479679&sr=8-2&keywords=beatles', image: "https://images-na.ssl-images-amazon.com/images/I/61i4ik3IBjL._SS500_PJStripe-Robin-Large,TopLeft,0,0.jpg", thumbnail_image: 'https://images-na.ssl-images-amazon.com/images/I/61i4ik3IBjL._SS500_PJStripe-Robin-Large,TopLeft,0,0.jpg' }, { title: '1', artist: 'The Beatles', url: 'https://www.amazon.com/1-Beatles/dp/B01929HAK2/ref=sr_1_4?ie=UTF8&qid=1486479679&sr=8-4&keywords=beatles', image: "https://images-na.ssl-images-amazon.com/images/I/31i5mjTO0FL._SS500.jpg", thumbnail_image: 'https://images-na.ssl-images-amazon.com/images/I/31i5mjTO0FL._SS500.jpg' }, { title: 'Rubber Soul', artist: 'The Beatles', url: 'https://www.amazon.com/Rubber-Soul-Beatles/dp/B01929HXIG/ref=sr_1_8?ie=UTF8&qid=1486479679&sr=8-8&keywords=beatles', image: "https://images-na.ssl-images-amazon.com/images/I/61spT89nxEL._SS500_PJStripe-Robin-Large,TopLeft,0,0.jpg", thumbnail_image: 'https://images-na.ssl-images-amazon.com/images/I/61spT89nxEL._SS500_PJStripe-Robin-Large,TopLeft,0,0.jpg' }, ]; res.json(albums); }); module.exports = router;
mit
saulmadi/Encomiendas
src/Encomiendas.Web/app/services/httpq.js
1452
angular.module('Encomiendas.Services').factory('$httpq', function ($http, $q) { return { post: function (resource, payload) { var defer = $q.defer(); $http.post(resource, payload) .success(function (data) { defer.resolve(data); }).error(function (data) { defer.reject(data); }); return defer.promise; }, put: function (resource, payload) { var defer = $q.defer(); $http.put(resource, payload) .success(function (data) { defer.resolve(data); }).error(function (data) { defer.reject(data); }); return defer.promise; }, get: function (resource) { var defer = $q.defer(); $http.get(resource) .success(function (data) { defer.resolve(data); }).error(function (data) { defer.reject(data); }); return defer.promise; }, delete: function (resource) { var defer = $q.defer(); $http.delete(resource) .success(function (data) { defer.resolve(data); }).error(function (data) { defer.reject(data); }); return defer.promise; }, }; });
mit
justhardinal/codeigniter
application/views/news/detail.php
1057
<div class="clearfix"></div> <!-- merapihkan jeda judul "LAtest News --> <style> .kotak-atas { margin-top:40px; } </style> <!-- Latest News --> <section class="kotak-atas"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2><?php echo $berita->judul ?></h2> <hr class="star-light"> <hr> </div> </div> <div class="row"> <div class="col-lg-12"> <p><img src="<?php echo base_url('assets/upload/image/'.$berita->gambar) ?>" class="img img-responsive"></p> <?php echo $berita->isi ?> </div> <hr> <div class="col-lg-12 text-center"> <a href="<?php echo base_url('news')?>" class="btn btn-primary btn-lg"> <i class="fa fa-newspaper-o"></i> See More News.... </a> </div> </div> </div> </section>
mit
sharrinmanor/example_roulette
src/roulette/Bet.java
1057
package roulette; import util.ConsoleReader; /** * Represents player's attempt to bet on outcome of the roulette wheel's spin. * * @author Robert C. Duvall */ abstract class Bet { private String myDescription; private int myOdds; protected String chosenBet = ""; /** * Constructs a bet with the given name and odds. * * @param description name of this kind of bet * @param odds odds given by the house for this kind of bet */ public Bet (String description, int odds) { myDescription = description; myOdds = odds; } /** * @return odds given by the house for this kind of bet */ public int getOdds () { return myOdds; } /** * @return name of this kind of bet */ public String getDescription () { return myDescription; } public void placeBet(){ } public String getChosenBet(){ return chosenBet; } protected boolean betIsMade(Wheel color){ return false; } }
mit
DecipherNow/gm-fabric-dashboard
src/components/Glyphs/Bell.test.js
231
import React from "react"; import { shallow } from "enzyme"; import Bell from "./Bell"; describe("Bell", () => { it("matches snapshot", () => { const aBell = shallow(<Bell />); expect(aBell).toMatchSnapshot(); }); });
mit
Bromvlieg/Scratch
Scratch/CDictionary.cpp
7112
/* libscratch - Multipurpose objective C++ library. Copyright (c) 2015 Angelo Geels <spansjh@gmail.com> 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. */ #ifndef SCRATCH_CDICTIONARY_CPP_INCLUDED #define SCRATCH_CDICTIONARY_CPP_INCLUDED #include "CDictionary.h" SCRATCH_NAMESPACE_BEGIN; template<class TKey, class TValue> DictionaryPair<TKey, TValue>::DictionaryPair() { key = 0; value = 0; } template<class TKey, class TValue> DictionaryPair<TKey, TValue>::~DictionaryPair() { } template<class TKey, class TValue> void DictionaryPair<TKey, TValue>::Delete() { if(key != 0) { delete key; key = 0; } if(value != 0) { delete value; value = 0; } } template<class TKey, class TValue> Dictionary<TKey, TValue>::Dictionary(void) { dic_bAllowDuplicateKeys = FALSE; } template<class TKey, class TValue> Dictionary<TKey, TValue>::Dictionary(const Dictionary<TKey, TValue> &copy) : dic_saKeys(copy.dic_saKeys), dic_saValues(copy.dic_saValues) { dic_bAllowDuplicateKeys = copy.dic_bAllowDuplicateKeys; } template<class TKey, class TValue> Dictionary<TKey, TValue>::~Dictionary(void) { } /// Add to the dictionary template<class TKey, class TValue> void Dictionary<TKey, TValue>::Add(const TKey &key, const TValue &value) { // if the key has already been added if(!dic_bAllowDuplicateKeys && HasKey(key)) { ASSERT(FALSE); return; } // add it dic_saKeys.Push() = key; dic_saValues.Push() = value; } /// Push to the dictionary template<class TKey, class TValue> DictionaryPair<TKey, TValue> Dictionary<TKey, TValue>::Push(const TKey &key) { DictionaryPair<TKey, TValue> ret; ret.key = &(dic_saKeys.Push()); (*ret.key) = key; ret.value = &(dic_saValues.Push()); return ret; } /// Get the index of the given key template<class TKey, class TValue> INDEX Dictionary<TKey, TValue>::IndexByKey(const TKey &key) { int ctElements = Count(); // find the right index int iIndex = 0; for(; iIndex<ctElements; iIndex++) { if(dic_saKeys[iIndex] == key) { // this is the item, we found the index break; } } // return index, or element count if it doesn't exist if(iIndex < ctElements) { return iIndex; } return -1; } /// Get the index of the given value template<class TKey, class TValue> INDEX Dictionary<TKey, TValue>::IndexByValue(const TValue &value) { int ctElements = Count(); // find the right index int iIndex = 0; for(; iIndex<ctElements; iIndex++) { if(dic_saValues[iIndex] == value) { // this is the item, we found the index break; } } // return index, or -1 if it doesn't exist if(iIndex < ctElements) { return iIndex; } return -1; } /// Does this dictionary have the given key? template<class TKey, class TValue> BOOL Dictionary<TKey, TValue>::HasKey(const TKey &key) { return IndexByKey(key) != -1; } /// Does this dictionary have the given value? template<class TKey, class TValue> BOOL Dictionary<TKey, TValue>::HasValue(const TValue &value) { return IndexByValue(value) != -1; } /// Remove a value by its index template<class TKey, class TValue> void Dictionary<TKey, TValue>::RemoveByIndex(const INDEX iIndex) { // check if someone passed an invalid range if(iIndex < 0 || iIndex >= Count()) { ASSERT(FALSE); return; } // pop the values at that index delete dic_saKeys.PopAt(iIndex); delete dic_saValues.PopAt(iIndex); } /// Remove a value from the dictionary by key template<class TKey, class TValue> void Dictionary<TKey, TValue>::RemoveByKey(const TKey &key) { // remove by index RemoveByIndex(IndexByKey(key)); } /// Remove a value from the dictionary template<class TKey, class TValue> void Dictionary<TKey, TValue>::RemoveByValue(const TValue &value) { // remove by index RemoveByIndex(IndexByValue(value)); } /// Pop a value by its index template<class TKey, class TValue> DictionaryPair<TKey, TValue> Dictionary<TKey, TValue>::PopByIndex(const INDEX iIndex) { DictionaryPair<TKey, TValue> ret; ret.key = dic_saKeys.PopAt(iIndex); ret.value = dic_saValues.PopAt(iIndex); return ret; } /// Pop a value from the dictionary by key template<class TKey, class TValue> DictionaryPair<TKey, TValue> Dictionary<TKey, TValue>::PopByKey(const TKey &key) { return PopByIndex(IndexByKey(key)); } /// Pop a value from the dictionary template<class TKey, class TValue> DictionaryPair<TKey, TValue> Dictionary<TKey, TValue>::PopByValue(const TValue &value) { return PopByIndex(IndexByValue(value)); } /// Clear all items template<class TKey, class TValue> void Dictionary<TKey, TValue>::Clear(void) { // clear keys and values dic_saKeys.Clear(); dic_saValues.Clear(); } /// Return how many objects there currently are in the dictionary template<class TKey, class TValue> INDEX Dictionary<TKey, TValue>::Count(void) { // return the amount of keys (amount of values is the same) return dic_saKeys.Count(); } template<class TKey, class TValue> TValue& Dictionary<TKey, TValue>::operator[](const TKey &key) { // get the index INDEX iIndex = IndexByKey(key); // if the key doesn't exist if(iIndex == -1) { // make a new key dic_saKeys.Push() = key; // and make a new value which we'll return return dic_saValues.Push(); } // return the value return dic_saValues[iIndex]; } /// Get a pair from the dictionary using an index template<class TKey, class TValue> DictionaryPair<TKey, TValue> Dictionary<TKey, TValue>::GetPair(const INDEX iIndex) { DictionaryPair<TKey, TValue> pair; pair.key = &dic_saKeys[iIndex]; pair.value = &dic_saValues[iIndex]; return pair; } /// Get a key from the dictionary using an index template<class TKey, class TValue> TKey& Dictionary<TKey, TValue>::GetKeyByIndex(const INDEX iIndex) { // return the value return dic_saKeys[iIndex]; } /// Return value by index template<class TKey, class TValue> TValue& Dictionary<TKey, TValue>::GetValueByIndex(const INDEX iIndex) { // return the value return dic_saValues[iIndex]; } SCRATCH_NAMESPACE_END; #endif
mit
ls1intum/ArTEMiS
src/main/java/de/tum/in/www1/artemis/domain/quiz/scoring/ScoringStrategy.java
578
package de.tum.in.www1.artemis.domain.quiz.scoring; import de.tum.in.www1.artemis.domain.SubmittedAnswer; import de.tum.in.www1.artemis.domain.quiz.QuizQuestion; public interface ScoringStrategy { /** * Calculate the score for the given answer to the given quizQuestion * * @param quizQuestion the quizQuestion to score * @param submittedAnswer the answer to score * @return the resulting score (usually between 0.0 and quizQuestion.getScore()) */ double calculateScore(QuizQuestion quizQuestion, SubmittedAnswer submittedAnswer); }
mit
karaivanska/Programming-Fundamentals
Ext-RegEx-Exercises/extractSentencesByKeyword/ExtractSentencesByKeyword.cs
620
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; class ExtractSentencesByKeyword { static void Main() { string input = Console.ReadLine(); //judge 60/100 string text = Console.ReadLine(); string pattern = string.Format(@"\s?[A-Z][^A-Z]+(?<=\s)[{0}]*(?=\s)[^.!]+[^.!?]", input); MatchCollection matches = Regex.Matches(text, pattern); foreach (Match match in matches) { Console.WriteLine("{0}", match.Value.TrimStart(' ')); } } }
mit
rip-lang/samples
samples/enum.rb
142
#these enums would be equivalent mass_states = enum { gas liquid solid } water_states_2 = enum { gas = 1 liquid = 2 solid = 4 }
mit
idekerlab/deep-cell
frontend/client/components/TopPage/Footer.js
380
import React, {Component} from 'react' import style from './style.css' class Footer extends Component { render() { return ( <footer className={style.containerFooter}> <a href='http://www.cytoscape.org/' target='_blank'> &copy; 2016 University of California, San Diego Trey Ideker Lab </a> </footer> ) } } export default Footer
mit
Coding/Coding-Android
common-coding/src/main/java/net/coding/program/network/model/code/BranchMetrics.java
499
package net.coding.program.network.model.code; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.io.Serializable; public class BranchMetrics implements Serializable { private static final long serialVersionUID = -7032853125318221927L; @SerializedName("base") @Expose public String base = ""; @SerializedName("ahead") @Expose public int ahead; @SerializedName("behind") @Expose public int behind; }
mit
gossi/trixionary
src/model/SkillReference.php
460
<?php namespace gossi\trixionary\model; use gossi\trixionary\model\Base\SkillReference as BaseSkillReference; /** * Skeleton subclass for representing a row from the 'kk_trixionary_skill_reference' table. * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. */ class SkillReference extends BaseSkillReference { }
mit
MrHuxu/leetcode
problems/767_reorganize-string/test-cases.js
1136
module.exports = [{ input : ['aab'], output : 'aba' }, { input : ['aaab'], output : '' }, { input : ['tndsewnllhrtwsvxenkscbivijfqnysamckzoyfnapuotmdexzkkrpmppttficzerdndssuveompqkemtbwbodrhwsfpbmkafpwyedpcowruntvymxtyyejqtajkcjakghtdwmuygecjncxzcxezgecrxonnszmqmecgvqqkdagvaaucewelchsmebikscciegzoiamovdojrmmwgbxeygibxxltemfgpogjkhobmhwquizuwvhfaiavsxhiknysdghcawcrphaykyashchyomklvghkyabxatmrkmrfsppfhgrwywtlxebgzmevefcqquvhvgounldxkdzndwybxhtycmlybhaaqvodntsvfhwcuhvuccwcsxelafyzushjhfyklvghpfvknprfouevsxmcuhiiiewcluehpmzrjzffnrptwbuhnyahrbzqvirvmffbxvrmynfcnupnukayjghpusewdwrbkhvjnveuiionefmnfxao'], output : 'hkhkhkhkhkhkhkhkhkhkhkhkhkhuhuhuhuhuhuhuhuhuhuhuhuhuhuhueueueueueuesesesesesesesesesesesesesesesesesesesexexexexcxcxcxcxcxcxcxcxcxcxcxcxcxcxcpcpcpcpcpcpcpcpcpcpcpcpmpmpmpmpmpmpmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmrmgmgvgvgvgvgvgvgvgvgvgvgvgvgvgvgvgvovovovovovovovovonononononononononbnbnbnbnbnbnbnbnbnbnbnbnbnbnbfbftftftftftftftftftftftftftftftftfififififiyiyiyiyiyiyiyiyiyiyiyiydydydydydydydydydydydadadadadazazazazazazazazazazazazazazalalalalwlwlwlwlwlwlwlwjwjwjwjwjwjwjwjwjwjwjwqwqwqkqkqkqkqkqkqkqkq' }];
mit
ImagicTheCat/vRP
vrp/cfg/home_components.lua
306
local cfg = {} -- map_entity: {ent,cfg} will fill cfg.pos cfg.chest = { map_entity = {"PoI", {marker_id = 1}} } cfg.wardrobe = { map_entity = {"PoI", {marker_id = 1}} } cfg.gametable = { map_entity = {"PoI", {marker_id = 1}} } cfg.radio = { map_entity = {"PoI", {marker_id = 1}} } return cfg
mit
NCI-Agency/anet
client/src/components/Page.js
5630
import { gql } from "@apollo/client" import { Icon } from "@blueprintjs/core" import { IconNames } from "@blueprintjs/icons" import { setPageProps, setSearchProps } from "actions" import API from "api" import NotFound from "components/NotFound" import PropTypes from "prop-types" import React, { useEffect, useState } from "react" import { OverlayTrigger, Tooltip } from "react-bootstrap" import { hideLoading, showLoading } from "react-redux-loading-bar" import { animateScroll, Link } from "react-scroll" const GQL_CREATE_SUBSCRIPTION = gql` mutation($subscription: SubscriptionInput!) { createSubscription(subscription: $subscription) { uuid } } ` const GQL_DELETE_OBJECT_SUBSCRIPTION = gql` mutation($subscribedObjectUuid: String!) { deleteObjectSubscription(uuid: $subscribedObjectUuid) } ` export const mapPageDispatchersToProps = (dispatch, ownProps) => ({ pageDispatchers: { showLoading: () => dispatch(showLoading()), hideLoading: () => dispatch(hideLoading()), setPageProps: pageProps => dispatch(setPageProps(pageProps)), setSearchProps: searchProps => dispatch(setSearchProps(searchProps)) } }) export const PageDispatchersPropType = PropTypes.shape({ showLoading: PropTypes.func.isRequired, hideLoading: PropTypes.func.isRequired, setPageProps: PropTypes.func.isRequired, setSearchProps: PropTypes.func.isRequired }).isRequired export const AnchorLink = ({ to, children }) => ( <Link to={to} smooth duration={500} containerId="main-viewport"> {children} </Link> ) AnchorLink.propTypes = { to: PropTypes.string, children: PropTypes.node } export function jumpToTop() { animateScroll.scrollToTop({ duration: 500, delay: 100, smooth: "easeInOutQuint", containerId: "main-viewport" }) } export const useBoilerplate = ({ loading, pageProps, searchProps, error, modelName, uuid, pageDispatchers: { showLoading, hideLoading, setPageProps, setSearchProps } }) => { useEffect( () => { applyPageProps(setPageProps, pageProps) applySearchProps(setSearchProps, searchProps) }, [] // eslint-disable-line react-hooks/exhaustive-deps ) useEffect( () => { toggleLoading(loading, showLoading, hideLoading) return function cleanup() { // Make sure loading indicator is hidden when 'unmounting' toggleLoading(false, showLoading, hideLoading) } }, [loading] // eslint-disable-line react-hooks/exhaustive-deps ) if (loading) { return { done: true, result: <div className="loader" /> } } if (error) { return { done: true, result: renderError(error, modelName, uuid) } } return { done: false } } const renderError = (error, modelName, uuid) => { if (error.status === 404) { const text = modelName ? `${modelName} #${uuid}` : "Page" return <NotFound text={`${text} not found.`} /> } if (error.status === 500) { return ( <NotFound text="There was an error processing this request. Please contact an administrator." /> ) } return `${error.message}` } const toggleLoading = (loading, showLoading, hideLoading) => { if (loading) { showLoading() } else { hideLoading() } } const applyPageProps = (setPageProps, pageProps) => { if (pageProps) { setPageProps(Object.assign({}, pageProps)) } } const applySearchProps = (setSearchProps, searchProps) => { if (searchProps) { setSearchProps(Object.assign({}, searchProps)) } } export const SubscriptionIcon = ({ subscribedObjectType, subscribedObjectUuid, isSubscribed, updatedAt, refetch, setError, persistent }) => { const [disabled, setDisabled] = useState(false) const tooltip = isSubscribed ? "Click to unsubscribe" : "Click to subscribe" const icon = isSubscribed ? IconNames.FEED_SUBSCRIBED : IconNames.FEED // or perhaps: const icon = isSubscribed ? IconNames.EYE_ON : IconNames.EYE_OFF const color = isSubscribed ? "green" : "grey" return ( <OverlayTrigger placement="top" overlay={<Tooltip id="subscribe">{tooltip}</Tooltip>} > <Icon icon={icon} color={color} style={{ background: "none", border: "none", verticalAlign: "middle" }} type="button" tagName="button" disabled={disabled} onClick={async() => { persistent && setDisabled(true) await toggleSubscription( subscribedObjectType, subscribedObjectUuid, isSubscribed, updatedAt, refetch, setError ) // TODO: Changing the state of an unmounted component cause warnings. persistent prop can be removed if this changes with react 17 persistent && setDisabled(false) }} /> </OverlayTrigger> ) } SubscriptionIcon.propTypes = { subscribedObjectType: PropTypes.string.isRequired, subscribedObjectUuid: PropTypes.string.isRequired, isSubscribed: PropTypes.bool.isRequired, updatedAt: PropTypes.number, refetch: PropTypes.func.isRequired, setError: PropTypes.func.isRequired, persistent: PropTypes.bool } const toggleSubscription = ( subscribedObjectType, subscribedObjectUuid, isSubscribed, updatedAt, refetch, setError ) => { const variables = isSubscribed ? { subscribedObjectUuid } : { subscription: { subscribedObjectType, subscribedObjectUuid, updatedAt } } return API.mutation( isSubscribed ? GQL_DELETE_OBJECT_SUBSCRIPTION : GQL_CREATE_SUBSCRIPTION, variables ) .then(data => refetch()) .catch(setError) }
mit
PeterKow/serverAurity
server/utils/crone.js
3386
const CronJob = require('cron').CronJob; const checkGet = require('../api/tweets/tweet').checkGet const userFirends = require('../mock/users.mock.js').userFirends const userFirends100 = require('../mock/users100.mock.js').userFirends const userFirends200 = require('../mock/users200.mock.js').userFirends const userFirends300 = require('../mock/users300.mock.js').userFirends const userFirends400 = require('../mock/users400.mock.js').userFirends const userFirends500 = require('../mock/users500.mock.js').userFirends const userFirends600 = require('../mock/users600.mock.js').userFirends const userFirends700 = require('../mock/users700.mock.js').userFirends createSyncTask('15 13 * * *', userFirends300) createSyncTask('31 13 * * *', userFirends400) createSyncTask('47 13 * * *', userFirends500) createSyncTask('03 14 * * *', userFirends600) createSyncTask('19 14 * * *', userFirends700) createSyncTask('35 14 * * *', userFirends) createSyncTask('51 14 * * *', userFirends100) createSyncTask('07 15 * * *', userFirends200) function createSyncTask(croneTime, userFriends) { console.log('CRON SET FOR: ', croneTime) var job = new CronJob(croneTime, function () { /* * Runs every weekday (Monday through Friday) * at 11:30:00 AM. It does not run on Saturday * or Sunday. */ console.log('start CRONE', new Date) syncTweetsAll(userFriends) }, function () { console.log('stop CRONE') /* This function is executed when the job stops */ }, true /* Start the job right now */ ) job.start(); } function syncTweetsAll (userFirends){ const minRetweets = 0 const minFaves = 0 userFirends.map(function(user_screen) { var cronQuery = { query: "from:" + user_screen + " min_retweets:" + minRetweets + " OR min_faves:" + minFaves } checkGet(cronQuery) }) } /* * For testing only ------> */ //const getFriends = require('../app/twitterSearch.js').getFriends //const getLookupUsers = require('../app/twitterSearch.js').getLookupUsers //const userFriendID = require('../mock/userId.mock.js').userFriendID //runTestTrash() function runTestTrash() { var user = 'dan_abramov' //var user = '70345946' //var user = 'peter_kow' var minRetweets = 0 var minFaves = 0 var cronQuery = {query: "from:" + user + " min_retweets:" + minRetweets + " OR min_faves:" + minFaves} //setTimeout( getFriends({ body: { query: "CRONE TASK friends" }}, null, syncFriendsTweets), 2000) setTimeout(function() { checkGet(cronQuery)}, 4000) //setTimeout(syncFriendsTweets({ ids: userFriendID.filter(function(id, index) { if(index >= 700 && index < 800 ) return id }) }), 2000) //setTimeout(syncTweetsAll(userFirends), 2000) //setTimeout(syncTweetsAll(userFirends100), 2000) //next_cursor: 1528715716440134400, // next_cursor_str: '1528715716440134330', // previous_cursor: 0, // previous_cursor_str: '0' } } function syncFriendsTweets(data) { console.log('Friends list # ', data.ids.length ) var idsSearch = data.ids.reduce(function(old, newId) { return old + ", "+ newId }) console.log('idsSearch', idsSearch) getLookupUsers({ body: { query: { user_id: idsSearch }}}, null, function(data){ //console.log('users list', data.map(function(user) { return user.screen_name })) console.log('users list', data.map(function(user) { return user.screen_name })) }) }
mit
the-zebulan/CodeWars
tests/beta_tests/test_how_many_stairs_will_suzuki_climb_in_20_years.py
3034
import unittest from katas.beta.how_many_stairs_will_suzuki_climb_in_20_years import \ stairs_in_20 class StairsIn20YearsTestCase(unittest.TestCase): def test_something(self): self.assertEqual(stairs_in_20([ [[6737, 7244, 5776, 9826, 7057, 9247, 5842, 5484, 6543, 5153, 6832, 8274, 7148, 6152, 5940, 8040, 9174, 7555, 7682, 5252, 8793, 8837, 7320, 8478, 6063, 5751, 9716, 5085, 7315, 7859, 6628, 5425, 6331, 7097, 6249, 8381, 5936, 8496, 6934, 8347, 7036, 6421, 6510, 5821, 8602, 5312, 7836, 8032, 9871, 5990, 6309, 7825]], [[9175, 7883, 7596, 8635, 9274, 9675, 5603, 6863, 6442, 9500, 7468, 9719, 6648, 8180, 7944, 5190, 6209, 7175, 5984, 9737, 5548, 6803, 9254, 5932, 7360, 9221, 5702, 5252, 7041, 7287, 5185, 9139, 7187, 8855, 9310, 9105, 9769, 9679, 7842, 7466, 7321, 6785, 8770, 8108, 7985, 5186, 9021, 9098, 6099, 5828, 7217, 9387]], [[8646, 6945, 6364, 9563, 5627, 5068, 9157, 9439, 5681, 8674, 6379, 8292, 7552, 5370, 7579, 9851, 8520, 5881, 7138, 7890, 6016, 5630, 5985, 9758, 8415, 7313, 7761, 9853, 7937, 9268, 7888, 6589, 9366, 9867, 5093, 6684, 8793, 8116, 8493, 5265, 5815, 7191, 9515, 7825, 9508, 6878, 7180, 8756, 5717, 7555, 9447, 7703]], [[6353, 9605, 5464, 9752, 9915, 7446, 9419, 6520, 7438, 6512, 7102, 5047, 6601, 8303, 9118, 5093, 8463, 7116, 7378, 9738, 9998, 7125, 6445, 6031, 8710, 5182, 9142, 9415, 9710, 7342, 9425, 7927, 9030, 7742, 8394, 9652, 5783, 7698, 9492, 6973, 6531, 7698, 8994, 8058, 6406, 5738, 7500, 8357, 7378, 9598, 5405, 9493]], [[6149, 6439, 9899, 5897, 8589, 7627, 6348, 9625, 9490, 5502, 5723, 8197, 9866, 6609, 6308, 7163, 9726, 7222, 7549, 6203, 5876, 8836, 6442, 6752, 8695, 8402, 9638, 9925, 5508, 8636, 5226, 9941, 8936, 5047, 6445, 8063, 6083, 7383, 7548, 5066, 7107, 6911, 9302, 5202, 7487, 5593, 8620, 8858, 5360, 6638, 8012, 8701]], [[5000, 5642, 9143, 7731, 8477, 8000, 7411, 8813, 8288, 5637, 6244, 6589, 6362, 6200, 6781, 8371, 7082, 5348, 8842, 9513, 5896, 6628, 8164, 8473, 5663, 9501, 9177, 8384, 8229, 8781, 9160, 6955, 9407, 7443, 8934, 8072, 8942, 6859, 5617, 5078, 8910, 6732, 9848, 8951, 9407, 6699, 9842, 7455, 8720, 5725, 6960, 5127]], [[5448, 8041, 6573, 8104, 6208, 5912, 7927, 8909, 7000, 5059, 6412, 6354, 8943, 5460, 9979, 5379, 8501, 6831, 7022, 7575, 5828, 5354, 5115, 9625, 7795, 7003, 5524, 9870, 6591, 8616, 5163, 6656, 8150, 8826, 6875, 5242, 9585, 9649, 9838, 7150, 6567, 8524, 7613, 7809, 5562, 7799, 7179, 5184, 7960, 9455, 5633, 9085]] ]), 54636040)
mit
y10k/runsh
test/test_engine.rb
5825
#!/usr/local/bin/ruby # -*- coding: utf-8 -*- require 'runsh' require 'test/unit' module RunSh::Test class ScriptContextTest < Test::Unit::TestCase def setup @program_name = 'foo' @args = %w[ apple banana orange ] @pid = 1234 @env = { 'ENV1' => 'Alice', 'ENV2' => 'Bob' } @context = RunSh::ScriptContext.new(pid: @pid, env: @env) @context.program_name = @program_name @context.args = @args end def test_program_name assert_equal(@program_name, @context.program_name) assert_equal(@program_name, @context.get_var('0')) end def test_args assert_equal(@args, @context.args) assert_equal(@args.length.to_s, @context.get_var('#')) @args.each_with_index do |expected_value, i| n = i + 1 assert_equal(expected_value, @context.get_var(n.to_s), "num:#{n}") end assert_equal('apple banana orange', @context.get_var('@')) assert_equal('apple banana orange', @context.get_var('*')) end def test_pid assert_equal(@pid, @context.pid) assert_equal(@pid.to_s, @context.get_var('$')) end def test_command_status assert_equal(0, @context.command_status) assert_equal('0', @context.get_var('?')) @context.command_status = 1 assert_equal(1, @context.command_status) assert_equal('1', @context.get_var('?')) end def test_shell_var assert_equal('Alice', @context.get_var('ENV1')) assert_equal('Bob', @context.get_var('ENV2')) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ] ], @context.each_var.to_a) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ] ], @env.to_a) assert_nil(@context.get_var('var1')) assert_nil(@env['var1']) @context.put_var('var1', 'Carol') assert_equal('Alice', @context.get_var('ENV1')) assert_equal('Bob', @context.get_var('ENV2')) assert_equal('Carol', @context.get_var('var1')) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'var1', 'Carol' ] ], @context.each_var.to_a) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ] ], @env.to_a) assert_nil(@env['var1']) @context.export('var1') assert_equal('Carol', @env['var1']) assert_equal('Alice', @context.get_var('ENV1')) assert_equal('Bob', @context.get_var('ENV2')) assert_equal('Carol', @context.get_var('var1')) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'var1', 'Carol' ] ], @context.each_var.to_a) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'var1', 'Carol' ] ], @env.to_a) assert_nil(@env['ENV3']) @context.export('ENV3') assert_equal('', @env['ENV3']) assert_equal('Alice', @context.get_var('ENV1')) assert_equal('Bob', @context.get_var('ENV2')) assert_equal('Carol', @context.get_var('var1')) assert_equal('', @context.get_var('ENV3')) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'var1', 'Carol' ], [ 'ENV3', '' ] ], @context.each_var.to_a) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'var1', 'Carol' ], [ 'ENV3', '' ] ], @env.to_a) @context.unset_var('var1') assert_nil(@context.get_var('var1')) assert_nil(@env['var1']) assert_equal('Alice', @context.get_var('ENV1')) assert_equal('Bob', @context.get_var('ENV2')) assert_equal('', @context.get_var('ENV3')) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'ENV3', '' ] ], @context.each_var.to_a) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'ENV3', '' ] ], @env.to_a) assert_nil(@env['var2']) assert_nil(@env['var3']) @context.put_var('var2', 'Dave') @context.put_var('var3', 'Ellen') assert_nil(@env['var2']) assert_nil(@env['var3']) assert_equal('Alice', @context.get_var('ENV1')) assert_equal('Bob', @context.get_var('ENV2')) assert_equal('', @context.get_var('ENV3')) assert_equal('Dave', @context.get_var('var2')) assert_equal('Ellen', @context.get_var('var3')) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'ENV3', '' ], [ 'var2', 'Dave' ], [ 'var3', 'Ellen' ] ], @context.each_var.to_a) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'ENV3', '' ] ], @env.to_a) @context.unset_var('var2') assert_nil(@context.get_var('var2')) assert_equal('Alice', @context.get_var('ENV1')) assert_equal('Bob', @context.get_var('ENV2')) assert_equal('', @context.get_var('ENV3')) assert_equal('Ellen', @context.get_var('var3')) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'ENV3', '' ], [ 'var3', 'Ellen' ] ], @context.each_var.to_a) assert_equal([ [ 'ENV1', 'Alice' ], [ 'ENV2', 'Bob' ], [ 'ENV3', '' ] ], @env.to_a) end end end # Local Variables: # indent-tabs-mode: nil # End:
mit
TomaszRewak/TREPL
Source/scripts/compiler/Elements/ValueOf.ts
1963
module L { export class ValueOf extends LogicElement { constructor( public log_value: LogicElement ) { super(); } _compile(environment: Compiler.TypeEnvironment): boolean { this.errorIfEmpty(this.log_value); this.cs = this.log_value.compile(environment) && this.cs; if (!this.cs) return false; this.errorIfNot(this.log_value.returns.varType instanceof TS.ReferenceType, 'Expected reference', this.log_value); if (!this.cs) return false; var reference = <TS.ReferenceType>this.log_value.returns.varType; this.returns = new TS.LValueOfType(reference.prototypeType.referencedPrototypeType.declaresType()); return this.cs; } *execute(environment: Memory.Environment): IterableIterator<Operation> { yield* this.log_value.run(environment); var reference = <TS.Reference> environment.popTempValue().getValue(); environment.pushTempAlias(reference.reference); yield Operation.tempMemory(this); return; } } } module E { export class ValueOf extends Element { getJSONName() { return 'ValueOf' } c_object: C.DropField constructor( object: E.Element = null) { super(); this.c_object = new C.DropField(this, object) this.initialize([ [ new C.Label('val of'), this.c_object, ] ], ElementType.Value); } constructCode(): L.LogicElement { var logic = new L.ValueOf( this.c_object.constructCode() ); logic.setObserver(this); return logic; } getCopy(): Element { return new ValueOf( this.c_object.getContentCopy()).copyMetadata(this); } } }
mit
danmorrisonNZ/digital_graveyard
grave_controller.rb
1319
require_relative 'grave_model.rb' require_relative 'grave_view.rb' class Undertaker def initialize @tombstone_parse = TombstoneParse.new @tombstone_view = TombstoneView.new end def create request_name request_date_of_birth request_date_of_death request_last_words new_user_creation end def request_name @tombstone_view.render_name_request new_tombstone_input end def user_input @tombstone_view.user_input end def new_tombstone_input tombstone_info = @tombstone_view.tombstone_input @tombstone_parse.new_tombstones << tombstone_info end def new_user_creation @tombstone_parse.new_user_tombstone end def request_date_of_birth @tombstone_view.render_date_of_birth_request new_tombstone_input end def request_date_of_death @tombstone_view.render_date_of_death_request new_tombstone_input end def request_last_words @tombstone_view.render_last_words_request new_tombstone_input end def welcome_message @tombstone_view.render_welcome end def menu_message @tombstone_view.render_menu end def view_all_tombstones all_tombstones = @tombstone_parse.graveyard @tombstone_view.render_tombstones(all_tombstones) end def incorrect_message @tombstone_view.render_error_message end end
mit
Nahalius/testo
DataTypes/ConsoleApplication2/ConsoleApplication2/Program - DaysSinceB .cs
527
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class DaysSinceB { static void Main6(string[] args) { byte years = byte.Parse(Console.ReadLine()); int days = years * 365; int hours = days * 24; int minutes = hours * 60; Console.WriteLine("{0} years = {1} days = {2} hours = {3} minutes .", years, days, hours, minutes); } } }
mit
pablojmartinez/theatreofpain
theatreofpain/entities/entities/gib_chunk/shared.lua
100
ENT.Type = "anim" ENT.Base = "base_anim" ENT.PrintName = "Gib Chunk" ENT.Author = "Dvondrake"
mit
hogasa/normalizador-amba
tests/test.py
1832
# coding: UTF-8 from __future__ import absolute_import import os import sys import unittest sys.path.insert(0, os.path.abspath('..')) from CommonsTestCase import CommonsTestCase from CallejeroTestCase import CallejeroTestCase from NormalizadorDireccionesTestCase import NormalizadorDireccionesTestCase from CalleYCalleTestCase import CalleYCalleTestCase from CalleAlturaTestCase import CalleAlturaTestCase from NormalizadorDireccionesAMBATestCase import NormalizadorDireccionesAMBATestCase from NormalizadorDireccionesAMBACalleYCalleTestCase import NormalizadorDireccionesAMBACalleYCalleTestCase from NormalizadorDireccionesAMBACalleAlturaTestCase import NormalizadorDireccionesAMBACalleAlturaTestCase from NormalizadorDireccionesAMBAConCabaTestCase import NormalizadorDireccionesAMBAConCabaTestCase from BuscadorDireccionesTestCase import BuscadorDireccionesTestCase from BuscadorDireccionesAMBATestCase import BuscadorDireccionesAMBATestCase '''''''''''''''''''''''' ''' Comienza el test ''' '''''''''''''''''''''''' if __name__ == '__main__': tl = unittest.TestLoader() testables = [ CommonsTestCase, CallejeroTestCase, NormalizadorDireccionesTestCase, CalleYCalleTestCase, CalleAlturaTestCase, NormalizadorDireccionesAMBATestCase, NormalizadorDireccionesAMBACalleYCalleTestCase, NormalizadorDireccionesAMBACalleAlturaTestCase, NormalizadorDireccionesAMBAConCabaTestCase, BuscadorDireccionesTestCase, BuscadorDireccionesAMBATestCase ] for testable in testables: print '' print ''.center(80, '=') print (u' {0} '.format(testable.__name__)).center(80, '=') print ''.center(80, '=') suite = tl.loadTestsFromTestCase(testable) unittest.TextTestRunner(verbosity=2).run(suite)
mit
Sw1cH/Android-Ebook
assets/source/RollTwoPairs.java
1488
public class RollTwoPairs { public static void main(String[] args) { PairOfDice firstDice; // Refers to the first pair of dice. firstDice = new PairOfDice(); PairOfDice secondDice; // Refers to the second pair of dice. secondDice = new PairOfDice(); int countRolls; // Counts how many times the two pairs of // dice have been rolled. int total1; // Total showing on first pair of dice. int total2; // Total showing on second pair of dice. countRolls = 0; do { // Roll the two pairs of dice until totals are the same. firstDice.roll(); // Roll the first pair of dice. total1 = firstDice.die1 + firstDice.die2; // Get total. System.out.println("First pair comes up " + total1); secondDice.roll(); // Roll the second pair of dice. total2 = secondDice.die1 + secondDice.die2; // Get total. System.out.println("Second pair comes up " + total2); countRolls++; // Count this roll. System.out.println(); // Blank line. } while (total1 != total2); System.out.println("It took " + countRolls + " rolls until the totals were the same."); } // end main() } // end class RollTwoPairs
mit
drweissbrot/Ponygon
app/Games/Instance.php
2335
<?php namespace App\Games; use App\Events\Player\MatchData; use App\Models\Match; use App\Models\Player; use Exception; use Illuminate\Http\Request; abstract class Instance { public $match; protected $cache = []; public function __construct(Match $match) { $this->match = $match; } abstract public function init(); /** * Makes a move based on the provided params. * * @return bool whether or not all players should receive updated match data */ abstract public function makeMove(Player $player, array $params) : bool; abstract public function dataForPlayer(Player $player) : array; public function authorizeMoveRequest(Request $request) : bool { $this->match->loadMissing('lobby.members'); return $this->match->lobby->members->contains($request->user()); } public function authorizeEndingMatch(Request $request) : bool { return $request->user()->id === $this->match->lobby->leader_id; } public function authorizeRematch(Request $request) : bool { return false; } public function initiateRematch() : bool { return true; } public function validateMoveRequest(Request $request) : array { return $request->validate($this->getMoveRequestRules($request)); } public function getMoveRequestRules(Request $request) : array { throw new Exception('No validation rules provided for this game.'); } public function sendMatchDataToPlayers() : void { foreach ($this->match->lobby->members as $player) { $this->sendMatchDataTo($player); } } public function sendMatchDataTo(Player $player) : void { MatchData::dispatch($player, $this->dataForPlayer($player)); } public function config(...$args) { if (! array_key_exists('config', $this->cache)) { $this->cache['config'] = new Config($this); } return (empty($args)) ? $this->cache['config'] : $this->cache['config']->get(...$args); } public function state(...$args) { if (! array_key_exists('state', $this->cache)) { $this->cache['state'] = new State($this); } return (empty($args)) ? $this->cache['state'] : $this->cache['state']->get(...$args); } public function get($item) { switch ($item) { case 'config': return $this->config(); case 'state': return $this->state(); default: throw new Exception("[{$item}] does not exist on this instance"); } } }
mit
S00157097/GP
modules/core/tests/client/home.client.controller.tests.js
717
'use strict'; (function () { describe('HomeController', function () { //Initialize global variables var scope, HomeController; // Load the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); HomeController = $controller('HomeController', { $scope: scope }); })); it('should expose the authentication service', function () { expect(HomeController.authentication).toBeTruthy(); }); it('should populate 3 services in an array', function () { expect(HomeController.services.length).toBe(3); }); }); })();
mit
jamesmontemagno/Hanselman.Forms
src/Hanselman/Views/Blog/BlogCollectionPage.xaml.cs
1796
using Hanselman.Interfaces; using Hanselman.ViewModels; using Xamarin.Essentials; using Xamarin.Forms; // ChrisNTR cheered 100 on October 18th 2019 // HuniePop donated $2.50 on November 22nd 2019 // mattleibow cheered 5 on November 22nd 2019 // KymPhillpotts cheered 69 on November 22nd 2019 // CommitttedBlock5 subscribed on November 22nd 2019 // ptDave20 gift sub to andre_abrantes on November 22nd 2019 // KymPhillpotts subscribed for the 11 month on November 22nd 2019 namespace Hanselman.Views { public partial class BlogCollectionPage : ContentPage, IPageHelpers { BlogFeedViewModel? viewModel; BlogFeedViewModel? ViewModel => viewModel ??= BindingContext as BlogFeedViewModel; public BlogCollectionPage() { InitializeComponent(); BindingContext = new BlogFeedViewModel(); } void SetSpan() { var gil = (GridItemsLayout)CollectionViewBlog.ItemsLayout; gil.Span = (int)Application.Current.Resources["BlogSpan"]; } private void App_SpanChanged(object sender, System.EventArgs e) { SetSpan(); } protected override void OnDisappearing() { base.OnDisappearing(); App.SpanChanged -= App_SpanChanged; } protected override void OnAppearing() { base.OnAppearing(); OnPageVisible(); SetSpan(); App.SpanChanged += App_SpanChanged; } public void OnPageVisible() { if (ViewModel == null || !ViewModel.CanLoadMore || ViewModel.IsBusy || ViewModel.FeedItems.Count > 0) { return; } ViewModel.LoadCommand.Execute(true); } } }
mit