code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.thilko.springdoc; @SuppressWarnings("all") public class CredentialsCode { Integer age; double anotherValue; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public double getAnotherValue() { return anotherValue; } public void setAnotherValue(double anotherValue) { this.anotherValue = anotherValue; } }
thilko/gradle-springdoc-plugin
src/test/java/com/thilko/springdoc/CredentialsCode.java
Java
mit
435
<?php use yii\helpers\Html; use yii\grid\GridView; use yii\widgets\Pjax; /* @var $this yii\web\View */ /* @var $searchModel yii2learning\chartbuilder\models\DatasourceSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = Yii::t('app', 'Datasources'); $this->params['breadcrumbs'][] = $this->title; ?> <div class="datasource-index"> <h1><?= Html::encode($this->title) ?></h1> <?=$this->render('/_menus') ?> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?= Html::a('<i class="glyphicon glyphicon-plus"></i> '.Yii::t('app', 'Create Datasource'), ['create'], ['class' => 'btn btn-success']) ?> </p> <?php Pjax::begin(); ?> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'name', // 'created_at', // 'updated_at', // 'created_by', 'updated_by:dateTime', [ 'class' => 'yii\grid\ActionColumn', 'options'=>['style'=>'width:150px;'], 'buttonOptions'=>['class'=>'btn btn-default'], 'template'=>'<div class="btn-group btn-group-sm text-center" role="group">{view} {update} {delete} </div>', ] ], ]); ?> <?php Pjax::end(); ?></div>
Yii2Learning/yii2-chart-builder
views/datasource/index.php
PHP
mit
1,401
module Web::Controllers::Books class Create include Web::Action expose :book params do param :book do param :title, presence: true param :author, presence: true end end def call(params) if params.valid? @book = BookRepository.create(Book.new(params[:book])) redirect_to routes.books_path end end end end
matiasleidemer/lotus-bookshelf
apps/web/controllers/books/create.rb
Ruby
mit
393
// @flow (require('../../lib/git'): any).rebaseRepoMaster = jest.fn(); import { _clearCustomCacheDir as clearCustomCacheDir, _setCustomCacheDir as setCustomCacheDir, } from '../../lib/cacheRepoUtils'; import {copyDir, mkdirp} from '../../lib/fileUtils'; import {parseDirString as parseFlowDirString} from '../../lib/flowVersion'; import { add as gitAdd, commit as gitCommit, init as gitInit, setLocalConfig as gitConfig, } from '../../lib/git'; import {fs, path, child_process} from '../../lib/node'; import {getNpmLibDefs} from '../../lib/npm/npmLibDefs'; import {testProject} from '../../lib/TEST_UTILS'; import { _determineFlowVersion as determineFlowVersion, _installNpmLibDefs as installNpmLibDefs, _installNpmLibDef as installNpmLibDef, run, } from '../install'; const BASE_FIXTURE_ROOT = path.join(__dirname, '__install-fixtures__'); function _mock(mockFn) { return ((mockFn: any): JestMockFn<*, *>); } async function touchFile(filePath) { await fs.close(await fs.open(filePath, 'w')); } async function writePkgJson(filePath, pkgJson) { await fs.writeJson(filePath, pkgJson); } describe('install (command)', () => { describe('determineFlowVersion', () => { it('infers version from path if arg not passed', () => { return testProject(async ROOT_DIR => { const ARBITRARY_PATH = path.join(ROOT_DIR, 'some', 'arbitrary', 'path'); await Promise.all([ mkdirp(ARBITRARY_PATH), touchFile(path.join(ROOT_DIR, '.flowconfig')), writePkgJson(path.join(ROOT_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.40.0', }, }), ]); const flowVer = await determineFlowVersion(ARBITRARY_PATH); expect(flowVer).toEqual({ kind: 'specific', ver: { major: 0, minor: 40, patch: 0, prerel: null, }, }); }); }); it('uses explicitly specified version', async () => { const explicitVer = await determineFlowVersion('/', '0.7.0'); expect(explicitVer).toEqual({ kind: 'specific', ver: { major: 0, minor: 7, patch: 0, prerel: null, }, }); }); it("uses 'v'-prefixed explicitly specified version", async () => { const explicitVer = await determineFlowVersion('/', 'v0.7.0'); expect(explicitVer).toEqual({ kind: 'specific', ver: { major: 0, minor: 7, patch: 0, prerel: null, }, }); }); }); describe('installNpmLibDefs', () => { const origConsoleError = console.error; beforeEach(() => { (console: any).error = jest.fn(); }); afterEach(() => { (console: any).error = origConsoleError; }); it('errors if unable to find a project root (.flowconfig)', () => { return testProject(async ROOT_DIR => { const result = await installNpmLibDefs({ cwd: ROOT_DIR, flowVersion: parseFlowDirString('flow_v0.40.0'), explicitLibDefs: [], libdefDir: 'flow-typed', verbose: false, overwrite: false, skip: false, ignoreDeps: [], useCacheUntil: 1000 * 60, }); expect(result).toBe(1); expect(_mock(console.error).mock.calls).toEqual([ [ 'Error: Unable to find a flow project in the current dir or any of ' + "it's parent dirs!\n" + 'Please run this command from within a Flow project.', ], ]); }); }); it( "errors if an explicitly specified libdef arg doesn't match npm " + 'pkgver format', () => { return testProject(async ROOT_DIR => { await touchFile(path.join(ROOT_DIR, '.flowconfig')); await writePkgJson(path.join(ROOT_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.40.0', }, }); const result = await installNpmLibDefs({ cwd: ROOT_DIR, flowVersion: parseFlowDirString('flow_v0.40.0'), explicitLibDefs: ['INVALID'], libdefDir: 'flow-typed', verbose: false, overwrite: false, skip: false, ignoreDeps: [], useCacheUntil: 1000 * 60, }); expect(result).toBe(1); expect(_mock(console.error).mock.calls).toEqual([ [ 'ERROR: Package not found from package.json.\n' + 'Please specify version for the package in the format of `foo@1.2.3`', ], ]); }); }, ); it('warns if 0 dependencies are found in package.json', () => { return testProject(async ROOT_DIR => { await Promise.all([ touchFile(path.join(ROOT_DIR, '.flowconfig')), writePkgJson(path.join(ROOT_DIR, 'package.json'), { name: 'test', }), ]); const result = await installNpmLibDefs({ cwd: ROOT_DIR, flowVersion: parseFlowDirString('flow_v0.40.0'), explicitLibDefs: [], libdefDir: 'flow-typed', verbose: false, overwrite: false, skip: false, ignoreDeps: [], useCacheUntil: 1000 * 60, }); expect(result).toBe(0); expect(_mock(console.error).mock.calls).toEqual([ ["No dependencies were found in this project's package.json!"], ]); }); }); }); describe('installNpmLibDef', () => { const FIXTURE_ROOT = path.join(BASE_FIXTURE_ROOT, 'installNpmLibDef'); const FIXTURE_FAKE_CACHE_REPO_DIR = path.join( FIXTURE_ROOT, 'fakeCacheRepo', ); const origConsoleLog = console.log; beforeEach(() => { (console: any).log = jest.fn(); }); afterEach(() => { (console: any).log = origConsoleLog; }); it('installs scoped libdefs within a scoped directory', () => { return testProject(async ROOT_DIR => { const FAKE_CACHE_DIR = path.join(ROOT_DIR, 'fakeCache'); const FAKE_CACHE_REPO_DIR = path.join(FAKE_CACHE_DIR, 'repo'); const FLOWPROJ_DIR = path.join(ROOT_DIR, 'flowProj'); const FLOWTYPED_DIR = path.join(FLOWPROJ_DIR, 'flow-typed', 'npm'); await Promise.all([mkdirp(FAKE_CACHE_REPO_DIR), mkdirp(FLOWTYPED_DIR)]); await Promise.all([ copyDir(FIXTURE_FAKE_CACHE_REPO_DIR, FAKE_CACHE_REPO_DIR), touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.40.0', }, }), ]); await gitInit(FAKE_CACHE_REPO_DIR), await gitAdd(FAKE_CACHE_REPO_DIR, 'definitions'); await gitCommit(FAKE_CACHE_REPO_DIR, 'FIRST'); setCustomCacheDir(FAKE_CACHE_DIR); const availableLibDefs = await getNpmLibDefs( path.join(FAKE_CACHE_REPO_DIR, 'definitions'), ); await installNpmLibDef(availableLibDefs[0], FLOWTYPED_DIR, false); }); }); }); describe('end-to-end tests', () => { const FIXTURE_ROOT = path.join(BASE_FIXTURE_ROOT, 'end-to-end'); const FIXTURE_FAKE_CACHE_REPO_DIR = path.join( FIXTURE_ROOT, 'fakeCacheRepo', ); const origConsoleLog = console.log; const origConsoleError = console.error; beforeEach(() => { (console: any).log = jest.fn(); (console: any).error = jest.fn(); }); afterEach(() => { (console: any).log = origConsoleLog; (console: any).error = origConsoleError; }); async function fakeProjectEnv(runTest) { return await testProject(async ROOT_DIR => { const FAKE_CACHE_DIR = path.join(ROOT_DIR, 'fakeCache'); const FAKE_CACHE_REPO_DIR = path.join(FAKE_CACHE_DIR, 'repo'); const FLOWPROJ_DIR = path.join(ROOT_DIR, 'flowProj'); const FLOWTYPED_DIR = path.join(FLOWPROJ_DIR, 'flow-typed', 'npm'); await Promise.all([mkdirp(FAKE_CACHE_REPO_DIR), mkdirp(FLOWTYPED_DIR)]); await copyDir(FIXTURE_FAKE_CACHE_REPO_DIR, FAKE_CACHE_REPO_DIR); await gitInit(FAKE_CACHE_REPO_DIR), await Promise.all([ gitConfig(FAKE_CACHE_REPO_DIR, 'user.name', 'Test Author'), gitConfig(FAKE_CACHE_REPO_DIR, 'user.email', 'test@flow-typed.org'), ]); await gitAdd(FAKE_CACHE_REPO_DIR, 'definitions'); await gitCommit(FAKE_CACHE_REPO_DIR, 'FIRST'); setCustomCacheDir(FAKE_CACHE_DIR); const origCWD = process.cwd; (process: any).cwd = () => FLOWPROJ_DIR; try { await runTest(FLOWPROJ_DIR); } finally { (process: any).cwd = origCWD; clearCustomCacheDir(); } }); } it('installs available libdefs', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, ignoreDeps: [], explicitLibDefs: [], }); // Installs libdefs expect( await Promise.all([ fs.exists( path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'flow-bin_v0.x.x.js', ), ), fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), ]), ).toEqual([true, true]); // Signs installed libdefs const fooLibDefContents = await fs.readFile( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), 'utf8', ); expect(fooLibDefContents).toContain('// flow-typed signature: '); expect(fooLibDefContents).toContain('// flow-typed version: '); }); }); it('installs available libdefs using PnP', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', installConfig: { pnp: true, }, devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { // Use local foo for initial install foo: 'file:./foo', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'foo')), ]); await writePkgJson(path.join(FLOWPROJ_DIR, 'foo/package.json'), { name: 'foo', version: '1.2.3', }); // Yarn install so PnP file resolves to local foo await child_process.execP('yarn install', {cwd: FLOWPROJ_DIR}); // Overwrite foo dep so it's like we installed from registry instead writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', installConfig: { pnp: true, }, devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }); // Run the install command await run({ overwrite: false, verbose: false, skip: false, ignoreDeps: [], explicitLibDefs: [], }); // Installs libdefs expect( await Promise.all([ fs.exists( path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'flow-bin_v0.x.x.js', ), ), fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), ]), ).toEqual([true, true]); // Signs installed libdefs const fooLibDefRawContents = await fs.readFile( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ); const fooLibDefContents = fooLibDefRawContents.toString(); expect(fooLibDefContents).toContain('// flow-typed signature: '); expect(fooLibDefContents).toContain('// flow-typed version: '); }); }); it('ignores libdefs in dev, bundled, optional or peer dependencies when flagged', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { foo: '1.2.3', }, peerDependencies: { 'flow-bin': '^0.43.0', }, optionalDependencies: { foo: '2.0.0', }, bundledDependencies: { bar: '^1.6.9', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'bar')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, ignoreDeps: ['dev', 'optional', 'bundled'], explicitLibDefs: [], }); // Installs libdefs expect( await Promise.all([ fs.exists( path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'flow-bin_v0.x.x.js', ), ), fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'bar_v1.x.x.js'), ), ]), ).toEqual([true, true, false]); }); }); it('stubs unavailable libdefs', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { someUntypedDep: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'someUntypedDep')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, explicitLibDefs: [], }); // Installs a stub for someUntypedDep expect( await fs.exists( path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'someUntypedDep_vx.x.x.js', ), ), ).toBe(true); }); }); it("doesn't stub unavailable libdefs when --skip is passed", () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { someUntypedDep: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'someUntypedDep')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: true, explicitLibDefs: [], }); // Installs a stub for someUntypedDep expect( await fs.exists(path.join(FLOWPROJ_DIR, 'flow-typed', 'npm')), ).toBe(true); }); }); it('overwrites stubs when libdef becomes available (with --overwrite)', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); await fs.writeFile( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_vx.x.x.js'), '', ); // Run the install command await run({ overwrite: true, verbose: false, skip: false, explicitLibDefs: [], }); // Replaces the stub with the real typedef expect( await Promise.all([ fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_vx.x.x.js'), ), fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), ]), ).toEqual([false, true]); }); }); it("doesn't overwrite tweaked libdefs (without --overwrite)", () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, explicitLibDefs: [], }); const libdefFilePath = path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js', ); // Tweak the libdef for foo const libdefFileContent = (await fs.readFile(libdefFilePath, 'utf8')) + '\n// TWEAKED!'; await fs.writeFile(libdefFilePath, libdefFileContent); // Run install command again await run({ overwrite: false, verbose: false, skip: false, explicitLibDefs: [], }); // Verify that the tweaked libdef file wasn't overwritten expect(await fs.readFile(libdefFilePath, 'utf8')).toBe( libdefFileContent, ); }); }); it('overwrites tweaked libdefs when --overwrite is passed', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, explicitLibDefs: [], }); const libdefFilePath = path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js', ); // Tweak the libdef for foo const libdefFileContent = await fs.readFile(libdefFilePath, 'utf8'); await fs.writeFile(libdefFilePath, libdefFileContent + '\n// TWEAKED!'); // Run install command again await run({ overwrite: true, skip: false, verbose: false, explicitLibDefs: [], }); // Verify that the tweaked libdef file wasn't overwritten expect(await fs.readFile(libdefFilePath, 'utf8')).toBe( libdefFileContent, ); }); }); it('uses flow-bin defined in another package.json', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), writePkgJson(path.join(FLOWPROJ_DIR, '..', 'package.json'), { name: 'parent', devDependencies: { 'flow-bin': '^0.45.0', }, }), mkdirp(path.join(FLOWPROJ_DIR, '..', 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, packageDir: path.join(FLOWPROJ_DIR, '..'), explicitLibDefs: [], }); // Installs libdef expect( await fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), ).toEqual(true); }); }); it('uses .flowconfig from specified root directory', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ mkdirp(path.join(FLOWPROJ_DIR, 'src')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); await touchFile(path.join(FLOWPROJ_DIR, 'src', '.flowconfig')); // Run the install command await run({ overwrite: false, verbose: false, skip: false, rootDir: path.join(FLOWPROJ_DIR, 'src'), explicitLibDefs: [], }); // Installs libdef expect( await fs.exists( path.join( FLOWPROJ_DIR, 'src', 'flow-typed', 'npm', 'foo_v1.x.x.js', ), ), ).toEqual(true); }); }); }); });
splodingsocks/FlowTyped
cli/src/commands/__tests__/install-test.js
JavaScript
mit
23,904
import React, { Component } from 'react' import PropTypes from 'prop-types' import { assign } from 'lodash' import autoBind from '../utils/autoBind' const styles = { 'ClosedPanelWrapper': { height: '40px' }, 'PanelWrapper': { position: 'relative' }, 'Over': { border: '1px dashed white', overflowY: 'hidden' }, 'PanelTitle': { width: '100%', height: '40px', lineHeight: '40px', backgroundColor: '#000', color: '#fff', paddingLeft: '10px', position: 'relative', whiteSpace: 'nowrap', overflowX: 'hidden', textOverflow: 'ellipsis', paddingRight: '8px', cursor: 'pointer', WebkitUserSelect: 'none', userSelect: 'none' }, 'Handle': { cursor: '-webkit-grab', position: 'absolute', zIndex: '2', color: 'white', right: '10px', fontSize: '16px', top: '12px' }, 'OpenPanel': { position: 'relative', zIndex: '2', top: '0', left: '0', padding: '7px', paddingTop: '5px', maxHeight: '30%', display: 'block' }, 'ClosedPanel': { height: '0', position: 'relative', zIndex: '2', top: '-1000px', left: '0', overflow: 'hidden', maxHeight: '0', display: 'none' } } class Panel extends Component { constructor() { super() this.state = { dragIndex: null, overIndex: null, isOver: false } autoBind(this, [ 'handleTitleClick', 'handleDragStart', 'handleDragOver', 'handleDragEnter', 'handleDragLeave', 'handleDrop', 'handleDragEnd' ]) } handleTitleClick() { const { index, isOpen, openPanel } = this.props openPanel(isOpen ? -1 : index) } handleDragStart(e) { // e.target.style.opacity = '0.4'; // this / e.target is the source node. e.dataTransfer.setData('index', e.target.dataset.index) } handleDragOver(e) { if (e.preventDefault) { e.preventDefault() // Necessary. Allows us to drop. } return false } handleDragEnter(e) { const overIndex = e.target.dataset.index if (e.dataTransfer.getData('index') !== overIndex) { // e.target.classList.add('Over') // e.target is the current hover target. this.setState({ isOver: true }) } } handleDragLeave() { this.setState({ isOver: false }) // e.target.classList.remove('Over') // e.target is previous target element. } handleDrop(e) { if (e.stopPropagation) { e.stopPropagation() // stops the browser from redirecting. } const dragIndex = e.dataTransfer.getData('index') const dropIndex = this.props.index.toString() if (dragIndex !== dropIndex) { this.props.reorder(dragIndex, dropIndex) } return false } handleDragEnd() { this.setState({ isOver: false, dragIndex: null, overIndex: null }) } render() { const { isOpen, orderable } = this.props const { isOver } = this.state return ( <div style={assign({}, styles.PanelWrapper, isOpen ? {} : styles.ClosedPanelWrapper, isOver ? styles.Over : {})} onDragStart={this.handleDragStart} onDragEnter={this.handleDragEnter} onDragOver={this.handleDragOver} onDragLeave={this.handleDragLeave} onDrop={this.handleDrop} onDragEnd={this.handleDragEnd} > <div style={styles.PanelTitle} onClick={this.handleTitleClick} draggable={orderable} data-index={this.props.index} > {this.props.header} {orderable && (<i className="fa fa-th" style={styles.Handle}></i>)} </div> { isOpen && ( <div style={isOpen ? styles.OpenPanel : styles.ClosedPanel}> {this.props.children} </div> ) } </div> ) } } Panel.propTypes = { children: PropTypes.any, index: PropTypes.any, openPanel: PropTypes.func, isOpen: PropTypes.any, header: PropTypes.any, orderable: PropTypes.any, reorder: PropTypes.func } Panel.defaultProps = { isOpen: false, header: '', orderable: false } export default Panel
jcgertig/react-struct-editor
src/components/Panel.js
JavaScript
mit
4,120
'use strict'; // src\services\message\hooks\timestamp.js // // Use this hook to manipulate incoming or outgoing data. // For more information on hooks see: http://docs.feathersjs.com/hooks/readme.html const defaults = {}; module.exports = function(options) { options = Object.assign({}, defaults, options); return function(hook) { const usr = hook.params.user; const txt = hook.data.text; hook.data = { text: txt, createdBy: usr._id, createdAt: Date.now() } }; };
zorqie/bfests
src/services/message/hooks/timestamp.js
JavaScript
mit
488
package fr.lteconsulting.pomexplorer.commands; import fr.lteconsulting.pomexplorer.AppFactory; import fr.lteconsulting.pomexplorer.Client; import fr.lteconsulting.pomexplorer.Log; public class HelpCommand { @Help( "gives this message" ) public void main( Client client, Log log ) { log.html( AppFactory.get().commands().help() ); } }
ltearno/pom-explorer
pom-explorer/src/main/java/fr/lteconsulting/pomexplorer/commands/HelpCommand.java
Java
mit
342
namespace CAAssistant.Models { public class ClientFileViewModel { public ClientFileViewModel() { } public ClientFileViewModel(ClientFile clientFile) { Id = clientFile.Id; FileNumber = clientFile.FileNumber; ClientName = clientFile.ClientName; ClientContactPerson = clientFile.ClientContactPerson; AssociateReponsible = clientFile.AssociateReponsible; CaSign = clientFile.CaSign; DscExpiryDate = clientFile.DscExpiryDate; FileStatus = clientFile.FileStatus; } public string Id { get; set; } public int FileNumber { get; set; } public string ClientName { get; set; } public string ClientContactPerson { get; set; } public string AssociateReponsible { get; set; } public string CaSign { get; set; } public string DscExpiryDate { get; set; } public string FileStatus { get; set; } public string UserName { get; set; } public FileStatusModification InitialFileStatus { get; set; } } }
vishipayyallore/CAAssitant
CAAssistant/Models/ClientFileViewModel.cs
C#
mit
1,131
<?php /**************************************************************************** * todoyu is published under the BSD License: * http://www.opensource.org/licenses/bsd-license.php * * Copyright (c) 2013, snowflake productions GmbH, Switzerland * All rights reserved. * * This script is part of the todoyu project. * The todoyu project is free software; you can redistribute it and/or modify * it under the terms of the BSD License. * * This script 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 BSD License * for more details. * * This copyright notice MUST APPEAR in all copies of the script. *****************************************************************************/ /** * Task asset object * * @package Todoyu * @subpackage Assets */ class TodoyuAssetsTaskAsset extends TodoyuAssetsAsset { /** * Get task ID * * @return Integer */ public function getTaskID() { return $this->getParentID(); } /** * Get task object * * @return Task */ public function getTask() { return TodoyuProjectTaskManager::getTask($this->getTaskID()); } } ?>
JoAutomation/todo-for-you
ext/assets/model/TodoyuAssetsTaskAsset.class.php
PHP
mit
1,210
<?php namespace IdeHelper\Test\TestCase\Utility; use Cake\Core\Configure; use Cake\TestSuite\TestCase; use IdeHelper\Utility\Plugin; class PluginTest extends TestCase { /** * @return void */ protected function setUp(): void { parent::setUp(); Configure::delete('IdeHelper.plugins'); } /** * @return void */ protected function tearDown(): void { parent::tearDown(); Configure::delete('IdeHelper.plugins'); } /** * @return void */ public function testAll() { $result = Plugin::all(); $this->assertArrayHasKey('IdeHelper', $result); $this->assertArrayHasKey('Awesome', $result); $this->assertArrayHasKey('MyNamespace/MyPlugin', $result); $this->assertArrayNotHasKey('FooBar', $result); Configure::write('IdeHelper.plugins', ['FooBar', '-MyNamespace/MyPlugin']); $result = Plugin::all(); $this->assertArrayHasKey('FooBar', $result); $this->assertArrayNotHasKey('MyNamespace/MyPlugin', $result); } }
dereuromark/cakephp-ide-helper
tests/TestCase/Utility/PluginTest.php
PHP
mit
953
<?php /** * The Initial Developer of the Original Code is * Tarmo Alexander Sundström <ta@sundstrom.im>. * * Portions created by the Initial Developer are * Copyright (C) 2014 Tarmo Alexander Sundström <ta@sundstrom.im> * * All Rights Reserved. * * Contributor(s): * * 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. */ namespace Webvaloa; use Libvaloa\Db; use RuntimeException; /** * Manage and run plugins. */ class Plugin { private $db; private $plugins; private $runnablePlugins; private $plugin; // Objects that plugins can access public $_properties; public $ui; public $controller; public $request; public $view; public $xhtml; public static $properties = array( // Vendor tag 'vendor' => 'ValoaApplication', // Events 'events' => array( 'onAfterFrontControllerInit', 'onBeforeController', 'onAfterController', 'onBeforeRender', 'onAfterRender', ), // Skip plugins in these controllers 'skipControllers' => array( 'Setup', ), ); public function __construct($plugin = false) { $this->plugin = $plugin; $this->event = false; $this->plugins = false; $this->runnablePlugins = false; // Plugins can access and modify these $this->_properties = false; $this->ui = false; $this->controller = false; $this->request = false; $this->view = false; $this->xhtml = false; try { $this->db = \Webvaloa\Webvaloa::DBConnection(); } catch (Exception $e) { } } public function setEvent($e) { if (in_array($e, self::$properties['events'])) { $this->event = $e; } } public function plugins() { if (!method_exists($this->db, 'prepare')) { // Just bail out return false; } if (method_exists($this->request, 'getMainController') && (in_array($this->request->getMainController(), self::$properties['skipControllers']))) { return false; } $query = ' SELECT id, plugin, system_plugin FROM plugin WHERE blocked = 0 ORDER BY ordering ASC'; try { $stmt = $this->db->prepare($query); $stmt->execute(); $this->plugins = $stmt->fetchAll(); return $this->plugins; } catch (PDOException $e) { } } public function pluginExists($name) { $name = trim($name); foreach ($this->plugins as $k => $plugin) { if ($plugin->plugin == $name) { return true; } } return false; } public function hasRunnablePlugins() { // Return runnable plugins if we already gathered them if ($this->runnablePlugins) { return $this->runnablePlugins; } if (!$this->request) { throw new RuntimeException('Instance of request is required'); } if (in_array($this->request->getMainController(), self::$properties['skipControllers'])) { return false; } // Load plugins if (!$this->plugins) { $this->plugins(); } if (!is_array($this->plugins)) { return false; } $controller = $this->request->getMainController(); // Look for executable plugins foreach ($this->plugins as $k => $plugin) { if ($controller && strpos($plugin->plugin, $controller) === false && strpos($plugin->plugin, 'Plugin') === false) { continue; } $this->runnablePlugins[] = $plugin; } return (bool) ($this->runnablePlugins && !empty($this->runnablePlugins)) ? $this->runnablePlugins : false; } public function runPlugins() { if (!$this->runnablePlugins || empty($this->runnablePlugins)) { return false; } $e = $this->event; foreach ($this->runnablePlugins as $k => $v) { $p = '\\'.self::$properties['vendor'].'\Plugins\\'.$v->plugin.'Plugin'; $plugin = new $p(); $plugin->view = &$this->view; $plugin->ui = &$this->ui; $plugin->request = &$this->request; $plugin->controller = &$this->controller; $plugin->xhtml = &$this->xhtml; $plugin->_properties = &$this->_properties; if (method_exists($plugin, $e)) { $plugin->{$e}(); } } } public static function getPluginStatus($pluginID) { $query = ' SELECT blocked FROM plugin WHERE system_plugin = 0 AND id = ?'; try { $db = \Webvaloa\Webvaloa::DBConnection(); $stmt = $db->prepare($query); $stmt->set((int) $pluginID); $stmt->execute(); $row = $stmt->fetch(); if (isset($row->blocked)) { return $row->blocked; } return false; } catch (PDOException $e) { } } public static function setPluginStatus($pluginID, $status = 0) { $query = ' UPDATE plugin SET blocked = ? WHERE id = ?'; try { $db = \Webvaloa\Webvaloa::DBConnection(); $stmt = $db->prepare($query); $stmt->set((int) $status); $stmt->set((int) $pluginID); $stmt->execute(); } catch (PDOException $e) { } } public static function setPluginOrder($pluginID, $ordering = 0) { $query = ' UPDATE plugin SET ordering = ? WHERE id = ?'; try { $db = \Webvaloa\Webvaloa::DBConnection(); $stmt = $db->prepare($query); $stmt->set((int) $ordering); $stmt->set((int) $pluginID); $stmt->execute(); } catch (PDOException $e) { } } public function install() { if (!$this->plugin) { return false; } $installable = $this->discover(); if (!in_array($this->plugin, $installable)) { return false; } $db = \Webvaloa\Webvaloa::DBConnection(); // Install plugin $object = new Db\Object('plugin', $db); $object->plugin = $this->plugin; $object->system_plugin = 0; $object->blocked = 0; $object->ordering = 1; $id = $object->save(); return $id; } public function uninstall() { if (!$this->plugin) { return false; } $db = \Webvaloa\Webvaloa::DBConnection(); $query = ' DELETE FROM plugin WHERE system_plugin = 0 AND plugin = ?'; $stmt = $db->prepare($query); try { $stmt->set($this->plugin); $stmt->execute(); return true; } catch (Exception $e) { } return false; } public function discover() { // Installed plugins $tmp = $this->plugins(); foreach ($tmp as $v => $plugin) { $plugins[] = $plugin->plugin; } // Discovery paths $paths[] = LIBVALOA_INSTALLPATH.DIRECTORY_SEPARATOR.self::$properties['vendor'].DIRECTORY_SEPARATOR.'Plugins'; $paths[] = LIBVALOA_EXTENSIONSPATH.DIRECTORY_SEPARATOR.self::$properties['vendor'].DIRECTORY_SEPARATOR.'Plugins'; $skip = array( '.', '..', ); $plugins = array_merge($plugins, $skip); // Look for new plugins foreach ($paths as $path) { if ($handle = opendir($path)) { while (false !== ($entry = readdir($handle))) { if ($entry == '.' || $entry == '..') { continue; } if (substr($entry, -3) != 'php') { continue; } $pluginName = str_replace('Plugin.php', '', $entry); if (!isset($installablePlugins)) { $installablePlugins = array(); } if (!in_array($pluginName, $plugins) && !in_array($pluginName, $installablePlugins)) { $installablePlugins[] = $pluginName; } } closedir($handle); } } if (isset($installablePlugins)) { return $installablePlugins; } return array(); } }
lahdekorpi/webvaloa
vendor/Webvaloa/Plugin.php
PHP
mit
9,863
const electron = window.require('electron'); const events = window.require('events'); const { ipcRenderer } = electron; const { EventEmitter } = events; class Emitter extends EventEmitter {} window.Events = new Emitter(); module.exports = () => { let settings = window.localStorage.getItem('settings'); if (settings === null) { const defaultSettings = { general: { launch: true, clipboard: true }, images: { copy: false, delete: true }, notifications: { enabled: true } }; window.localStorage.setItem('settings', JSON.stringify(defaultSettings)); settings = defaultSettings; } ipcRenderer.send('settings', JSON.parse(settings)); };
vevix/focus
app/js/init.js
JavaScript
mit
740
using System; using System.Collections.Generic; using System.Linq; using BohFoundation.ApplicantsRepository.Repositories.Implementations; using BohFoundation.AzureStorage.TableStorage.Implementations.Essay.Entities; using BohFoundation.AzureStorage.TableStorage.Interfaces.Essay; using BohFoundation.AzureStorage.TableStorage.Interfaces.Essay.Helpers; using BohFoundation.Domain.Dtos.Applicant.Essay; using BohFoundation.Domain.Dtos.Applicant.Notifications; using BohFoundation.Domain.Dtos.Common.AzureQueuryObjects; using BohFoundation.Domain.EntityFrameworkModels.Applicants; using BohFoundation.Domain.EntityFrameworkModels.Common; using BohFoundation.Domain.EntityFrameworkModels.Persons; using BohFoundation.EntityFrameworkBaseClass; using BohFoundation.TestHelpers; using EntityFramework.Extensions; using FakeItEasy; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BohFoundation.ApplicantsRepository.Tests.IntegrationTests { [TestClass] public class ApplicantsEssayRepositoryIntegrationTests { private static IEssayRowKeyGenerator _rowKeyGenerator; private static IAzureEssayRepository _azureAzureEssayRepository; private static ApplicantsEssayRepository _applicantsEssayRepository; private static ApplicantsesNotificationRepository _applicantsesNotification; [ClassInitialize] public static void InitializeClass(TestContext ctx) { Setup(); FirstTestOfNotifications(); FirstUpsert(); SecondUpsert(); SecondTestOfNotifications(); } #region SettingUp private static void Setup() { TestHelpersCommonFields.InitializeFields(); TestHelpersCommonFakes.InitializeFakes(); ApplicantsGuid = Guid.NewGuid(); Prompt = "prompt" + ApplicantsGuid; TitleOfEssay = "title" + ApplicantsGuid; _azureAzureEssayRepository = A.Fake<IAzureEssayRepository>(); _rowKeyGenerator = A.Fake<IEssayRowKeyGenerator>(); CreateEssayTopicAndApplicant(); SetupFakes(); _applicantsesNotification = new ApplicantsesNotificationRepository(TestHelpersCommonFields.DatabaseName, TestHelpersCommonFakes.ClaimsInformationGetters, TestHelpersCommonFakes.DeadlineUtilities); _applicantsEssayRepository = new ApplicantsEssayRepository(TestHelpersCommonFields.DatabaseName, TestHelpersCommonFakes.ClaimsInformationGetters, _azureAzureEssayRepository, _rowKeyGenerator); } private static void CreateEssayTopicAndApplicant() { var random = new Random(); GraduatingYear = random.Next(); var subject = new EssayTopic { EssayPrompt = Prompt, TitleOfEssay = TitleOfEssay, RevisionDateTime = DateTime.UtcNow }; var subject2 = new EssayTopic { EssayPrompt = Prompt + 2, TitleOfEssay = TitleOfEssay + 2, RevisionDateTime = DateTime.UtcNow }; var subject3 = new EssayTopic { EssayPrompt = "SHOULD NOT SHOW UP IN LIST", TitleOfEssay = "REALLY SHOULDN't SHOW up", RevisionDateTime = DateTime.UtcNow, }; var graduatingYear = new GraduatingClass { GraduatingYear = GraduatingYear, EssayTopics = new List<EssayTopic> { subject, subject2 } }; var applicant = new Applicant { Person = new Person { Guid = ApplicantsGuid, DateCreated = DateTime.UtcNow }, ApplicantPersonalInformation = new ApplicantPersonalInformation { GraduatingClass = graduatingYear, Birthdate = DateTime.UtcNow, LastUpdated = DateTime.UtcNow } }; using (var context = GetRootContext()) { context.EssayTopics.Add(subject3); context.GraduatingClasses.Add(graduatingYear); context.Applicants.Add(applicant); context.EssayTopics.Add(subject); context.SaveChanges(); EssayTopicId = context.EssayTopics.First(topic => topic.EssayPrompt == Prompt).Id; EssayTopicId2 = context.EssayTopics.First(topic => topic.EssayPrompt == Prompt + 2).Id; } } private static int EssayTopicId2 { get; set; } private static void SetupFakes() { RowKey = "THISISTHEROWKEYFORTHEAPPLICANT"; A.CallTo(() => TestHelpersCommonFakes.ClaimsInformationGetters.GetApplicantsGraduatingYear()) .Returns(GraduatingYear); A.CallTo(() => TestHelpersCommonFakes.ClaimsInformationGetters.GetUsersGuid()).Returns(ApplicantsGuid); A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId)).Returns(RowKey); } private static string RowKey { get; set; } private static int GraduatingYear { get; set; } private static string TitleOfEssay { get; set; } private static string Prompt { get; set; } private static Guid ApplicantsGuid { get; set; } #endregion #region FirstNotifications private static void FirstTestOfNotifications() { FirstNotificationResult = _applicantsesNotification.GetApplicantNotifications(); } private static ApplicantNotificationsDto FirstNotificationResult { get; set; } [TestMethod, TestCategory("Integration")] public void ApplicantsNotificationRepository_FirstGetNotifications_Should_Have_Two_EssayTopics() { Assert.AreEqual(2, FirstNotificationResult.EssayNotifications.Count); } [TestMethod, TestCategory("Integration")] public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_No_LastUpdated() { foreach (var essayTopic in FirstNotificationResult.EssayNotifications) { Assert.IsNull(essayTopic.RevisionDateTime); } } [TestMethod, TestCategory("Integration")] public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_Right_EssayTopic() { foreach (var essayTopic in FirstNotificationResult.EssayNotifications) { if (essayTopic.EssayPrompt == Prompt) { Assert.AreEqual(TitleOfEssay, essayTopic.TitleOfEssay); } else { Assert.AreEqual(TitleOfEssay + 2, essayTopic.TitleOfEssay); } } } [TestMethod, TestCategory("Integration")] public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_Right_Ids() { foreach (var essayTopic in FirstNotificationResult.EssayNotifications) { Assert.AreEqual(essayTopic.EssayPrompt == Prompt ? EssayTopicId : EssayTopicId2, essayTopic.EssayTopicId); } } #endregion #region FirstUpsert private static void FirstUpsert() { Essay = "Essay"; var dto = new EssayDto {Essay = Essay + 1, EssayPrompt = Prompt, EssayTopicId = EssayTopicId}; _applicantsEssayRepository.UpsertEssay(dto); using (var context = GetRootContext()) { EssayUpsertResult1 = context.Essays.First( essay => essay.EssayTopic.Id == EssayTopicId && essay.Applicant.Person.Guid == ApplicantsGuid); } } private static Essay EssayUpsertResult1 { get; set; } private static string Essay { get; set; } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_FirstUpsert_Should_Have_6_Characters() { Assert.AreEqual(6, EssayUpsertResult1.CharacterLength); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Have_RecentUpdated() { TestHelpersTimeAsserts.RecentTime(EssayUpsertResult1.RevisionDateTime); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Have_Correct_RowKey() { Assert.AreEqual(RowKey, EssayUpsertResult1.RowKey); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Have_Correct_PartitionKey() { Assert.AreEqual(GraduatingYear.ToString(), EssayUpsertResult1.PartitionKey); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Positive_Id() { TestHelpersCommonAsserts.IsGreaterThanZero(EssayUpsertResult1.Id); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_FirstUpsert_Should_Call_CreateRowKey() { A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId)).MustHaveHappened(); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_FirstUpsert_Should_Call_UpsertEssay() { //Not checking time. It just isn't coming up. I did an in class check to see if it worked. It did. A.CallTo(() => _azureAzureEssayRepository.UpsertEssay(A<EssayAzureTableEntityDto> .That.Matches(x => x.Essay == Essay + 1 && x.EssayPrompt == Prompt && x.EssayTopicId == EssayTopicId && x.PartitionKey == GraduatingYear.ToString() && x.RowKey == RowKey ))).MustHaveHappened(); } #endregion #region SecondUpsert private static void SecondUpsert() { var dto = new EssayDto {Essay = Essay + Essay + Essay, EssayPrompt = Prompt, EssayTopicId = EssayTopicId}; _applicantsEssayRepository.UpsertEssay(dto); using (var context = GetRootContext()) { EssayUpsertResult2 = context.Essays.First( essay => essay.EssayTopic.Id == EssayTopicId && essay.Applicant.Person.Guid == ApplicantsGuid); } } private static Essay EssayUpsertResult2 { get; set; } private static int EssayTopicId { get; set; } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_SecondUpsert_Should_Have_15_Characters() { Assert.AreEqual(15, EssayUpsertResult2.CharacterLength); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Have_RecentUpdated_More_Recent_Than_First() { TestHelpersTimeAsserts.IsGreaterThanOrEqual(EssayUpsertResult2.RevisionDateTime, EssayUpsertResult1.RevisionDateTime); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Have_Correct_RowKey() { Assert.AreEqual(RowKey, EssayUpsertResult2.RowKey); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Have_Correct_PartitionKey() { Assert.AreEqual(GraduatingYear.ToString(), EssayUpsertResult2.PartitionKey); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Equal_Id_To_First() { Assert.AreEqual(EssayUpsertResult1.Id, EssayUpsertResult2.Id); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_SecondUpsert_Should_Call_CreateRowKey() { A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId)) .MustHaveHappened(Repeated.AtLeast.Times(3)); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_SecondUpsert_Should_Call_UpsertEssay() { //Not checking time. It just isn't coming up. I did an in class check to see if it worked. It did. A.CallTo(() => _azureAzureEssayRepository.UpsertEssay(A<EssayAzureTableEntityDto> .That.Matches(x => x.Essay == Essay + Essay + Essay && x.EssayPrompt == Prompt && x.EssayTopicId == EssayTopicId && x.PartitionKey == GraduatingYear.ToString() && x.RowKey == RowKey ))).MustHaveHappened(); } #endregion #region SecondNotifications private static void SecondTestOfNotifications() { SecondNotificationResult = _applicantsesNotification.GetApplicantNotifications(); } private static ApplicantNotificationsDto SecondNotificationResult { get; set; } [TestMethod, TestCategory("Integration")] public void ApplicantsNotificationRepository_SecondGetNotifications_Should_Have_Two_EssayTopics() { Assert.AreEqual(2, SecondNotificationResult.EssayNotifications.Count); } [TestMethod, TestCategory("Integration")] public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_No_LastUpdated() { foreach (var essayTopic in SecondNotificationResult.EssayNotifications) { if (essayTopic.EssayPrompt == Prompt) { Assert.AreEqual(EssayUpsertResult2.RevisionDateTime, essayTopic.RevisionDateTime); } else { Assert.IsNull(essayTopic.RevisionDateTime); } } } [TestMethod, TestCategory("Integration")] public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_Right_EssayTopic() { foreach (var essayTopic in SecondNotificationResult.EssayNotifications) { if (essayTopic.EssayPrompt == Prompt) { Assert.AreEqual(TitleOfEssay, essayTopic.TitleOfEssay); } else { Assert.AreEqual(TitleOfEssay + 2, essayTopic.TitleOfEssay); } } } [TestMethod, TestCategory("Integration")] public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_Right_Ids() { foreach (var essayTopic in SecondNotificationResult.EssayNotifications) { Assert.AreEqual(essayTopic.EssayPrompt == Prompt ? EssayTopicId : EssayTopicId2, essayTopic.EssayTopicId); } } #endregion #region Utilities private static DatabaseRootContext GetRootContext() { return new DatabaseRootContext(TestHelpersCommonFields.DatabaseName); } [ClassCleanup] public static void CleanDb() { using (var context = new DatabaseRootContext(TestHelpersCommonFields.DatabaseName)) { context.Essays.Where(essay => essay.Id > 0).Delete(); context.EssayTopics.Where(essayTopic => essayTopic.Id > 0).Delete(); context.ApplicantPersonalInformations.Where(info => info.Id > 0).Delete(); context.GraduatingClasses.Where(gradClass => gradClass.Id > 0).Delete(); } } #endregion #region GetEssay [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_GetEssay_Should_Call_CreateRowKeyForEssay() { GetEssay(); A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId)).MustHaveHappened(); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_GetEssay_Should_Call_AzureEssayRepository() { GetEssay(); A.CallTo( () => _azureAzureEssayRepository.GetEssay( A<AzureTableStorageEntityKeyDto>.That.Matches( x => x.PartitionKey == GraduatingYear.ToString() && x.RowKey == RowKey))).MustHaveHappened(); } [TestMethod, TestCategory("Integration")] public void ApplicantsEssayRepository_GetEssay_Should_Return_Whatever_TheAzureRepoReturns() { var essayDto = new EssayDto(); A.CallTo(() => _azureAzureEssayRepository.GetEssay(A<AzureTableStorageEntityKeyDto>.Ignored)) .Returns(essayDto); Assert.AreSame(essayDto, GetEssay()); } private EssayDto GetEssay() { return _applicantsEssayRepository.GetEssay(EssayTopicId); } #endregion } }
Sobieck00/BOH-Bulldog-Scholarship-Application-Management
BohFoundation.ApplicantsRepository.Tests/IntegrationTests/ApplicantsEssayRepositoryIntegrationTests.cs
C#
mit
17,599
class AddAuthorAndSubjectToClaimStateTransitions < ActiveRecord::Migration[4.2] def change add_column :claim_state_transitions, :author_id, :integer add_column :claim_state_transitions, :subject_id, :integer end end
ministryofjustice/advocate-defence-payments
db/migrate/20160909150238_add_author_and_subject_to_claim_state_transitions.rb
Ruby
mit
228
require 'test_helper' require 'cache_value/util' class UtilTest < Test::Unit::TestCase include CacheValue::Util context 'hex_digest' do should 'return the same digest for identical hashes' do hex_digest({ :ha => 'ha'}).should == hex_digest({ :ha => 'ha'}) end end end
tobias/cache_value
test/util_test.rb
Ruby
mit
298
# This migration comes from thinkspace_resource (originally 20150502000000) class AddFingerprintToFile < ActiveRecord::Migration def change add_column :thinkspace_resource_files, :file_fingerprint, :string end end
sixthedge/cellar
packages/opentbl/api/db/migrate/20170511210074_add_fingerprint_to_file.thinkspace_resource.rb
Ruby
mit
222
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_04_01; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; /** * Tags object for patch operations. */ public class TagsObject { /** * Resource tags. */ @JsonProperty(value = "tags") private Map<String, String> tags; /** * Get resource tags. * * @return the tags value */ public Map<String, String> tags() { return this.tags; } /** * Set resource tags. * * @param tags the tags value to set * @return the TagsObject object itself. */ public TagsObject withTags(Map<String, String> tags) { this.tags = tags; return this; } }
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2020_04_01/src/main/java/com/microsoft/azure/management/network/v2020_04_01/TagsObject.java
Java
mit
954
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.common.mixin.core.server.network; import net.minecraft.network.NetworkManager; import net.minecraft.network.login.server.S00PacketDisconnect; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.ServerConfigurationManager; import net.minecraft.server.network.NetHandlerLoginServer; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; import org.apache.logging.log4j.Logger; import org.spongepowered.api.event.cause.NamedCause; import org.spongepowered.api.profile.GameProfile; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.network.RemoteConnection; import org.spongepowered.api.text.Text; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.interfaces.IMixinNetHandlerLoginServer; import org.spongepowered.common.text.SpongeTexts; import java.net.SocketAddress; import java.util.Optional; @Mixin(NetHandlerLoginServer.class) public abstract class MixinNetHandlerLoginServer implements IMixinNetHandlerLoginServer { @Shadow private static Logger logger; @Shadow public NetworkManager networkManager; @Shadow private MinecraftServer server; @Shadow private com.mojang.authlib.GameProfile loginGameProfile; @Shadow public abstract String getConnectionInfo(); @Shadow public abstract com.mojang.authlib.GameProfile getOfflineProfile(com.mojang.authlib.GameProfile profile); @Redirect(method = "tryAcceptPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/management/ServerConfigurationManager;" + "allowUserToConnect(Ljava/net/SocketAddress;Lcom/mojang/authlib/GameProfile;)Ljava/lang/String;")) public String onAllowUserToConnect(ServerConfigurationManager confMgr, SocketAddress address, com.mojang.authlib.GameProfile profile) { return null; // We handle disconnecting } private void closeConnection(IChatComponent reason) { try { logger.info("Disconnecting " + this.getConnectionInfo() + ": " + reason.getUnformattedText()); this.networkManager.sendPacket(new S00PacketDisconnect(reason)); this.networkManager.closeChannel(reason); } catch (Exception exception) { logger.error("Error whilst disconnecting player", exception); } } private void disconnectClient(Optional<Text> disconnectMessage) { IChatComponent reason = null; if (disconnectMessage.isPresent()) { reason = SpongeTexts.toComponent(disconnectMessage.get()); } else { reason = new ChatComponentTranslation("disconnect.disconnected"); } this.closeConnection(reason); } @Override public boolean fireAuthEvent() { Optional<Text> disconnectMessage = Optional.of(Text.of("You are not allowed to log in to this server.")); ClientConnectionEvent.Auth event = SpongeEventFactory.createClientConnectionEventAuth(Cause.of(NamedCause.source(this.loginGameProfile)), disconnectMessage, disconnectMessage, (RemoteConnection) this.networkManager, (GameProfile) this.loginGameProfile); SpongeImpl.postEvent(event); if (event.isCancelled()) { this.disconnectClient(event.getMessage()); } return event.isCancelled(); } @Inject(method = "processLoginStart", at = @At(value = "FIELD", target = "Lnet/minecraft/server/network/NetHandlerLoginServer;" + "currentLoginState:Lnet/minecraft/server/network/NetHandlerLoginServer$LoginState;", opcode = Opcodes.PUTFIELD, ordinal = 1), cancellable = true) public void fireAuthEventOffline(CallbackInfo ci) { // Move this check up here, so that the UUID isn't null when we fire the event if (!this.loginGameProfile.isComplete()) { this.loginGameProfile = this.getOfflineProfile(this.loginGameProfile); } if (this.fireAuthEvent()) { ci.cancel(); } } }
kashike/SpongeCommon
src/main/java/org/spongepowered/common/mixin/core/server/network/MixinNetHandlerLoginServer.java
Java
mit
5,729
from otp.ai.AIBaseGlobal import * import DistributedCCharBaseAI from direct.directnotify import DirectNotifyGlobal from direct.fsm import ClassicFSM, State from direct.fsm import State from direct.task import Task import random from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer import CharStateDatasAI class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI') def __init__(self, air): DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy) self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']), State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']), State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']), State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']), State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off') self.fsm.enterInitialState() self.handleHolidays() def delete(self): self.fsm.requestFinalState() DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self) self.lonelyDoneEvent = None self.lonely = None self.chattyDoneEvent = None self.chatty = None self.walkDoneEvent = None self.walk = None return def generate(self): DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self) name = self.getName() self.lonelyDoneEvent = self.taskName(name + '-lonely-done') self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self) self.chattyDoneEvent = self.taskName(name + '-chatty-done') self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self) self.walkDoneEvent = self.taskName(name + '-walk-done') if self.diffPath == None: self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self) else: self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath) return def walkSpeed(self): return ToontownGlobals.GoofySpeed def start(self): self.fsm.request('Lonely') def __decideNextState(self, doneStatus): if self.transitionToCostume == 1: curWalkNode = self.walk.getDestNode() if simbase.air.holidayManager: if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]: simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self) self.fsm.request('TransitionToCostume') elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]: simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self) self.fsm.request('TransitionToCostume') else: self.notify.warning('transitionToCostume == 1 but no costume holiday') else: self.notify.warning('transitionToCostume == 1 but no holiday Manager') if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done': self.fsm.request('Walk') elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done': self.fsm.request('Walk') elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done': if len(self.nearbyAvatars) > 0: self.fsm.request('Chatty') else: self.fsm.request('Lonely') def enterOff(self): pass def exitOff(self): DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self) def enterLonely(self): self.lonely.enter() self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState) def exitLonely(self): self.ignore(self.lonelyDoneEvent) self.lonely.exit() def __goForAWalk(self, task): self.notify.debug('going for a walk') self.fsm.request('Walk') return Task.done def enterChatty(self): self.chatty.enter() self.acceptOnce(self.chattyDoneEvent, self.__decideNextState) def exitChatty(self): self.ignore(self.chattyDoneEvent) self.chatty.exit() def enterWalk(self): self.notify.debug('going for a walk') self.walk.enter() self.acceptOnce(self.walkDoneEvent, self.__decideNextState) def exitWalk(self): self.ignore(self.walkDoneEvent) self.walk.exit() def avatarEnterNextState(self): if len(self.nearbyAvatars) == 1: if self.fsm.getCurrentState().getName() != 'Walk': self.fsm.request('Chatty') else: self.notify.debug('avatarEnterNextState: in walk state') else: self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars))) def avatarExitNextState(self): if len(self.nearbyAvatars) == 0: if self.fsm.getCurrentState().getName() != 'Walk': self.fsm.request('Lonely') def handleHolidays(self): DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self) if hasattr(simbase.air, 'holidayManager'): if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays: if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState(): self.diffPath = TTLocalizer.Donald return def getCCLocation(self): if self.diffPath == None: return 1 else: return 0 return def enterTransitionToCostume(self): pass def exitTransitionToCostume(self): pass
ksmit799/Toontown-Source
toontown/classicchars/DistributedGoofySpeedwayAI.py
Python
mit
6,450
<?php namespace Rmc\Core\StaticPageBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('rmc_core_static_page'); $rootNode ->children() ->arrayNode('static_page') ->children() ->scalarNode('is_enabled')->end() ->scalarNode('source')->end() ->scalarNode('entity_manager_name')->end() ->scalarNode('entity_class')->end() ->scalarNode('local_feed_path')->defaultFalse()->end() ->end() ->end() ->end(); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
jignesh-russmediatech/rmcdemo
src/Rmc/Core/StaticPageBundle/DependencyInjection/Configuration.php
PHP
mit
1,405
import React from 'react'; import { Link } from 'react-router'; import HotdotActions from '../actions/HotdotActions'; import HotdotObjStore from '../stores/HotdotObjStore'; import MyInfoNavbar from './MyInfoNavbar'; import Weixin from './Weixin'; class Hotdot extends React.Component { constructor(props) { super(props); this.state = HotdotObjStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { HotdotActions.getHotdotDatas(); $(".month-search").hide(); $(".navbar-hotdot").on("touchend",function(){ var index = $(this).index(); if(index==0){ //本周 $(".month-search").hide(); $(".week-search").show(); }else{ //本月 $(".month-search").show(); $(".week-search").hide(); } }); HotdotObjStore.listen(this.onChange); Weixin.getUrl(); Weixin.weixinReady(); } componentWillUnmount() { HotdotObjStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } getUpOrDown(curData,preData,isWeek){ var preDataItem = isWeek ? preData.week:preData.month; if(preData==false || preData == [] || preDataItem==undefined){ return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span> <span className="badge">{curData.value}</span></span>); }else{ for(var i = 0;i < preDataItem.length;i++){ if(preDataItem[i].word == curData.word){ if(preDataItem[i].value < curData.value){ return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span> <span className="badge">{curData.value}</span></span>); }else{ return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-down"></span> <span className="badge" style={{backgroundColor:"#4F81E3"}}>{curData.value}</span></span>); } } } } return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span> <span className="badge">{curData.value}</span></span>); } render() { var hotdotData = (this.state.data); var firstHotData = hotdotData[0]; var preHotData ; if(hotdotData.length > 7){ preHotData = hotdotData[7]; }else{ preHotData = []; } if(firstHotData){ var weekList = firstHotData.week.map((weekItem,i)=>( <li className="list-group-item" key={i}> {this.getUpOrDown(weekItem,preHotData,true)} {weekItem.word} </li> )); if(weekList.length==0){ weekList = <div className = "noData">数据还没有准备好,要不去其他页面瞅瞅?</div> } var monthList = firstHotData.month.map((monthItem,i)=>( <li className="list-group-item" key={i}> {this.getUpOrDown(monthItem,preHotData,false)} {monthItem.word} </li> )); if(monthList.length==0){ monthList = <div className = "noData">Whops,这个页面的数据没有准备好,去其他页面瞅瞅?</div> } }else{ var weekList = (<span>正在构建,敬请期待...</span>); var monthList = (<span>正在构建,敬请期待...</span>); } return (<div> <div className="content-container"> <div className="week-search"> <div className="panel panel-back"> <div className="panel-heading"> <span className="panel-title">本周关键字排行榜</span> <div className="navbar-key-container"> <span className="navbar-hotdot navbar-week navbar-hotdot-active">本周</span> <span className="navbar-hotdot navbar-month">本月</span> </div> </div> <div className="panel-body"> <ul className="list-group"> {weekList} </ul> </div> </div> </div> <div className="month-search"> <div className="panel panel-back"> <div className="panel-heading"> <span className="panel-title">本月关键字排行榜</span> <div className="navbar-key-container"> <span className="navbar-hotdot navbar-week">本周</span> <span className="navbar-hotdot navbar-month navbar-hotdot-active">本月</span> </div> </div> <div className="panel-body"> <ul className="list-group"> {monthList} </ul> </div> </div> </div> </div> </div>); } } export default Hotdot;
kongchun/BigData-Web
app/m_components/Hotdot.js
JavaScript
mit
5,621
<?php namespace PayU\Api\Response\Builder; use PayU\Api\Request\RequestInterface; use PayU\Api\Response\AbstractResponse; use Psr\Http\Message\ResponseInterface; /** * Interface BuilderInterface * * Provides a common interface to build response objects based on request context * * @package PayU\Api\Response\Builder * @author Lucas Mendes <devsdmf@gmail.com> */ interface BuilderInterface { /** * Build a response object * * @param RequestInterface $request * @param ResponseInterface $response * @param string $context * @return AbstractResponse */ public function build(RequestInterface $request, ResponseInterface $response, $context = null); }
devsdmf/payu-php-sdk
src/PayU/Api/Response/Builder/BuilderInterface.php
PHP
mit
713
using SolrExpress.Search.Parameter; using System; using System.Globalization; using System.Linq; using System.Text; namespace SolrExpress.Utility { /// <summary> /// Helper class used to extract information inside parameters /// </summary> internal static class ParameterUtil { /// <summary> /// Get the sort type and direction /// </summary> /// <param name="solrFacetSortType">Type used in match</param> /// <param name="typeName">Type name</param> /// <param name="sortName">Sort direction</param> public static void GetFacetSort(FacetSortType solrFacetSortType, out string typeName, out string sortName) { switch (solrFacetSortType) { case FacetSortType.IndexAsc: typeName = "index"; sortName = "asc"; break; case FacetSortType.IndexDesc: typeName = "index"; sortName = "desc"; break; case FacetSortType.CountAsc: typeName = "count"; sortName = "asc"; break; case FacetSortType.CountDesc: typeName = "count"; sortName = "desc"; break; default: throw new ArgumentException(nameof(solrFacetSortType)); } } /// <summary> /// Calculate and returns spatial formule /// </summary> /// <param name="fieldName">Field name</param> /// <param name="functionType">Function used in spatial filter</param> /// <param name="centerPoint">Center point to spatial filter</param> /// <param name="distance">Distance from center point</param> /// <returns>Spatial formule</returns> internal static string GetSpatialFormule(string fieldName, SpatialFunctionType functionType, GeoCoordinate centerPoint, decimal distance) { var functionTypeStr = functionType.ToString().ToLower(); var latitude = centerPoint.Latitude.ToString("G", CultureInfo.InvariantCulture); var longitude = centerPoint.Longitude.ToString("G", CultureInfo.InvariantCulture); var distanceStr = distance.ToString("G", CultureInfo.InvariantCulture); return $"{{!{functionTypeStr} sfield={fieldName} pt={latitude},{longitude} d={distanceStr}}}"; } /// <summary> /// Get the field with excludes /// </summary> /// <param name="excludes">Excludes tags</param> /// <param name="aliasName">Alias name</param> /// <param name="fieldName">Field name</param> internal static string GetFacetName(string[] excludes, string aliasName, string fieldName) { var sb = new StringBuilder(); var needsBraces = (excludes?.Any() ?? false) || !string.IsNullOrWhiteSpace(aliasName); if (needsBraces) { sb.Append("{!"); } if (excludes?.Any() ?? false) { sb.Append($"ex={string.Join(",", excludes)}"); } if (sb.Length > 2) { sb.Append(" "); } if (!string.IsNullOrWhiteSpace(aliasName)) { sb.Append($"key={aliasName}"); } if (needsBraces) { sb.Append("}"); } sb.Append(fieldName); return sb.ToString(); } /// <summary> /// Get the filter with tag /// </summary> /// <param name="query">Query value</param> /// <param name="aliasName">Alias name</param> public static string GetFilterWithTag(string query, string aliasName) { return !string.IsNullOrWhiteSpace(aliasName) ? $"{{!tag={aliasName}}}{query}" : query; } } }
solr-express/solr-express
src/SolrExpress/Utility/ParameterUtil.cs
C#
mit
4,034
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'babel-polyfill'; import ReactDOM from 'react-dom'; import React from 'react'; import FastClick from 'fastclick'; import Router from './routes'; import Location from './core/Location'; import { addEventListener, removeEventListener } from './core/DOMUtils'; import { ApolloClient, createNetworkInterface } from 'react-apollo'; function getCookie(name) { let value = "; " + document.cookie; let parts = value.split("; " + name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } const networkInterface = createNetworkInterface('/graphql', { credentials: 'same-origin', uri: '/graphql', headers: { Cookie: getCookie("id_token") } }); const client = new ApolloClient({ connectToDevTools: true, networkInterface: networkInterface, }); let cssContainer = document.getElementById('css'); const appContainer = document.getElementById('app'); const context = { insertCss: styles => styles._insertCss(), onSetTitle: value => (document.title = value), onSetMeta: (name, content) => { // Remove and create a new <meta /> tag in order to make it work // with bookmarks in Safari const elements = document.getElementsByTagName('meta'); Array.from(elements).forEach((element) => { if (element.getAttribute('name') === name) { element.parentNode.removeChild(element); } }); const meta = document.createElement('meta'); meta.setAttribute('name', name); meta.setAttribute('content', content); document .getElementsByTagName('head')[0] .appendChild(meta); }, client }; // Google Analytics tracking. Don't send 'pageview' event after the first // rendering, as it was already sent by the Html component. let trackPageview = () => (trackPageview = () => window.ga('send', 'pageview')); function render(state) { Router.dispatch(state, (newState, component) => { ReactDOM.render( component, appContainer, () => { // Restore the scroll position if it was saved into the state if (state.scrollY !== undefined) { window.scrollTo(state.scrollX, state.scrollY); } else { window.scrollTo(0, 0); } trackPageview(); // Remove the pre-rendered CSS because it's no longer used // after the React app is launched if (cssContainer) { cssContainer.parentNode.removeChild(cssContainer); cssContainer = null; } }); }); } function run() { let currentLocation = null; let currentState = null; // Make taps on links and buttons work fast on mobiles FastClick.attach(document.body); // Re-render the app when window.location changes const unlisten = Location.listen(location => { currentLocation = location; currentState = Object.assign({}, location.state, { path: location.pathname, query: location.query, state: location.state, context, }); render(currentState); }); // Save the page scroll position into the current location's state const supportPageOffset = window.pageXOffset !== undefined; const isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat'); const setPageOffset = () => { currentLocation.state = currentLocation.state || Object.create(null); if (supportPageOffset) { currentLocation.state.scrollX = window.pageXOffset; currentLocation.state.scrollY = window.pageYOffset; } else { currentLocation.state.scrollX = isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft; currentLocation.state.scrollY = isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop; } }; addEventListener(window, 'scroll', setPageOffset); addEventListener(window, 'pagehide', () => { removeEventListener(window, 'scroll', setPageOffset); unlisten(); }); } // Run the application when both DOM is ready and page content is loaded if (['complete', 'loaded', 'interactive'].includes(document.readyState) && document.body) { run(); } else { document.addEventListener('DOMContentLoaded', run, false); }
reicheltp/Sonic
src/client.js
JavaScript
mit
4,372
var $M = require("@effectful/debugger"), $x = $M.context, $ret = $M.ret, $unhandled = $M.unhandled, $brk = $M.brk, $lset = $M.lset, $mcall = $M.mcall, $m = $M.module("file.js", null, typeof module === "undefined" ? null : module, null, "$", { __webpack_require__: typeof __webpack_require__ !== "undefined" && __webpack_require__ }, null), $s$1 = [{ e: [1, "1:9-1:10"] }, null, 0], $s$2 = [{}, $s$1, 1], $m$0 = $M.fun("m$0", "file.js", null, null, [], 0, 2, "1:0-4:0", 32, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $lset($l, 1, $m$1($)); $.goto = 2; continue; case 1: $.goto = 2; return $unhandled($.error); case 2: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 0, [[0, "1:0-3:1", $s$1], [16, "4:0-4:0", $s$1], [16, "4:0-4:0", $s$1]]), $m$1 = $M.fun("m$1", "e", null, $m$0, [], 0, 2, "1:0-3:1", 0, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; $p = ($x.call = eff)(1); $.state = 2; case 2: $l[1] = $p; $.goto = 3; $p = ($x.call = eff)(2); $.state = 3; case 3: $.goto = 4; $mcall("log", console, $l[1] + $p); $.state = 4; case 4: $.goto = 6; $brk(); continue; case 5: $.goto = 6; return $unhandled($.error); case 6: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 1, [[4, "2:2-2:31", $s$2], [2, "2:14-2:20", $s$2], [2, "2:23-2:29", $s$2], [2, "2:2-2:30", $s$2], [36, "3:1-3:1", $s$2], [16, "3:1-3:1", $s$2], [16, "3:1-3:1", $s$2]]); $M.moduleExports();
awto/effectfuljs
packages/core/test/samples/simple/expr/test04-out-ds.js
JavaScript
mit
1,801
module Shiphawk module Api # Company API # # @see https://shiphawk.com/api-docs # # The following API actions provide the CRUD interface to managing a shipment's tracking. # module ShipmentsStatus def shipments_status_update options put_request status_path, options end end end end
ShipHawk/shiphawk-ruby
lib/shiphawk/api/shipments_status.rb
Ruby
mit
342
import "bootstrap-slider"; import "bootstrap-switch"; export module profile { function onInfoSubmit() { var params: { [key: string]: string } = {}; $("#info-container .info-field").each(function() { let name: string = this.getAttribute("name"); if (name == null) { return; } let value: string = $(this).val(); if ($(this).hasClass("info-slider")) { let valueTokens: string[] = this.getAttribute("data-value").split(","); name = name.substring(0, 1).toUpperCase() + name.substring(1); params["min" + name] = valueTokens[0]; params["max" + name] = valueTokens[1]; return; } else if (this.getAttribute("type") == "checkbox") { value = (this.checked ? 1 : 0).toString(); } params[name] = value; }); $.post("/office/post/update-profile", params, function(data) { $("#errors").addClass("hidden"); $("#success").removeClass("hidden"); window.scrollTo(0, 0); }, "json").fail(function(err) { $("#success").addClass("hidden"); $("#errors").text(`Error code ${err.status} occurred. Please contact a developer.`); $("#errors").removeClass("hidden"); window.scrollTo(0, 0); }); } $(document).ready(function() { (<any>$("#hours-slider")).bootstrapSlider({}); $("input.info-field[type='text']").on("keydown", function(evt) { if (evt.which == 13) { onInfoSubmit.apply(this); } }); $("input.info-field[type='checkbox']").each(function(index: number, element: HTMLElement) { let $element: JQuery = $(element); $element.bootstrapSwitch({ "state": $element.prop("checked") }); }); $("button.iu-button[type='submit']").on("click", onInfoSubmit); }); }
crossroads-education/eta-office
static/js/profile.ts
TypeScript
mit
2,030
// Copyright (c) 2020 Uber Technologies, Inc. // // 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 main import ( "context" "os" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/uber-go/dosa" "github.com/uber-go/dosa/mocks" ) func TestQuery_ServiceDefault(t *testing.T) { tcs := []struct { serviceName string expected string }{ // service = "" -> default { expected: _defServiceName, }, // service = "foo" -> foo { serviceName: "foo", expected: "foo", }, } for _, tc := range tcs { for _, cmd := range []string{"read", "range"} { os.Args = []string{ "dosa", "--service", tc.serviceName, "query", cmd, "--namePrefix", "foo", "--scope", "bar", "--path", "../../testentity", "TestEntity", "StrKey:eq:foo", } main() assert.Equal(t, tc.expected, options.ServiceName) } } } func TestQuery_Read_Happy(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mc := mocks.NewMockConnector(ctrl) mc.EXPECT().Read(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Do(func(_ context.Context, ei *dosa.EntityInfo, keys map[string]dosa.FieldValue, minimumFields []string) { assert.NotNil(t, ei) assert.Equal(t, dosa.FieldValue("foo"), keys["strkey"]) assert.Equal(t, []string{"strkey", "int64key"}, minimumFields) }).Return(map[string]dosa.FieldValue{}, nil).MinTimes(1) mc.EXPECT().Shutdown().Return(nil) table, err := dosa.FindEntityByName("../../testentity", "TestEntity") assert.NoError(t, err) reg, err := newSimpleRegistrar(scope, namePrefix, table) assert.NoError(t, err) provideClient := func(opts GlobalOptions, scope, prefix, path, structName string) (ShellQueryClient, error) { return newShellQueryClient(reg, mc), nil } queryRead := QueryRead{ QueryCmd: &QueryCmd{ QueryOptions: &QueryOptions{ Fields: "StrKey,Int64Key", }, Scope: scopeFlag("scope"), NamePrefix: "foo", Path: "../../testentity", provideClient: provideClient, }, } queryRead.Args.EntityName = "TestEntity" queryRead.Args.Queries = []string{"StrKey:eq:foo"} err = queryRead.Execute([]string{}) assert.NoError(t, err) } func TestQuery_Range_Happy(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mc := mocks.NewMockConnector(ctrl) mc.EXPECT().Range(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Do(func(_ context.Context, ei *dosa.EntityInfo, columnConditions map[string][]*dosa.Condition, minimumFields []string, token string, limit int) { assert.NotNil(t, ei) assert.Len(t, columnConditions, 1) assert.Len(t, columnConditions["int64key"], 1) assert.Equal(t, []string{"strkey", "int64key"}, minimumFields) }).Return([]map[string]dosa.FieldValue{{"key": "value"}}, "", nil) mc.EXPECT().Shutdown().Return(nil) table, err := dosa.FindEntityByName("../../testentity", "TestEntity") assert.NoError(t, err) reg, err := newSimpleRegistrar(scope, namePrefix, table) assert.NoError(t, err) provideClient := func(opts GlobalOptions, scope, prefix, path, structName string) (ShellQueryClient, error) { return newShellQueryClient(reg, mc), nil } queryRange := QueryRange{ QueryCmd: &QueryCmd{ QueryOptions: &QueryOptions{ Fields: "StrKey,Int64Key", }, Scope: scopeFlag("scope"), NamePrefix: "foo", Path: "../../testentity", provideClient: provideClient, }, } queryRange.Args.EntityName = "TestEntity" queryRange.Args.Queries = []string{"Int64Key:lt:200"} err = queryRange.Execute([]string{}) assert.NoError(t, err) } func TestQuery_NewQueryObj(t *testing.T) { qo := newQueryObj("StrKey", "eq", "foo") assert.NotNil(t, qo) assert.Equal(t, "StrKey", qo.fieldName) assert.Equal(t, "eq", qo.op) assert.Equal(t, "foo", qo.valueStr) } func TestQuery_ScopeRequired(t *testing.T) { for _, cmd := range []string{"read", "range"} { c := StartCapture() exit = func(r int) {} os.Args = []string{ "dosa", "query", cmd, "--namePrefix", "foo", "--path", "../../testentity", "TestEntity", "StrKey:eq:foo", } main() assert.Contains(t, c.stop(true), "-s, --scope' was not specified") } } func TestQuery_PrefixRequired(t *testing.T) { for _, cmd := range []string{"read", "range"} { c := StartCapture() exit = func(r int) {} os.Args = []string{ "dosa", "query", cmd, "--scope", "foo", "--path", "../../testentity", "TestEntity", "StrKey:eq:foo", } main() assert.Contains(t, c.stop(true), "--namePrefix' was not specified") } } func TestQuery_PathRequired(t *testing.T) { for _, cmd := range []string{"read", "range"} { c := StartCapture() exit = func(r int) {} os.Args = []string{ "dosa", "query", cmd, "--scope", "foo", "--namePrefix", "foo", "StrKey:eq:foo", } main() assert.Contains(t, c.stop(true), "--path' was not specified") } } func TestQuery_NoEntityFound(t *testing.T) { for _, cmd := range []string{"read", "range"} { c := StartCapture() exit = func(r int) {} os.Args = []string{ "dosa", "query", cmd, "--scope", "foo", "--namePrefix", "foo", "--path", "../../testentity", "TestEntity1", "StrKey:eq:foo", } main() assert.Contains(t, c.stop(true), "no entity named TestEntity1 found") } }
uber-go/dosa
cmd/dosa/query_test.go
GO
mit
6,402
<?php // This file is an extension of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. defined('MOODLE_INTERNAL') || die(); /** * Plugin details * * @package filter * @subpackage podlille * @copyright 2014-2016 Gaël Mifsud / SEMM Université Lille1 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later / MIT / Public Domain */ $plugin->component = 'filter_podlille1'; // Full name of the plugin (used for diagnostics) $plugin->version = 2016011101; // The current plugin version (Date: YYYYMMDDXX) $plugin->requires = 2013111800; // Requires this Moodle version $plugin->release = '1.0.3'; // Human-friendly version name http://docs.moodle.org/dev/Releases $plugin->maturity = MATURITY_STABLE; // This version's maturity level
SemmLille/filter_podlille1
version.php
PHP
mit
1,422
<?php $this->load->Model('exam/Exam_manager_model'); $this->load->model('Branch/Course_model'); $exams = $this->Exam_manager_model->exam_details(); $exam_type = $this->Exam_manager_model->get_all_exam_type(); $branch = $this->Course_model->order_by_column('c_name'); ?> <div class="row"> <div class=col-lg-12> <!-- col-lg-12 start here --> <div class="panel-default toggle panelMove panelClose panelRefresh"></div> <div class=panel-body> <?php echo form_open(base_url() . 'exam/internal_create', array('class' => 'form-horizontal form-groups-bordered validate', 'role' => 'form', 'id' => 'examform', 'target' => '_top')); ?> <div class="padded"> <div class="form-group"> <label class="col-sm-4 control-label"><?php echo ucwords("Branch"); ?><span style="color:red">*</span></label> <div class="col-sm-8"> <select class="form-control" name="course" id="course"> <?php foreach ($branch as $course): ?> <option value="<?php echo $course->course_id; ?>"><?php echo $course->c_name; ?></option> <?php endforeach; ?> </select> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label"><?php echo ucwords("Semester"); ?><span style="color:red">*</span></label> <div class="col-sm-8"> <select class="form-control" name="semester" id="semester"> </select> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label"><?php echo ucwords("Subejct"); ?><span style="color:red">*</span></label> <div class="col-sm-8"> <select class="form-control" name="subject" id="subject"> </select> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label"><?php echo ucwords("Title"); ?><span style="color:red">*</span></label> <div class="col-sm-8"> <input type="text" class="form-control" name="exam_name" id="exam_name" value="<?php echo set_value('exam_name'); ?>"/> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label"><?php echo ucwords("Total Marks"); ?><span style="color:red">*</span></label> <div class="col-sm-8"> <input type="number" class="form-control" name="total_marks" id="total_marks" min="0" value="<?php echo set_value('total_marks'); ?>"/> </div> </div> <div class="form-group"> <div class="col-sm-offset-4 col-sm-8"> <button type="submit" class="btn btn-info vd_bg-green"><?php echo ucwords("Add"); ?></button> </div> </div> <?php echo form_close(); ?> </div> </div> <!-- End .panel --> </div> <!-- col-lg-12 end here --> </div> <script> $(document).ready(function () { var js_date_format = '<?php echo js_dateformat(); ?>'; var date = ''; var start_date = ''; $('#edit_start_date').datepicker({ format: js_date_format, startDate: new Date(), autoclose: true, todayHighlight: true, }); $('#edit_start_date').on('change', function () { date = new Date($(this).val()); start_date = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear(); console.log(start_date); setTimeout(function () { $("#edit_end_date_time").datepicker({ format: js_date_format, autoclose: true, startDate: start_date }); }, 700); }); }) </script> <script type="text/javascript"> $.validator.setDefaults({ submitHandler: function (form) { form.submit(); } }); $().ready(function () { $("#examform").validate({ rules: { course: "required", semester: "required", subject:"required", exam_name:"required", total_marks: "required" }, messages: { course: "Select branch", semester: "Select semester", subject:"Select subject", exam_name:"Enter title", total_marks: "Enter total marks", } }); }); </script> <script> $(document).ready(function () { //course by degree $('#degree').on('change', function () { var course_id = $('#course').val(); var degree_id = $(this).val(); //remove all present element $('#course').find('option').remove().end(); $('#course').append('<option value="">Select</option>'); var degree_id = $(this).val(); $.ajax({ url: '<?php echo base_url(); ?>branch/department_branch/' + degree_id, type: 'get', success: function (content) { var course = jQuery.parseJSON(content); $.each(course, function (key, value) { $('#course').append('<option value=' + value.course_id + '>' + value.c_name + '</option>'); }) } }) batch_from_degree_and_course(degree_id, course_id); }); //batch from course and degree $('#course').on('change', function () { var course_id = $(this).val(); get_semester_from_branch(course_id); }) //find batch from degree and course function batch_from_degree_and_course(degree_id, course_id) { //remove all element from batch $('#batch').find('option').remove().end(); $.ajax({ url: '<?php echo base_url(); ?>batch/department_branch_batch/' + degree_id + '/' + course_id, type: 'get', success: function (content) { $('#batch').append('<option value="">Select</option>'); var batch = jQuery.parseJSON(content); console.log(batch); $.each(batch, function (key, value) { $('#batch').append('<option value=' + value.b_id + '>' + value.b_name + '</option>'); }) } }) } function get_subject_from_branch_semester(course_id,semester_id) { $('#subject').find('option').remove().end(); $.ajax({ url: '<?php echo base_url(); ?>subject/subejct_list_branch_sem/' + course_id +'/'+semester_id, type: 'get', success: function (content) { $('#subject').append('<option value="">Select</option>'); var subject = jQuery.parseJSON(content); $.each(subject, function (key, value) { $('#subject').append('<option value=' + value.sm_id + '>' + value.subject_name + '</option>'); }) } }) } //get semester from brach function get_semester_from_branch(branch_id) { $('#semester').find('option').remove().end(); $.ajax({ url: '<?php echo base_url(); ?>semester/semester_branch/' + branch_id, type: 'get', success: function (content) { $('#semester').append('<option value="">Select</option>'); var semester = jQuery.parseJSON(content); $.each(semester, function (key, value) { $('#semester').append('<option value=' + value.s_id + '>' + value.s_name + '</option>'); }) } }) } $("#semester").change(function(){ var course_id = $("#course").val(); var semester_id = $(this).val(); get_subject_from_branch_semester(course_id,semester_id); }); }) </script> <script> $(document).ready(function () { $('#total_marks').on('blur', function () { var total_marks = $(this).val(); $('#passing_marks').attr('max', total_marks); $('#passing_marks').attr('required', ''); }); $('#passing_marks').on('focus', function () { var total_marks = $('#total_marks').val(); $(this).attr('max', total_marks); }) }) </script> <script> $(document).ready(function () { var date = ''; var start_date = ''; $("#date").datepicker({ format: ' MM dd, yyyy', startDate: new Date(), todayHighlight: true, autoclose: true }); $('#date').on('change', function () { date = new Date($(this).val()); start_date = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear(); console.log(start_date); setTimeout(function () { $("#end_date_time").datepicker({ format: ' MM dd, yyyy', todayHighlight: true, startDate: start_date, autoclose: true, }); }, 700); }); }) </script>
mayursn/lms_hmvc_live
application/modules/exam/views/addinternal.php
PHP
mit
10,084
<?php namespace Augwa\QuickBooks\Model; /** * Master Account is the list of accounts in the master list. The master * list is the complete list of accounts prescribed by the French * Government. These accounts can be created in the company on a need * basis. The account create API needs to be used to create an account. * * Class MasterAccountModel * @package Augwa\QuickBooks\Model */ class MasterAccountModel extends AccountModel { /** * @var bool */ private $AccountExistsInCompany; /** * Product: ALL * Specifies whether the account has been created in the company. * * @return bool */ public function getAccountExistsInCompany() { return $this->AccountExistsInCompany; } /** * Product: ALL * Specifies whether the account has been created in the company. * * @param bool $AccountExistsInCompany * * @return MasterAccountModel */ public function setAccountExistsInCompany( $AccountExistsInCompany ) { $this->AccountExistsInCompany = $AccountExistsInCompany; return $this; } }
augwa/quickbooks-php-sdk
src/Model/MasterAccountModel.php
PHP
mit
1,145
require 'spec_helper' module Gisele module Compiling describe Gisele2Gts, "on_task_def" do before do subject subject.ith_state(0).initial! end subject do code = <<-GIS.strip task Main Hello end GIS Gisele2Gts.compile(code, :root => :task_def) end let :expected do Gts.new do add_state :kind =>:event, :initial => true add_state :kind => :fork add_state :kind => :event add_state :kind => :listen, :accepting => true add_state :kind => :event add_state :kind => :end, :accepting => true add_state :kind => :join, :accepting => true add_state :kind => :event add_state :kind => :end, :accepting => true connect 0, 1, :symbol => :start, :event_args => [ "Main" ] connect 1, 2, :symbol => :"(forked)" connect 2, 3, :symbol => :start, :event_args => [ "Hello" ] connect 3, 4, :symbol => :ended connect 4, 5, :symbol => :end, :event_args => [ "Hello" ] connect 5, 6, :symbol => :"(notify)" connect 1, 6, :symbol => :"(wait)" connect 6, 7, :symbol => nil connect 7, 8, :symbol => :end, :event_args => [ "Main" ] end end it 'generates an equivalent transition system' do subject.bytecode_equivalent!(expected).should be_true end end end end
gisele-tool/gisele-vm
spec/unit/compiling/gisele2gts/test_on_task_def.rb
Ruby
mit
1,476
#include "transactiondesc.h" #include "guiutil.h" #include "lusocoinunits.h" #include "main.h" #include "wallet.h" #include "db.h" #include "ui_interface.h" #include "base58.h" #include <string> QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx) { if (!wtx.IsFinal()) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) return tr("Open for %n more block(s)", "", wtx.nLockTime - nBestHeight + 1); else return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime)); } else { int nDepth = wtx.GetDepthInMainChain(); if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) return tr("%1/offline").arg(nDepth); else if (nDepth < 6) return tr("%1/unconfirmed").arg(nDepth); else return tr("%1 confirmations").arg(nDepth); } } QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx) { QString strHTML; { LOCK(wallet->cs_wallet); strHTML.reserve(4000); strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>"; int64 nTime = wtx.GetTxTime(); int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx); int nRequests = wtx.GetRequestCount(); if (nRequests != -1) { if (nRequests == 0) strHTML += tr(", has not been successfully broadcast yet"); else if (nRequests > 0) strHTML += tr(", broadcast through %n node(s)", "", nRequests); } strHTML += "<br>"; strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>"; // // From // if (wtx.IsCoinBase()) { strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>"; } else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty()) { // Online transaction strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>"; } else { // Offline transaction if (nNet > 0) { // Credit BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if (wallet->IsMine(txout)) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) { if (wallet->mapAddressBook.count(address)) { strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>"; strHTML += "<b>" + tr("To") + ":</b> "; strHTML += GUIUtil::HtmlEscape(CLusocoinAddress(address).ToString()); if (!wallet->mapAddressBook[address].empty()) strHTML += " (" + tr("own address") + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + ")"; else strHTML += " (" + tr("own address") + ")"; strHTML += "<br>"; } } break; } } } } // // To // if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty()) { // Online transaction std::string strAddress = wtx.mapValue["to"]; strHTML += "<b>" + tr("To") + ":</b> "; CTxDestination dest = CLusocoinAddress(strAddress).Get(); if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest]) + " "; strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>"; } // // Amount // if (wtx.IsCoinBase() && nCredit == 0) { // // Coinbase // int64 nUnmatured = 0; BOOST_FOREACH(const CTxOut& txout, wtx.vout) nUnmatured += wallet->GetCredit(txout); strHTML += "<b>" + tr("Credit") + ":</b> "; if (wtx.IsInMainChain()) strHTML += LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")"; else strHTML += "(" + tr("not accepted") + ")"; strHTML += "<br>"; } else if (nNet > 0) { // // Credit // strHTML += "<b>" + tr("Credit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, nNet) + "<br>"; } else { bool fAllFromMe = true; BOOST_FOREACH(const CTxIn& txin, wtx.vin) fAllFromMe = fAllFromMe && wallet->IsMine(txin); bool fAllToMe = true; BOOST_FOREACH(const CTxOut& txout, wtx.vout) fAllToMe = fAllToMe && wallet->IsMine(txout); if (fAllFromMe) { // // Debit // BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if (wallet->IsMine(txout)) continue; if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty()) { // Offline transaction CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { strHTML += "<b>" + tr("To") + ":</b> "; if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " "; strHTML += GUIUtil::HtmlEscape(CLusocoinAddress(address).ToString()); strHTML += "<br>"; } } strHTML += "<b>" + tr("Debit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, -txout.nValue) + "<br>"; } if (fAllToMe) { // Payment to self int64 nChange = wtx.GetChange(); int64 nValue = nCredit - nChange; strHTML += "<b>" + tr("Debit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, -nValue) + "<br>"; strHTML += "<b>" + tr("Credit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, nValue) + "<br>"; } int64 nTxFee = nDebit - wtx.GetValueOut(); if (nTxFee > 0) strHTML += "<b>" + tr("Transaction fee") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, -nTxFee) + "<br>"; } else { // // Mixed debit transaction // BOOST_FOREACH(const CTxIn& txin, wtx.vin) if (wallet->IsMine(txin)) strHTML += "<b>" + tr("Debit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, -wallet->GetDebit(txin)) + "<br>"; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (wallet->IsMine(txout)) strHTML += "<b>" + tr("Credit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, wallet->GetCredit(txout)) + "<br>"; } } strHTML += "<b>" + tr("Net amount") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, nNet, true) + "<br>"; // // Message // if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty()) strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>"; if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty()) strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>"; strHTML += "<b>" + tr("Transaction ID") + ":</b> " + wtx.GetHash().ToString().c_str() + "<br>"; if (wtx.IsCoinBase()) strHTML += "<br>" + tr("Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.") + "<br>"; // // Debug view // if (fDebug) { strHTML += "<hr><br>" + tr("Debug information") + "<br><br>"; BOOST_FOREACH(const CTxIn& txin, wtx.vin) if(wallet->IsMine(txin)) strHTML += "<b>" + tr("Debit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, -wallet->GetDebit(txin)) + "<br>"; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if(wallet->IsMine(txout)) strHTML += "<b>" + tr("Credit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, wallet->GetCredit(txout)) + "<br>"; strHTML += "<br><b>" + tr("Transaction") + ":</b><br>"; strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true); strHTML += "<br><b>" + tr("Inputs") + ":</b>"; strHTML += "<ul>"; { LOCK(wallet->cs_wallet); BOOST_FOREACH(const CTxIn& txin, wtx.vin) { COutPoint prevout = txin.prevout; CCoins prev; if(pcoinsTip->GetCoins(prevout.hash, prev)) { if (prevout.n < prev.vout.size()) { strHTML += "<li>"; const CTxOut &vout = prev.vout[prevout.n]; CTxDestination address; if (ExtractDestination(vout.scriptPubKey, address)) { if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " "; strHTML += QString::fromStdString(CLusocoinAddress(address).ToString()); } strHTML = strHTML + " " + tr("Amount") + "=" + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, vout.nValue); strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) ? tr("true") : tr("false")) + "</li>"; } } } } strHTML += "</ul>"; } strHTML += "</font></html>"; } return strHTML; }
lusocoin/lusocoin
src/src/qt/transactiondesc.cpp
C++
mit
11,484
<?php /** * Orinoco Framework - A lightweight PHP framework. * * Copyright (c) 2008-2015 Ryan Yonzon, http://www.ryanyonzon.com/ * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php */ namespace Orinoco\Framework; use RuntimeException; class View { // layout name public $layout; // Orinoco\Framework\Http class private $http; // Orinoco\Framework\Route class private $route; // Passed controller's variables (to be used by view template) private $variables; // explicit view page private $page_view; /** * Constructor * * @param Http object $http * @param Route object $route * @return void */ public function __construct(Http $http, Route $route) { $this->http = $http; $this->route = $route; } /** * Getter method * * @param Variable name $var_name * @return Variable value */ public function __get($var_name) { if (isset($this->variables[$var_name])) { return $this->variables[$var_name]; } return false; } /** * Set HTML layout * * @param Layout name * @return void */ public function setLayout($layout_name) { $this->layout = $layout_name; } /** * Set page/view template to use * * @param Page/view name Array or String * @return void */ public function setPage($page_view) { // initialize default page view/template $page = array( 'controller' => $this->route->getController(), 'action' => $this->route->getAction() ); // check if passed parameter is an array if (is_array($page_view)) { if (isset($page_view['controller'])) { $page['controller'] = $page_view['controller']; } if (isset($page_view['action'])) { $page['action'] = $page_view['action']; } // string } else if (is_string($page_view)) { $exploded = explode('#', $page_view); // use '#' as separator (we can also use '/') if (count($exploded) > 1) { if (isset($exploded[0])) { $page['controller'] = $exploded[0]; } if (isset($exploded[1])) { $page['action'] = $exploded[1]; } } else { $page['action'] = $page_view; } } $this->page_view = (object) $page; } /** * Render view template/page (including layout) * * @param $page_view Explicit page view/template file * @param $obj_vars Variables to be passed to the layout and page template * @return void */ public function render($page_view = null, $obj_vars = array()) { if (isset($page_view)) { $this->setPage($page_view); } // store variables (to be passed to the layout and page template) // accessible via '__get' method $this->variables = $obj_vars; // check if layout is defined if(isset($this->layout)) { $layout_file = APPLICATION_LAYOUT_DIR . str_replace(PHP_FILE_EXTENSION, '', $this->layout) . PHP_FILE_EXTENSION; if (!file_exists($layout_file)) { $this->http->setHeader($this->http->getValue('SERVER_PROTOCOL') . ' 500 Internal Server Error', true, 500); if (DEVELOPMENT) { throw new RuntimeException('It seems that "' . str_replace(ROOT_DIR, '', $layout_file) . '" does not exists.'); } else { $this->renderErrorPage(500); } } else { require $layout_file; } } else { $default_layout = $this->getDefaultLayout(); if (file_exists($default_layout)) { require $default_layout; } else { $this->http->setHeader($this->http->getValue('SERVER_PROTOCOL') . ' 500 Internal Server Error', true, 500); if (DEVELOPMENT) { throw new RuntimeException('It seems that "' . str_replace(ROOT_DIR, '', $default_layout) . '" does not exists.'); } else { $this->renderErrorPage(500); } } } } /** * Render error page * * @param Error code (e.g. 404, 500, etc) * @return void */ public function renderErrorPage($error_code = null) { if (defined('ERROR_' . $error_code . '_PAGE')) { $error_page = constant('ERROR_' . $error_code . '_PAGE'); $error_page_file = APPLICATION_ERROR_PAGE_DIR . str_replace(PHP_FILE_EXTENSION, '', $error_page) . PHP_FILE_EXTENSION; if (file_exists($error_page_file)) { require $error_page_file; } else { // error page not found? show this error message $this->http->setHeader($this->http->getValue('SERVER_PROTOCOL') . ' 500 Internal Server Error', true, 500); $this->setContent('500 - Internal Server Error (Unable to render ' . $error_code . ' error page)'); } } else { // error page not found? show this error message $this->http->setHeader($this->http->getValue('SERVER_PROTOCOL') . ' 500 Internal Server Error', true, 500); $this->setContent('500 - Internal Server Error (Unable to render ' . $error_code . ' error page)'); } } /** * Get action (presentation) content * * @return bool; whether or not content file exists */ public function getContent() { // check if page view is specified or not if (!isset($this->page_view)) { $content_view = APPLICATION_PAGE_DIR . $this->route->getController() . '/' . $this->route->getAction() . PHP_FILE_EXTENSION; } else { $content_view = APPLICATION_PAGE_DIR . $this->page_view->controller . '/' . $this->page_view->action . PHP_FILE_EXTENSION; } /** * @todo Should we render an error page, saying something like "the page template aren't found"? */ if(!file_exists($content_view)) { // No verbose return false; } require $content_view; } /** * Get partial (presentation) content * * @param String Partial name/path $partial_name * @return bool; whether or not partial file exists */ public function getPartial($partial_name) { $partial_view = APPLICATION_PARTIAL_DIR . $partial_name . PHP_FILE_EXTENSION; if(!file_exists($partial_view)) { // No verbose return false; } require $partial_view; } /** * Clear output buffer content * * @return void */ public function clearContent() { ob_clean(); } /** * Print out passed content * * @return void */ public function setContent($content = null) { print($content); } /** * Flush output buffer content * * @return void */ public function flush() { ob_flush(); } /** * Return the default layout path * * @return string */ private function getDefaultLayout() { return APPLICATION_LAYOUT_DIR . DEFAULT_LAYOUT . PHP_FILE_EXTENSION; } /** * Construct JSON string (and also set HTTP header as 'application/json') * * @param $data Array * @return void */ public function renderJSON($data = array()) { $json = json_encode($data); $this->http->setHeader(array( 'Content-Length' => strlen($json), 'Content-type' => 'application/json;' )); $this->setContent($json); } /** * Redirect using header * * @param string|array $mixed * @param Use 'refresh' instead of 'location' $use_refresh * @param Time to refresh $refresh_time * @return void */ public function redirect($mixed, $use_refresh = false, $refresh_time = 3) { $url = null; if (is_string($mixed)) { $url = trim($mixed); } else if (is_array($mixed)) { $controller = $this->route->getController(); $action = null; if (isset($mixed['controller'])) { $controller = trim($mixed['controller']); } $url = '/' . $controller; if (isset($mixed['action'])) { $action = trim($mixed['action']); } if (isset($action)) { $url .= '/' . $action; } if (isset($mixed['query'])) { $query = '?'; foreach ($mixed['query'] as $k => $v) { $query .= $k . '=' . urlencode($v) . '&'; } $query[strlen($query) - 1] = ''; $query = trim($query); $url .= $query; } } if (!$use_refresh) { $this->http->setHeader('Location: ' . $url); } else { $this->http->setHeader('refresh:' . $refresh_time . ';url=' . $url); } // exit normally exit(0); } }
rawswift/orinoco-framework-php
lib/Orinoco/Framework/View.php
PHP
mit
9,496
<?php namespace ibrss\Http\Requests; class RegisterRequest extends Request { /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'email' => 'required|email|unique:users', 'password' => 'required|confirmed|min:8', ]; } /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } }
pavel-voronin/Itty-Bitty-RSS
app/Http/Requests/RegisterRequest.php
PHP
mit
451
package util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Taken from * http://www.javaworld.com/article/2077578/learn-java/java-tip-76--an-alternative-to-the-deep-copy-technique.html * * @author David Miller (maybe) */ public class ObjectCloner { // so that nobody can accidentally create an ObjectCloner object private ObjectCloner() { } // returns a deep copy of an object static public Object deepCopy(Object oldObj) throws Exception { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A oos = new ObjectOutputStream(bos); // B // serialize and pass the object oos.writeObject(oldObj); // C oos.flush(); // D ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E ois = new ObjectInputStream(bin); // F // return the new object return ois.readObject(); // G } catch (Exception e) { System.out.println("Exception in ObjectCloner = " + e); throw (e); } finally { oos.close(); ois.close(); } } }
mokonzi131/gatech-colorwar
CS 2340 Agent Simulation/src/util/ObjectCloner.java
Java
mit
1,184
import java.awt.*; public class ListFonts { public static void main(String[] args) { String[] fontNames = GraphicsEnvironment .getLocalGraphicsEnvironment() .getAvailableFontFamilyNames(); for (int i = 0; i < fontNames.length; i++) System.out.println(fontNames[i]); } }
vivekprocoder/teaching
java/lecture 14/ListFonts.java
Java
mit
336
import { Event } from "../events/Event" import { EventDispatcher } from "../events/EventDispatcher" import { Browser } from "../utils/Browser" import { Byte } from "../utils/Byte" /** * 连接建立成功后调度。 * @eventType Event.OPEN * */ /*[Event(name = "open", type = "laya.events.Event")]*/ /** * 接收到数据后调度。 * @eventType Event.MESSAGE * */ /*[Event(name = "message", type = "laya.events.Event")]*/ /** * 连接被关闭后调度。 * @eventType Event.CLOSE * */ /*[Event(name = "close", type = "laya.events.Event")]*/ /** * 出现异常后调度。 * @eventType Event.ERROR * */ /*[Event(name = "error", type = "laya.events.Event")]*/ /** * <p> <code>Socket</code> 封装了 HTML5 WebSocket ,允许服务器端与客户端进行全双工(full-duplex)的实时通信,并且允许跨域通信。在建立连接后,服务器和 Browser/Client Agent 都能主动的向对方发送或接收文本和二进制数据。</p> * <p>要使用 <code>Socket</code> 类的方法,请先使用构造函数 <code>new Socket</code> 创建一个 <code>Socket</code> 对象。 <code>Socket</code> 以异步方式传输和接收数据。</p> */ export class Socket extends EventDispatcher { /** * <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。</p> * <p> LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p> * <p> BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。</p> */ static LITTLE_ENDIAN: string = "littleEndian"; /** * <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。</p> * <p> BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。</p> * <p> LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p> */ static BIG_ENDIAN: string = "bigEndian"; /**@internal */ _endian: string; /**@private */ protected _socket: any; /**@private */ private _connected: boolean; /**@private */ private _addInputPosition: number; /**@private */ private _input: any; /**@private */ private _output: any; /** * 不再缓存服务端发来的数据,如果传输的数据为字符串格式,建议设置为true,减少二进制转换消耗。 */ disableInput: boolean = false; /** * 用来发送和接收数据的 <code>Byte</code> 类。 */ private _byteClass: new () => any; /** * <p>子协议名称。子协议名称字符串,或由多个子协议名称字符串构成的数组。必须在调用 connect 或者 connectByUrl 之前进行赋值,否则无效。</p> * <p>指定后,只有当服务器选择了其中的某个子协议,连接才能建立成功,否则建立失败,派发 Event.ERROR 事件。</p> * @see https://html.spec.whatwg.org/multipage/comms.html#dom-websocket */ protocols: any = []; /** * 缓存的服务端发来的数据。 */ get input(): any { return this._input; } /** * 表示需要发送至服务端的缓冲区中的数据。 */ get output(): any { return this._output; } /** * 表示此 Socket 对象目前是否已连接。 */ get connected(): boolean { return this._connected; } /** * <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。</p> * <p> LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p> * <p> BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。</p> */ get endian(): string { return this._endian; } set endian(value: string) { this._endian = value; if (this._input != null) this._input.endian = value; if (this._output != null) this._output.endian = value; } /** * <p>创建新的 Socket 对象。默认字节序为 Socket.BIG_ENDIAN 。若未指定参数,将创建一个最初处于断开状态的套接字。若指定了有效参数,则尝试连接到指定的主机和端口。</p> * @param host 服务器地址。 * @param port 服务器端口。 * @param byteClass 用于接收和发送数据的 Byte 类。如果为 null ,则使用 Byte 类,也可传入 Byte 类的子类。 * @param protocols 子协议名称。子协议名称字符串,或由多个子协议名称字符串构成的数组 * @see laya.utils.Byte */ constructor(host: string|null = null, port: number = 0, byteClass: new () => any = null, protocols: any[]|null = null) { super(); this._byteClass = byteClass ? byteClass : Byte; this.protocols = protocols; this.endian = Socket.BIG_ENDIAN; if (host && port > 0 && port < 65535) this.connect(host, port); } /** * <p>连接到指定的主机和端口。</p> * <p>连接成功派发 Event.OPEN 事件;连接失败派发 Event.ERROR 事件;连接被关闭派发 Event.CLOSE 事件;接收到数据派发 Event.MESSAGE 事件; 除了 Event.MESSAGE 事件参数为数据内容,其他事件参数都是原生的 HTML DOM Event 对象。</p> * @param host 服务器地址。 * @param port 服务器端口。 */ connect(host: string, port: number): void { var url: string = "ws://" + host + ":" + port; this.connectByUrl(url); } /** * <p>连接到指定的服务端 WebSocket URL。 URL 类似 ws://yourdomain:port。</p> * <p>连接成功派发 Event.OPEN 事件;连接失败派发 Event.ERROR 事件;连接被关闭派发 Event.CLOSE 事件;接收到数据派发 Event.MESSAGE 事件; 除了 Event.MESSAGE 事件参数为数据内容,其他事件参数都是原生的 HTML DOM Event 对象。</p> * @param url 要连接的服务端 WebSocket URL。 URL 类似 ws://yourdomain:port。 */ connectByUrl(url: string): void { if (this._socket != null) this.close(); this._socket && this.cleanSocket(); if (!this.protocols || this.protocols.length == 0) { this._socket = new Browser.window.WebSocket(url); } else { this._socket = new Browser.window.WebSocket(url, this.protocols); } this._socket.binaryType = "arraybuffer"; this._output = new this._byteClass(); this._output.endian = this.endian; this._input = new this._byteClass(); this._input.endian = this.endian; this._addInputPosition = 0; this._socket.onopen = (e: any) => { this._onOpen(e); }; this._socket.onmessage = (msg: any): void => { this._onMessage(msg); }; this._socket.onclose = (e: any): void => { this._onClose(e); }; this._socket.onerror = (e: any): void => { this._onError(e); }; } /** * 清理Socket:关闭Socket链接,关闭事件监听,重置Socket */ cleanSocket(): void { this.close(); this._connected = false; this._socket.onopen = null; this._socket.onmessage = null; this._socket.onclose = null; this._socket.onerror = null; this._socket = null; } /** * 关闭连接。 */ close(): void { if (this._socket != null) { try { this._socket.close(); } catch (e) { } } } /** * @private * 连接建立成功 。 */ protected _onOpen(e: any): void { this._connected = true; this.event(Event.OPEN, e); } /** * @private * 接收到数据处理方法。 * @param msg 数据。 */ protected _onMessage(msg: any): void { if (!msg || !msg.data) return; var data: any = msg.data; if (this.disableInput && data) { this.event(Event.MESSAGE, data); return; } if (this._input.length > 0 && this._input.bytesAvailable < 1) { this._input.clear(); this._addInputPosition = 0; } var pre: number = this._input.pos; !this._addInputPosition && (this._addInputPosition = 0); this._input.pos = this._addInputPosition; if (data) { if (typeof (data) == 'string') { this._input.writeUTFBytes(data); } else { this._input.writeArrayBuffer(data); } this._addInputPosition = this._input.pos; this._input.pos = pre; } this.event(Event.MESSAGE, data); } /** * @private * 连接被关闭处理方法。 */ protected _onClose(e: any): void { this._connected = false; this.event(Event.CLOSE, e) } /** * @private * 出现异常处理方法。 */ protected _onError(e: any): void { this.event(Event.ERROR, e) } /** * 发送数据到服务器。 * @param data 需要发送的数据,可以是String或者ArrayBuffer。 */ send(data: any): void { this._socket.send(data); } /** * 发送缓冲区中的数据到服务器。 */ flush(): void { if (this._output && this._output.length > 0) { var evt: any; try { this._socket && this._socket.send(this._output.__getBuffer().slice(0, this._output.length)); } catch (e) { evt = e; } this._output.endian = this.endian; this._output.clear(); if (evt) this.event(Event.ERROR, evt); } } }
layabox/layaair
src/layaAir/laya/net/Socket.ts
TypeScript
mit
10,026
'use strict'; module.exports = require('./is-implemented')() ? Array.prototype.concat : require('./shim');
runningfun/angular_project
node_modules/bower/node_modules/inquirer/node_modules/cli-color/node_modules/es5-ext/array/#/concat/index.js
JavaScript
mit
112
import React from "react"; import { Link } from "@curi/react-dom"; import { TitledPlainSection, HashSection, Paragraph, CodeBlock, Note, IJS } from "../../components/guide/common"; let meta = { title: "Apollo Integration" }; let setupMeta = { title: "Setup", hash: "setup" }; let looseMeta = { title: "Loose Pairing", hash: "loose-pairing" }; let prefetchMeta = { title: "Prefetching", hash: "prefetch" }; let tightMeta = { title: "Tight Pairing", hash: "tight-pairing", children: [prefetchMeta] }; let contents = [setupMeta, looseMeta, tightMeta]; function ApolloGuide() { return ( <React.Fragment> <TitledPlainSection title={meta.title}> <Paragraph> <a href="https://apollographql.com">Apollo</a> is a great solution for managing an application's data using{" "} <a href="http://graphql.org">GraphQL</a>. </Paragraph> <Paragraph> There are a few different implementation strategies for integrating Apollo and Curi based on how tightly you want them to be paired. </Paragraph> <Note> <Paragraph> This guide only covers integration between Curi and Apollo. If you are not already familiar with how to use Apollo, you will want to learn that first. </Paragraph> <Paragraph> Also, this guide will only be referencing Apollo's React implementation, but the principles are the same no matter how you render your application. </Paragraph> </Note> </TitledPlainSection> <HashSection meta={setupMeta} tag="h2"> <Paragraph> Apollo's React package provides an <IJS>ApolloProvider</IJS> component for accessing your Apollo client throughout the application. The{" "} <IJS>Router</IJS> (or whatever you name the root Curi component) should be a descendant of the <IJS>ApolloProvider</IJS> because we don't need to re-render the <IJS>ApolloProvider</IJS> for every new response. </Paragraph> <CodeBlock lang="jsx"> {`import { ApolloProvider } from "react-apollo"; import { createRouterComponent } from "@curi/react-dom"; let Router = createRouterComponent(router); ReactDOM.render(( <ApolloProvider client={client}> <Router> <App /> </Router> </ApolloProvider> ), holder);`} </CodeBlock> </HashSection> <HashSection meta={looseMeta} tag="h2"> <Paragraph> Apollo and Curi don't actually have to know about each other. Curi can create a response without doing any data fetching and let Apollo handle that with its <IJS>Query</IJS> component. </Paragraph> <CodeBlock> {`// routes.js import Noun from "./pages/Noun"; // nothing Apollo related in here let routes = prepareRoutes([ { name: 'Noun', path: 'noun/:word', respond: () => { return { body: Noun }; } } ]);`} </CodeBlock> <Paragraph> Any location data that a query needs can be taken from the response object. The best way to access this is to read the current{" "} <IJS>response</IJS> from the context. This can either be done in the component or the response can be passed down from the root app. </Paragraph> <CodeBlock lang="jsx"> {`import { useResponse } from "@curi/react-dom"; function App() { let { response } = useResponse(); let { body:Body } = response; return <Body response={response} />; }`} </CodeBlock> <Paragraph> Because we pass the <IJS>response</IJS> to the route's <IJS>body</IJS>{" "} component, we can pass a <IJS>Query</IJS> the response's location params using <IJS>props.response.params</IJS>. </Paragraph> <CodeBlock lang="jsx"> {`// pages/Nouns.js import { Query } from "react-apollo"; let GET_NOUN = gql\` query noun(\$word: String!) { noun(word: $word) { word, type, definition } } \`; // use the "word" param from the response props // to query the correct data let Noun = ({ response }) => ( <Query query={GET_NOUN} variables={{ word: response.params.word }} > {({ loading, error, data }) => { if (loading) { return <Loading />; } // ... return ( <article> <h1>{data.noun.word}</h1> <Paragraph>{data.noun.definition}</Paragraph> </article> ) }} </Query> );`} </CodeBlock> </HashSection> <HashSection meta={tightMeta} tag="h2"> <Paragraph> You can use your Apollo client instance to call queries in a route's{" "} <IJS>resolve</IJS> function. <IJS>resolve</IJS> is expected to return a Promise, which is exactly what <IJS>client.query</IJS> returns. Tightly pairing Curi and Apollo is mostly center around using{" "} <IJS>resolve</IJS> to return a <IJS>client.query</IJS> call. This will delay navigation until after a route's GraphQL data has been loaded by Apollo. </Paragraph> <Paragraph> The <IJS>external</IJS> option can be used when creating the router to make the Apollo client accessible from routes. </Paragraph> <CodeBlock> {`import client from "./apollo"; let router = createRouter(browser, routes, { external: { client } });`} </CodeBlock> <CodeBlock> {`import { EXAMPLE_QUERY } from "./queries"; let routes = prepareRoutes([ { name: "Example", path: "example/:id", resolve({ params }, external) { return external.client.query({ query: EXAMPLE_QUERY, variables: { id: params.id } }); } } ]);`} </CodeBlock> <Paragraph>There are two strategies for doing this.</Paragraph> <Paragraph> The first approach is to avoid the <IJS>Query</IJS> altogether. Instead, you can use a route's <IJS>response</IJS> property to attach the data fetched by Apollo directly to a response through its{" "} <IJS>data</IJS> property. </Paragraph> <Paragraph> While we know at this point that the query has executed, we should also check <IJS>error</IJS> in the <IJS>respond</IJS> function to ensure that the query was executed successfully. </Paragraph> <CodeBlock> {`// routes.js import GET_VERB from "./queries"; import Verb from "./pages/Verb"; export default [ { name: "Verb", path: "verb/:word", resolve({ params }, external) { return external.client.query({ query: GET_VERB, variables: { word: params.word } }); }, respond({ error, resolved }) { if (error) { // handle failed queries } return { body: Verb, data: resolved.verb.data } } } ];`} </CodeBlock> <Paragraph> When rendering, you can access the query data through the{" "} <IJS>response</IJS>'s <IJS>data</IJS> property. </Paragraph> <CodeBlock lang="jsx"> {`// pages/Verb.js let Verb = ({ response }) => ( <article> <h1>{response.data.verb.word}</h1> <Paragraph> {response.data.verb.definition} </Paragraph> </article> )`} </CodeBlock> <Paragraph> The second approach is to use the <IJS>resolve</IJS> function as a way to cache the data, but also use <IJS>Query</IJS>. With this approach, we do not have to attach the query data to the response; we are relying on the fact that Apollo will execute and cache the results prior to navigation. </Paragraph> <CodeBlock> {`// routes.js import { GET_VERB } from "./queries"; export default [ { name: "Verb", path: "verb/:word", resolve({ params, external }) { // load the data so it is cached by // your Apollo client return external.client.query({ query: GET_VERB, variables: { word: params.word } }); } } ];`} </CodeBlock> <Paragraph> The route's component will render a <IJS>Query</IJS> to also call the query. Because the query has already been executed, Apollo will grab the data from its cache instead of re-sending a request to your server. </Paragraph> <CodeBlock lang="jsx"> {`// pages/Verb.js import { GET_VERB } from "../queries"; let Verb = ({ response }) => ( <Query query={GET_VERB} variables={{ word: response.params.word }} > {({ loading, error, data }) => { // ... return ( <article> <h1>{data.verb.word}</h1> <Paragraph> {data.verb.definition} </Paragraph> </article> ); }} </Query> )`} </CodeBlock> <HashSection meta={prefetchMeta} tag="h3"> <Paragraph> One additional benefit of adding queries to routes using{" "} <IJS>resolve</IJS> is that you can prefetch data for a route. </Paragraph> <Paragraph> The{" "} <Link name="Package" params={{ package: "interactions", version: "v2" }} hash="prefetch" > <IJS>prefetch</IJS> </Link>{" "} interaction lets you programmatically fetch the data for a route prior to navigating to a location. </Paragraph> <CodeBlock> {`// index.js import { prefetch } from "@curi/router"; let routes = prepareRoutes([ { name: "Example", path: "example/:id", resolve({ params }, external) { return external.client.query({ query: GET_EXAMPLES, variables: { id: params.id } }); } } ]); let router = createRouter(browser, routes); // this will call the GET_EXAMPLES query // and Apollo will cache the results let exampleRoute = router.route("Example"); prefetch(exampleRoute, { params: { id: 2 }});`} </CodeBlock> </HashSection> </HashSection> </React.Fragment> ); } export { ApolloGuide as component, contents };
pshrmn/curi
website/src/pages/Guides/apollo.js
JavaScript
mit
10,462
require 'net/http' require 'net/https' require 'active_merchant/billing/response' module ActiveMerchant #:nodoc: module Billing #:nodoc: # # == Description # The Gateway class is the base class for all ActiveMerchant gateway implementations. # # The standard list of gateway functions that most concrete gateway subclasses implement is: # # * <tt>purchase(money, creditcard, options = {})</tt> # * <tt>authorize(money, creditcard, options = {})</tt> # * <tt>capture(money, authorization, options = {})</tt> # * <tt>void(identification, options = {})</tt> # * <tt>credit(money, identification, options = {})</tt> # # Some gateways include features for recurring billing # # * <tt>recurring(money, creditcard, options = {})</tt> # # Some gateways also support features for storing credit cards: # # * <tt>store(creditcard, options = {})</tt> # * <tt>unstore(identification, options = {})</tt> # # === Gateway Options # The options hash consists of the following options: # # * <tt>:order_id</tt> - The order number # * <tt>:ip</tt> - The IP address of the customer making the purchase # * <tt>:customer</tt> - The name, customer number, or other information that identifies the customer # * <tt>:invoice</tt> - The invoice number # * <tt>:merchant</tt> - The name or description of the merchant offering the product # * <tt>:description</tt> - A description of the transaction # * <tt>:email</tt> - The email address of the customer # * <tt>:currency</tt> - The currency of the transaction. Only important when you are using a currency that is not the default with a gateway that supports multiple currencies. # * <tt>:billing_address</tt> - A hash containing the billing address of the customer. # * <tt>:shipping_address</tt> - A hash containing the shipping address of the customer. # # The <tt>:billing_address</tt>, and <tt>:shipping_address</tt> hashes can have the following keys: # # * <tt>:name</tt> - The full name of the customer. # * <tt>:company</tt> - The company name of the customer. # * <tt>:address1</tt> - The primary street address of the customer. # * <tt>:address2</tt> - Additional line of address information. # * <tt>:city</tt> - The city of the customer. # * <tt>:state</tt> - The state of the customer. The 2 digit code for US and Canadian addresses. The full name of the state or province for foreign addresses. # * <tt>:country</tt> - The [ISO 3166-1-alpha-2 code](http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm) for the customer. # * <tt>:zip</tt> - The zip or postal code of the customer. # * <tt>:phone</tt> - The phone number of the customer. # # == Implmenting new gateways # # See the {ActiveMerchant Guide to Contributing}[http://code.google.com/p/activemerchant/wiki/Contributing] # class Gateway include PostsData include RequiresParameters include CreditCardFormatting include Utils DEBIT_CARDS = [ :switch, :solo ] cattr_reader :implementations @@implementations = [] def self.inherited(subclass) super @@implementations << subclass end # The format of the amounts used by the gateway # :dollars => '12.50' # :cents => '1250' class_inheritable_accessor :money_format self.money_format = :dollars # The default currency for the transactions if no currency is provided class_inheritable_accessor :default_currency # The countries of merchants the gateway supports class_inheritable_accessor :supported_countries self.supported_countries = [] # The supported card types for the gateway class_inheritable_accessor :supported_cardtypes self.supported_cardtypes = [] # Indicates if the gateway supports 3D Secure authentication or not class_inheritable_accessor :supports_3d_secure self.supports_3d_secure = false class_inheritable_accessor :homepage_url class_inheritable_accessor :display_name # The application making the calls to the gateway # Useful for things like the PayPal build notation (BN) id fields superclass_delegating_accessor :application_id self.application_id = 'ActiveMerchant' attr_reader :options # Use this method to check if your gateway of interest supports a credit card of some type def self.supports?(card_type) supported_cardtypes.include?(card_type.to_sym) end def self.card_brand(source) result = source.respond_to?(:brand) ? source.brand : source.type result.to_s.downcase end def card_brand(source) self.class.card_brand(source) end # Initialize a new gateway. # # See the documentation for the gateway you will be using to make sure there are no other # required options. def initialize(options = {}) end # Are we running in test mode? def test? Base.gateway_mode == :test end private # :nodoc: all def name self.class.name.scan(/\:\:(\w+)Gateway/).flatten.first end def amount(money) return nil if money.nil? cents = if money.respond_to?(:cents) warn "Support for Money objects is deprecated and will be removed from a future release of ActiveMerchant. Please use an Integer value in cents" money.cents else money end if money.is_a?(String) or cents.to_i < 0 raise ArgumentError, 'money amount must be a positive Integer in cents.' end if self.money_format == :cents cents.to_s else sprintf("%.2f", cents.to_f / 100) end end def currency(money) money.respond_to?(:currency) ? money.currency : self.default_currency end def requires_start_date_or_issue_number?(credit_card) return false if card_brand(credit_card).blank? DEBIT_CARDS.include?(card_brand(credit_card).to_sym) end end end end
raldred/active_merchant
lib/active_merchant/billing/gateway.rb
Ruby
mit
6,376
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace DevDataControl { public partial class FrmObjectDataSource1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
ac9831/StudyProject-Asp.Net
DevDataControl/DevDataControl/FrmObjectDataSource.aspx.cs
C#
mit
332
require 'tilt/erb' module May class Templator class Template def initialize(path) @file = File.open(path, 'r') if path end def path @file.path end def body return '' unless @file @body ||= @file.read end end class Generator def initialize(bind) @binding = bind end def generate(template) Tilt::ERBTemplate.new(template.path, { trim: '<>' }).render(@binding) end end def initialize(template_path, destination, bind) @template_path, @destination, @binding = template_path, destination, bind end def render template = Template.new(@template_path) Generator.new(@binding).generate(template) end def write File.open(@destination, 'w') do |f| f.puts render end end end end
ainame/may
lib/may/templator.rb
Ruby
mit
865
/** * before : before(el, newEl) * Inserts a new element `newEl` just before `el`. * * var before = require('dom101/before'); * var newNode = document.createElement('div'); * var button = document.querySelector('#submit'); * * before(button, newNode); */ function before (el, newEl) { if (typeof newEl === 'string') { return el.insertAdjacentHTML('beforebegin', newEl) } else { return el.parentNode.insertBefore(newEl, el) } } module.exports = before
rstacruz/dom101
before.js
JavaScript
mit
492
<? $page_title = "Mobile Grid System" ?> <?php include("includes/_header.php"); ?> <style> .example .row, .example .row .column, .example .row .columns { background: #f4f4f4; } .example .row { margin-bottom: 10px; } .example .row .column, .example .row .columns { background: #eee; border: 1px solid #ddd; } @media handheld, only screen and (max-width: 767px) { .example .row { height: auto; } .example .row .column, .example .row .columns { margin-bottom: 10px; } .example .row .column:last-child, .example .row .columns:last-child { margin-bottom: 0; } } </style> <header> <div class="row"> <div class="twelve columns"> <h1>Mobile Grids</h1> <h4></h4> </div> </div> </header> <section id="mainContent" class="example"> <div class="row"> <div class="twelve columns"> <h3>On phones, columns become stacked.</h3> <p>That means this twelve column section will be the full width, and so will the three sections you see below.</p> </div> </div> <div class="row"> <div class="four columns"> <h5>Section 1</h5> <img src="http://placehold.it/300x100" /> <p>This is a four column section (so three of them across add up to twelve). As noted above on mobile, these columns will be stacked on top of each other.</p> </div> <div class="four columns"> <h5>Section 2</h5> <img src="http://placehold.it/300x100" /> <p>This is another four column section which will be stacked on top of the others. The next section though&#8230;</p> </div> <div class="four columns"> <h5>Section 3</h5> <p>Here we've used a block grid (.block-grid.three-up). These are perfect for similarly sized elements that you want to present in a grid even on mobile devices. If you view this on a phone (or small browser window) you can see what we mean.</p> <ul class="block-grid three-up"> <li> <img src="http://placehold.it/128x128" /> </li> <li> <img src="http://placehold.it/128x128" /> </li> <li> <img src="http://placehold.it/128x128" /> </li> <li> <img src="http://placehold.it/128x128" /> </li> <li> <img src="http://placehold.it/128x128" /> </li> <li> <img src="http://placehold.it/128x128" /> </li> </ul> </div> </div> </section> <?php include("includes/_footer.php"); ?>
aaron-lebo/kodefund
resources/public/foundation3/marketing/grid-example3.php
PHP
mit
2,446
package astilog import "flag" // Flags var ( AppName = flag.String("logger-app-name", "", "the logger's app name") Filename = flag.String("logger-filename", "", "the logger's filename") Verbose = flag.Bool("logger-verbose", false, "if true, then log level is debug") ) // Formats const ( FormatJSON = "json" FormatText = "text" ) // Outs const ( OutFile = "file" OutStdOut = "stdout" OutSyslog = "syslog" ) // Configuration represents the configuration of the logger type Configuration struct { AppName string `toml:"app_name"` DisableColors bool `toml:"disable_colors"` DisableTimestamp bool `toml:"disable_timestamp"` Filename string `toml:"filename"` FullTimestamp bool `toml:"full_timestamp"` Format string `toml:"format"` MessageKey string `toml:"message_key"` Out string `toml:"out"` TimestampFormat string `toml:"timestamp_format"` Verbose bool `toml:"verbose"` } // SetHandyFlags sets handy flags func SetHandyFlags() { Verbose = flag.Bool("v", false, "if true, then log level is debug") } // FlagConfig generates a Configuration based on flags func FlagConfig() Configuration { return Configuration{ AppName: *AppName, Filename: *Filename, Verbose: *Verbose, } }
OpenBazaar/spvwallet
vendor/github.com/asticode/go-astilog/configuration.go
GO
mit
1,282
<?php require_once('../../lib/Laposta.php'); Laposta::setApiKey("JdMtbsMq2jqJdQZD9AHC"); // initialize field with list_id $field = new Laposta_Field("BaImMu3JZA"); try { // get field info, use field_id or email as argument // $result will contain een array with the response from the server $result = $field->get("iPcyYaTCkG"); print '<pre>';print_r($result);print '</pre>'; } catch (Exception $e) { // you can use the information in $e to react to the exception print '<pre>';print_r($e);print '</pre>'; } ?>
laposta/laposta-api-php
examples/field/get.php
PHP
mit
520
import React, { PropTypes } from 'react'; import Page from './Page'; import ProjectListItem from './ProjectListItem'; import AspectContainer from './AspectContainer'; import BannerImage from './BannerImage'; import styles from './Projects.css'; const Projects = ({ projects }) => ( <Page Hero={() => <AspectContainer> <BannerImage url="https://placebear.com/900/1200" /> </AspectContainer> } title="Projects" > <div className={styles.projects}> {projects.map(project => <ProjectListItem key={project.id} {...project} />)} </div> </Page> ); Projects.propTypes = { projects: PropTypes.arrayOf(PropTypes.object), }; export default Projects;
neffbirkley/o
thomaswooster/src/components/Projects.js
JavaScript
mit
697
(function($) { var FourthWallConfiguration = function() { this.token = localStorage.getItem('token'); this.gitlab_host = localStorage.getItem('gitlab_host'); } FourthWallConfiguration.prototype.save = function() { localStorage.setItem('token', this.token); localStorage.setItem('gitlab_host', this.gitlab_host); $(this).trigger('updated'); } var FourthWallConfigurationForm = function(form, config) { this.form = form; this.statusField = $('#form-status', form) this.config = config; this.form.submit(this.onSubmit.bind(this)); }; FourthWallConfigurationForm.prototype.updateStatus = function(string) { this.statusField.text(string).show(); }; FourthWallConfigurationForm.prototype.onSubmit = function(e) { var values = this.form.serializeArray(); for( var i in values ) { this.config[values[i].name] = values[i].value; } this.config.save(); this.updateStatus('Data saved!'); return false; } var FourthWallConfigurationDisplay = function(element) { this.configurationList = element; }; FourthWallConfigurationDisplay.prototype.display = function(config) { var tokenValue = $('<li>').text('Token: ' + config.token); var hostnameValue = $('<li>').text('Hostname: ' + config.gitlab_host); this.configurationList.empty(); this.configurationList.append(tokenValue); this.configurationList.append(hostnameValue); }; $(document).ready(function() { var form = $('#fourth-wall-config'); var savedValues = $('#saved-values'); var config = new FourthWallConfiguration(); var form = new FourthWallConfigurationForm(form, config); var configDisplay = new FourthWallConfigurationDisplay(savedValues); configDisplay.display(config); $(config).on('updated', function() { configDisplay.display(config); }); }); })(jQuery);
dxw/fourth-wall-for-gitlab
javascript/config-form.js
JavaScript
mit
1,883
"use strict"; ace.define("ace/snippets/golang", ["require", "exports", "module"], function (require, exports, module) { "use strict"; exports.snippetText = undefined; exports.scope = "golang"; });
IonicaBizau/arc-assembler
clients/ace-builds/src-noconflict/snippets/golang.js
JavaScript
mit
204
export default { A: [[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[4,4]], B: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4]], C: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]], D: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4]], E: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]], F: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[0,3],[0,4]], G: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], H: [[0,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[4,4]], I: [[0,0],[1,0],[2,0],[3,0],[4,0],[2,1],[2,2],[2,3],[0,4],[1,4],[2,4],[3,4],[4,4]], J: [[4,0],[4,1],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], K: [[0,0],[4,0],[0,1],[3,1],[0,2],[1,2],[2,2],[0,3],[3,3],[0,4],[4,4]], L: [[0,0],[0,1],[0,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]], M: [[0,0],[4,0],[0,1],[1,1],[3,1],[4,1],[0,2],[2,2],[4,2],[0,3],[4,3],[0,4],[4,4]], N: [[0,0],[4,0],[0,1],[1,1],[4,1],[0,2],[2,2],[4,2],[0,3],[3,3],[4,3],[0,4],[4,4]], O: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], P: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[0,4]], Q: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[3,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], R: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[3,3],[0,4],[4,4]], S: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], T: [[0,0],[1,0],[2,0],[3,0],[4,0],[2,1],[2,2],[2,3],[2,4]], U: [[0,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], V: [[0,0],[4,0],[0,1],[4,1],[0,2],[4,2],[1,3],[3,3],[2,4]], W: [[0,0],[4,0],[0,1],[4,1],[0,2],[2,2],[4,2],[0,3],[1,3],[3,3],[4,3],[0,4],[4,4]], X: [[0,0],[4,0],[1,1],[3,1],[2,2],[1,3],[3,3],[0,4],[4,4]], Y: [[0,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[2,3],[2,4]], Z: [[0,0],[1,0],[2,0],[3,0],[4,0],[3,1],[2,2],[1,3],[0,4],[1,4],[2,4],[3,4],[4,4]], Å: [[2,0],[0,1],[1,1],[2,1],[3,1],[4,1],[0,2],[4,2],[0,3],[1,3],[2,3],[3,3],[4,3],[0,4],[4,4]], Ä: [[1,0],[3,0],[0,1],[1,1],[2,1],[3,1],[4,1],[0,2],[4,2],[0,3],[1,3],[2,3],[3,3],[4,3],[0,4],[4,4]], Ö: [[1,0],[3,0],[0,1],[1,1],[2,1],[3,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], 0: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], 1: [[1,0],[2,0],[3,0],[3,1],[3,2],[3,3],[3,4]], 2: [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]], 3: [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], 4: [[0,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[4,4]], 5: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], 6: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], 7: [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[4,2],[4,3],[4,4]], 8: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], 9: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]], '\@': [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[2,2],[3,2],[4,2],[0,3],[2,3],[4,3],[0,4],[2,4],[3,4],[4,4]], '\#': [[1,0],[3,0],[0,1],[1,1],[2,1],[3,1],[4,1],[1,2],[3,2],[0,3],[1,3],[2,3],[3,3],[4,3],[1,4],[3,4]], '\?': [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[2,2],[3,2],[4,2],[2,4]], '\%': [[0,0],[1,0],[4,0],[0,1],[1,1],[3,1],[2,2],[1,3],[3,3],[4,3],[0,4],[3,4],[4,4]], '\/': [[4,0],[3,1],[2,2],[1,3],[0,4]], '\+': [[2,0],[2,1],[0,2],[1,2],[2,2],[3,2],[4,2],[2,3],[2,4]], '\-': [[1,2],[2,2],[3,2]], '\_': [[0,4],[1,4],[2,4],[3,4],[4,4]], '\=': [[0,1],[1,1],[2,1],[3,1],[4,1],[0,3],[1,3],[2,3],[3,3],[4,3]], '\*': [[0,1],[2,1],[4,1],[1,2],[2,2],[3,2],[0,3],[2,3],[4,3]], '\'': [[2,0],[2,1]], '\"': [[1,0],[3,0],[1,1],[3,1]], '\(': [[2,0],[1,1],[1,2],[1,3],[2,4]], '\)': [[2,0],[3,1],[3,2],[3,3],[2,4]], '\.': [[2,4]], '\,': [[3,3],[2,3]], '\;': [[2,1],[2,3],[2,4]], '\:': [[2,1],[2,4]], '\!': [[2,0],[2,1],[2,2],[2,4]], '\{': [[2,0],[3,0],[2,1],[1,2],[2,2],[2,3],[2,4],[3,4]], '\}': [[1,0],[2,0],[2,1],[2,2],[3,2],[2,3],[1,4],[2,4]], '\]': [[1,0],[2,0],[2,1],[2,2],[2,3],[1,4],[2,4]], '\[': [[2,0],[3,0],[2,1],[2,2],[2,3],[2,4],[3,4]], '\^': [[2,0],[1,1],[3,1]], '\<': [[3,0],[2,1],[1,2],[2,3],[3,4]], '\>': [[1,0],[2,1],[3,2],[2,3],[1,4]] }
Aapzu/aapzu.xyz
config/characters.js
JavaScript
mit
4,761
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Plugin; use Composer\Composer; use Composer\EventDispatcher\EventSubscriberInterface; use Composer\IO\IOInterface; use Composer\Package\Package; use Composer\Package\Version\VersionParser; use Composer\Repository\RepositoryInterface; use Composer\Package\AliasPackage; use Composer\Package\PackageInterface; use Composer\Package\Link; use Composer\Package\LinkConstraint\VersionConstraint; use Composer\DependencyResolver\Pool; /** * Plugin manager * * @author Nils Adermann <naderman@naderman.de> * @author Jordi Boggiano <j.boggiano@seld.be> */ class PluginManager { protected $composer; protected $io; protected $globalComposer; protected $versionParser; protected $plugins = array(); protected $registeredPlugins = array(); private static $classCounter = 0; /** * Initializes plugin manager * * @param IOInterface $io * @param Composer $composer * @param Composer $globalComposer */ public function __construct(IOInterface $io, Composer $composer, Composer $globalComposer = null) { $this->io = $io; $this->composer = $composer; $this->globalComposer = $globalComposer; $this->versionParser = new VersionParser(); } /** * Loads all plugins from currently installed plugin packages */ public function loadInstalledPlugins() { $repo = $this->composer->getRepositoryManager()->getLocalRepository(); $globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null; if ($repo) { $this->loadRepository($repo); } if ($globalRepo) { $this->loadRepository($globalRepo); } } /** * Adds a plugin, activates it and registers it with the event dispatcher * * @param PluginInterface $plugin plugin instance */ public function addPlugin(PluginInterface $plugin) { $this->plugins[] = $plugin; $plugin->activate($this->composer, $this->io); if ($plugin instanceof EventSubscriberInterface) { $this->composer->getEventDispatcher()->addSubscriber($plugin); } } /** * Gets all currently active plugin instances * * @return array plugins */ public function getPlugins() { return $this->plugins; } /** * Load all plugins and installers from a repository * * Note that plugins in the specified repository that rely on events that * have fired prior to loading will be missed. This means you likely want to * call this method as early as possible. * * @param RepositoryInterface $repo Repository to scan for plugins to install * * @throws \RuntimeException */ public function loadRepository(RepositoryInterface $repo) { foreach ($repo->getPackages() as $package) { if ($package instanceof AliasPackage) { continue; } if ('composer-plugin' === $package->getType()) { $requiresComposer = null; foreach ($package->getRequires() as $link) { if ($link->getTarget() == 'composer-plugin-api') { $requiresComposer = $link->getConstraint(); } } if (!$requiresComposer) { throw new \RuntimeException("Plugin ".$package->getName()." is missing a require statement for a version of the composer-plugin-api package."); } if (!$requiresComposer->matches(new VersionConstraint('==', $this->versionParser->normalize(PluginInterface::PLUGIN_API_VERSION)))) { $this->io->write("<warning>The plugin ".$package->getName()." requires a version of composer-plugin-api that does not match your composer installation. You may need to run composer update with the '--no-plugins' option.</warning>"); } $this->registerPackage($package); } // Backward compatibility if ('composer-installer' === $package->getType()) { $this->registerPackage($package); } } } /** * Recursively generates a map of package names to packages for all deps * * @param Pool $pool Package pool of installed packages * @param array $collected Current state of the map for recursion * @param PackageInterface $package The package to analyze * * @return array Map of package names to packages */ protected function collectDependencies(Pool $pool, array $collected, PackageInterface $package) { $requires = array_merge( $package->getRequires(), $package->getDevRequires() ); foreach ($requires as $requireLink) { $requiredPackage = $this->lookupInstalledPackage($pool, $requireLink); if ($requiredPackage && !isset($collected[$requiredPackage->getName()])) { $collected[$requiredPackage->getName()] = $requiredPackage; $collected = $this->collectDependencies($pool, $collected, $requiredPackage); } } return $collected; } /** * Resolves a package link to a package in the installed pool * * Since dependencies are already installed this should always find one. * * @param Pool $pool Pool of installed packages only * @param Link $link Package link to look up * * @return PackageInterface|null The found package */ protected function lookupInstalledPackage(Pool $pool, Link $link) { $packages = $pool->whatProvides($link->getTarget(), $link->getConstraint()); return (!empty($packages)) ? $packages[0] : null; } /** * Register a plugin package, activate it etc. * * If it's of type composer-installer it is registered as an installer * instead for BC * * @param PackageInterface $package * @param bool $failOnMissingClasses By default this silently skips plugins that can not be found, but if set to true it fails with an exception * * @throws \UnexpectedValueException */ public function registerPackage(PackageInterface $package, $failOnMissingClasses = false) { $oldInstallerPlugin = ($package->getType() === 'composer-installer'); if (in_array($package->getName(), $this->registeredPlugins)) { return; } $extra = $package->getExtra(); if (empty($extra['class'])) { throw new \UnexpectedValueException('Error while installing '.$package->getPrettyName().', composer-plugin packages should have a class defined in their extra key to be usable.'); } $classes = is_array($extra['class']) ? $extra['class'] : array($extra['class']); $localRepo = $this->composer->getRepositoryManager()->getLocalRepository(); $globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null; $pool = new Pool('dev'); $pool->addRepository($localRepo); if ($globalRepo) { $pool->addRepository($globalRepo); } $autoloadPackages = array($package->getName() => $package); $autoloadPackages = $this->collectDependencies($pool, $autoloadPackages, $package); $generator = $this->composer->getAutoloadGenerator(); $autoloads = array(); foreach ($autoloadPackages as $autoloadPackage) { $downloadPath = $this->getInstallPath($autoloadPackage, ($globalRepo && $globalRepo->hasPackage($autoloadPackage))); $autoloads[] = array($autoloadPackage, $downloadPath); } $map = $generator->parseAutoloads($autoloads, new Package('dummy', '1.0.0.0', '1.0.0')); $classLoader = $generator->createLoader($map); $classLoader->register(); foreach ($classes as $class) { if (class_exists($class, false)) { $code = file_get_contents($classLoader->findFile($class)); $code = preg_replace('{^(\s*)class\s+(\S+)}mi', '$1class $2_composer_tmp'.self::$classCounter, $code); eval('?>'.$code); $class .= '_composer_tmp'.self::$classCounter; self::$classCounter++; } if ($oldInstallerPlugin) { $installer = new $class($this->io, $this->composer); $this->composer->getInstallationManager()->addInstaller($installer); } elseif (class_exists($class)) { $plugin = new $class(); $this->addPlugin($plugin); $this->registeredPlugins[] = $package->getName(); } elseif ($failOnMissingClasses) { throw new \UnexpectedValueException('Plugin '.$package->getName().' could not be initialized, class not found: '.$class); } } } /** * Retrieves the path a package is installed to. * * @param PackageInterface $package * @param bool $global Whether this is a global package * * @return string Install path */ public function getInstallPath(PackageInterface $package, $global = false) { if (!$global) { return $this->composer->getInstallationManager()->getInstallPath($package); } return $this->globalComposer->getInstallationManager()->getInstallPath($package); } }
kocsismate/composer
src/Composer/Plugin/PluginManager.php
PHP
mit
9,901
export default { modules: require('glob!./glob.txt'), options: { name: 'Comment', }, info: true, utils: {}, };
sb-Milky-Way/Comment
.storybook/params.js
JavaScript
mit
125
using Content.Shared.Sound; using Robust.Shared.GameObjects; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Server.Storage.Components { /// <summary> /// Allows locking/unlocking, with access determined by AccessReader /// </summary> [RegisterComponent] public sealed class LockComponent : Component { [ViewVariables(VVAccess.ReadWrite)] [DataField("locked")] public bool Locked { get; set; } = true; [ViewVariables(VVAccess.ReadWrite)] [DataField("lockOnClick")] public bool LockOnClick { get; set; } = false; [ViewVariables(VVAccess.ReadWrite)] [DataField("unlockingSound")] public SoundSpecifier UnlockSound { get; set; } = new SoundPathSpecifier("/Audio/Machines/door_lock_off.ogg"); [ViewVariables(VVAccess.ReadWrite)] [DataField("lockingSound")] public SoundSpecifier LockSound { get; set; } = new SoundPathSpecifier("/Audio/Machines/door_lock_off.ogg"); } }
space-wizards/space-station-14
Content.Server/Lock/LockComponent.cs
C#
mit
986
// Copyright 2008 Adrian Akison // Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx using System; using System.Collections.Generic; using System.Text; namespace RaidScheduler.Domain.DomainModels.Combinations { /// <summary> /// Interface for Permutations, Combinations and any other classes that present /// a collection of collections based on an input collection. The enumerators that /// this class inherits defines the mechanism for enumerating through the collections. /// </summary> /// <typeparam name="T">The of the elements in the collection, not the type of the collection.</typeparam> interface IMetaCollection<T> : IEnumerable<IList<T>> { /// <summary> /// The count of items in the collection. This is not inherited from /// ICollection since this meta-collection cannot be extended by users. /// </summary> long Count { get; } /// <summary> /// The type of the meta-collection, determining how the collections are /// determined from the inputs. /// </summary> GenerateOption Type { get; } /// <summary> /// The upper index of the meta-collection, which is the size of the input collection. /// </summary> int UpperIndex { get; } /// <summary> /// The lower index of the meta-collection, which is the size of each output collection. /// </summary> int LowerIndex { get; } } }
mac10688/FFXIVRaidScheduler
RaidScheduler.Domain/DomainServices/PartyMaker/Combinatorics/IMetaCollection.cs
C#
mit
1,512
using DragonSpark.Model.Results; namespace DragonSpark.Application.Security.Identity; public interface IUsers<T> : IResult<UsersSession<T>> where T : class {}
DragonSpark/Framework
DragonSpark.Application/Security/Identity/IUsers.cs
C#
mit
163
#!/usr/bin/env node process.env.FORCE_COLOR = true; const program = require('commander'); const package = require('../package.json'); /** * CLI Commands * */ program .version((package.name) + '@' + (package.version)); /** * Command for creating and seeding */ program .command('create [dataObject]', 'Generate seed data').alias('c') .command('teardown', 'Tear down seed data').alias('t') .parse(process.argv);
generationtux/cufflink
src/cufflink.js
JavaScript
mit
434
var hb = require('handlebars') , fs = require('vinyl-fs') , map = require('vinyl-map') module.exports = function (opts, cb) { if (!opts || typeof opts === 'function') throw new Error('opts is required') if (!opts.origin) throw new Error('opts.origin is required') if (!opts.target) throw new Error('opts.target is required') if (!opts.context) throw new Error('opts.context is required') var render = map(function (code, filename) { var t = hb.compile(code.toString()) return t(opts.context) }) fs.src([opts.origin+'/**']) .pipe(render) .pipe(fs.dest(opts.target)) .on('error', cb) .on('end', cb) }
Techwraith/hbs-dir
index.js
JavaScript
mit
642
package boun.swe573.accessbadger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ABHelloWorld { @RequestMapping("/welcome") public String helloWorld() { String message = "<br><div style='text-align:center;'>" + "<h3>********** Hello World **********</div><br><br>"; return message; } }
alihaluk/swe573main
src/boun/swe573/accessbadger/ABHelloWorld.java
Java
mit
393
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017, STEREOLABS. // // All rights reserved. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// /**************************************************************************************************** ** This sample is a wrapper for the ZED library in order to use the ZED Camera with ROS. ** ** A set of parameters can be specified in the launch file. ** ****************************************************************************************************/ #include <csignal> #include <cstdio> #include <math.h> #include <limits> #include <thread> #include <chrono> #include <memory> #include <sys/stat.h> #include <ros/ros.h> #include <nodelet/nodelet.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/CameraInfo.h> #include <sensor_msgs/distortion_models.h> #include <sensor_msgs/image_encodings.h> #include <image_transport/image_transport.h> #include <dynamic_reconfigure/server.h> #include <autobot/AutobotConfig.h> #include <nav_msgs/Odometry.h> #include <tf2/LinearMath/Quaternion.h> #include <tf2_ros/transform_broadcaster.h> #include <geometry_msgs/TransformStamped.h> #include <autobot/compound_img.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <boost/make_shared.hpp> #include <boost/thread.hpp> //#include <sensor_msgs/PointCloud2.h> //#include <pcl_conversions/pcl_conversions.h> //#include <pcl/point_cloud.h> //#include <pcl/point_types.h> #include <sl/Camera.hpp> using namespace std; namespace autobot { class ZEDWrapperNodelet : public nodelet::Nodelet { ros::NodeHandle nh; ros::NodeHandle nh_ns; boost::shared_ptr<boost::thread> device_poll_thread; image_transport::Publisher pub_rgb; image_transport::Publisher pub_raw_rgb; image_transport::Publisher pub_left; image_transport::Publisher pub_raw_left; image_transport::Publisher pub_right; image_transport::Publisher pub_raw_right; image_transport::Publisher pub_depth; ros::Publisher pub_compound_img; ros::Publisher pub_cloud; ros::Publisher pub_rgb_cam_info; ros::Publisher pub_left_cam_info; ros::Publisher pub_right_cam_info; ros::Publisher pub_depth_cam_info; ros::Publisher pub_odom; // tf tf2_ros::TransformBroadcaster transform_odom_broadcaster; std::string left_frame_id; std::string right_frame_id; std::string rgb_frame_id; std::string depth_frame_id; std::string cloud_frame_id; std::string odometry_frame_id; std::string odometry_transform_frame_id; // Launch file parameters int resolution; int quality; int sensing_mode; int rate; int gpu_id; int zed_id; std::string odometry_DB; std::string svo_filepath; //Tracking variables sl::Pose pose; // zed object sl::InitParameters param; std::unique_ptr<sl::Camera> zed; // flags int confidence; bool computeDepth; bool grabbing = false; int openniDepthMode = 0; // 16 bit UC data in mm else 32F in m, for more info http://www.ros.org/reps/rep-0118.html // Point cloud variables //sl::Mat cloud; //string point_cloud_frame_id = ""; //ros::Time point_cloud_time; /* \brief Convert an sl:Mat to a cv::Mat * \param mat : the sl::Mat to convert */ cv::Mat toCVMat(sl::Mat &mat) { if (mat.getMemoryType() == sl::MEM_GPU) mat.updateCPUfromGPU(); int cvType; switch (mat.getDataType()) { case sl::MAT_TYPE_32F_C1: cvType = CV_32FC1; break; case sl::MAT_TYPE_32F_C2: cvType = CV_32FC2; break; case sl::MAT_TYPE_32F_C3: cvType = CV_32FC3; break; case sl::MAT_TYPE_32F_C4: cvType = CV_32FC4; break; case sl::MAT_TYPE_8U_C1: cvType = CV_8UC1; break; case sl::MAT_TYPE_8U_C2: cvType = CV_8UC2; break; case sl::MAT_TYPE_8U_C3: cvType = CV_8UC3; break; case sl::MAT_TYPE_8U_C4: cvType = CV_8UC4; break; } return cv::Mat((int) mat.getHeight(), (int) mat.getWidth(), cvType, mat.getPtr<sl::uchar1>(sl::MEM_CPU), mat.getStepBytes(sl::MEM_CPU)); } /* \brief Test if a file exist * \param name : the path to the file */ bool file_exist(const std::string& name) { struct stat buffer; return (stat(name.c_str(), &buffer) == 0); } /* \brief Image to ros message conversion * \param img : the image to publish * \param encodingType : the sensor_msgs::image_encodings encoding type * \param frameId : the id of the reference frame of the image * \param t : the ros::Time to stamp the image */ sensor_msgs::ImagePtr imageToROSmsg(cv::Mat img, const std::string encodingType, std::string frameId, ros::Time t) { sensor_msgs::ImagePtr ptr = boost::make_shared<sensor_msgs::Image>(); sensor_msgs::Image& imgMessage = *ptr; imgMessage.header.stamp = t; imgMessage.header.frame_id = frameId; imgMessage.height = img.rows; imgMessage.width = img.cols; imgMessage.encoding = encodingType; int num = 1; //for endianness detection imgMessage.is_bigendian = !(*(char *) &num == 1); imgMessage.step = img.cols * img.elemSize(); size_t size = imgMessage.step * img.rows; imgMessage.data.resize(size); if (img.isContinuous()) memcpy((char*) (&imgMessage.data[0]), img.data, size); else { uchar* opencvData = img.data; uchar* rosData = (uchar*) (&imgMessage.data[0]); for (unsigned int i = 0; i < img.rows; i++) { memcpy(rosData, opencvData, imgMessage.step); rosData += imgMessage.step; opencvData += img.step; } } return ptr; } /* \brief Publish the pose of the camera with a ros Publisher * \param pose : the 4x4 matrix representing the camera pose * \param pub_odom : the publisher object to use * \param odom_frame_id : the id of the reference frame of the pose * \param t : the ros::Time to stamp the image */ //void publishOdom(sl::Pose pose, ros::Publisher &pub_odom, string odom_frame_id, ros::Time t) { //nav_msgs::Odometry odom; //odom.header.stamp = t; //odom.header.frame_id = odom_frame_id; ////odom.child_frame_id = "zed_optical_frame"; //sl::Translation translation = pose.getTranslation(); //odom.pose.pose.position.x = translation(2); //odom.pose.pose.position.y = -translation(0); //odom.pose.pose.position.z = -translation(1); //sl::Orientation quat = pose.getOrientation(); //odom.pose.pose.orientation.x = quat(2); //odom.pose.pose.orientation.y = -quat(0); //odom.pose.pose.orientation.z = -quat(1); //odom.pose.pose.orientation.w = quat(3); //pub_odom.publish(odom); //} /* \brief Publish the pose of the camera as a transformation * \param pose : the 4x4 matrix representing the camera pose * \param trans_br : the TransformBroadcaster object to use * \param odometry_transform_frame_id : the id of the transformation * \param t : the ros::Time to stamp the image */ //void publishTrackedFrame(sl::Pose pose, tf2_ros::TransformBroadcaster &trans_br, string odometry_transform_frame_id, ros::Time t) { //geometry_msgs::TransformStamped transformStamped; //transformStamped.header.stamp = ros::Time::now(); //transformStamped.header.frame_id = "zed_initial_frame"; //transformStamped.child_frame_id = odometry_transform_frame_id; //sl::Translation translation = pose.getTranslation(); //transformStamped.transform.translation.x = translation(2); //transformStamped.transform.translation.y = -translation(0); //transformStamped.transform.translation.z = -translation(1); //sl::Orientation quat = pose.getOrientation(); //transformStamped.transform.rotation.x = quat(2); //transformStamped.transform.rotation.y = -quat(0); //transformStamped.transform.rotation.z = -quat(1); //transformStamped.transform.rotation.w = quat(3); //trans_br.sendTransform(transformStamped); //} /* \brief Publish a cv::Mat image with a ros Publisher * \param img : the image to publish * \param pub_img : the publisher object to use * \param img_frame_id : the id of the reference frame of the image * \param t : the ros::Time to stamp the image */ void publishImage(cv::Mat img, image_transport::Publisher &pub_img, string img_frame_id, ros::Time t) { pub_img.publish(imageToROSmsg(img, sensor_msgs::image_encodings::BGR8, img_frame_id, t)); } /* \brief Publish a cv::Mat depth image with a ros Publisher * \param depth : the depth image to publish * \param pub_depth : the publisher object to use * \param depth_frame_id : the id of the reference frame of the depth image * \param t : the ros::Time to stamp the depth image */ void publishDepth(cv::Mat depth, image_transport::Publisher &pub_depth, string depth_frame_id, ros::Time t) { string encoding; if (openniDepthMode) { depth *= 1000.0f; depth.convertTo(depth, CV_16UC1); // in mm, rounded encoding = sensor_msgs::image_encodings::TYPE_16UC1; } else { encoding = sensor_msgs::image_encodings::TYPE_32FC1; } pub_depth.publish(imageToROSmsg(depth, encoding, depth_frame_id, t)); } void publishDepthPlusImage(cv::Mat img, cv::Mat depth, ros::Publisher &pub_compound_img, string img_frame_id, string depth_frame_id, ros::Time t) { string encoding; if (openniDepthMode) { depth *= 1000.0f; depth.convertTo(depth, CV_16UC1); // in mm, rounded encoding = sensor_msgs::image_encodings::TYPE_16UC1; } else { encoding = sensor_msgs::image_encodings::TYPE_32FC1; } sensor_msgs::ImagePtr img_msg = imageToROSmsg(img, sensor_msgs::image_encodings::BGR8, img_frame_id, t); sensor_msgs::ImagePtr depth_msg = imageToROSmsg(depth, encoding, depth_frame_id, t); boost::shared_ptr<autobot::compound_img> comp_img = boost::make_shared<autobot::compound_img>();; comp_img->img = *img_msg.get(); comp_img->depthImg = *depth_msg.get(); pub_compound_img.publish<autobot::compound_img>(comp_img); } /* \brief Publish a pointCloud with a ros Publisher * \param width : the width of the point cloud * \param height : the height of the point cloud * \param pub_cloud : the publisher object to use void publishPointCloud(int width, int height, ros::Publisher &pub_cloud) { pcl::PointCloud<pcl::PointXYZRGB> point_cloud; point_cloud.width = width; point_cloud.height = height; int size = width*height; point_cloud.points.resize(size); sl::Vector4<float>* cpu_cloud = cloud.getPtr<sl::float4>(); for (int i = 0; i < size; i++) { point_cloud.points[i].x = cpu_cloud[i][2]; point_cloud.points[i].y = -cpu_cloud[i][0]; point_cloud.points[i].z = -cpu_cloud[i][1]; point_cloud.points[i].rgb = cpu_cloud[i][3]; } sensor_msgs::PointCloud2 output; pcl::toROSMsg(point_cloud, output); // Convert the point cloud to a ROS message output.header.frame_id = point_cloud_frame_id; // Set the header values of the ROS message output.header.stamp = point_cloud_time; output.height = height; output.width = width; output.is_bigendian = false; output.is_dense = false; pub_cloud.publish(output); } */ /* \brief Publish the informations of a camera with a ros Publisher * \param cam_info_msg : the information message to publish * \param pub_cam_info : the publisher object to use * \param t : the ros::Time to stamp the message */ void publishCamInfo(sensor_msgs::CameraInfoPtr cam_info_msg, ros::Publisher pub_cam_info, ros::Time t) { static int seq = 0; cam_info_msg->header.stamp = t; cam_info_msg->header.seq = seq; pub_cam_info.publish(cam_info_msg); seq++; } /* \brief Get the information of the ZED cameras and store them in an information message * \param zed : the sl::zed::Camera* pointer to an instance * \param left_cam_info_msg : the information message to fill with the left camera informations * \param right_cam_info_msg : the information message to fill with the right camera informations * \param left_frame_id : the id of the reference frame of the left camera * \param right_frame_id : the id of the reference frame of the right camera */ void fillCamInfo(sl::Camera* zed, sensor_msgs::CameraInfoPtr left_cam_info_msg, sensor_msgs::CameraInfoPtr right_cam_info_msg, string left_frame_id, string right_frame_id) { int width = zed->getResolution().width; int height = zed->getResolution().height; sl::CameraInformation zedParam = zed->getCameraInformation(); float baseline = zedParam.calibration_parameters.T[0] * 0.001; // baseline converted in meters float fx = zedParam.calibration_parameters.left_cam.fx; float fy = zedParam.calibration_parameters.left_cam.fy; float cx = zedParam.calibration_parameters.left_cam.cx; float cy = zedParam.calibration_parameters.left_cam.cy; // There is no distorsions since the images are rectified double k1 = 0; double k2 = 0; double k3 = 0; double p1 = 0; double p2 = 0; left_cam_info_msg->distortion_model = sensor_msgs::distortion_models::PLUMB_BOB; right_cam_info_msg->distortion_model = sensor_msgs::distortion_models::PLUMB_BOB; left_cam_info_msg->D.resize(5); right_cam_info_msg->D.resize(5); left_cam_info_msg->D[0] = right_cam_info_msg->D[0] = k1; left_cam_info_msg->D[1] = right_cam_info_msg->D[1] = k2; left_cam_info_msg->D[2] = right_cam_info_msg->D[2] = k3; left_cam_info_msg->D[3] = right_cam_info_msg->D[3] = p1; left_cam_info_msg->D[4] = right_cam_info_msg->D[4] = p2; left_cam_info_msg->K.fill(0.0); right_cam_info_msg->K.fill(0.0); left_cam_info_msg->K[0] = right_cam_info_msg->K[0] = fx; left_cam_info_msg->K[2] = right_cam_info_msg->K[2] = cx; left_cam_info_msg->K[4] = right_cam_info_msg->K[4] = fy; left_cam_info_msg->K[5] = right_cam_info_msg->K[5] = cy; left_cam_info_msg->K[8] = right_cam_info_msg->K[8] = 1.0; left_cam_info_msg->R.fill(0.0); right_cam_info_msg->R.fill(0.0); left_cam_info_msg->P.fill(0.0); right_cam_info_msg->P.fill(0.0); left_cam_info_msg->P[0] = right_cam_info_msg->P[0] = fx; left_cam_info_msg->P[2] = right_cam_info_msg->P[2] = cx; left_cam_info_msg->P[5] = right_cam_info_msg->P[5] = fy; left_cam_info_msg->P[6] = right_cam_info_msg->P[6] = cy; left_cam_info_msg->P[10] = right_cam_info_msg->P[10] = 1.0; right_cam_info_msg->P[3] = (-1 * fx * baseline); left_cam_info_msg->width = right_cam_info_msg->width = width; left_cam_info_msg->height = right_cam_info_msg->height = height; left_cam_info_msg->header.frame_id = left_frame_id; right_cam_info_msg->header.frame_id = right_frame_id; } void callback(autobot::AutobotConfig &config, uint32_t level) { NODELET_INFO("Reconfigure confidence : %d", config.confidence); confidence = config.confidence; } void device_poll() { ros::Rate loop_rate(rate); ros::Time old_t = ros::Time::now(); bool old_image = false; bool tracking_activated = false; // Get the parameters of the ZED images int width = zed->getResolution().width; int height = zed->getResolution().height; NODELET_DEBUG_STREAM("Image size : " << width << "x" << height); cv::Size cvSize(width, height); cv::Mat leftImRGB(cvSize, CV_8UC3); cv::Mat rightImRGB(cvSize, CV_8UC3); // Create and fill the camera information messages //sensor_msgs::CameraInfoPtr rgb_cam_info_msg(new sensor_msgs::CameraInfo()); sensor_msgs::CameraInfoPtr left_cam_info_msg(new sensor_msgs::CameraInfo()); sensor_msgs::CameraInfoPtr right_cam_info_msg(new sensor_msgs::CameraInfo()); sensor_msgs::CameraInfoPtr depth_cam_info_msg(new sensor_msgs::CameraInfo()); fillCamInfo(zed.get(), left_cam_info_msg, right_cam_info_msg, left_frame_id, right_frame_id); //rgb_cam_info_msg = depth_cam_info_msg = left_cam_info_msg; // the reference camera is the Left one (next to the ZED logo) sl::RuntimeParameters runParams; runParams.sensing_mode = static_cast<sl::SENSING_MODE> (sensing_mode); sl::TrackingParameters trackParams; trackParams.area_file_path = odometry_DB.c_str(); sl::Mat leftZEDMat, rightZEDMat, depthZEDMat; // Main loop while (nh_ns.ok()) { // Check for subscribers int rgb_SubNumber = pub_rgb.getNumSubscribers(); int rgb_raw_SubNumber = pub_raw_rgb.getNumSubscribers(); int left_SubNumber = pub_left.getNumSubscribers(); int left_raw_SubNumber = pub_raw_left.getNumSubscribers(); int right_SubNumber = pub_right.getNumSubscribers(); int right_raw_SubNumber = pub_raw_right.getNumSubscribers(); int depth_SubNumber = pub_depth.getNumSubscribers(); int compound_SubNumber = pub_compound_img.getNumSubscribers(); int cloud_SubNumber = pub_cloud.getNumSubscribers(); int odom_SubNumber = pub_odom.getNumSubscribers(); bool runLoop = (rgb_SubNumber + rgb_raw_SubNumber + left_SubNumber + left_raw_SubNumber + right_SubNumber + right_raw_SubNumber + depth_SubNumber + cloud_SubNumber + odom_SubNumber) > 0; runParams.enable_point_cloud = false; if (cloud_SubNumber > 0) runParams.enable_point_cloud = true; ros::Time t = ros::Time::now(); // Get current time // Run the loop only if there is some subscribers if (true) { if (odom_SubNumber > 0 && !tracking_activated) { //Start the tracking if (odometry_DB != "" && !file_exist(odometry_DB)) { odometry_DB = ""; NODELET_WARN("odometry_DB path doesn't exist or is unreachable."); } zed->enableTracking(trackParams); tracking_activated = true; } else if (odom_SubNumber == 0 && tracking_activated) { //Stop the tracking zed->disableTracking(); tracking_activated = false; } computeDepth = (depth_SubNumber + cloud_SubNumber + odom_SubNumber) > 0; // Detect if one of the subscriber need to have the depth information grabbing = true; if (computeDepth) { int actual_confidence = zed->getConfidenceThreshold(); if (actual_confidence != confidence) zed->setConfidenceThreshold(confidence); runParams.enable_depth = true; // Ask to compute the depth } else runParams.enable_depth = false; old_image = zed->grab(runParams); // Ask to not compute the depth grabbing = false; if (old_image) { // Detect if a error occurred (for example: the zed have been disconnected) and re-initialize the ZED NODELET_DEBUG("Wait for a new image to proceed"); std::this_thread::sleep_for(std::chrono::milliseconds(2)); if ((t - old_t).toSec() > 5) { // delete the old object before constructing a new one zed.reset(); zed.reset(new sl::Camera()); NODELET_INFO("Re-openning the ZED"); sl::ERROR_CODE err = sl::ERROR_CODE_CAMERA_NOT_DETECTED; while (err != sl::SUCCESS) { err = zed->open(param); // Try to initialize the ZED NODELET_INFO_STREAM(errorCode2str(err)); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); } tracking_activated = false; if (odom_SubNumber > 0) { //Start the tracking if (odometry_DB != "" && !file_exist(odometry_DB)) { odometry_DB = ""; NODELET_WARN("odometry_DB path doesn't exist or is unreachable."); } zed->enableTracking(trackParams); tracking_activated = true; } } continue; } old_t = ros::Time::now(); // Publish the left == rgb image if someone has subscribed to if (left_SubNumber > 0 || rgb_SubNumber > 0) { // Retrieve RGBA Left image zed->retrieveImage(leftZEDMat, sl::VIEW_LEFT); cv::cvtColor(toCVMat(leftZEDMat), leftImRGB, CV_RGBA2RGB); if (left_SubNumber > 0) { publishCamInfo(left_cam_info_msg, pub_left_cam_info, t); publishImage(leftImRGB, pub_left, left_frame_id, t); } //if (rgb_SubNumber > 0) { //publishCamInfo(rgb_cam_info_msg, pub_rgb_cam_info, t); //publishImage(leftImRGB, pub_rgb, rgb_frame_id, t); // rgb is the left image //} } // Publish the left_raw == rgb_raw image if someone has subscribed to //if (left_raw_SubNumber > 0 || rgb_raw_SubNumber > 0) { //// Retrieve RGBA Left image //zed->retrieveImage(leftZEDMat, sl::VIEW_LEFT_UNRECTIFIED); //cv::cvtColor(toCVMat(leftZEDMat), leftImRGB, CV_RGBA2RGB); //if (left_raw_SubNumber > 0) { //publishCamInfo(left_cam_info_msg, pub_left_cam_info, t); //publishImage(leftImRGB, pub_raw_left, left_frame_id, t); //} //if (rgb_raw_SubNumber > 0) { //publishCamInfo(rgb_cam_info_msg, pub_rgb_cam_info, t); //publishImage(leftImRGB, pub_raw_rgb, rgb_frame_id, t); //} //} // Publish the right image if someone has subscribed to if (right_SubNumber > 0) { // Retrieve RGBA Right image zed->retrieveImage(rightZEDMat, sl::VIEW_RIGHT); cv::cvtColor(toCVMat(rightZEDMat), rightImRGB, CV_RGBA2RGB); publishCamInfo(right_cam_info_msg, pub_right_cam_info, t); publishImage(rightImRGB, pub_right, right_frame_id, t); } // Publish the right image if someone has subscribed to //if (right_raw_SubNumber > 0) { //// Retrieve RGBA Right image //zed->retrieveImage(rightZEDMat, sl::VIEW_RIGHT_UNRECTIFIED); //cv::cvtColor(toCVMat(rightZEDMat), rightImRGB, CV_RGBA2RGB); //publishCamInfo(right_cam_info_msg, pub_right_cam_info, t); //publishImage(rightImRGB, pub_raw_right, right_frame_id, t); //} //Publish the depth image if someone has subscribed to //if (depth_SubNumber > 0) { if (depth_SubNumber > 0) { zed->retrieveMeasure(depthZEDMat, sl::MEASURE_DEPTH); publishCamInfo(depth_cam_info_msg, pub_depth_cam_info, t); publishDepth(toCVMat(depthZEDMat), pub_depth, depth_frame_id, t); // in meters } // subscription-based publishing not working with vanilla ros::publisher so turning off // for compound image // if (compound_SubNumber > 0) { zed->retrieveImage(leftZEDMat, sl::VIEW_LEFT); cv::cvtColor(toCVMat(leftZEDMat), leftImRGB, CV_RGBA2RGB); zed->retrieveMeasure(depthZEDMat, sl::MEASURE_DEPTH); publishDepthPlusImage(leftImRGB, toCVMat(depthZEDMat), pub_compound_img, left_frame_id, depth_frame_id, t); // in meters //} // Publish the point cloud if someone has subscribed to //if (cloud_SubNumber > 0) { //// Run the point cloud convertion asynchronously to avoid slowing down all the program //// Retrieve raw pointCloud data //zed->retrieveMeasure(cloud, sl::MEASURE_XYZBGRA); //point_cloud_frame_id = cloud_frame_id; //point_cloud_time = t; //publishPointCloud(width, height, pub_cloud); //} // Publish the odometry if someone has subscribed to //if (odom_SubNumber > 0) { //zed->getPosition(pose); //publishOdom(pose, pub_odom, odometry_frame_id, t); //} //Note, the frame is published, but its values will only change if someone has subscribed to odom //publishTrackedFrame(pose, transform_odom_broadcaster, odometry_transform_frame_id, t); //publish the tracked Frame loop_rate.sleep(); } else { //publishTrackedFrame(pose, transform_odom_broadcaster, odometry_transform_frame_id, ros::Time::now()); //publish the tracked Frame before the sleep std::this_thread::sleep_for(std::chrono::milliseconds(10)); // No subscribers, we just wait } } // while loop zed.reset(); } void onInit() { // Launch file parameters resolution = sl::RESOLUTION_HD720; quality = sl::DEPTH_MODE_PERFORMANCE; //sensing_mode = sl::SENSING_MODE_STANDARD; sensing_mode = sl::SENSING_MODE_FILL; rate = 30; gpu_id = -1; zed_id = 0; odometry_DB = ""; std::string img_topic = "image_rect_color"; std::string img_raw_topic = "image_raw_color"; // Set the default topic names string rgb_topic = "rgb/" + img_topic; string rgb_raw_topic = "rgb/" + img_raw_topic; string rgb_cam_info_topic = "rgb/camera_info"; rgb_frame_id = "/zed_current_frame"; string left_topic = "left/" + img_topic; string left_raw_topic = "left/" + img_raw_topic; string left_cam_info_topic = "left/camera_info"; left_frame_id = "/zed_current_frame"; string right_topic = "right/" + img_topic; string right_raw_topic = "right/" + img_raw_topic; string right_cam_info_topic = "right/camera_info"; right_frame_id = "/zed_current_frame"; string depth_topic = "depth/"; if (openniDepthMode) depth_topic += "depth_raw_registered"; else depth_topic += "depth_registered"; string compound_topic = "compound_img/"; string depth_cam_info_topic = "depth/camera_info"; depth_frame_id = "/zed_depth_frame"; string point_cloud_topic = "point_cloud/cloud_registered"; cloud_frame_id = "/zed_current_frame"; string odometry_topic = "odom"; odometry_frame_id = "/zed_initial_frame"; odometry_transform_frame_id = "/zed_current_frame"; nh = getMTNodeHandle(); nh_ns = getMTPrivateNodeHandle(); // Get parameters from launch file nh_ns.getParam("resolution", resolution); nh_ns.getParam("quality", quality); nh_ns.getParam("sensing_mode", sensing_mode); nh_ns.getParam("frame_rate", rate); nh_ns.getParam("odometry_DB", odometry_DB); nh_ns.getParam("openni_depth_mode", openniDepthMode); nh_ns.getParam("gpu_id", gpu_id); nh_ns.getParam("zed_id", zed_id); if (openniDepthMode) NODELET_INFO_STREAM("Openni depth mode activated"); nh_ns.getParam("rgb_topic", rgb_topic); nh_ns.getParam("rgb_raw_topic", rgb_raw_topic); nh_ns.getParam("rgb_cam_info_topic", rgb_cam_info_topic); nh_ns.getParam("left_topic", left_topic); nh_ns.getParam("left_raw_topic", left_raw_topic); nh_ns.getParam("left_cam_info_topic", left_cam_info_topic); nh_ns.getParam("right_topic", right_topic); nh_ns.getParam("right_raw_topic", right_raw_topic); nh_ns.getParam("right_cam_info_topic", right_cam_info_topic); nh_ns.getParam("depth_topic", depth_topic); nh_ns.getParam("depth_cam_info_topic", depth_cam_info_topic); nh_ns.getParam("point_cloud_topic", point_cloud_topic); nh_ns.getParam("odometry_topic", odometry_topic); nh_ns.param<std::string>("svo_filepath", svo_filepath, std::string()); // Create the ZED object zed.reset(new sl::Camera()); // Try to initialize the ZED if (!svo_filepath.empty()) param.svo_input_filename = svo_filepath.c_str(); else { param.camera_fps = rate; param.camera_resolution = static_cast<sl::RESOLUTION> (resolution); param.camera_linux_id = zed_id; } param.coordinate_units = sl::UNIT_METER; param.coordinate_system = sl::COORDINATE_SYSTEM_IMAGE; param.depth_mode = static_cast<sl::DEPTH_MODE> (quality); param.sdk_verbose = true; param.sdk_gpu_id = gpu_id; sl::ERROR_CODE err = sl::ERROR_CODE_CAMERA_NOT_DETECTED; while (err != sl::SUCCESS) { err = zed->open(param); NODELET_INFO_STREAM(errorCode2str(err)); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); } cout << "ZED OPENED" << endl; //ERRCODE display dynamic_reconfigure::Server<autobot::AutobotConfig> server; dynamic_reconfigure::Server<autobot::AutobotConfig>::CallbackType f; f = boost::bind(&ZEDWrapperNodelet::callback, this, _1, _2); server.setCallback(f); confidence = 80; // Create all the publishers // Image publishers image_transport::ImageTransport it_zed(nh); //pub_rgb = it_zed.advertise(rgb_topic, 1); //rgb //NODELET_INFO_STREAM("Advertized on topic " << rgb_topic); //pub_raw_rgb = it_zed.advertise(rgb_raw_topic, 1); //rgb raw //NODELET_INFO_STREAM("Advertized on topic " << rgb_raw_topic); pub_left = it_zed.advertise(left_topic, 2); //left NODELET_INFO_STREAM("Advertized on topic " << left_topic); //pub_raw_left = it_zed.advertise(left_raw_topic, 1); //left raw //NODELET_INFO_STREAM("Advertized on topic " << left_raw_topic); pub_right = it_zed.advertise(right_topic, 2); //right NODELET_INFO_STREAM("Advertized on topic " << right_topic); //pub_raw_right = it_zed.advertise(right_raw_topic, 1); //right raw //NODELET_INFO_STREAM("Advertized on topic " << right_raw_topic); pub_depth = it_zed.advertise(depth_topic, 2); //depth NODELET_INFO_STREAM("Advertized on topic " << depth_topic); pub_compound_img = nh.advertise<autobot::compound_img>(compound_topic, 2); //depth NODELET_INFO_STREAM("Advertized on topic " << compound_topic); ////PointCloud publisher //pub_cloud = nh.advertise<sensor_msgs::PointCloud2> (point_cloud_topic, 1); //NODELET_INFO_STREAM("Advertized on topic " << point_cloud_topic); // Camera info publishers //pub_rgb_cam_info = nh.advertise<sensor_msgs::CameraInfo>(rgb_cam_info_topic, 1); //rgb //NODELET_INFO_STREAM("Advertized on topic " << rgb_cam_info_topic); pub_left_cam_info = nh.advertise<sensor_msgs::CameraInfo>(left_cam_info_topic, 1); //left NODELET_INFO_STREAM("Advertized on topic " << left_cam_info_topic); pub_right_cam_info = nh.advertise<sensor_msgs::CameraInfo>(right_cam_info_topic, 1); //right NODELET_INFO_STREAM("Advertized on topic " << right_cam_info_topic); pub_depth_cam_info = nh.advertise<sensor_msgs::CameraInfo>(depth_cam_info_topic, 1); //depth NODELET_INFO_STREAM("Advertized on topic " << depth_cam_info_topic); //Odometry publisher //pub_odom = nh.advertise<nav_msgs::Odometry>(odometry_topic, 1); //NODELET_INFO_STREAM("Advertized on topic " << odometry_topic); device_poll_thread = boost::shared_ptr<boost::thread> (new boost::thread(boost::bind(&ZEDWrapperNodelet::device_poll, this))); } }; // class ZEDROSWrapperNodelet } // namespace #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(autobot::ZEDWrapperNodelet, nodelet::Nodelet);
atkvo/masters-bot
src/autobot/src/zed_wrapper_nodelet.cpp
C++
mit
37,455
# frozen_string_literal: true # == Schema Information # # Table name: tags # # id :uuid not null, primary key # shared :boolean not null # tag_name :string not null # created_at :datetime not null # updated_at :datetime not null # organization_id :bigint not null # # Indexes # # index_tags_on_organization_id (organization_id) # FactoryBot.define do factory :tag do tag_name { Faker::Games::Pokemon.name } organization { create :organization } shared { true } end end
MindLeaps/tracker
spec/factories/tags.rb
Ruby
mit
590
#!/usr/bin/python # -*- coding: utf-8 -*- from scrapy.spider import Spider from scrapy.selector import Selector from my_settings import name_file, test_mode, difference_days from datetime import datetime, timedelta print "Run spider NewenglandFilm" file_output = open(name_file, 'a') email_current_session = [] email_in_file = open(name_file, 'r').readlines() if test_mode: current_date = (datetime.today() - timedelta(days=difference_days)).strftime('%m/%d/%Y') else: current_date = datetime.today().strftime('%m/%d/%Y') class NewenglandFilm(Spider): name = 'newenglandfilm' allowed_domains = ["newenglandfilm.com"] start_urls = ["http://newenglandfilm.com/jobs.htm"] def parse(self, response): sel = Selector(response) for num_div in xrange(1, 31): date = sel.xpath('//*[@id="mainContent"]/div[{0}]/span/text()'.format(str(num_div))).re('(\d{1,2}\/\d{1,2}\/\d{4})')[0] email = sel.xpath('//*[@id="mainContent"]/div[{0}]/div/text()'.format(str(num_div))).re('(\w+@[a-zA-Z0-9_]+?\.[a-zA-Z]{2,6})') if current_date == date: for address in email: if address + "\n" not in email_in_file and address not in email_current_session: file_output.write(address + "\n") email_current_session.append(address) print "Spider: NewenglandFilm. Email {0} added to file".format(address) else: print "Spider: NewenglandFilm. Email {0} already in the file".format(address)
dcondrey/scrapy-spiders
dist/spiders/newenglandfilm.py
Python
mit
1,625
module Tabulo # @!visibility private module Util NEWLINE = /\r\n|\n|\r/ # @!visibility private def self.condense_lines(lines) join_lines(lines.reject(&:empty?)) end # @!visibility private def self.divides?(smaller, larger) larger % smaller == 0 end # @!visibility private def self.join_lines(lines) lines.join($/) end # @!visibility private def self.max(x, y) x > y ? x : y end # @!visibility private def self.slice_hash(hash, *keys) new_hash = {} keys.each { |k| new_hash[k] = hash[k] if hash.include?(k) } new_hash end # @!visibility private # @return [Integer] the length of the longest segment of str when split by newlines def self.wrapped_width(str) return 0 if str.empty? segments = str.split(NEWLINE) segments.inject(1) do |longest_length_so_far, segment| Util.max(longest_length_so_far, Unicode::DisplayWidth.of(segment)) end end end end
matt-harvey/tabulo
lib/tabulo/util.rb
Ruby
mit
1,017
<?php //Get Variables $favuserid = $_POST['userid']; $ownprofile = $_POST['ownprofile']; $ownusername = $_POST['ownusername']; //Connect to mysql database $connection = mysql_connect("localhost", "6470", "6470") or die("mySQL Connection Error<br />\n"); $database='6470_main'; mysql_select_db($database) or die('Error, could not access database '.$database."\n"); //Convert username to id $result = mysql_query("SELECT * FROM user WHERE username = '$ownusername'") or die(mysql_error()); $row = mysql_fetch_array($result); $ownuserid = $row['id']; //Check useruserfav $result = mysql_query("SELECT * FROM useruserfav WHERE (user1id = '$ownuserid' && user2id = '$favuserid')") or die(mysql_error()); $row = mysql_fetch_array($result); if($row['id']=='' || $row['id']==null){//Search the other way around $result = mysql_query("SELECT * FROM useruserfav WHERE (user2id = '$ownuserid' && user1id = '$favuserid')") or die(mysql_error()); $row = mysql_fetch_array($result); if($row['id']=='' || $row['id']==null){//Not friended yet, become a friend mysql_query("INSERT INTO useruserfav (user1id, user2id) VALUES('$ownuserid','$favuserid')") or die(mysql_error()); echo 'You are now friends with this person. '; }else{//Already friended, delete friend $id = $row['id']; mysql_query("DELETE FROM useruserfav WHERE id='$id'") or die(mysql_error()); echo 'You are no longer friends with this person.'; } }else{//Already friended, delete friend $id = $row['id']; mysql_query("DELETE FROM useruserfav WHERE id='$id'") or die(mysql_error()); echo 'You are no longer friends with this person.'; } ?>
albertyw/6.470
src/process/profilefavchange.php
PHP
mit
1,615
var request = require('request'); var url = require('url'); var authenticate = require('./oauthentication'); var Request = function(obj){ this.obj = obj; }; Request.prototype.mailboxes = function(method, specific_url, params, callback){ /* * @params: * @ param : if user wants to call specific mailbox e.g. : / * @ callback: function to pass the following parameters to: * @error * @response * @body */ makeRequest(this, method, 'https://api.slice.com/api/v1/mailboxes', specific_url, params, callback); }; Request.prototype.users = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/users', specific_url, params, callback); }; Request.prototype.orders = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/orders', specific_url, params, callback); }; Request.prototype.items = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/items', specific_url, params, callback); }; Request.prototype.shipments = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/shipments', specific_url, params, callback); }; Request.prototype.recalls = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/recalls', specific_url, params, callback); }; Request.prototype.emails = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/emails', specific_url, params, callback); }; Request.prototype.merchants = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/merchants', specific_url, params, callback); }; Request.prototype.actions = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/actions/update', specific_url, params, callback); }; Request.prototype.setAccessToken = function(access_token){ this.access_token = access_token; } var makeRequest = function(obj, method, url, specific_url, params, callback){ this.params = params || ''; this.param_url = compileRequest(this.params); this.method = method || 'GET'; // defaults to 'GET' this.specific_url = specific_url || ''; request({ uri : url+this.specific_url+this.params, headers : { 'Authorization' : 'Bearer ' + obj.access_token }, method : this.method, timeout : 1000, followRedirect : true, maxRedirects : 4, }, function(error, response, body){ if(error){ throw error; } callback(error, response, body); }); }; var compileRequest = function(params){ var param_url = '?'; for(var key in params){ param_url += key + '=' + params[key] + '&'; } return param_url.substring(0, param_url.length-1); }; module.exports = Request; module.exports.users = Request.users; module.exports.mailboxes = Request.mailboxes; module.exports.orders = Request.orders; module.exports.items = Request.items; module.exports.shipments = Request.shipments; module.exports.recalls = Request.recalls; module.exports.emails = Request.emails; module.exports.merchants = Request.merchants; module.exports.actions = Request.actions;
slicedev/slice-node
lib/requests.js
JavaScript
mit
3,323
<?php namespace Sasedev\Commons\SharedBundle\HtmlModel\Tags; use Sasedev\Commons\SharedBundle\HtmlModel\Attributes\Src; use Sasedev\Commons\SharedBundle\HtmlModel\Attributes\Type; use Sasedev\Commons\SharedBundle\HtmlModel\Attributes\Charset; use Sasedev\Commons\SharedBundle\HtmlModel\Attributes\Defer; use Sasedev\Commons\SharedBundle\HtmlModel\Attributes\Async; use Sasedev\Commons\SharedBundle\HtmlModel\HtmlTag; /** * * @author sasedev <seif.salah@gmail.com> */ class Script extends HtmlTag { /** * * @var string */ const NAME = 'script'; /** * * @var boolean */ const SELF_CLOSING = false; /** * Constructor * * @param Src|string $src * @param string $type * @param string $charset * @param boolean $defer * @param boolean $async * @param string $content */ public function __construct($src = null, $type = null, $charset = null, $defer = false, $async = false, $content = null) { $attributes = array(); if (null != $src) { if ($src instanceof Src) { $srcAttribute = $src; } else { $srcAttribute = new Src($src); } $attributes[] = $srcAttribute; } if (null != $type) { $typeAttribute = new Type($type); $attributes[] = $typeAttribute; } if (null != $charset) { $charsetAttribute = new Charset($charset); $attributes[] = $charsetAttribute; } if (null != $defer) { $deferAttribute = new Defer(); $attributes[] = $deferAttribute; } if (null != $async) { $asyncAttribute = new Async(); $attributes[] = $asyncAttribute; } parent::__construct(self::NAME, $attributes, self::SELF_CLOSING, $content); } }
sasedev/commons-shared-bundle
src/Sasedev/Commons/SharedBundle/HtmlModel/Tags/Script.php
PHP
mit
1,621
package gradebookdata; /** * Represents one row of the course table in the GradeBook database * * @author Eric Carlton * */ public class Course { private String name; private int weight; private int ID; /** * Create a course with all fields filled * * @param name * name of course * @param weight * credit hours ( or weight ) of course * @param ID * course_ID in course table */ public Course(String name, int weight, int ID) { this.name = name; this.weight = weight; this.ID = ID; } /** * Create a generic course */ public Course() { this("no name", 0, -1); } public String getName() { return name; } public Integer getWeight() { return weight; } public Integer getID() { return ID; } /** * Returns a string formatted as: * course_name * course_weight hour(s) */ @Override public String toString() { String result = name + "\n" + weight; if (weight == 1) result = result + " hour"; else result = result + " hours"; return result; } }
Eric-Carlton/GradeBook
GradeBook/src/gradebookdata/Course.java
Java
mit
1,062
#include "RDom.h" #include "Util.h" #include "IROperator.h" #include "IRPrinter.h" namespace Halide { using namespace Internal; using std::string; using std::vector; RVar::operator Expr() const { if (!min().defined() || !extent().defined()) { user_error << "Use of undefined RDom dimension: " << (name().empty() ? "<unknown>" : name()) << "\n"; } return Variable::make(Int(32), name(), domain()); } Expr RVar::min() const { if (_domain.defined()) { return _var().min; } else { return Expr(); } } Expr RVar::extent() const { if (_domain.defined()) { return _var().extent; } else { return Expr(); } } const std::string &RVar::name() const { if (_domain.defined()) { return _var().var; } else { return _name; } } template <int N> ReductionDomain build_domain(ReductionVariable (&vars)[N]) { vector<ReductionVariable> d(&vars[0], &vars[N]); ReductionDomain dom(d); return dom; } // This just initializes the predefined x, y, z, w members of RDom. void RDom::init_vars(string name) { static string var_names[] = { "x", "y", "z", "w" }; const std::vector<ReductionVariable> &dom_vars = dom.domain(); RVar *vars[] = { &x, &y, &z, &w }; for (size_t i = 0; i < sizeof(vars)/sizeof(vars[0]); i++) { if (i < dom_vars.size()) { *(vars[i]) = RVar(dom, i); } else { *(vars[i]) = RVar(name + "." + var_names[i]); } } } RDom::RDom(ReductionDomain d) : dom(d) { if (d.defined()) { init_vars(""); } } // We suffix all RVars with $r to prevent unintentional name matches with pure vars called x, y, z, w. RDom::RDom(Expr min, Expr extent, string name) { if (name == "") { name = make_entity_name(this, "Halide::RDom", 'r'); } ReductionVariable vars[] = { { name + ".x$r", cast<int>(min), cast<int>(extent) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, string name) { if (name == "") { name = make_entity_name(this, "Halide::RDom", 'r'); } ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, string name) { if (name == "") { name = make_entity_name(this, "Halide::RDom", 'r'); } ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, string name) { if (name == "") { name = make_entity_name(this, "Halide::RDom", 'r'); } ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, string name) { if (name == "") { name = make_entity_name(this, "Halide::RDom", 'r'); } ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, Expr min5, Expr extent5, string name) { if (name == "") { name = make_entity_name(this, "Halide::RDom", 'r'); } ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, { name + ".5$r", cast<int>(min5), cast<int>(extent5) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, Expr min5, Expr extent5, Expr min6, Expr extent6, string name) { if (name == "") { name = make_entity_name(this, "Halide::RDom", 'r'); } ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, { name + ".5$r", cast<int>(min5), cast<int>(extent5) }, { name + ".6$r", cast<int>(min6), cast<int>(extent6) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, Expr min5, Expr extent5, Expr min6, Expr extent6, Expr min7, Expr extent7, string name) { if (name == "") { name = make_entity_name(this, "Halide::RDom", 'r'); } ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, { name + ".5$r", cast<int>(min5), cast<int>(extent5) }, { name + ".6$r", cast<int>(min6), cast<int>(extent6) }, { name + ".7$r", cast<int>(min7), cast<int>(extent7) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Buffer b) { static string var_names[] = {"x$r", "y$r", "z$r", "w$r"}; std::vector<ReductionVariable> vars; for (int i = 0; i < b.dimensions(); i++) { ReductionVariable var = { b.name() + "." + var_names[i], b.min(i), b.extent(i) }; vars.push_back(var); } dom = ReductionDomain(vars); init_vars(b.name()); } RDom::RDom(ImageParam p) { static string var_names[] = {"x$r", "y$r", "z$r", "w$r"}; std::vector<ReductionVariable> vars; for (int i = 0; i < p.dimensions(); i++) { ReductionVariable var = { p.name() + "." + var_names[i], p.min(i), p.extent(i) }; vars.push_back(var); } dom = ReductionDomain(vars); init_vars(p.name()); } int RDom::dimensions() const { return (int)dom.domain().size(); } RVar RDom::operator[](int i) const { if (i == 0) return x; if (i == 1) return y; if (i == 2) return z; if (i == 3) return w; if (i < dimensions()) { return RVar(dom, i); } user_error << "Reduction domain index out of bounds: " << i << "\n"; return x; // Keep the compiler happy } RDom::operator Expr() const { if (dimensions() != 1) { user_error << "Error: Can't treat this multidimensional RDom as an Expr:\n" << (*this) << "\n" << "Only single-dimensional RDoms can be cast to Expr.\n"; } return Expr(x); } RDom::operator RVar() const { if (dimensions() != 1) { user_error << "Error: Can't treat this multidimensional RDom as an RVar:\n" << (*this) << "\n" << "Only single-dimensional RDoms can be cast to RVar.\n"; } return x; } /** Emit an RVar in a human-readable form */ std::ostream &operator<<(std::ostream &stream, RVar v) { stream << v.name() << "(" << v.min() << ", " << v.extent() << ")"; return stream; } /** Emit an RDom in a human-readable form. */ std::ostream &operator<<(std::ostream &stream, RDom dom) { stream << "RDom(\n"; for (int i = 0; i < dom.dimensions(); i++) { stream << " " << dom[i] << "\n"; } stream << ")\n"; return stream; } }
gchauras/Halide
src/RDom.cpp
C++
mit
8,892
(function () { 'use strict'; angular.module('atacamaApp').directive('atacamaIndicator', indicatorDirective); function indicatorDirective() { return { templateUrl: 'app/components/widgets/indicator/indicator.html', link: linkFunc, controller: 'IndicatorWidgetController', controllerAs: 'vm', bindToController: true // because the scope is isolated }; } function linkFunc(scope, element, attrs) { //set to null by default so images will not try to load until the data is returned scope.selectedLocation = null; scope.isLoaded = false; scope.hasError = false; // scope.offsetParent = element.offsetParent(); } })();
the-james-burton/atacama
src/app/components/widgets/indicator/indicator.directive.js
JavaScript
mit
689
define(['tantaman/web/css_manip/CssManip'], function(CassManip) { var el = CassManip.getStyleElem({ id: 'customBackgrounds', create: true }); /** * This is essentially a view class that * render the stylesheet of background classes whenever * new background classes are created. * * @param {EditorModel} editorModel */ function CustomBgStylesheet(editorModel) { this.model = editorModel; editorModel.on('change:customBackgrounds', this.render, this); } CustomBgStylesheet.prototype = { /** * render the stylesheet. Should never * need to be called explicitly. */ render: function(m, customBgs) { if (!customBgs) return; el.innerHTML = JST['strut.presentation_generator/CustomBgStylesheet'](customBgs.get('bgs')); }, /** * Unregister from the model so this component * can be cleaned up. */ dispose: function() { this.model.off(null, null, this); } } return CustomBgStylesheet; });
shirshendu/kine_type
public/editor/bundles/app/strut.editor/CustomBgStylesheet.js
JavaScript
mit
957
import { sp } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/user-custom-actions"; import { ISearchQuery } from "@pnp/sp/search"; import { Web } from "@pnp/sp/webs"; export default class ApplicationCustomizersService { /** * fetchAllApplictionCustomizers */ public fetchAllApplictionCustomizers = async (webURL: string) => { let web = Web(webURL); let response; try { response = await web.userCustomActions(); console.log(response); //let temp = await sp.site.userCustomActions(); //console.log(temp); } catch (error) { console.log(error); response = error; } return response; } /** * getAllSiteCollection */ public getAllSiteCollection = async () => { let response; try { response = await sp.search(<ISearchQuery>{ Querytext: "contentclass:STS_Site", SelectProperties: ["Title", "SPSiteUrl", "WebTemplate"], RowLimit: 1000, TrimDuplicates: true }); console.log(response.PrimarySearchResults); } catch (error) { console.log(error); response = error; } return response; } /** * updateApplicationCustomizer */ public updateApplicationCustomizer = async (webURL: string | number, selectedID: string, updateJSON: any) => { let web = Web(webURL as string); let response; try { response = await web.userCustomActions.getById(selectedID).update(updateJSON); } catch (error) { console.log(error); } } }
AJIXuMuK/sp-dev-fx-webparts
samples/react-Edit-ApplicationCustomizer/src/webparts/applicationCustomizers/service/ApplicationCustomizersService.ts
TypeScript
mit
1,722
package host import ( "errors" "io/ioutil" "path/filepath" "testing" "time" "github.com/NebulousLabs/Sia/crypto" "github.com/NebulousLabs/Sia/modules" "github.com/NebulousLabs/Sia/modules/renter" "github.com/NebulousLabs/Sia/types" ) const ( testUploadDuration = 20 // Duration in blocks of a standard upload during testing. // Helper variables to indicate whether renew is being toggled as input to // uploadFile. renewEnabled = true renewDisabled = false ) // uploadFile uploads a file to the host from the tester's renter. The data // used to make the file is returned. The nickname of the file in the renter is // the same as the name provided as input. func (ht *hostTester) uploadFile(path string, renew bool) ([]byte, error) { // Check that renting is initialized properly. err := ht.initRenting() if err != nil { return nil, err } // Create a file to upload to the host. source := filepath.Join(ht.persistDir, path+".testfile") datasize := uint64(1024) data, err := crypto.RandBytes(int(datasize)) if err != nil { return nil, err } err = ioutil.WriteFile(source, data, 0600) if err != nil { return nil, err } // Have the renter upload to the host. rsc, err := renter.NewRSCode(1, 1) if err != nil { return nil, err } fup := modules.FileUploadParams{ Source: source, SiaPath: path, Duration: testUploadDuration, Renew: renew, ErasureCode: rsc, PieceSize: 0, } err = ht.renter.Upload(fup) if err != nil { return nil, err } // Wait until the upload has finished. for i := 0; i < 100; i++ { time.Sleep(time.Millisecond * 100) // Asynchronous processes in the host access obligations by id, // therefore a lock is required to scan the set of obligations. if func() bool { ht.host.mu.Lock() defer ht.host.mu.Unlock() for _, ob := range ht.host.obligationsByID { if ob.fileSize() >= datasize { return true } } return false }() { break } } // Block until the renter is at 50 upload progress - it takes time for the // contract to confirm renter-side. complete := false for i := 0; i < 50 && !complete; i++ { fileInfos := ht.renter.FileList() for _, fileInfo := range fileInfos { if fileInfo.UploadProgress >= 50 { complete = true } } if complete { break } time.Sleep(time.Millisecond * 50) } if !complete { return nil, errors.New("renter never recognized that the upload completed") } // The rest of the upload can be performed under lock. ht.host.mu.Lock() defer ht.host.mu.Unlock() if len(ht.host.obligationsByID) != 1 { return nil, errors.New("expecting a single obligation") } for _, ob := range ht.host.obligationsByID { if ob.fileSize() >= datasize { return data, nil } } return nil, errors.New("ht.uploadFile: upload failed") } // TestRPCUPload attempts to upload a file to the host, adding coverage to the // upload function. func TestRPCUpload(t *testing.T) { if testing.Short() { t.SkipNow() } ht, err := newHostTester("TestRPCUpload") if err != nil { t.Fatal(err) } ht.host.mu.RLock() baselineAnticipatedRevenue := ht.host.anticipatedRevenue baselineSpace := ht.host.spaceRemaining ht.host.mu.RUnlock() _, err = ht.uploadFile("TestRPCUpload - 1", renewDisabled) if err != nil { t.Fatal(err) } var expectedRevenue types.Currency func() { ht.host.mu.RLock() defer ht.host.mu.RUnlock() if ht.host.anticipatedRevenue.Cmp(baselineAnticipatedRevenue) <= 0 { t.Error("Anticipated revenue did not increase after a file was uploaded") } if baselineSpace <= ht.host.spaceRemaining { t.Error("space remaining on the host does not seem to have decreased") } expectedRevenue = ht.host.anticipatedRevenue }() // Mine until the storage proof goes through, and the obligation gets // cleared. for i := types.BlockHeight(0); i <= testUploadDuration+confirmationRequirement+defaultWindowSize; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Check that the storage proof has succeeded. ht.host.mu.Lock() defer ht.host.mu.Unlock() if len(ht.host.obligationsByID) != 0 { t.Error("host still has obligation, when it should have completed the obligation and submitted a storage proof.") } if !ht.host.anticipatedRevenue.IsZero() { t.Error("host anticipated revenue was not set back to zero") } if ht.host.spaceRemaining != baselineSpace { t.Error("host does not seem to have reclaimed the space after a successful obligation") } if expectedRevenue.Cmp(ht.host.revenue) != 0 { t.Error("host's revenue was not moved from anticipated to expected") } } // TestRPCRenew attempts to upload a file to the host, adding coverage to the // upload function. func TestRPCRenew(t *testing.T) { t.Skip("test skipped because the renter renew function isn't block based") if testing.Short() { t.SkipNow() } ht, err := newHostTester("TestRPCRenew") if err != nil { t.Fatal(err) } _, err = ht.uploadFile("TestRPCRenew- 1", renewEnabled) if err != nil { t.Fatal(err) } ht.host.mu.RLock() expectedRevenue := ht.host.anticipatedRevenue expectedSpaceRemaining := ht.host.spaceRemaining ht.host.mu.RUnlock() // Mine until the storage proof goes through, and the obligation gets // cleared. for i := types.BlockHeight(0); i <= testUploadDuration+confirmationRequirement+defaultWindowSize; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Check that the rewards for the first obligation went through, and that // there is another from the contract being renewed. ht.host.mu.Lock() defer ht.host.mu.Unlock() if len(ht.host.obligationsByID) != 1 { t.Error("file contract was not renenwed after being completed") } if ht.host.anticipatedRevenue.IsZero() { t.Error("host anticipated revenue should be nonzero") } if ht.host.spaceRemaining != expectedSpaceRemaining { t.Error("host space remaining changed after a renew happened") } if expectedRevenue.Cmp(ht.host.revenue) > 0 { t.Error("host's revenue was not increased though a proof was successful") } // TODO: Download the file that got renewed, see if the data is correct. } // TestFailedObligation tests that the host correctly handles missing a storage // proof. func TestFailedObligation(t *testing.T) { if testing.Short() { t.SkipNow() } ht, err := newHostTester("TestFailedObligation") if err != nil { t.Fatal(err) } ht.host.mu.RLock() baselineSpace := ht.host.spaceRemaining ht.host.mu.RUnlock() _, err = ht.uploadFile("TestFailedObligation - 1", renewDisabled) if err != nil { t.Fatal(err) } ht.host.mu.RLock() expectedLostRevenue := ht.host.anticipatedRevenue ht.host.mu.RUnlock() // Close the host, then mine enough blocks that the host has missed the // storage proof window. err = ht.host.Close() if err != nil { t.Fatal(err) } for i := types.BlockHeight(0); i <= testUploadDuration+defaultWindowSize+2; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Restart the host. While catching up, the host should realize that it // missed a storage proof, and should delete the obligation. rebootHost, err := New(ht.cs, ht.tpool, ht.wallet, ":0", filepath.Join(ht.persistDir, modules.HostDir)) if err != nil { t.Fatal(err) } // Host should delete the obligation before finishing startup. rebootHost.mu.Lock() defer rebootHost.mu.Unlock() if len(rebootHost.obligationsByID) != 0 { t.Error("host did not delete a dead storage proof at startup") } if !rebootHost.anticipatedRevenue.IsZero() { t.Error("host did not subtract out anticipated revenue") } if rebootHost.spaceRemaining != baselineSpace { t.Error("host did not reallocate space after failed storage proof") } if rebootHost.lostRevenue.Cmp(expectedLostRevenue) != 0 { t.Error("host did not correctly report lost revenue") } } // TestRestartSuccessObligation tests that a host who went offline for a few // blocks is still able to successfully submit a storage proof. func TestRestartSuccessObligation(t *testing.T) { if testing.Short() { t.SkipNow() } ht, err := newHostTester("TestRestartSuccessObligation") if err != nil { t.Fatal(err) } ht.host.mu.RLock() baselineSpace := ht.host.spaceRemaining ht.host.mu.RUnlock() _, err = ht.uploadFile("TestRestartSuccessObligation - 1", renewDisabled) if err != nil { t.Fatal(err) } ht.host.mu.RLock() expectedRevenue := ht.host.anticipatedRevenue ht.host.mu.RUnlock() // Close the host, then mine some blocks, but not enough that the host // misses the storage proof. err = ht.host.Close() if err != nil { t.Fatal(err) } for i := 0; i <= 5; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Restart the host, and mine enough blocks that the host can submit a // successful storage proof. rebootHost, err := New(ht.cs, ht.tpool, ht.wallet, ":0", filepath.Join(ht.persistDir, modules.HostDir)) if err != nil { t.Fatal(err) } if rebootHost.blockHeight != ht.cs.Height() { t.Error("Host block height does not match the cs block height") } for i := types.BlockHeight(0); i <= testUploadDuration+defaultWindowSize+confirmationRequirement-5; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Confirm that the storage proof was successful. rebootHost.mu.Lock() defer rebootHost.mu.Unlock() if len(rebootHost.obligationsByID) != 0 { t.Error("host did not delete a finished obligation") } if !rebootHost.anticipatedRevenue.IsZero() { t.Error("host did not subtract out anticipated revenue") } if rebootHost.spaceRemaining != baselineSpace { t.Error("host did not reallocate space after storage proof") } if rebootHost.revenue.Cmp(expectedRevenue) != 0 { t.Error("host did not correctly report revenue gains") } } // TestRestartCorruptSuccessObligation tests that a host who went offline for a // few blocks, corrupted the consensus database, but is still able to correctly // create a storage proof. func TestRestartCorruptSuccessObligation(t *testing.T) { if testing.Short() { t.SkipNow() } ht, err := newHostTester("TestRestartCorruptSuccessObligation") if err != nil { t.Fatal(err) } ht.host.mu.RLock() baselineSpace := ht.host.spaceRemaining ht.host.mu.RUnlock() _, err = ht.uploadFile("TestRestartCorruptSuccessObligation - 1", renewDisabled) if err != nil { t.Fatal(err) } ht.host.mu.RLock() expectedRevenue := ht.host.anticipatedRevenue ht.host.mu.RUnlock() // Corrupt the host's consensus tracking, close the host, then mine some // blocks, but not enough that the host misses the storage proof. The host // will need to perform a rescan and update its obligations correctly. ht.host.mu.Lock() ht.host.recentChange[0]++ ht.host.mu.Unlock() err = ht.host.Close() if err != nil { t.Fatal(err) } for i := 0; i <= 3; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Restart the host, and mine enough blocks that the host can submit a // successful storage proof. rebootHost, err := New(ht.cs, ht.tpool, ht.wallet, ":0", filepath.Join(ht.persistDir, modules.HostDir)) if err != nil { t.Fatal(err) } if rebootHost.blockHeight != ht.cs.Height() { t.Error("Host block height does not match the cs block height") } if len(rebootHost.obligationsByID) == 0 { t.Error("host did not correctly reload its obligation") } for i := types.BlockHeight(0); i <= testUploadDuration+defaultWindowSize+confirmationRequirement-3; i++ { _, err := ht.miner.AddBlock() if err != nil { t.Fatal(err) } } // Confirm that the storage proof was successful. rebootHost.mu.Lock() defer rebootHost.mu.Unlock() if len(rebootHost.obligationsByID) != 0 { t.Error("host did not delete a finished obligation") } if !rebootHost.anticipatedRevenue.IsZero() { t.Error("host did not subtract out anticipated revenue") } if rebootHost.spaceRemaining != baselineSpace { t.Error("host did not reallocate space after storage proof") } if rebootHost.revenue.Cmp(expectedRevenue) != 0 { t.Error("host did not correctly report revenue gains") } if rebootHost.lostRevenue.Cmp(expectedRevenue) == 0 { t.Error("host is reporting losses on the file contract") } }
Mingling94/Sia
modules/host/upload_test.go
GO
mit
12,230
/** * @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 { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Comp624Component } from './comp-624.component'; describe('Comp624Component', () => { let component: Comp624Component; let fixture: ComponentFixture<Comp624Component>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ Comp624Component ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(Comp624Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
angular/angular-cli-stress-test
src/app/components/comp-624/comp-624.component.spec.ts
TypeScript
mit
840
#include "glprogram.h" #include <gl/gl3w.h> #include <cstdio> bool compileStatus(GLuint shader) { int ret; glGetShaderiv(shader, GL_COMPILE_STATUS, &ret); return ret; } bool linkStatus(GLuint program) { int ret; glGetProgramiv(program, GL_LINK_STATUS, &ret); return ret; } bool compileShader(GLuint handle, GLenum stype, const char* src) { int shader_len = strlen(src); glShaderSource(handle, 1, &src, &shader_len); glCompileShader(handle); if (!compileStatus(handle)) { char buff[2048]; int nwritten; glGetShaderInfoLog(handle, 2048, &nwritten, buff); const char* typelabel = stype == GL_VERTEX_SHADER ? "vertex" : (stype == GL_FRAGMENT_SHADER ? "fragment" : "unknown"); printf("Error in %s shader\n%s\n", typelabel, buff); return false; } return true; } int compileShader(GLenum type, const char* src) { GLuint handle = glCreateShader(type); compileShader(handle, type, src); return handle; } bool linkProgram(GLuint handle, GLuint vshader, GLuint fshader) { glAttachShader(handle, vshader); glAttachShader(handle, fshader); glLinkProgram(handle); if (!linkStatus(handle)) { char buff[2048]; int nwritten; glGetProgramInfoLog(handle, 2048, &nwritten, buff); printf("Program link error:\n%s\n", buff); return false; } return true; } int linkProgram(const char* vshader_src, const char* fshader_src) { GLuint program = glCreateProgram(); GLuint vshader = compileShader(GL_VERTEX_SHADER, vshader_src); GLuint fshader = compileShader(GL_FRAGMENT_SHADER, fshader_src); if (!linkProgram(program, vshader, fshader)) { glDeleteProgram(program); program = 0; } glDeleteShader(vshader); glDeleteShader(fshader); return program; }
lmurmann/hellogl
hellogl/glprogram.cpp
C++
mit
1,692
#include <climits> #include <cstdlib> #include <cstring> #include "orderline.h" #include "../src/schema/conversion.h" using namespace std; void OrderlineStore::add(string elements[10]) { add_instance(atoi(elements[0].c_str()), atoi(elements[1].c_str()), atoi(elements[2].c_str()), atoi(elements[3].c_str()), atoi(elements[4].c_str()), atoi(elements[5].c_str()), db_stod(elements[6]), db_stol(elements[7]), db_stol(elements[8]), elements[9]); } void OrderlineStore::add_instance(int32_t ol_o_id, int32_t ol_d_id, int32_t ol_w_id, int32_t ol_number, int32_t ol_i_id, int32_t ol_supply_w_id, uint64_t ol_delivery_d, int64_t ol_quantity, int64_t ol_amount, std::string ol_dist_info) { this->ol_o_id.push_back(ol_o_id); this->ol_d_id.push_back(ol_d_id); this->ol_w_id.push_back(ol_w_id); this->ol_number.push_back(ol_number); this->ol_i_id.push_back(ol_i_id); this->ol_supply_w_id.push_back(ol_supply_w_id); this->ol_delivery_d.push_back(ol_delivery_d); this->ol_quantity.push_back(ol_quantity); this->ol_amount.push_back(ol_amount); this->ol_dist_info.push_back(ol_dist_info); pkIndex[std::make_tuple(this->ol_w_id[tid], this->ol_d_id[tid], this->ol_o_id[tid], this->ol_number[tid])] = tid; tid++; } void OrderlineStore::remove(uint64_t tid) { auto pkKey = std::make_tuple(this->ol_w_id[tid], this->ol_d_id[tid], this->ol_o_id[tid], this->ol_number[tid]); auto pkIt = pkIndex.find(pkKey); pkIndex.erase(pkIt); // We want to move the last item to the deleted item's position // We have one item less now, so decrease TID for next add_instance uint64_t tidToSwap = --this->tid; if (tid != tidToSwap) { // Move data from last item to deleted item's position this->ol_o_id[tid] = this->ol_o_id[tidToSwap]; this->ol_d_id[tid] = this->ol_d_id[tidToSwap]; this->ol_w_id[tid] = this->ol_w_id[tidToSwap]; this->ol_number[tid] = this->ol_number[tidToSwap]; this->ol_i_id[tid] = this->ol_i_id[tidToSwap]; this->ol_supply_w_id[tid] = this->ol_supply_w_id[tidToSwap]; this->ol_delivery_d[tid] = this->ol_delivery_d[tidToSwap]; this->ol_quantity[tid] = this->ol_quantity[tidToSwap]; this->ol_amount[tid] = this->ol_amount[tidToSwap]; this->ol_dist_info.set(tid, this->ol_dist_info[tidToSwap]); // Set swapped item's TID in index pkIndex[std::make_tuple(this->ol_w_id[tid], this->ol_d_id[tid], this->ol_o_id[tid], this->ol_number[tid])] = tid; } // Delete the data this->ol_o_id.pop_back(); this->ol_d_id.pop_back(); this->ol_w_id.pop_back(); this->ol_number.pop_back(); this->ol_i_id.pop_back(); this->ol_supply_w_id.pop_back(); this->ol_delivery_d.pop_back(); this->ol_quantity.pop_back(); this->ol_amount.pop_back(); this->ol_dist_info.pop_back(); } uint64_t OrderlineStore::get(int32_t ol_w_id, int32_t ol_d_id, int32_t ol_o_id, int32_t ol_number) { return pkIndex[std::make_tuple(ol_w_id, ol_d_id, ol_o_id, ol_number)]; } std::pair<OrderlineStore::pkIndexType::iterator, OrderlineStore::pkIndexType::iterator> OrderlineStore::get(int32_t ol_w_id, int32_t ol_d_id, int32_t ol_o_id) { return std::make_pair( pkIndex.lower_bound(std::make_tuple(ol_w_id, ol_d_id, ol_o_id, 0)), pkIndex.upper_bound(std::make_tuple(ol_w_id, ol_d_id, ol_o_id, INT_MAX))); }
fwalch/imlab
gen/orderline.cpp
C++
mit
3,313
using Microsoft.Owin.Security.OAuth; using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace CodeReaction.Web { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.EnableCors(); } } }
tecsoft/code-reaction
WebApp/App_Start/WebApiConfig.cs
C#
mit
642
require 'spec_helper' describe Emarsys::Broadcast::Email do it 'should validate valid email' do expect(Emarsys::Broadcast::Email::validate 'winston.smith-1984@big.brother.ru').to be_truthy expect(Emarsys::Broadcast::Email::validate 'abc@example.com').to be_truthy end it 'should not validate invalid email' do expect(Emarsys::Broadcast::Email::validate 'some invalid@email').to be_falsey end end
Valve/emarsys-broadcast-ruby
spec/email_spec.rb
Ruby
mit
416
var dp = jQuery; dp.noConflict(); dp(document).ready(function() { //SMOOTH SCROLL dp('a[href^="#"]').bind('click.smoothscroll', function(e) { e.preventDefault(); dp('html,body').animate({ scrollTop: dp(this.hash).offset().top }, 1200); }); //SUPER SLIDES // dp('#home-slide').superslides({ // animation: 'fade', // You can choose either fade or slide // play: 6000 // }); //ANIMAZE dp('.animaze').bind('inview', function(event, visible) { if (visible) { dp(this).stop().animate({ opacity: 1, top: '0px' }, 500); } /* REMOVE THIS if you want to repeat the animation after the element not in view else { $(this).stop().animate({ opacity: 0 }); $(this).removeAttr('style'); }*/ }); dp('.animaze').stop().animate({ opacity: 0 }); //SERVICES dp("#dp-service").sudoSlider({ customLink: 'a.servicesLink', responsive: true, speed: 350, prevNext: false, useCSS: true, effect: "fadeOutIn", continuous: true, updateBefore: true }); //TEXT ROTATOR dp(".rotatez").textrotator({ animation: "fade", separator: ",", speed: 1700 }); //PORTFOLIO dp('.portfolioContainer').mixitup({ filterSelector: '.portfolioFilter a', targetSelector: '.portfolio-item', effects: ['fade', 'scale'] }); //QUOTE SLIDE dp("#quote-slider").sudoSlider({ customLink: 'a.quoteLink', speed: 425, prevNext: true, responsive: true, prevHtml: '<a href="#" class="quote-left-indicator"><i class="icon-arrow-left"></i></a>', nextHtml: '<a href="#" class="quote-right-indicator"><i class="icon-arrow-right"></i></a>', useCSS: true, continuous: true, effect: "fadeOutIn", updateBefore: true }); //MAGNIFIC POPUP dp('.popup').magnificPopup({ type: 'image' }); //PARALLAX dp('.parallaxize').parallax("50%", 0.3); // CONTACT SLIDER dp("#contact-slider").sudoSlider({ customLink: 'a.contactLink', speed: 750, responsive: true, prevNext: false, useCSS: false, continuous: false, updateBefore: true, effect: "fadeOutIn" }); //Map dp('#map').gmap3({ map: { options: { maxZoom: 15 } }, marker: { address: "Haltern am See, Weseler Str. 151", // PUT YOUR ADDRESS HERE options: { icon: new google.maps.MarkerImage( "http://cdn.webiconset.com/map-icons/images/pin6.png", new google.maps.Size(42, 69, "px", "px") ) } } }, "autofit"); }); dp(window).load(function() { dp("#lazyload").fadeOut(); });
mromrell/quotadeck-frontend
public/partials/js/main.js
JavaScript
mit
3,100
<?php require "header.php"; require "menu.php"; session_start(); require "config.php"; require_once __DIR__ . '/src/Facebook/autoload.php'; $fb = new Facebook\Facebook([ 'app_id' => APP_ID, 'app_secret' => APP_SECRET, 'default_graph_version' => APP_VERSION ]); $helper = $fb->getRedirectLoginHelper(); $permissions = ['email']; // optional try { if (isset($_SESSION['facebook_access_token'])) { $accessToken = $_SESSION['facebook_access_token']; } else { $accessToken = $helper->getAccessToken(); } } catch(Facebook\Exceptions\FacebookResponseException $e) { // When Graph returns an error echo 'Graph returned an error: ' . $e->getMessage(); exit; } catch(Facebook\Exceptions\FacebookSDKException $e) { // When validation fails or other local issues echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } if (isset($accessToken)) { if (isset($_SESSION['facebook_access_token'])) { $fb->setDefaultAccessToken($_SESSION['facebook_access_token']); } else { // getting short-lived access token $_SESSION['facebook_access_token'] = (string) $accessToken; // OAuth 2.0 client handler $oAuth2Client = $fb->getOAuth2Client(); // Exchanges a short-lived access token for a long-lived one $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']); $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken; // setting default access token to be used in script $fb->setDefaultAccessToken($_SESSION['facebook_access_token']); } // redirect the user back to the same page if it has "code" GET variable if (isset($_GET['code'])) { header('Location: ./'); } // getting basic info about user try { $profile_request = $fb->get('/me?fields=name,first_name,last_name,email'); $profile = $profile_request->getGraphNode()->asArray(); } catch(Facebook\Exceptions\FacebookResponseException $e) { // When Graph returns an error echo 'Graph returned an error: ' . $e->getMessage(); session_destroy(); // redirecting user back to app login page header("Location: ./"); exit; } catch(Facebook\Exceptions\FacebookSDKException $e) { // When validation fails or other local issues echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } // printing $profile array on the screen which holds the basic info about user print_r($profile); // Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token'] } else { // replace your website URL same as added in the developers.facebook.com/apps e.g. if you used http instead of https and you used non-www version or www version of your website then you must add the same here $loginUrl = $helper->getLoginUrl('https://sohaibilyas.com/fbapp/', $permissions); echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>'; } include "footer.php";
Alavifuentes/conectate
sdkphp/index.php
PHP
mit
3,096
<?php namespace Propel\Tests\Generator\Migration; /** * @group database */ class ForeignKeyTest extends MigrationTestCase { public function testAdd() { $originXml = ' <database> <entity name="migration_test_6"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> </entity> <entity name="migration_test_7"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> <field name="test_6_id" /> </entity> </database> '; $targetXml = ' <database> <entity name="migration_test_6"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> </entity> <entity name="migration_test_7"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> <field name="test_6_id" type="integer" /> <foreign-key foreignTable="migration_test_6" onDelete="cascade" onUpdate="cascade"> <reference local="test_6_id" foreign="id" /> </foreign-key> </entity> </database> '; $this->migrateAndTest($originXml, $targetXml); } public function testAddNotUnique() { $originXml = ' <database> <entity name="migration_test_6_1"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> </entity> </database> '; $targetXml = ' <database> <entity name="migration_test_6_1"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="id2" type="integer"/> <field name="title" required="true" /> </entity> <entity name="migration_test_7_1"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> <field name="test_6_id" type="integer" /> <foreign-key foreignTable="migration_test_6_1" onDelete="cascade" onUpdate="cascade"> <reference local="test_6_id" foreign="id2" /> </foreign-key> </entity> </database> '; $this->migrateAndTest($originXml, $targetXml); } public function testRemove() { $originXml = ' <database> <entity name="migration_test_6"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> </entity> <entity name="migration_test_7"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> <field name="test_6_id" type="integer" /> <foreign-key foreignTable="migration_test_6" onDelete="cascade" onUpdate="cascade"> <reference local="test_6_id" foreign="id" /> </foreign-key> </entity> </database> '; $targetXml = ' <database> <entity name="migration_test_6"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> </entity> <entity name="migration_test_7"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> <field name="test_6_id" /> </entity> </database> '; $this->migrateAndTest($originXml, $targetXml); } public function testChange() { $originXml = ' <database> <entity name="migration_test_6"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="id2" type="integer" primaryKey="true"/> <field name="title" required="true" /> </entity> <entity name="migration_test_7"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> <field name="test_6_id" type="integer" /> <field name="test_6_id2" type="integer" /> <foreign-key foreignTable="migration_test_6" onDelete="cascade" onUpdate="cascade"> <reference local="test_6_id" foreign="id" /> <reference local="test_6_id2" foreign="id2" /> </foreign-key> </entity> </database> '; $targetXml = ' <database> <entity name="migration_test_6"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="id2" type="integer" primaryKey="true"/> <field name="title" required="true" /> </entity> <entity name="migration_test_7"> <field name="id" type="integer" primaryKey="true" autoIncrement="true" /> <field name="title" required="true" /> <field name="test_6_id" /> <field name="test_6_id2" /> </entity> </database> '; $this->migrateAndTest($originXml, $targetXml); } }
propelorm/Propel3
tests/Generator/Migration/ForeignKeyTest.php
PHP
mit
4,945
<?php namespace Theintz\PhpDaemon\Plugin; use Theintz\PhpDaemon\Daemon; use Theintz\PhpDaemon\Exception; use Theintz\PhpDaemon\IPlugin; use Theintz\PhpDaemon\Lib\Command; /** * Create a simple socket server. * Supply an IP and Port for incoming connections. Add any number of Command objects to parse client input. * * Used in blocking mode, this can be the backbone of a Daemon based server with a loop_interval set to Null. * Alternatively, you could set $blocking = false and use it to interact with a timer-based Daemon application. * * Can be combined with the Worker API by adding Command objects that call methods attached to a Worker. That would leave * the main Application process to handle connections and client input, worker process management, and passing commands * between client input to worker calls, and worker return values to client output. * */ class Server implements IPlugin { const COMMAND_CONNECT = 'CLIENT_CONNECT'; const COMMAND_DISCONNECT = 'CLIENT_DISCONNECT'; const COMMAND_DESTRUCT = 'SERVER_DISCONNECT'; /** * @var Daemon */ public $daemon; /** * The IP Address server will listen on * @var string IP */ public $ip; /** * The Port the server will listen on * @var integer */ public $port; /** * The socket resource * @var Resource */ public $socket; /** * Maximum number of concurrent clients * @var int */ public $max_clients = 10; /** * Maximum bytes read from a given client connection at a time * @var int */ public $max_read = 1024; /** * Array of stdClass client structs. * @var stdClass[] */ public $clients = array(); /** * Is this a Blocking server or a Polling server? When in blocking mode, the server will * wait for connections & commands indefinitely. When polling, it will look for any connections or commands awaiting * a response and return immediately if there aren't any. * @var bool */ public $blocking = false; /** * Write verbose logging to the application log when true. * @var bool */ public $debug = true; /** * Array of Command objects to match input against. * Note: In addition to input rec'd from the client, the server will emit the following commands when appropriate: * CLIENT_CONNECT(stdClass Client) * CLIENT_DISCONNECT(stdClass Client) * SERVER_DISCONNECT * * @var Command[] */ private $commands = array(); public function __construct(Daemon $daemon) { $this->daemon = $daemon; } public function __destruct() { unset($this->daemon); } /** * Called on Construct or Init * @return void */ public function setup() { $this->socket = socket_create(AF_INET, SOCK_STREAM, 0); if (!socket_bind($this->socket, $this->ip, $this->port)) { $errno = socket_last_error(); $this->error(sprintf('Could not bind to address %s:%s [%s] %s', $this->ip, $this->port, $errno, socket_strerror($errno))); throw new Exception('Could not start server.'); } socket_listen($this->socket); $this->daemon->on(Daemon::ON_POSTEXECUTE, array($this, 'run')); } /** * Called on Destruct * @return void */ public function teardown() { foreach(array_keys($this->clients) as $slot) $this->disconnect($slot); @ socket_shutdown($this->socket, 1); usleep(500); @ socket_shutdown($this->socket, 0); @ socket_close($this->socket); $this->socket = null; } /** * This is called during object construction to validate any dependencies * NOTE: At a minimum you should ensure that if $errors is not empty that you pass it along as the return value. * @return Array Return array of error messages (Think stuff like "GD Library Extension Required" or "Cannot open /tmp for Writing") or an empty array */ public function check_environment(array $errors = array()) { if (!is_callable('socket_create')) $errors[] = 'Socket support is currently unavailable: You must add the php_sockets extension to your php.ini or recompile php with the --enable-sockets option set'; return $errors; } /** * Add a Command object to the command queue. Input from a client is evaluated against these commands * in the order they are added * * @param Command $command */ public function addCommand(Command $command) { $this->commands[] = $command; return $this; } /** * An alternative to addCommand - a simple factory for Command objects. * @param $regex * @param $callable */ public function newCommand($regex, $callable) { $cmd = new Command(); $cmd->regex = $regex; $cmd->callable = $callable; return $this->addCommand($cmd); } public function run() { // Build an array of sockets and select any with pending I/O $read = array ( 0 => $this->socket ); foreach($this->clients as $client) $read[] = $client->socket; $result = @ socket_select($read, $write = null, $except = null, $this->blocking ? null : 1); if ($result === false || ($result === 0 && $this->blocking)) { $this->error('Socket Select Interruption: ' . socket_strerror(socket_last_error())); return false; } // If the master socket is in the $read array, there's a pending connection if (in_array($this->socket, $read)) $this->connect(); // Handle input from sockets in the $read array. $daemon = $this->daemon; $printer = function($str) use ($daemon) { $daemon->log($str, 'SocketServer'); }; foreach($this->clients as $slot => $client) { if (!in_array($client->socket, $read)) continue; $input = socket_read($client->socket, $this->max_read); if ($input === null) { $this->disconnect($slot); continue; } $this->command($input, array($client->write, $printer)); } } private function connect() { $slot = $this->slot(); if ($slot === null) throw new Exception(sprintf('%s Failed - Maximum number of connections has been reached.', __METHOD__)); $this->debug("Creating New Connection"); $client = new \stdClass(); $client->socket = socket_accept($this->socket); if (empty($client->socket)) throw new Exception(sprintf('%s Failed - socket_accept failed with error: %s', __METHOD__, socket_last_error())); socket_getpeername($client->socket, $client->ip); $client->write = function($string, $term = "\r\n") use($client) { if($term) $string .= $term; return socket_write($client->socket, $string, strlen($string)); }; $this->clients[$slot] = $client; // @todo clean this up $daemon = $this->daemon; $this->command(self::COMMAND_CONNECT, array($client->write, function($str) use ($daemon) { $daemon->log($str, 'SocketServer'); })); } private function command($input, array $args = array()) { foreach($this->commands as $command) if($command->match($input, $args) && $command->exclusive) break; } private function disconnect($slot) { $daemon = $this->daemon; $this->command(self::COMMAND_DISCONNECT, array($this->clients[$slot]->write, function($str) use ($daemon) { $daemon->log($str, 'SocketServer'); })); @ socket_shutdown($this->clients[$slot]->socket, 1); usleep(500); @ socket_shutdown($this->clients[$slot]->socket, 0); @ socket_close($this->clients[$slot]->socket); unset($this->clients[$slot]); } private function slot() { for($i=0; $i < $this->max_clients; $i++ ) if (empty($this->clients[$i])) return $i; return null; } private function debug($message) { if (!$this->debug) return; $this->daemon->debug($message, 'SocketServer'); } private function error($message) { $this->daemon->error($message, 'SocketServer'); } private function log($message) { $this->daemon->log($message, 'SocketServer'); } }
theintz/PHP-Daemon
src/PhpDaemon/Plugin/Server.php
PHP
mit
8,663
#include "bitcoinunits.h" #include <QStringList> BitcoinUnits::BitcoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits() { QList<BitcoinUnits::Unit> unitlist; unitlist.append(BTC); unitlist.append(mBTC); unitlist.append(uBTC); return unitlist; } bool BitcoinUnits::valid(int unit) { switch(unit) { case BTC: case mBTC: case uBTC: return true; default: return false; } } QString BitcoinUnits::name(int unit) { switch(unit) { case BTC: return QString("LTCC"); case mBTC: return QString("mLTCC"); case uBTC: return QString::fromUtf8("μLTCC"); default: return QString("???"); } } QString BitcoinUnits::description(int unit) { switch(unit) { case BTC: return QString("Litecoin Classic"); case mBTC: return QString("milli Litecoin Classic (1 / 1,000)"); case uBTC: return QString("micro Litecoin Classic (1 / 1,000,000)"); default: return QString("???"); } } //a single unit (.00000001) of Litecoin Classic is called a "wander." qint64 BitcoinUnits::factor(int unit) { switch(unit) { case BTC: return 100000000; case mBTC: return 100000; case uBTC: return 100; default: return 100000000; } } int BitcoinUnits::amountDigits(int unit) { switch(unit) { case BTC: return 8; // 21,000,000 (# digits, without commas) case mBTC: return 11; // 21,000,000,000 case uBTC: return 14; // 21,000,000,000,000 default: return 0; } } int BitcoinUnits::decimals(int unit) { switch(unit) { case BTC: return 8; case mBTC: return 5; case uBTC: return 2; default: return 0; } } QString BitcoinUnits::format(int unit, qint64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Right-trim excess 0's after the decimal point int nTrim = 0; for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i) ++nTrim; remainder_str.chop(nTrim); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); return quotient_str + QString(".") + remainder_str; } QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign) { return format(unit, amount, plussign) + QString(" ") + name(unit); } bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); QStringList parts = value.split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } qint64 retvalue = str.toLongLong(&ok); if(val_out) { *val_out = retvalue; } return ok; } int BitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); }
render2k/litecoinclassic
src/qt/bitcoinunits.cpp
C++
mit
4,375
namespace AgileObjects.AgileMapper.Api.Configuration.Projection { /// <summary> /// Enables chaining of configurations for the same source and result type. /// </summary> /// <typeparam name="TSourceElement">The source type to which the configuration should apply.</typeparam> /// <typeparam name="TResultElement">The result type to which the configuration should apply.</typeparam> public interface IProjectionConfigContinuation<TSourceElement, TResultElement> { /// <summary> /// Perform another configuration of how this mapper projects to and from the source and result types /// being configured. This property exists purely to provide a more fluent configuration interface. /// </summary> IFullProjectionConfigurator<TSourceElement, TResultElement> And { get; } /// <summary> /// Perform an alternative configuration of how this mapper projects to and from the source and result /// types being configured. This property exists purely to provide a more fluent configuration interface. /// </summary> IFullProjectionConfigurator<TSourceElement, TResultElement> But { get; } } }
agileobjects/AgileMapper
AgileMapper/Api/Configuration/Projection/IProjectionConfigContinuation.cs
C#
mit
1,199
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SetupEnviroment { class Application { public static void Main(string[] args) { NameSelector.DoExample(); //IdSelector.Main(); //NoSuchElement.DoExample(); Console.ReadKey(); } } }
ilse-macias/SeleniumSetup
SetupEnviroment/Application.cs
C#
mit
397
/* ********************************************************************************************************** * The MIT License (MIT) * * * * Copyright (c) 2016 Hypermediasystems Ges. f. Software mbH * * Web: http://www.hypermediasystems.de * * This file is part of hmssp * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * ************************************************************************************************************ */ using System; using System.Collections.Generic; using System.Dynamic; using System.Reflection; using Newtonsoft.Json; namespace HMS.SP{ /// <summary> /// <para>https://msdn.microsoft.com/en-us/library/office/dn600183.aspx#bk_Notes</para> /// </summary> public class Implementationnotes : SPBase{ [JsonProperty("__HMSError")] public HMS.Util.__HMSError __HMSError_ { set; get; } [JsonProperty("__status")] public SP.__status __status_ { set; get; } [JsonProperty("__deferred")] public SP.__deferred __deferred_ { set; get; } [JsonProperty("__metadata")] public SP.__metadata __metadata_ { set; get; } public Dictionary<string, string> __rest; // no properties found /// <summary> /// <para> Endpoints </para> /// </summary> static string[] endpoints = { }; public Implementationnotes(ExpandoObject expObj) { try { var use_EO = ((dynamic)expObj).entry.content.properties; HMS.SP.SPUtil.expando2obj(use_EO, this, typeof(Implementationnotes)); } catch (Exception ex) { } } // used by Newtonsoft.JSON public Implementationnotes() { } public Implementationnotes(string json) { if( json == String.Empty ) return; dynamic jobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json); dynamic refObj = jobject; if (jobject.d != null) refObj = jobject.d; string errInfo = ""; if (refObj.results != null) { if (refObj.results.Count > 1) errInfo = "Result is Collection, only 1. entry displayed."; refObj = refObj.results[0]; } List<string> usedFields = new List<string>(); usedFields.Add("__HMSError"); HMS.SP.SPUtil.dyn_ValueSet("__HMSError", refObj, this); usedFields.Add("__deferred"); this.__deferred_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.__deferred)); usedFields.Add("__metadata"); this.__metadata_ = new SP.__metadata(HMS.SP.SPUtil.dyn_toString(refObj.__metadata)); this.__rest = new Dictionary<string, string>(); var dyn = ((Newtonsoft.Json.Linq.JContainer)refObj).First; while (dyn != null) { string Name = ((Newtonsoft.Json.Linq.JProperty)dyn).Name; string Value = ((Newtonsoft.Json.Linq.JProperty)dyn).Value.ToString(); if ( !usedFields.Contains( Name )) this.__rest.Add( Name, Value); dyn = dyn.Next; } if( errInfo != "") this.__HMSError_.info = errInfo; } } }
helmuttheis/hmsspx
hmssp/SP.gen/Implementationnotes.cs
C#
mit
4,804
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Web.UI; using System.Web.UI.WebControls; using Vevo; using Vevo.Domain.DataInterfaces; using Vevo.Shared.Utilities; using Vevo.WebAppLib; using Vevo.Base.Domain; public partial class Components_SearchFilterNew : Vevo.WebUI.International.BaseLanguageUserControl, ISearchFilter { private NameValueCollection FieldTypes { get { if (ViewState["FieldTypes"] == null) ViewState["FieldTypes"] = new NameValueCollection(); return (NameValueCollection) ViewState["FieldTypes"]; } } private string GenerateShowHideScript( bool textPanel, bool boolPanel, bool valueRangePanel, bool dateRangePanel ) { string script; if (textPanel) script = String.Format( "document.getElementById('{0}').style.display = '';", uxTextPanel.ClientID ); else script = String.Format( "document.getElementById('{0}').style.display = 'none';", uxTextPanel.ClientID ); if (boolPanel) script += String.Format( "document.getElementById('{0}').style.display = '';", uxBooleanPanel.ClientID ); else script += String.Format( "document.getElementById('{0}').style.display = 'none';", uxBooleanPanel.ClientID ); if (valueRangePanel) script += String.Format( "document.getElementById('{0}').style.display = '';", uxValueRangePanel.ClientID ); else script += String.Format( "document.getElementById('{0}').style.display = 'none';", uxValueRangePanel.ClientID ); if (dateRangePanel) script += String.Format( "document.getElementById('{0}').style.display = '';", uxDateRangePanel.ClientID ); else script += String.Format( "document.getElementById('{0}').style.display = 'none';", uxDateRangePanel.ClientID ); return script; } private void ShowTextFilterInput() { uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "" ); uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); } private void ShowBooleanFilterInput() { uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "" ); uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); } private void ShowValueRangeFilterInput() { uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "" ); uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); } private void ShowDateRangeFilterInput() { uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "" ); } private void HideAllInput() { uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" ); } private void RegisterDropDownPostback() { string script = "if(this.value == ''){ javascript:__doPostBack('" + uxFilterDrop.UniqueID + "',''); }"; foreach (ListItem item in uxFilterDrop.Items) { switch (ParseSearchType( FieldTypes[item.Value] )) { case SearchFilter.SearchFilterType.Text: script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( true, false, false, false ) + "}"; break; case SearchFilter.SearchFilterType.Boolean: script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( false, true, false, false ) + "}"; break; case SearchFilter.SearchFilterType.ValueRange: script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( false, false, true, false ) + "}"; break; case SearchFilter.SearchFilterType.Date: script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( false, false, false, true ) + "}"; break; } } script += "document.getElementById( '" + uxValueText.ClientID + "' ).value = '';"; script += "document.getElementById( '" + uxBooleanDrop.ClientID + "' ).value = 'True';"; script += "document.getElementById( '" + uxLowerText.ClientID + "' ).value = '';"; script += "document.getElementById( '" + uxUpperText.ClientID + "' ).value = '';"; script += "document.getElementById( '" + uxStartDateText.ClientID + "' ).value = '';"; script += "document.getElementById( '" + uxEndDateText.ClientID + "' ).value = '';"; uxFilterDrop.Attributes.Add( "onchange", script ); } private string GetFilterType( Type dataType ) { string type; if (dataType == Type.GetType( "System.Byte" ) || dataType == Type.GetType( "System.SByte" ) || dataType == Type.GetType( "System.Char" ) || dataType == Type.GetType( "System.String" )) { type = SearchFilter.SearchFilterType.Text.ToString(); } else if (dataType == Type.GetType( "System.Boolean" )) { type = SearchFilter.SearchFilterType.Boolean.ToString(); } else if ( dataType == Type.GetType( "System.Decimal" ) || dataType == Type.GetType( "System.Double" ) || dataType == Type.GetType( "System.Int16" ) || dataType == Type.GetType( "System.Int32" ) || dataType == Type.GetType( "System.Int64" ) || dataType == Type.GetType( "System.UInt16" ) || dataType == Type.GetType( "System.UInt32" ) || dataType == Type.GetType( "System.UInt64" )) { type = SearchFilter.SearchFilterType.ValueRange.ToString(); } else if (dataType == Type.GetType( "System.DateTime" )) { type = SearchFilter.SearchFilterType.Date.ToString(); } else { type = String.Empty; } return type; } private SearchFilter.SearchFilterType ParseSearchType( string searchFilterType ) { SearchFilter.SearchFilterType type; if (String.Compare( searchFilterType, SearchFilter.SearchFilterType.Text.ToString(), true ) == 0) type = SearchFilter.SearchFilterType.Text; else if (String.Compare( searchFilterType, SearchFilter.SearchFilterType.Boolean.ToString(), true ) == 0) type = SearchFilter.SearchFilterType.Boolean; else if (String.Compare( searchFilterType, SearchFilter.SearchFilterType.ValueRange.ToString(), true ) == 0) type = SearchFilter.SearchFilterType.ValueRange; else if (String.Compare( searchFilterType, SearchFilter.SearchFilterType.Date.ToString(), true ) == 0) type = SearchFilter.SearchFilterType.Date; else type = SearchFilter.SearchFilterType.None; return type; } private void RemoveSearchFilter() { SearchFilterObj = SearchFilter.GetFactory() .Create(); uxMessageLabel.Text = String.Empty; } private void TieTextBoxesWithButtons() { WebUtilities.TieButton( this.Page, uxValueText, uxTextSearchImageButton ); WebUtilities.TieButton( this.Page, uxLowerText, uxValueRangeSearchImageButton ); WebUtilities.TieButton( this.Page, uxUpperText, uxValueRangeSearchImageButton ); WebUtilities.TieButton( this.Page, uxStartDateText, uxDateRangeImageButton ); WebUtilities.TieButton( this.Page, uxEndDateText, uxDateRangeImageButton ); } private void DisplayTextSearchMessage( string fieldName, string value ) { if (!String.IsNullOrEmpty( value )) { uxMessageLabel.Text = String.Format( Resources.SearchFilterMessages.TextMessage, value, fieldName ); } } private void DisplayBooleanSearchMessage( string fieldName, string value ) { bool boolValue; if (Boolean.TryParse( value, out boolValue )) { uxMessageLabel.Text = String.Format( Resources.SearchFilterMessages.BooleanMessage, ConvertUtilities.ToYesNo( boolValue ), fieldName ); } } private void DisplayValueRangeMessage( string fieldName, string value1, string value2 ) { if (!String.IsNullOrEmpty( value1 ) && !String.IsNullOrEmpty( value2 )) { uxMessageLabel.Text = String.Format( Resources.SearchFilterMessages.ValueRangeBothMessage, value1, value2, fieldName ); } else if (!String.IsNullOrEmpty( value1 )) { uxMessageLabel.Text = String.Format( Resources.SearchFilterMessages.ValueRangeLowerOnlyMessage, value1, fieldName ); } else if (!String.IsNullOrEmpty( value2 )) { uxMessageLabel.Text = String.Format( Resources.SearchFilterMessages.ValueRangeUpperOnlyMessage, value2, fieldName ); } } private void RestoreControls() { uxFilterDrop.SelectedValue = SearchFilterObj.FieldName; switch (SearchFilterObj.FilterType) { case SearchFilter.SearchFilterType.Text: uxValueText.Text = SearchFilterObj.Value1; DisplayTextSearchMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1 ); break; case SearchFilter.SearchFilterType.Boolean: uxBooleanDrop.SelectedValue = ConvertUtilities.ToBoolean( SearchFilterObj.Value1 ).ToString(); DisplayBooleanSearchMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1 ); break; case SearchFilter.SearchFilterType.ValueRange: uxLowerText.Text = SearchFilterObj.Value1; uxUpperText.Text = SearchFilterObj.Value2; DisplayValueRangeMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1, SearchFilterObj.Value2 ); break; case SearchFilter.SearchFilterType.Date: uxStartDateText.Text = ConvertUtilities.ToDateTime( SearchFilterObj.Value1 ).ToString( "MMMM d,yyyy" ); uxEndDateText.Text = ConvertUtilities.ToDateTime( SearchFilterObj.Value2 ).ToString( "MMMM d,yyyy" ); DisplayValueRangeMessage( SearchFilterObj.FieldName, uxStartDateText.Text, uxEndDateText.Text ); break; } } private void ShowSelectedInput( SearchFilter.SearchFilterType filterType ) { switch (filterType) { case SearchFilter.SearchFilterType.Text: ShowTextFilterInput(); break; case SearchFilter.SearchFilterType.Boolean: ShowBooleanFilterInput(); break; case SearchFilter.SearchFilterType.ValueRange: ShowValueRangeFilterInput(); break; case SearchFilter.SearchFilterType.Date: ShowDateRangeFilterInput(); break; default: HideAllInput(); RemoveSearchFilter(); break; } } private bool IsShowAllSelected() { return String.IsNullOrEmpty( uxFilterDrop.SelectedValue ); } private void LoadDefaultFromQuery() { ShowSelectedInput( SearchFilterObj.FilterType ); RestoreControls(); } protected void Page_Load( object sender, EventArgs e ) { TieTextBoxesWithButtons(); if (!IsPostBack) { LoadDefaultFromQuery(); } } protected void uxFilterDrop_SelectedIndexChanged( object sender, EventArgs e ) { ShowSelectedInput( ParseSearchType( FieldTypes[uxFilterDrop.SelectedValue] ) ); if (IsShowAllSelected()) OnBubbleEvent( e ); } protected void uxTextSearchButton_Click( object sender, EventArgs e ) { PopulateValueFilter( SearchFilter.SearchFilterType.Text, uxFilterDrop.SelectedValue, uxValueText.Text, e ); } protected void uxBooleanSearchButton_Click( object sender, EventArgs e ) { PopulateValueFilter( SearchFilter.SearchFilterType.Boolean, uxFilterDrop.SelectedValue, uxBooleanDrop.SelectedValue, e ); } protected void uxValueRangeSearchButton_Click( object sender, EventArgs e ) { PopulateValueRangeFilter( SearchFilter.SearchFilterType.ValueRange, uxFilterDrop.SelectedValue, uxLowerText.Text, uxUpperText.Text, e ); } protected void uxDateRangeButton_Click( object sender, EventArgs e ) { PopulateValueRangeFilter( SearchFilter.SearchFilterType.Date, uxFilterDrop.SelectedValue, uxStartDateText.Text, uxEndDateText.Text, e ); } private void PopulateValueFilter( SearchFilter.SearchFilterType typeField, string value, string val1, EventArgs e ) { SearchFilterObj = SearchFilter.GetFactory() .WithFilterType( typeField ) .WithFieldName( value ) .WithValue1( val1 ) .Create(); if (typeField == SearchFilter.SearchFilterType.Text) DisplayTextSearchMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1 ); else if (typeField == SearchFilter.SearchFilterType.Boolean) DisplayBooleanSearchMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1 ); // Propagate event to parent OnBubbleEvent( e ); } private void PopulateValueRangeFilter( SearchFilter.SearchFilterType typeField, string value, string val1, string val2, EventArgs e ) { SearchFilterObj = SearchFilter.GetFactory() .WithFilterType( typeField ) .WithFieldName( value ) .WithValue1( val1 ) .WithValue2( val2 ) .Create(); DisplayValueRangeMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1, SearchFilterObj.Value2 ); // Propagate event to parent OnBubbleEvent( e ); } public void SetUpSchema( IList<TableSchemaItem> columnList, params string[] excludingColumns ) { uxFilterDrop.Items.Clear(); FieldTypes.Clear(); uxFilterDrop.Items.Add( new ListItem( Resources.SearchFilterMessages.FilterShowAll, String.Empty ) ); FieldTypes[Resources.SearchFilterMessages.FilterShowAll] = SearchFilter.SearchFilterType.None.ToString(); for (int i = 0; i < columnList.Count; i++) { if (!StringUtilities.IsStringInArray( excludingColumns, columnList[i].ColumnName, true )) { string type = GetFilterType( columnList[i].DataType ); if (!String.IsNullOrEmpty( type )) { uxFilterDrop.Items.Add( columnList[i].ColumnName ); FieldTypes[columnList[i].ColumnName] = type; } } } RegisterDropDownPostback(); } public void SetUpSchema( IList<TableSchemaItem> columnList, NameValueCollection renameList, params string[] excludingColumns ) { SetUpSchema( columnList, excludingColumns ); for (int i = 0; i < renameList.Count; i++) { for (int j = 0; j < columnList.Count; j++) { if (renameList.AllKeys[i].ToString() == columnList[j].ColumnName) { string type = GetFilterType( columnList[j].DataType ); if (!String.IsNullOrEmpty( type )) { uxFilterDrop.Items[j + 1].Text = renameList[i].ToString(); uxFilterDrop.Items[j + 1].Value = renameList.AllKeys[i].ToString(); FieldTypes[renameList[i].ToString()] = type; } } } } RegisterDropDownPostback(); } public SearchFilter SearchFilterObj { get { if (ViewState["SearchFilter"] == null) return SearchFilter.GetFactory() .Create(); else return (SearchFilter) ViewState["SearchFilter"]; } set { ViewState["SearchFilter"] = value; } } public void ClearFilter() { RemoveSearchFilter(); uxFilterDrop.SelectedValue = ""; HideAllInput(); } public void UpdateBrowseQuery( UrlQuery urlQuery ) { urlQuery.RemoveQuery( "Type" ); urlQuery.RemoveQuery( "FieldName" ); urlQuery.RemoveQuery( "FieldValue" ); urlQuery.RemoveQuery( "Value1" ); urlQuery.RemoveQuery( "Value2" ); if (SearchFilterObj.FilterType != SearchFilter.SearchFilterType.None) { urlQuery.AddQuery( "Type", SearchFilterObj.FilterType.ToString() ); urlQuery.AddQuery( "FieldName", SearchFilterObj.FieldName ); urlQuery.AddQuery( "Value1", SearchFilterObj.Value1 ); if (!String.IsNullOrEmpty( SearchFilterObj.Value2 )) urlQuery.AddQuery( "Value2", SearchFilterObj.Value2 ); } } }
holmes2136/ShopCart
Components/SearchFilterNew.ascx.cs
C#
mit
18,341
<?php namespace Eeemarv\EeemarvBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use MimeMailParser\Parser; use MimeMailParser\Attachment; class MailCommand extends ContainerAwareCommand { private $returnErrors = array(); private $domain = 'localhost'; protected function configure() { $this ->setName('eeemarv:mail') ->setDescription('pipes mails. use -q option. mailParse php extension has to be enabled.') ->addArgument('path', InputArgument::OPTIONAL, 'The path to the email-file.') ; } protected function execute(InputInterface $input, OutputInterface $output) { $parser = new Parser(); $path = $input->getArgument('path'); if ($path){ $parser->setPath($path); } else { $parser->setStream(fopen('php://stdin', 'r')); } if ($parser->getHeader('cc')){ exit; // feedback error (todo) } $subject = $parser->getHeader('subject'); if (!$subject){ exit; // feedback error (todo) } list($toId, $toDomain) = $this->decompose($parser->getHeader('to')); list($fromId, $fromDomain) = $this->decompose($parser->getHeader('from'), $toDomain); list($uniqueId, $domain) = $this->decompose($parser->getHeader('message-id'), $toDomain); $returnPath = $parser->getHeader('return-path'); $body = $parser->getMessageBody('html'); if (!$body){ $body = $parser->getMessageBody('text'); if (!$body){ exit; } } /* $attachments = $parser->getAttachments(); foreach ($attachments as $attachment) { $filename = $attachment->filename; if ($f = fopen($save_dir.$filename, 'w')) { while($bytes = $attachment->read()) { fwrite($f, $bytes); } fclose($f); } } */ $output->writeln('from id:'.$fromId); $output->writeln('to id:'.$toId); $output->writeln('subject:'.$subject); $output->writeln('return-path:'.$returnPath); $output->writeln('message-id:'.$uniqueId.'@'.$domain); $output->writeln('unique-id:'.$uniqueId); $output->writeln('domain:'.$domain); $output->writeln('body:'.$body); $output->writeln('html:'.$html); } private function decompose($address, $compareDomain = null) { $addressAry = mailparse_rfc822_parse_addresses($address); if (!sizeOf($addressAry)){ // missing address exit; } if (sizeOf($addressAry) > 1){ // more than one address (feedback error - todo ) exit; } $address = $addressAry[0]['address']; list($id, $domain) = explode('@', $address); if (!$id || !$domain || $domain == $compareDomain){ exit; } return array($id, $domain); } }
eeemarv/eeemarv
src/Eeemarv/EeemarvBundle/Command/MailCommand.php
PHP
mit
3,016
/* * aem-sling-contrib * https://github.com/dherges/aem-sling-contrib * * Copyright (c) 2016 David Herges * Licensed under the MIT license. */ define([ "./core", "./var/slice", "./callbacks" ], function( jQuery, slice ) { jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // Add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // If we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); return jQuery; });
dherges/aem-sling-contrib
content/bootstrap/src/main/content/jcr_root/etc/clientlibs/bootstrap/vendor/jquery/src/deferred.js
JavaScript
mit
4,564
/// <reference path="../../../typings/index.d.ts" /> import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { UserList } from '../components/users'; export class People extends React.Component<{}, {}> { render () { return ( <div className="row"> <div id="content"> <UserList /> </div> </div> ); } }
arnabdas/yam-in
src/app/views/people.tsx
TypeScript
mit
375
var http = require("http"); var url = require("url"); function start(route, handle) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received."); route(handle, pathname, response); } http.createServer(onRequest).listen(8888); console.log("Server has started"); } exports.start = start;
ombt/ombt
jssrc/nodebeginner/server/ver4/server.js
JavaScript
mit
421
<?php /** * Copyright (c) 2015 Tobias Schindler * * 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. */ namespace Alcys\Core\Db\Facade; use Alcys\Core\Db\Factory\DbFactoryInterface; use Alcys\Core\Db\References\ColumnInterface; use Alcys\Core\Db\References\OrderModeEnumInterface; use Alcys\Core\Db\References\TableInterface; use Alcys\Core\Db\Statement\ConditionStatementInterface; use Alcys\Core\Db\Statement\StatementInterface; use Alcys\Core\Db\Statement\UpdateInterface; use Alcys\Core\Types\Numeric; /** * Class UpdateFacade * @package Alcys\Core\Db\Facade */ class UpdateFacade implements UpdateFacadeInterface, WhereConditionFacadeInterface { /** * @var \PDO */ private $pdo; /** * @var UpdateInterface|StatementInterface|ConditionStatementInterface */ private $update; /** * @var DbFactoryInterface */ private $factory; /** * @var array */ private $columnsArray = array(); /** * Initialize the update facade. * Set all required properties to update entries in the database. * * @param \PDO $pdo PDO connection. * @param UpdateInterface $update Select statement. * @param DbFactoryInterface $factory Factory to create several objects. * @param string $table Name of the table from which should select (tables can get extended). */ public function __construct(\PDO $pdo, UpdateInterface $update, DbFactoryInterface $factory, $table) { $this->pdo = $pdo; $this->update = $update; $this->factory = $factory; /** @var TableInterface $tableObj */ $tableObj = $this->factory->references('Table', $table); $this->update->table($tableObj); } /** * Execute the query and update the expected entries in the database. * * @throws \Exception When an error occur while updating. */ public function execute() { $query = $this->factory->builder($this->update)->process(); $result = $this->pdo->query($query); if(!$result) { throw new \Exception('An error while updating is occurred'); } } /** * Set a single column to the query which should get an update. * Afterwards, you have to call the UpdateFacade::value() method!!! * This process can done multiple times to update more then one column. * * @param string $column Name of the column which should updated. * * @return $this The same instance to concatenate methods. */ public function column($column) { /** @var ColumnInterface $columnObj */ $columnObj = $this->factory->references('Column', $column); $this->update->column($columnObj); return $this; } /** * Set the value for the column, which is passed as argument in the UpdateFacade::column() method. * You have to call this method immediate after the column method. * Before calling this method again, the column() has to be invoked. * * @param string $value The value which should set. * * @return $this The same instance to concatenate methods. * @throws \Exception When UpdateFacade::column() was not called before. */ public function value($value, $type = null) { $refType = ($type === 'column') ? 'Column' : 'Value'; $valueObj = $this->factory->references($refType, $value); $this->update->value($valueObj); return $this; } /** * Set multiple columns to the query which should get an update. * Afterwards, you have to call the UpdateFacade::values() method!!! * * @param array $columns An usual array with the column names as elements. * * @return $this The same instance to concatenate methods. */ public function columns(array $columns) { $this->columnsArray = $columns; return $this; } /** * Set values for the columns, which are passed as array argument in the UpdateFacade::columns() method. * You have to call this method immediate after the columns method. * Before calling this method again, the columns() has to be invoked. * * @param array $values An usual array with the values as elements. * * @return $this The same instance to concatenate methods. * @throws \Exception When the UpdateFacade::columns() method was not called before. */ public function values(array $values) { $columnsArraySize = count($this->columnsArray); if($columnsArraySize === 0 || $columnsArraySize !== count($values)) { throw new \Exception('Columns method must called before and both passed array require the same amount of elements'); } foreach($this->columnsArray as $number => $column) { /** @var ColumnInterface $columnObj */ $columnObj = $this->factory->references('Column', $column); $valueObj = $this->factory->references('Value', $values[$number]); $this->update->column($columnObj)->value($valueObj); } return $this; } /** * Add a where expression to the query. * * @param ConditionFacadeInterface $condition The configured condition object, get by conditionBuilder method. * * @return $this The same instance to concatenate methods. */ public function where(ConditionFacadeInterface $condition) { $this->update->where($condition->getCondition()); return $this; } /** * Add an order by expression to the query. * * @param string $column Column Name. * @param string|null $orderMode Order mode, whether desc or asc. * * @return $this The same instance to concatenate methods. */ public function orderBy($column, $orderMode = null) { /** @var ColumnInterface $columnObj */ $columnObj = $this->factory->references('Column', $column); /** @var OrderModeEnumInterface $orderModeObj */ $orderModeObj = ($orderMode) ? $this->factory->references('OrderModeEnum', $orderMode) : null; $this->update->orderBy($columnObj, $orderModeObj); return $this; } /** * Add a limit expression to the query. * * @param int $beginAmount Amount if only one arg isset, if two, the first entry which will used. * @param int|null $amount (Optional) Amount of entries which. * * @return $this The same instance to concatenate methods. */ public function limit($beginAmount, $amount = null) { $beginObj = new Numeric((int)$beginAmount); $amountObj = ($amount) ? new Numeric((int)$amount) : null; $this->update->limit($beginObj, $amountObj); return $this; } /** * Return an condition facade to create where conditions for the query. * * @return ConditionFacade Instance of conditionFacade. */ public function condition() { $condition = $this->factory->expression('Condition'); return $this->factory->expressionFacade('Condition', $condition); } }
AlcyZ/Alcys-ORM
src/Core/Db/Facade/UpdateFacade.php
PHP
mit
7,554
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import * as platform from 'vs/base/common/platform'; import { FileChangeType, FileChangesEvent } from 'vs/platform/files/common/files'; import uri from 'vs/base/common/uri'; import { IRawFileChange, toFileChangesEvent, normalize } from 'vs/workbench/services/files/node/watcher/common'; import { Event, Emitter } from 'vs/base/common/event'; class TestFileWatcher { private readonly _onFileChanges: Emitter<FileChangesEvent>; constructor() { this._onFileChanges = new Emitter<FileChangesEvent>(); } public get onFileChanges(): Event<FileChangesEvent> { return this._onFileChanges.event; } public report(changes: IRawFileChange[]): void { this.onRawFileEvents(changes); } private onRawFileEvents(events: IRawFileChange[]): void { // Normalize let normalizedEvents = normalize(events); // Emit through event emitter if (normalizedEvents.length > 0) { this._onFileChanges.fire(toFileChangesEvent(normalizedEvents)); } } } enum Path { UNIX, WINDOWS, UNC } suite('Watcher', () => { test('watching - simple add/update/delete', function (done: () => void) { const watch = new TestFileWatcher(); const added = uri.file('/users/data/src/added.txt'); const updated = uri.file('/users/data/src/updated.txt'); const deleted = uri.file('/users/data/src/deleted.txt'); const raw: IRawFileChange[] = [ { path: added.fsPath, type: FileChangeType.ADDED }, { path: updated.fsPath, type: FileChangeType.UPDATED }, { path: deleted.fsPath, type: FileChangeType.DELETED }, ]; watch.onFileChanges(e => { assert.ok(e); assert.equal(e.changes.length, 3); assert.ok(e.contains(added, FileChangeType.ADDED)); assert.ok(e.contains(updated, FileChangeType.UPDATED)); assert.ok(e.contains(deleted, FileChangeType.DELETED)); done(); }); watch.report(raw); }); let pathSpecs = platform.isWindows ? [Path.WINDOWS, Path.UNC] : [Path.UNIX]; pathSpecs.forEach((p) => { test('watching - delete only reported for top level folder (' + p + ')', function (done: () => void) { const watch = new TestFileWatcher(); const deletedFolderA = uri.file(p === Path.UNIX ? '/users/data/src/todelete1' : p === Path.WINDOWS ? 'C:\\users\\data\\src\\todelete1' : '\\\\localhost\\users\\data\\src\\todelete1'); const deletedFolderB = uri.file(p === Path.UNIX ? '/users/data/src/todelete2' : p === Path.WINDOWS ? 'C:\\users\\data\\src\\todelete2' : '\\\\localhost\\users\\data\\src\\todelete2'); const deletedFolderBF1 = uri.file(p === Path.UNIX ? '/users/data/src/todelete2/file.txt' : p === Path.WINDOWS ? 'C:\\users\\data\\src\\todelete2\\file.txt' : '\\\\localhost\\users\\data\\src\\todelete2\\file.txt'); const deletedFolderBF2 = uri.file(p === Path.UNIX ? '/users/data/src/todelete2/more/test.txt' : p === Path.WINDOWS ? 'C:\\users\\data\\src\\todelete2\\more\\test.txt' : '\\\\localhost\\users\\data\\src\\todelete2\\more\\test.txt'); const deletedFolderBF3 = uri.file(p === Path.UNIX ? '/users/data/src/todelete2/super/bar/foo.txt' : p === Path.WINDOWS ? 'C:\\users\\data\\src\\todelete2\\super\\bar\\foo.txt' : '\\\\localhost\\users\\data\\src\\todelete2\\super\\bar\\foo.txt'); const deletedFileA = uri.file(p === Path.UNIX ? '/users/data/src/deleteme.txt' : p === Path.WINDOWS ? 'C:\\users\\data\\src\\deleteme.txt' : '\\\\localhost\\users\\data\\src\\deleteme.txt'); const addedFile = uri.file(p === Path.UNIX ? '/users/data/src/added.txt' : p === Path.WINDOWS ? 'C:\\users\\data\\src\\added.txt' : '\\\\localhost\\users\\data\\src\\added.txt'); const updatedFile = uri.file(p === Path.UNIX ? '/users/data/src/updated.txt' : p === Path.WINDOWS ? 'C:\\users\\data\\src\\updated.txt' : '\\\\localhost\\users\\data\\src\\updated.txt'); const raw: IRawFileChange[] = [ { path: deletedFolderA.fsPath, type: FileChangeType.DELETED }, { path: deletedFolderB.fsPath, type: FileChangeType.DELETED }, { path: deletedFolderBF1.fsPath, type: FileChangeType.DELETED }, { path: deletedFolderBF2.fsPath, type: FileChangeType.DELETED }, { path: deletedFolderBF3.fsPath, type: FileChangeType.DELETED }, { path: deletedFileA.fsPath, type: FileChangeType.DELETED }, { path: addedFile.fsPath, type: FileChangeType.ADDED }, { path: updatedFile.fsPath, type: FileChangeType.UPDATED } ]; watch.onFileChanges(e => { assert.ok(e); assert.equal(e.changes.length, 5); assert.ok(e.contains(deletedFolderA, FileChangeType.DELETED)); assert.ok(e.contains(deletedFolderB, FileChangeType.DELETED)); assert.ok(e.contains(deletedFileA, FileChangeType.DELETED)); assert.ok(e.contains(addedFile, FileChangeType.ADDED)); assert.ok(e.contains(updatedFile, FileChangeType.UPDATED)); done(); }); watch.report(raw); }); }); test('watching - event normalization: ignore CREATE followed by DELETE', function (done: () => void) { const watch = new TestFileWatcher(); const created = uri.file('/users/data/src/related'); const deleted = uri.file('/users/data/src/related'); const unrelated = uri.file('/users/data/src/unrelated'); const raw: IRawFileChange[] = [ { path: created.fsPath, type: FileChangeType.ADDED }, { path: deleted.fsPath, type: FileChangeType.DELETED }, { path: unrelated.fsPath, type: FileChangeType.UPDATED }, ]; watch.onFileChanges(e => { assert.ok(e); assert.equal(e.changes.length, 1); assert.ok(e.contains(unrelated, FileChangeType.UPDATED)); done(); }); watch.report(raw); }); test('watching - event normalization: flatten DELETE followed by CREATE into CHANGE', function (done: () => void) { const watch = new TestFileWatcher(); const deleted = uri.file('/users/data/src/related'); const created = uri.file('/users/data/src/related'); const unrelated = uri.file('/users/data/src/unrelated'); const raw: IRawFileChange[] = [ { path: deleted.fsPath, type: FileChangeType.DELETED }, { path: created.fsPath, type: FileChangeType.ADDED }, { path: unrelated.fsPath, type: FileChangeType.UPDATED }, ]; watch.onFileChanges(e => { assert.ok(e); assert.equal(e.changes.length, 2); assert.ok(e.contains(deleted, FileChangeType.UPDATED)); assert.ok(e.contains(unrelated, FileChangeType.UPDATED)); done(); }); watch.report(raw); }); test('watching - event normalization: ignore UPDATE when CREATE received', function (done: () => void) { const watch = new TestFileWatcher(); const created = uri.file('/users/data/src/related'); const updated = uri.file('/users/data/src/related'); const unrelated = uri.file('/users/data/src/unrelated'); const raw: IRawFileChange[] = [ { path: created.fsPath, type: FileChangeType.ADDED }, { path: updated.fsPath, type: FileChangeType.UPDATED }, { path: unrelated.fsPath, type: FileChangeType.UPDATED }, ]; watch.onFileChanges(e => { assert.ok(e); assert.equal(e.changes.length, 2); assert.ok(e.contains(created, FileChangeType.ADDED)); assert.ok(!e.contains(created, FileChangeType.UPDATED)); assert.ok(e.contains(unrelated, FileChangeType.UPDATED)); done(); }); watch.report(raw); }); test('watching - event normalization: apply DELETE', function (done: () => void) { const watch = new TestFileWatcher(); const updated = uri.file('/users/data/src/related'); const updated2 = uri.file('/users/data/src/related'); const deleted = uri.file('/users/data/src/related'); const unrelated = uri.file('/users/data/src/unrelated'); const raw: IRawFileChange[] = [ { path: updated.fsPath, type: FileChangeType.UPDATED }, { path: updated2.fsPath, type: FileChangeType.UPDATED }, { path: unrelated.fsPath, type: FileChangeType.UPDATED }, { path: updated.fsPath, type: FileChangeType.DELETED } ]; watch.onFileChanges(e => { assert.ok(e); assert.equal(e.changes.length, 2); assert.ok(e.contains(deleted, FileChangeType.DELETED)); assert.ok(!e.contains(updated, FileChangeType.UPDATED)); assert.ok(e.contains(unrelated, FileChangeType.UPDATED)); done(); }); watch.report(raw); }); });
rishii7/vscode
src/vs/workbench/services/files/test/electron-browser/watcher.test.ts
TypeScript
mit
8,460
/* * XPropertyEvent.cs - Definitions for X event structures. * * Copyright (C) 2002, 2003 Southern Storm Software, Pty Ltd. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace Xsharp.Events { using System; using System.Runtime.InteropServices; using OpenSystem.Platform; using OpenSystem.Platform.X11; // Property change event. [StructLayout(LayoutKind.Sequential)] internal struct XPropertyEvent { // Structure fields. XAnyEvent common__; public XAtom atom; public XTime time; public Xlib.Xint state__; // Access parent class fields. public int type { get { return common__.type; } } public uint serial { get { return common__.serial; } } public bool send_event { get { return common__.send_event; } } public IntPtr display { get { return common__.display; } } public XWindow window { get { return common__.window; } } // Convert odd fields into types that are useful. public int state { get { return (int)state__; } } // Convert this object into a string. public override String ToString() { return common__.ToString() + " atom=" + ((ulong)atom).ToString() + " time=" + ((ulong)time).ToString() + " state=" + state.ToString(); } } // struct XPropertyEvent } // namespace Xsharp.Events
jjenki11/blaze-chem-rendering
qca_designer/lib/pnetlib-0.8.0/Xsharp/Events/XPropertyEvent.cs
C#
mit
1,970
import * as Models from './' export const ItemRequestPriority = [ 'low', 'standard', 'high', 'highest' ] as const export type ItemRequestPriorityTuple = typeof ItemRequestPriority export type ItemRequestPriority = ItemRequestPriorityTuple[number] export const ItemRequestDestination = ['Svařovna'] as const export type ItemRequestDestinationTuple = typeof ItemRequestDestination export type ItemRequestDestination = ItemRequestDestinationTuple[number] export interface ErrorData { errors: string[] warnings: string[] } export default interface ItemRequest { id: number name: string description: string | null priority: ItemRequestPriority orderMethod: string destination: string deadline: Date comment: string | null baseId: number supplierEshop: string | null supplierId: number | null attachmentId: number | null supervisorId: string | null approverId: string | null purchaserId: string | null itemBase?: Models.ItemBase supplier?: Models.Supplier approvals?: Models.Approval[] delays?: Models.Delay[] subitems?: number[] orders?: Models.Order[] inspections?: Models.Inspection[] attachment?: Models.File supervisor?: Models.User approver?: Models.User purchaser?: Models.User requestorName?: string statusId?: Models.StatusId statusName?: string uid?: string isActive?: boolean attachmentName?: string totalPrice?: number delayedDeadline?: Date currOrder?: Models.Order errorData?: ErrorData }
petrdsvoboda/prototype-orders
app/src/models/ItemRequest.ts
TypeScript
mit
1,446
package com.orbital.lead.controller.Activity; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.orbital.lead.R; import com.orbital.lead.controller.RecyclerViewAdapter.RecyclerDividerItemDecoration; import com.orbital.lead.controller.RecyclerViewAdapter.RecyclerProjectListAdapter; import com.orbital.lead.controller.RecyclerViewAdapter.RecyclerTagListAdapter; import com.orbital.lead.model.Constant; import com.orbital.lead.model.EnumDialogEditJournalType; import com.orbital.lead.model.EnumOpenPictureActivityType; import com.orbital.lead.model.Journal; import com.orbital.lead.model.Project; import com.orbital.lead.model.ProjectList; import com.orbital.lead.model.Tag; import com.orbital.lead.model.TagList; public class AddNewSpecificJournalActivity extends BaseActivity { private final String TAG = this.getClass().getSimpleName(); private View mToolbarView; private TextView mToolbarTitle; private TextView mTextJournalDate; private TextView mTextTag; private TextView mTextProject; private EditText mEditTextTitle; private EditText mEditTextContent; private AlertDialog mDialogSave; private Journal newJournal; private TagList newTagList; private ProjectList newProjectList; private Project newProject; private DatePickerDialog datePickerDialog; private DatePickerDialog.OnDateSetListener datePickerListener; private RecyclerView mRecyclerViewTagList; private RecyclerView mRecyclerViewProjectList; private RecyclerView.Adapter mRecyclerDialogTagAdapter; private RecyclerView.Adapter mRecyclerDialogProjectAdapter; //private String newJournalID; //private String newAlbumID; private int mYear; private int mMonth; private int mDay; private boolean toggleRefresh = false; private boolean isSaved = false; private boolean discard = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getLayoutInflater().inflate(R.layout.activity_add_new_specific_journal, getBaseFrameLayout()); this.initToolbar(); this.initToolbarTitle(); this.setToolbarTitle(Constant.TITLE_ADD_NEW_JOURNAL); this.pushToolbarToActionbar(); this.restoreCustomActionbar(); this.restoreDrawerHeaderValues(); this.initJournalReceiver(); this.retrieveNewJournalAlbumID(); this.initNewJournal(); this.initTextTitle(); this.initTextContent(); this.initTextJournalDate(); this.initTextTag(); this.initTextProject(); this.initNewTagList(); this.initNewProject(); this.initOnDateSetListener(); this.initTagSet(); this.retrievePreferenceTagSet(); this.newProjectList = new ProjectList(); this.newProjectList.setList(this.getCurrentUser().getProjectList()); Bundle getBundleExtra = getIntent().getExtras(); if (getBundleExtra != null) { } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!getNavigationDrawerFragment().isDrawerOpen()) { getMenuInflater().inflate(R.menu.menu_add_new_specific_journal, menu); this.restoreCustomActionbar(); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch(id) { case android.R.id.home: // save the current new journal //onBackPressed(); this.uploadNewJournal(); return true; case R.id.action_image: getLogic().displayPictureActivity(this, EnumOpenPictureActivityType.OPEN_FRAGMENT_LIST_PICTURES, this.getNewJournal().getAlbum(), this.getNewJournal().getJournalID()); return true; } return false; } @Override public void setToolbarTitle(String title){ this.mToolbarTitle.setText(title); } @Override public void onBackPressed() { if(!this.getIsSaved() && !this.getDiscard()) { // save and not discard this.showSaveDialog(); return; }else{ //if discard and don't save, delete album and return to previous activity this.deleteAlbum(); } Intent intent = new Intent(); intent.putExtra(Constant.BUNDLE_PARAM_JOURNAL_LIST_TOGGLE_REFRESH, this.getToggleRefresh()); setResult(Activity.RESULT_OK, intent); finish(); super.onBackPressed(); } private void restoreCustomActionbar(){ // disable the home button and onClick to open navigation drawer // enable the back arrow button getSupportActionBar().setDisplayShowHomeEnabled(false); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(true); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_done); } public void initToolbar() { this.mToolbarView = findViewById(R.id.custom_specific_journal_toolbar); ((Toolbar) this.mToolbarView).setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //onBackPressed(); getLogging().debug(TAG, "mToolbarView setNavigationOnClickListener onClick"); } }); } public void refreshRecyclerDialogTagAdapter(){ if(this.mRecyclerDialogTagAdapter != null) { this.mRecyclerDialogTagAdapter.notifyDataSetChanged(); } } public void setToggleRefresh(boolean val) { this.toggleRefresh = val; } public void setIsSaved(boolean val) { this.isSaved = val; } public void setDiscard(boolean val) { this.discard = val; } private void initToolbarTitle() { this.mToolbarTitle = (TextView) findViewById(R.id.toolbar_text_title); } private View getToolbar() { return this.mToolbarView; } private void pushToolbarToActionbar() { setSupportActionBar((Toolbar) this.getToolbar()); } private void retrieveNewJournalAlbumID() { this.getLogic().getNewJournalAlbumID(this, this.getCurrentUser().getUserID()); } private void initNewJournal() { this.newJournal = new Journal(); } private void initTextTitle() { this.mEditTextTitle = (EditText) findViewById(R.id.edit_text_title); } private void initTextContent(){ this.mEditTextContent = (EditText) findViewById(R.id.edit_text_content); } private void initTextJournalDate() { this.mTextJournalDate = (TextView) findViewById(R.id.text_journal_date); this.mTextJournalDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDatePickerDialog(); } }); } private void initOnDateSetListener() { this.datePickerListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; String databaseFormatDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth; setTextJournalDate(convertToDisplayDate(databaseFormatDate)); } }; } private void initTextTag() { this.mTextTag = (TextView) findViewById(R.id.text_journal_tag); this.mTextTag.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showTagDialog(getTagSet().getTagList()); } }); } private void initTextProject() { this.mTextProject = (TextView) findViewById(R.id.text_journal_project); this.mTextProject.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showProjectDialog(getCurrentUser().getProjectList()); } }); } private void initNewTagList() { this.newTagList = new TagList(); } private void initNewProject() { this.newProject = new Project(); } private void initDialogTagRecyclerView(View v){ RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); this.mRecyclerViewTagList = (RecyclerView) v.findViewById(R.id.recycler_edit_tag); this.mRecyclerViewTagList.setLayoutManager(layoutManager); this.mRecyclerViewTagList.setHasFixedSize(false); this.mRecyclerViewTagList.addItemDecoration(new RecyclerDividerItemDecoration(this, RecyclerDividerItemDecoration.VERTICAL_LIST)); this.mRecyclerViewTagList.setAdapter(this.getRecyclerDialogTagAdapter()); } private void initDialogProjectRecyclerView(View v){ RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); this.mRecyclerViewProjectList = (RecyclerView) v.findViewById(R.id.recycler_edit_project); this.mRecyclerViewProjectList.setLayoutManager(layoutManager); this.mRecyclerViewProjectList.setHasFixedSize(false); this.mRecyclerViewProjectList.addItemDecoration(new RecyclerDividerItemDecoration(this, RecyclerDividerItemDecoration.VERTICAL_LIST)); this.mRecyclerViewProjectList.setAdapter(this.getRecyclerDialogProjectAdapter()); } private void initRecyclerDialogTagAdapter(TagList currentUsedTagList){ getLogging().debug(TAG, "initRecyclerDialogTagAdapter"); this.mRecyclerDialogTagAdapter = new RecyclerTagListAdapter(currentUsedTagList); /* ((RecyclerTagListAdapter) mRecyclerDialogTagAdapter).setOnItemClickListener(new RecyclerTagListAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { getLogging().debug(TAG, "initRecyclerDialogTagAdapter onItemClick position -> " + position); } }); */ } private void initRecyclerProjectAdapter(ProjectList list){ getLogging().debug(TAG, "initRecyclerProjectAdapter"); if(this.newProject != null) { this.mRecyclerDialogProjectAdapter = new RecyclerProjectListAdapter(list, this.newProject.getProjectID()); }else{ this.mRecyclerDialogProjectAdapter = new RecyclerProjectListAdapter(list, ""); } } private RecyclerView.Adapter getRecyclerDialogTagAdapter(){ return this.mRecyclerDialogTagAdapter; } private RecyclerView.Adapter getRecyclerDialogProjectAdapter(){ return this.mRecyclerDialogProjectAdapter; } public void setNewJournalID(String id) { this.getLogging().debug(TAG, "setNewJournalID id => " + id); this.getNewJournal().setJournalID(id); } public void setNewAlbumID(String id) { this.getLogging().debug(TAG, "setNewAlbumID id => " + id); this.getNewJournal().getAlbum().setAlbumID(id); } public void setJournal(Journal j){ this.newJournal = j; } private void setEditTextTitle(String value){ this.mEditTextTitle.setText(value); } private void setEditTextContent(String value){ this.mEditTextContent.setText(value); } private void setTextJournalDate(String value) { this.mTextJournalDate.setText(value); } private void setTextTag(String value){ this.mTextTag.setText(value); } private void setTextProject(String value){ this.mTextProject.setText(value); } private void setNewProject(Project project) { this.newProject = project; } private String getEditTextTitle() { return this.mEditTextTitle.getText().toString(); } private String getTextJournalDate() { return this.mTextJournalDate.getText().toString(); } private String getTextTags() { return this.mTextTag.getText().toString(); } private String getTextProject() { return this.mTextProject.getText().toString(); } private String getEditTextContent() { return this.mEditTextContent.getText().toString(); } private TagList getTagList() { return this.newTagList; } private boolean getToggleRefresh() { return this.toggleRefresh; } private boolean getIsSaved() { return this.isSaved; } private boolean getDiscard() { return this.discard; } private Journal getNewJournal() { return this.newJournal; } private void updateNewTagList(TagList list) { this.newTagList.replaceWithTagList(list); } /*=============== DIALOGS ==========*/ private void showDatePickerDialog(){ this.datePickerDialog = new DatePickerDialog(this, this.getDatePickerListener(), this.mYear, this.mMonth, this.mDay); this.datePickerDialog.show(); } private DatePickerDialog.OnDateSetListener getDatePickerListener(){ return this.datePickerListener; } private void showTagDialog(TagList list){ AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = this.getLayoutInflater(); final View dialogView = inflater.inflate(R.layout.dialog_tag, null); this.initRecyclerDialogTagAdapter(list); this.initDialogTagRecyclerView(dialogView); ImageView addNewTag = (ImageView) dialogView.findViewById(R.id.image_toolbar_add_new_tag); addNewTag.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getLogic().showAddTagProjectDialog(AddNewSpecificJournalActivity.this, EnumDialogEditJournalType.ADD_TAG, ""); } }); builder.setView(dialogView) .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { TagList list = ((RecyclerTagListAdapter) getRecyclerDialogTagAdapter()).getTagList(); updateNewTagList(list); // update new tag list for (Tag t : newTagList.getList()) { getLogging().debug(TAG, "after update newTagList t.getName() => " + t.getName() + " checked => " + t.getIsChecked()); } setTextTag(newTagList.getCheckedToString()); // update the tag text, show only all checked tags } }); builder.create().show(); } private void showProjectDialog(ProjectList projectList){ AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = this.getLayoutInflater(); final View dialogView = inflater.inflate(R.layout.dialog_project, null); this.initRecyclerProjectAdapter(projectList); this.initDialogProjectRecyclerView(dialogView); ImageView addNewProject = (ImageView) dialogView.findViewById(R.id.image_toolbar_add_new_project); addNewProject.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getLogic().showAddTagProjectDialog(AddNewSpecificJournalActivity.this, EnumDialogEditJournalType.ADD_PROJECT, ""); } }); builder.setView(dialogView) .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Project selectedProject = ((RecyclerProjectListAdapter) getRecyclerDialogProjectAdapter()).getSelectedProject(); newProject = selectedProject; newProjectList.resetList(); if (selectedProject != null) { // sometimes user will not choose a project newProjectList.updateProject(selectedProject); } setTextProject(selectedProject != null ? selectedProject.getName() : ""); setNewProject(selectedProject); // update the new project } }); builder.create().show(); } private void showSaveDialog() { final AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = this.getLayoutInflater(); final View dialogView = inflater.inflate(R.layout.dialog_save_layout, null); builder.setView(dialogView) .setPositiveButton(R.string.dialog_save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { getLogging().debug(TAG, "showSaveDialog Save"); uploadNewJournal(); } }) .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { getLogging().debug(TAG, "showSaveDialog Cancel"); mDialogSave.dismiss(); } }) .setNeutralButton(R.string.dialog_discard, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { getLogging().debug(TAG, "showSaveDialog Discard"); setDiscard(true); setToggleRefresh(false); setIsSaved(false); onBackPressed(); } }); this.mDialogSave = builder.create(); this.mDialogSave.setCanceledOnTouchOutside(false); this.mDialogSave.setCancelable(true); this.mDialogSave.show(); } private void uploadNewJournal() { if(!this.isValidJournal()) { this.getLogging().debug(TAG, "uploadNewJournal it is not a valid new journal"); return; } this.getNewJournal().setJournalID(this.getNewJournal().getJournalID()); this.getNewJournal().setTitle(this.getEditTextTitle()); this.getNewJournal().setContent(this.getEditTextContent()); this.getNewJournal().setJournalDate(this.convertToDatabaseDate(this.getTextJournalDate())); this.getNewJournal().setTagList(this.newTagList); this.getNewJournal().setProject(this.newProject); String detail = this.getParser().uploadNewJournalToJson(this.getNewJournal()); this.getLogging().debug(TAG, "uploadNewJournal detail => " + detail); this.getLogic().insertNewJournal(this, this.getCurrentUser().getUserID(), this.getNewJournal().getJournalID(), this.getNewJournal().getAlbum().getAlbumID(), detail); } private void deleteAlbum() { this.getLogic().deleteAlbum(this, this.getNewJournal().getAlbum().getAlbumID()); } private boolean isValidJournal() { // Check title and content if(getParser().isStringEmpty(this.getEditTextTitle()) && getParser().isStringEmpty(this.getEditTextContent())) { return false; // if both empty, means it is not suitable to be uploaded as a new journal } return true; } }
orbitaljt/LEAD
Android/Lead/app/src/main/java/com/orbital/lead/controller/Activity/AddNewSpecificJournalActivity.java
Java
mit
20,434
const colors = require('colors/safe'); const shouldSilenceWarnings = (...messages) => [].some((msgRegex) => messages.some((msg) => msgRegex.test(msg))); const shouldNotThrowWarnings = (...messages) => [].some((msgRegex) => messages.some((msg) => msgRegex.test(msg))); const logOrThrow = (log, method, messages) => { const warning = `console.${method} calls not allowed in tests`; if (process.env.CI) { if (shouldSilenceWarnings(messages)) return; log(warning, '\n', ...messages); // NOTE: That some warnings should be logged allowing us to refactor graceully // without having to introduce a breaking change. if (shouldNotThrowWarnings(messages)) return; throw new Error(...messages); } else { log(colors.bgYellow.black(' WARN '), warning, '\n', ...messages); } }; // eslint-disable-next-line no-console const logMessage = console.log; global.console.log = (...messages) => { logOrThrow(logMessage, 'log', messages); }; // eslint-disable-next-line no-console const logInfo = console.info; global.console.info = (...messages) => { logOrThrow(logInfo, 'info', messages); }; // eslint-disable-next-line no-console const logWarning = console.warn; global.console.warn = (...messages) => { logOrThrow(logWarning, 'warn', messages); }; // eslint-disable-next-line no-console const logError = console.error; global.console.error = (...messages) => { logOrThrow(logError, 'error', messages); };
tdeekens/flopflip
throwing-console-patch.js
JavaScript
mit
1,445
/*********************************************************************************** Copyright (C) 2016 Mohammad D. Mottaghi Under the terms of the MIT license, permission is granted to anyone to use, copy, modify, publish, redistribute, and/or sell copies of this source code for any commercial and non-commercial purposes, subject to the following restrictions: 1. The above copyright notice and this permission notice shall not be removed from any source distribution. 2. The origin of this file shall not be misrepresented; The name of the original author shall be cited in any copy, or modified version of this source code. 3. If used in a product, acknowledgment in the product documentation would be appreciated, but is not required. 4. Modified versions must be plainly marked as such, and must not be misrepresented as being the original source code. This source code 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 author 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 this source code or the use or other dealings in it. Mohammd Mottaghi Dastjerdi (mamad[a~t]cs.duke.edu) Sep. 1,2016 ***********************************************************************************/ #include <vcl.h> #pragma hdrstop #include "fmStats.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TfrmStats *frmStats; //--------------------------------------------------------------------------- __fastcall TfrmStats::TfrmStats(TComponent* Owner) : TForm(Owner), total_html_tags(CJerdyParser::HtmlTags().CountLeft()), tag_descriptors(CJerdyParser::HtmlTags().Current()) { } //--------------------------------------------------------------------------- void __fastcall TfrmStats::CountTags(const CjHtmlElement* node) { tag_frequency[node->Meta()->id]++; for (long i=0, cnt = node->ChildrenCount() ; i < cnt ; i++) CountTags(node->Child(i)); } //--------------------------------------------------------------------------- void __fastcall TfrmStats::FormShow(TObject *Sender) { AnsiString title; title.cat_printf("Frequency Of Tags Under '%s' At Level %ld", subtree_root->TagName(), subtree_root->Level()); Caption = title; freqChart->Title->Text->Clear(); freqChart->Title->Text->Add(title); Series1->Clear(); tag_frequency = new long[total_html_tags+1]; memset(tag_frequency, 0, (total_html_tags+1) * sizeof(long)); CountTags(subtree_root); for (long index_max, max, i=0 ; i < total_html_tags ; i++) { index_max=tiNil; max=-1; for (long j=0 ; j < total_html_tags ; j++) if (max < tag_frequency[j]) { max = tag_frequency[j]; index_max = j; } if (index_max > tiRoot && tag_frequency[index_max]>0) Series1->Add(tag_frequency[index_max], tag_descriptors[index_max].meta.name); tag_frequency[index_max] = -1; } delete []tag_frequency; } //--------------------------------------------------------------------------- void __fastcall TfrmStats::FormKeyPress(TObject *Sender, char &Key) { if (Key==27) Close(); } //---------------------------------------------------------------------------
mmottaghi/Jerdy-Inspector
src/fmStats.cpp
C++
mit
3,488
require "chamberevents/version" require 'chamberevents/read' require 'chamberevents/ical' require 'chamberevents/upload' module Chamberevents def self.update! events = Read.current ical = Ical.new(events).to_s Upload.write('elginchamber-events.ics', ical) end end
JustinLove/chamberevents
lib/chamberevents.rb
Ruby
mit
281
require File.dirname(__FILE__) + '/test_helper' context "Resque::Scheduler" do setup do Resque::Scheduler.dynamic = false Resque.redis.flushall Resque::Scheduler.clear_schedule! end test 'set custom logger' do custom_logger = Logger.new('/dev/null') Resque::Scheduler.logger = custom_logger assert_equal(custom_logger, Resque::Scheduler.logger) end context 'logger default settings' do setup do nullify_logger end test 'uses STDOUT' do assert_equal(Resque::Scheduler.logger.instance_variable_get(:@logdev).dev, STDOUT) end test 'not verbose' do assert Resque::Scheduler.logger.level > Logger::DEBUG end test 'not muted' do assert Resque::Scheduler.logger.level < Logger::FATAL end teardown do nullify_logger end end context 'logger custom settings' do setup do nullify_logger end test 'uses logfile' do Resque::Scheduler.logfile = '/dev/null' assert_equal(Resque::Scheduler.logger.instance_variable_get(:@logdev).filename, '/dev/null') end test 'set verbosity' do Resque::Scheduler.verbose = true assert Resque::Scheduler.logger.level == Logger::DEBUG end test 'mute logger' do Resque::Scheduler.mute = true assert Resque::Scheduler.logger.level == Logger::FATAL end teardown do nullify_logger end end end
makepositive/Resque-Schedular
test/scheduler_setup_test.rb
Ruby
mit
1,413
/* * (C) Copyright 2015 Richard Greenlees * * 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: * * 1) The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.jumi.scene.objects; /** * * @author RGreenlees */ public class JUMISkinDeformer { String name; public JUMISubDeformer[] deformers = new JUMISubDeformer[0]; public JUMISkinDeformer(String inName) { name = inName; } public String toString() { String result = "Skin Deformer " + name + ":"; for (int i = 0; i < deformers.length; i++) { result = result + "\n\t" + deformers[i].name; } return result; } public JUMISubDeformer getSubDeformerByIndex(int index) { if (index >= deformers.length) { return null; } return deformers[index]; } public JUMISubDeformer getSubDeformerByName(String inName) { for (JUMISubDeformer a : deformers) { if (a.name.equals(inName)) { return a; } } return null; } }
RGreenlees/JUMI-Java-Model-Importer
src/com/jumi/scene/objects/JUMISkinDeformer.java
Java
mit
1,888