repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
aajungroth/testing-toyproblems | _powerSet/spec.js | 1159 | describe('powerSet', function() {
var result;
var expected;
beforeEach(function() {
// Something do to before each test
});
it('should pass a basic test', function() {
expect(1).to.equal(1);
});
it('should return an array for the power set of jump', function() {
this.timeout(3000);
result = powerSet('jump');
console.log('expected: ["", "j", "ju", "jm", "jp", "jmu", "jmp", "jpu", "jmpu", "u", "m", "p", "mu", "mp", "pu", "mpu"]');
console.log('actual: ' + result);
expect(result.length).to.equal(16);
});
it('should return an array for the power set of jumps', function() {
this.timeout(3000);
result = powerSet('jumps');
console.log('actual: ' + result);
console.log(result.length);
expect(result.length).to.equal(32);
});
it('should return an array for the power set of banana', function() {
this.timeout(3000);
result = powerSet('banana');
expected = powerSet('ban');
console.log('expected: ' + expected);
console.log('actual: ' + result);
console.log(result.length);
expect(result).to.eql(expected);
});
});
| mit |
encrypted-systems/Warehouse | application/views/index_polish_view.php | 2326 | <?php $this->load->view('template/header_view.php'); ?>
<!-- hero area (the grey one with a slider -->
<section id="hero" class="clearfix">
<!-- responsive FlexSlider image slideshow -->
<div class="wrapper">
<div class="row">
<div class="grid_5">
<h1>Projekt Warehouse</h1>
<p>...to <b>idealne</b> narzędzie do monitorowania stanów magazynowych. Udostępnia wiele poziomów
zarządzania produktami oraz przepływem danych w firmie.</p>
<b>Ta wersja systemu została wykonana dla Bibtex-pol Sp. z o.o. przez Encrypted Software Maciej
Lewandowski.</b>
</div>
<div class="grid_7 rightfloat">
<div class="flexslider">
<ul class="slides">
<li>
<img src="<?php echo base_url(); ?>images/warehouse-pic3.jpg"/>
<p class="flex-caption">Responsywny szablon - do odtwarzania na urządzeniach
mobilnych.</p>
</li>
<li>
<img src="<?php echo base_url(); ?>images/warehouse-pic4.jpg"/>
<p class="flex-caption">Log systemowy, by nic nie umknęło uwagi.</p>
</li>
<li>
<img src="<?php echo base_url(); ?>images/warehouse-pic1.jpg"/>
<p class="flex-caption">Kopia zapasowa pod jednym guzikiem.</p>
</li>
<li>
<img src="<?php echo base_url(); ?>images/warehouse-pic2.jpg"/>
<p class="flex-caption">Prosty export CSV (do odtworzenia w Microsoft Excel lub
Calc).</p>
</li>
</ul>
</div><!-- FlexSlider -->
</div><!-- end grid_7 -->
</div><!-- end row -->
</div><!-- end wrapper -->
</section><!-- end hero area -->
<?php $this->load->view('template/footer_view.php'); ?> | mit |
Terricide/ReVision | src/ReVision.Forms/WebSocket/WebSocketHandler.cs | 3066 | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ReVision.Forms
{
public class WebSocketHandler : IDisposable
{
public WebSocket Socket;
public DateTime? CreatedDate;
private readonly TaskQueue _sendQueue = new TaskQueue();
public WebSocketState State
{
get
{
try
{
return Socket.State;
}
catch (ObjectDisposedException)
{
return WebSocketState.Closed;
}
}
}
public WebSocketHandler(WebSocket socket)
{
this.Socket = socket;
}
public Task SendAsync(string message)
{
return Task.Run(() =>
{
var sendContext = new SendContext(this, message);
if (Socket.State != WebSocketState.Open)
{
return;
}
_sendQueue.Enqueue(new Task(() =>
{
if (sendContext.Handler.Socket.State != WebSocketState.Open)
{
return;
}
try
{
var buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message));
Socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None).Wait();
}
catch (Exception ex)
{
// Swallow exceptions on send
Trace.TraceError("Error while sending: " + ex);
}
}));
});
}
private class SendContext
{
public WebSocketHandler Handler;
public string Message;
public SendContext(WebSocketHandler webSocketHandler, string message)
{
Handler = webSocketHandler;
}
}
public void Dispose()
{
this.Socket.Dispose();
this.Socket = null;
}
internal Task CloseAsync(WebSocketCloseStatus webSocketCloseStatus, string p, CancellationToken cancellationToken)
{
return this.Socket.CloseAsync(webSocketCloseStatus, p, cancellationToken);
}
internal Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> arraySegment, CancellationToken cancellationToken)
{
return this.Socket.ReceiveAsync(arraySegment, cancellationToken);
}
internal Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType webSocketMessageType, bool endOfMessage, CancellationToken cancellationToken)
{
return this.Socket.SendAsync(buffer, webSocketMessageType, endOfMessage, cancellationToken);
}
}
}
| mit |
microfleet/core | packages/plugin-amqp/src/plugin.ts | 4401 | import type * as _ from '@microfleet/plugin-validator'
import type * as __ from '@microfleet/plugin-logger'
import { strict as assert } from 'assert'
import { resolve } from 'path'
import { NotFoundError, NotPermittedError, ConnectionError } from 'common-errors'
import { PluginInterface } from '@microfleet/core-types'
import { Microfleet, PluginTypes } from '@microfleet/core'
// @todo should be part of plugin-router-amqp
import { RequestCountTracker, ActionTransport } from '@microfleet/plugin-router'
import AMQPTransport = require('@microfleet/transport-amqp')
import type { AMQPPluginConfig } from './types/plugin'
const ERROR_NOT_STARTED = new NotPermittedError('amqp was not started')
const ERROR_ALREADY_STARTED = new NotPermittedError('amqp was already started')
const ERROR_NOT_HEALTHY = new ConnectionError('amqp is not healthy')
declare module '@microfleet/core-types' {
export interface Microfleet {
amqp: InstanceType<typeof AMQPTransport>
}
export interface ConfigurationOptional {
amqp: AMQPPluginConfig
}
}
export const name = 'amqp'
export const type = PluginTypes.transport
export const priority = 0
/**
* Attaches plugin to the Mthis class.
* @param {Object} config - AMQP plugin configuration.
*/
export function attach(
this: Microfleet,
options: Partial<AMQPPluginConfig> = {}
): PluginInterface {
assert(this.hasPlugin('logger'), new NotFoundError('log module must be included'))
assert(this.hasPlugin('validator'), new NotFoundError('validator module must be included'))
// load local schemas
this.validator.addLocation(resolve(__dirname, '../schemas'))
const config = this.validator.ifError<AMQPPluginConfig>('amqp', options)
/**
* Check if the service has an amqp transport.
* @returns A truthy value if the this has an instance of AMQPTransport.
*/
const isStarted = () => (
this.amqp && this.amqp instanceof AMQPTransport
)
// @todo should be part of plugin-router-amqp
const waitForRequestsToFinish = () => {
return RequestCountTracker.waitForRequestsToFinish(this, ActionTransport.amqp)
}
/**
* Check the state of a connection to the amqp server.
* @param amqp - Instance of AMQPTransport.
* @returns A truthy value if a provided connection is open.
*/
const isConnected = (amqp: InstanceType<typeof AMQPTransport>) => (
amqp._amqp && amqp._amqp.state === 'open'
)
// init logger if this is enabled
const logger = this.log.child({ namespace: '@microfleet/transport-amqp' })
return {
/**
* Generic AMQP Connector.
* @returns Opens connection to AMQP.
*/
async connect(this: Microfleet) {
if (this.amqp) {
throw ERROR_ALREADY_STARTED
}
// if this.router is present - we will consume messages
// if not - we will only create a client
const connectionOptions = {
...config.transport,
log: logger || null,
tracer: this.tracer,
}
// @todo plugin-router-amqp
// const amqp = this.amqp = await AMQPTransport.connect(connectionOptions, this.AMQPRouter)
const amqp = this.amqp = await AMQPTransport.connect(connectionOptions)
this.emit('plugin:connect:amqp', amqp)
return amqp
},
/**
* Health checker.
*
* Returns true if connection state is 'open', otherwise throws an error.
* Connection state depends on actual connection status, but it could be
* modified when a heartbeat message from a message broker is missed during
* a twice heartbeat interval.
* @returns A truthy value if all checks are passed.
*/
async status(this: Microfleet) {
assert(isStarted(), ERROR_NOT_STARTED)
assert(isConnected(this.amqp), ERROR_NOT_HEALTHY)
return true
},
// @todo should be part of plugin-router-amqp
getRequestCount(this: Microfleet) {
return RequestCountTracker.getRequestCount(this, ActionTransport.amqp)
},
/**
* Generic AMQP disconnector.
* @returns Closes connection to AMQP.
*/
async close(this: Microfleet) {
assert(isStarted(), ERROR_NOT_STARTED)
await this.amqp.closeAllConsumers()
// @todo should be part of plugin-router-amqp
// e.g. closeRouterConsumers() && waitForRequestsToFinish()
await waitForRequestsToFinish()
await this.amqp.close()
this.emit('plugin:close:amqp')
},
}
}
| mit |
Romakita/ts-express-decorators | packages/graphql/typegraphql/test/app/services/UsersRepository.ts | 694 | import {Adapter, InjectAdapter} from "@tsed/adapters";
import {Injectable} from "@tsed/di";
import {deserialize} from "@tsed/json-mapper";
import {User} from "../graphql/auth/User";
@Injectable()
export class UsersRepository {
@InjectAdapter("users", User)
adapter: Adapter<User>;
async $onInit() {
const accounts = await this.adapter.findAll();
if (!accounts.length) {
await this.adapter.create(deserialize({
email: "[email protected]",
password: "[email protected]",
emailVerified: true
}, {type: User, useAlias: false}));
}
}
async authenticate(email: string, password: string) {
return this.adapter.findOne({email, password});
}
} | mit |
egumerlock/skillnest | App/Components/MainMapView.js | 11613 | import Icon from 'react-native-vector-icons/Ionicons';
import MapView from 'react-native-maps';
import Spinner from 'react-native-spinkit';
import AnimatedRatingStars from './Helpers/AnimatedRatingStars'
import TeacherProfile from './TeacherProfile'
import User from './User'
import React, { Component } from 'react';
var CustomCallout = require('./CustomCallout.js')
import {
TabBarIOS,
StyleSheet,
Text,
View,
Dimensions,
Image,
TouchableOpacity
} from 'react-native';
var { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const SPACE = 0.01;
const myButton = (
<Icon.Button name="logo-facebook" backgroundColor="#3b5998" >
Login with Facebook
</Icon.Button>
);
class MainMapView extends Component {
constructor(props) {
super(props);
this.state = {
selectedTab: 'GoogleMap',
type: 'Bounce',
size: 80,
color: "#4598ff",
isVisible: true,
loadAll: false,
region: {
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0821,
},
markers: [
{
coordinate: {
latitude: 37.7824,
longitude: -122.4995,
},
name: "Jim Hadley",
field: "Surf Instructor",
capacity: "8/8",
pricing: "$30-$50 / hour",
avatar: 'https://www.shoptab.net/blog/wp-content/uploads/2014/07/profile-circle.png'
},
{
coordinate: {
latitude: 37.8324,
longitude: -122.4795,
},
name: "Megan Dudley",
field: "Surf Instructor",
capacity: "10/17",
pricing: "$40-$50 / hour",
avatar: 'http://1.bp.blogspot.com/-I2aPA52ms38/VcqtGNT0-9I/AAAAAAAAGQ8/QTuHSROZl2c/s1600/abby-circular-profile.png'
},
{
coordinate: {
latitude: 37.7524,
longitude: -122.4795,
},
name: "Jeanne Renault",
field: "Surf Instructor",
capacity: "11/26",
pricing: "$25-$40 / hour",
avatar: 'http://i.imgur.com/gKOpj8v.png'
},
{
coordinate: {
latitude: 37.7924,
longitude: -122.3995,
},
name: "Jacques LeMans",
field: "Surf Instructor",
capacity: "16/24",
pricing: "$40 / hour",
avatar: 'http://static1.squarespace.com/static/526839d5e4b0a6ea6c312276/526ef8b1e4b0aa6f78f3f614/5271642ce4b03e61739879b6/1383162937731/tim+in+India+profile_circle.png'
},
{
coordinate: {
latitude: 37.7424,
longitude: -122.3995,
},
name: "Thomas Linea",
field: "Surf Instructor",
capacity: "2/4",
pricing: "$50 / hour",
avatar: 'http://s3-us-west-2.amazonaws.com/s.cdpn.io/6083/profile/profile-512_1.jpg'
},
{
coordinate: {
latitude: 37.7484,
longitude: -122.4395,
},
name: "Sochie Lee",
field: "Surf Instructor",
capacity: "2/4",
pricing: "$20-$25 / hour",
avatar: 'https://www.sochiie.com/wp-content/uploads/2014/04/facebook-teerasej-profile-ball-circle.png'
},
{
coordinate: {
latitude: 37.7724,
longitude: -122.4395,
},
name: "Doug Bodder",
field: "Surf Instructor",
capacity: "8/8",
pricing: "$35-$45 / hour",
avatar: 'http://dynamicinfluence.com/wp-content/uploads/2014/06/Robert-Circle-Profile-Pic.png'
},
],
};
}
onProfilePress () {
this.props.navigator.push({
component: TeacherProfile,
name: "TeacherProfile"
})
}
onRegionChange(region) {
this.state.region = region;
}
componentWillMount() {
setTimeout(() => {
this.setState({isVisible: false, loadAll: true});
}, 2500);
}
startTrigger() {
this.setState({
startIndicator: true
})
setTimeout(() => {
this.setState({startIndicator: false});
}, 10000);
}
render() {
var starHolder = this.state.startIndicator ? <AnimatedRatingStars /> : <View></View>;
const { region, markers } = this.state;
var markersList = this.state.markers.map((item, index) => {
return (
<MapView.Marker
ref="m3"
key={index}
image={this.state.iconLoaded ? 'markerLoaded' : 'marker'}
showsUserLocation={true}
followUserLocation={true}
coordinate={markers[index].coordinate}
calloutAnchor={{ x: 0.1, y: 0.1 }}
calloutOffset={{ x: -7, y: 29 }}
onPress={this.startTrigger.bind(this)}
>
<Image source={require('./Helpers/mapicon.png')} onLoadEnd={() => {if (!this.state.iconLoaded) this.setState({iconLoaded: true});}}/>
<MapView.Callout tooltip>
<TouchableOpacity>
<CustomCallout style={styles.calloutOpacity}>
<View style={styles.container}>
<View style={styles.hero}>
<View style={styles.titleWrapper}>
<Text style={styles.title}>{markers[index].name} </Text>
</View>
<Image
style={styles.profilePic}
source={{uri: markers[index].avatar}}
/>
<View style={styles.footerWrapper}>
<Text style={styles.footerHeader}>{markers[index].field} </Text>
{starHolder}
<Text style={styles.footerText}>Availability: {markers[index].capacity} </Text>
<Text style={styles.footerTextBottom}>{markers[index].pricing} </Text>
</View>
</View>
<View style={styles.buttonWrapper}>
<TouchableOpacity style={styles.leftButton}
underlayColor="transparent"
onPress={() => this._onClassesButton(this.props.id)}>
<Text style={styles.buttonText}>
Classes
</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.rightButton}
underlayColor="transparent"
onPress={this.onProfilePress.bind(this)}>
<Text style={styles.buttonText}>
Profile
</Text>
</TouchableOpacity>
</View>
<View style={styles.history}>
</View>
</View>
</CustomCallout>
</TouchableOpacity>
</MapView.Callout>
</MapView.Marker>
)
});
let everything = this.state.loadAll ? (
<MapView
style={styles.map}
showsUserLocation={true}
initialRegion={this.state.region}
followUserLocation={true}
>
{markersList}
</MapView>
) : (
<View style={styles.mainContainer}>
<Spinner style={styles.spinner} isVisible={this.state.isVisible} size={this.state.size} type={this.state.type} color={this.state.color}/>
</View>
);
return (
<TabBarIOS
unselectedTintColor="white"
tintColor='#53D1E5'
barTintColor="white">
<Icon.TabBarItemIOS
iconName={"md-pin"}
style={styles.wrapper}
selected={this.state.selectedTab === 'GoogleMap'}
onPress={() => {
this.setState({
selectedTab: 'GoogleMap'
});
}} >
{everything}
</Icon.TabBarItemIOS>
<Icon.TabBarItemIOS
iconName={"md-person"}
style={styles.wrapper}
selected={this.state.selectedTab === 'Something'}
onPress={() => {
this.setState({
selectedTab: 'Something'
});
}} >
<User />
</Icon.TabBarItemIOS>
<Icon.TabBarItemIOS
iconName={"md-heart-outline"} >
</Icon.TabBarItemIOS>
<Icon.TabBarItemIOS
iconName={"ios-paper-plane"} >
</Icon.TabBarItemIOS>
</TabBarIOS>
);
}
}
const styles = StyleSheet.create({
container: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'red',
},
bubble: {
flex: 1,
backgroundColor: 'rgba(255,255,255,0.7)',
paddingHorizontal: 18,
paddingVertical: 12,
},
latlng: {
width: 200,
alignItems: 'stretch',
},
button: {
height: height * .08,
width: width * .20,
alignItems: 'center',
justifyContent: 'center'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'flex-end',
backgroundColor: 'transparent',
},
calloutHeader: {
fontSize: 24,
color: '#fff',
marginBottom: 5,
flex: 1
},
calloutText: {
color: '#fff',
flex: 1
},
calloutOpacity: {
borderRadius: 8,
opacity: .90
},
icon: {
height: 25,
width: 25,
},
icongood: {
height: 32,
width: 32,
},
middleicon: {
height: 33,
width: 33
},
calloutImage: {
height: height * .15,
width: width * .25,
alignSelf: 'center',
marginTop: 5,
borderRadius: 3,
borderWidth: 1,
},
wrapper: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between'
},
likebutton: {
marginTop: -10,
flex: 1,
height: 32,
width: 22
},
container: {
flex: 1,
backgroundColor: '#ffffff'
},
hero: {
flex: 3.25,
flexDirection: 'column',
backgroundColor: '#658D9F',
},
history: {
flex: 4,
backgroundColor: '#43C6C6'
},
titleWrapper: {
justifyContent: 'center',
backgroundColor: 'white',
flexDirection: 'row'
},
title: {
textAlign: 'center',
fontSize: 18,
color: '#658D9F',
padding: 15
},
profilePic:{
width: 125,
height: 125,
alignSelf: 'center',
backgroundColor: 'transparent',
marginVertical: 40,
},
buttonWrapper: {
flex: .75,
flexDirection: 'row',
},
leftButton: {
flex: 0.25,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#4598ff',
padding: 15,
borderWidth: 1,
borderColor: 'white'
},
rightButton: {
flex: 0.25,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#53e5b0',
padding: 15,
borderWidth: 1,
borderColor: 'white'
},
buttonText: {
fontSize: 20,
color: 'white'
},
field: {
color: 'white',
margin: 5
},
footerWrapper: {
backgroundColor: 'white',
flexDirection: 'column',
alignItems: 'center'
},
footerHeader: {
textAlign: 'center',
fontSize: 15,
color: '#658D9F',
marginTop: 10,
marginBottom: 6,
},
footerText: {
textAlign: 'center',
fontSize: 12,
color: '#658D9F',
justifyContent: 'center',
marginBottom: 6,
marginTop: 10,
},
footerTextBottom: {
textAlign: 'center',
fontSize: 12,
color: '#658D9F',
justifyContent: 'center',
marginBottom: 6,
},
spinner: {
marginLeft: 152,
marginBottom: 20
}
});
export default MainMapView
| mit |
crossroads/crm_super_tags | db/migrate/20101103072142_add_select_options_to_customfields.rb | 212 | class AddSelectOptionsToCustomfields < ActiveRecord::Migration
def self.up
add_column :customfields, :select_options, :text
end
def self.down
remove_column :customfields, :select_options
end
end
| mit |
zorqie/bfests | src/services/index.js | 584 | 'use strict';
const tickets = require('./tickets');
const fans = require('./fans');
const gig = require('./gig');
const act = require('./act');
const venue = require('./venue');
const message = require('./message');
const authentication = require('./authentication');
const user = require('./user');
module.exports = function() {
const app = this;
app.configure(authentication);
app.configure(user);
app.configure(message);
app.configure(venue);
app.configure(act);
app.configure(gig);
app.configure(tickets);
app.configure(fans); // read-only view of tickets
};
| mit |
tzpBingo/github-trending | codespace/python/tencentcloud/market/v20191010/errorcodes.py | 815 | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 操作失败。
FAILEDOPERATION = 'FailedOperation'
# 内部错误。
INTERNALERROR = 'InternalError'
# 参数错误。
INVALIDPARAMETER = 'InvalidParameter'
| mit |
coinsite/PikachuCoin | src/qt/guiutil.cpp | 13547 | #include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include "base58.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("PinkachuCoin"))
return false;
// check if the address is valid
CBitcoinAddress addressFromUri(uri.path().toStdString());
if (!addressFromUri.IsValid())
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert PinkachuCoin:// to PinkachuCoin:
//
// Cannot handle this later, PKCause PinkachuCoin:// will cause Qt to see the part after // as host,
// which will lowercase it (and thus invalidate the address).
if(uri.startsWith("PinkachuCoin://"))
{
uri.replace(0, 11, "PinkachuCoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.PKC)" or "Description (*.PKC *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "PinkachuCoin.lnk";
}
bool GetStartOnSystemStartup()
{
// check for PinkachuCoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "PinkachuCoin.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a PinkachuCoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=PinkachuCoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("PinkachuCoin-qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" PinkachuCoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("PinkachuCoin-qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in nonbreaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stderr, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
| mit |
isfit/alexandrie | db/migrate/20160221112719_create_join_table_gangs_positions.rb | 269 | class CreateJoinTableGangsPositions < ActiveRecord::Migration[5.0]
def change
create_join_table :gangs, :positions, table_name: :alexandrie_gangs_positions do |t|
# t.index [:gang_id, :position_id]
# t.index [:position_id, :gang_id]
end
end
end
| mit |
pierrelb/RMG-Java | source/RMG/jing/rxn/ReactionTemplate.java | 63739 | ////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2011 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// 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 jing.rxn;
import java.io.*;
import jing.chem.*;
import java.util.*;
import jing.param.*;
import jing.rxnSys.PrimaryKineticLibrary;
import jing.rxnSys.ReactionModelGenerator;
import jing.mathTool.*;
import jing.chemUtil.*;
import jing.chemParser.*;
import jing.chem.Species;
import jing.chem.ChemGraph;
import jing.rxnSys.Logger;
//## package jing::rxn
//----------------------------------------------------------------------------
//jing\rxn\ReactionTemplate.java
//----------------------------------------------------------------------------
/**
This is the reaction template that generates a family of reactions.
ItsStructureTemplates could be a bunch of single Structure templates, although for many cases, it will be only one for each reaction template.
reaction templates are mutable.
*/
//## class ReactionTemplate
public class ReactionTemplate {
/**
Reaction direction:
1: forward reaction
2: backward reaction
0: undertemined
*/
protected int direction = 0; //## attribute direction
protected LinkedHashMap fgDictionary = new LinkedHashMap(); //## attribute fgDictionary
protected String name = ""; //## attribute name
//protected HashMap reactionDictionaryByReactant = new HashMap(); //## attribute reactionDictionaryByReactant
protected WeakHashMap reactionDictionaryByStructure = new WeakHashMap(); //## attribute reactionDictionaryByStructure
protected KineticsTemplateLibrary kineticsTemplateLibrary;
protected ReactionAdjList reactionAdjList;
protected ReactionTemplate reverseReactionTemplate;
protected StructureTemplate structureTemplate;
protected LinkedHashMap forbiddenStructures = new LinkedHashMap();
// Constructors
/**
default constructor
*/
//## operation ReactionTemplate()
public ReactionTemplate() {
//#[ operation ReactionTemplate()
//#]
}
/*public int getNumberOfReactions(){
return reactionDictionaryByStructure.size();
}*/
//## operation ableToGeneratePDepWellPaths()
public boolean ableToGeneratePDepWellPaths() {
//#[ operation ableToGeneratePDepWellPaths()
return hasOneReactant();
//#]
}
//## operation addReaction(TemplateReaction)
public void addReaction(TemplateReaction p_templateReaction) {
//#[ operation addReaction(TemplateReaction)
if (p_templateReaction == null) return;
if (p_templateReaction.getReactionTemplate() != this) return;
Structure s = p_templateReaction.getStructure();
reactionDictionaryByStructure.put(s,p_templateReaction);
return;
//#]
}
public boolean removeFromReactionDictionaryByStructure(Structure s) {
// Returns true if it found and removed the structure.
if(reactionDictionaryByStructure.remove(s) == null)
return false;
//Logger.warning(String.format("ReactionTemplate %s Dictionary did not contain reaction structure %s",name,s));
//throw new RuntimeException(String.format("ReactionTemplate %s Dictionary did not contain reaction structure %s",name,s));
else return true;
}
//## operation calculateDepth(HashSet)
private static final int calculateDepth(HashSet p_treeNodeSet) {
//#[ operation calculateDepth(HashSet)
if (p_treeNodeSet==null) throw new NullPointerException();
int dep = 0;
for (Iterator iter = p_treeNodeSet.iterator(); iter.hasNext();) {
Object n = iter.next();
if (n instanceof DummyLeaf) {
dep += Math.abs(((DummyLeaf)n).getDepth());
}
else if (n instanceof HierarchyTreeNode) {
dep += Math.abs(((HierarchyTreeNode)n).getDepth());
}
else throw new InvalidKineticsKeyException();
}
return dep;
//#]
}
//## operation calculateDistance(HashSet,HashSet)
private static final int calculateDistance(HashSet p_treeNodeSet1, HashSet p_treeNodeSet2) {
//#[ operation calculateDistance(HashSet,HashSet)
return Math.abs(calculateDepth(p_treeNodeSet1)-calculateDepth(p_treeNodeSet2));
//#]
}
//## operation extractKineticsTemplateKey(HashSet)
private static final LinkedHashSet extractKineticsTemplateKey(LinkedHashSet p_treeNode) {
//#[ operation extractKineticsTemplateKey(HashSet)
LinkedHashSet key = new LinkedHashSet();
for (Iterator iter = p_treeNode.iterator(); iter.hasNext(); ) {
Object n = iter.next();
if (n instanceof DummyLeaf) {
String name = ((DummyLeaf)n).getName();
key.add(name);
}
else if (n instanceof HierarchyTreeNode) {
Matchable fg = (Matchable)((HierarchyTreeNode)n).getElement();
key.add(fg);
}
else {
throw new InvalidKineticsKeyException();
}
}
return key;
//#]
}
//## operation fillKineticsBottomToTop()
public void fillKineticsBottomToTop() {
//#[ operation fillKineticsBottomToTop()
LinkedHashSet rootSet = new LinkedHashSet();//6/26/09 gmagoon: changed from HashSet to LinkedHashSet to make behavior deterministic
Iterator tree_iter = getReactantTree();
while (tree_iter.hasNext()) {
HierarchyTree tree = (HierarchyTree)tree_iter.next();
rootSet.add(tree.getRoot());
}
fillKineticsByAverage(rootSet);
System.gc();
//#]
}
/**
Requires:
Effects:
Modifies:
*/
//## operation fillKineticsByAverage(HashSet)
private Kinetics fillKineticsByAverage(LinkedHashSet p_treeNodeSet) {
//#[ operation fillKineticsByAverage(HashSet)
// check if k is already in the library
// if it is, don't do any average;
// if it isn't, average all the k below this tree node set to get an estimated k for this tree node set;
LinkedHashSet key = extractKineticsTemplateKey(p_treeNodeSet);
Kinetics k = kineticsTemplateLibrary.getKinetics(key);
if (k==null || (k!=null && k.getRank()==0)) {
boolean allLeaf=true;
LinkedList fgc = new LinkedList();
Iterator iter = p_treeNodeSet.iterator();
while (iter.hasNext()) {
Object node = iter.next();
Stack path = new Stack();
if (node instanceof DummyLeaf) {
path.push(node);
}
else if (node instanceof HierarchyTreeNode) {
HierarchyTreeNode n = (HierarchyTreeNode)node;
if (n.isLeaf()) {
path.push(n);
}
else {
allLeaf = false;
if (n.hasDummyChild()) path.push(n.getDummyChild());
for (Iterator child_iter = n.getChildren(); child_iter.hasNext(); ) {
HierarchyTreeNode child = (HierarchyTreeNode)child_iter.next();
path.push(child);
}
}
}
else {
throw new InvalidKineticsKeyException();
}
fgc.add(path);
}
if (allLeaf) return null;
Collection allPossibleTreeNodeKeySet = MathTool.expand(fgc.iterator());
// this is the set that we could find for all the combinatorial generated from the p_fgc
LinkedHashSet kSet = new LinkedHashSet();
for (Iterator key_iter = allPossibleTreeNodeKeySet.iterator(); key_iter.hasNext(); ) {
LinkedHashSet keySet = new LinkedHashSet((Collection)key_iter.next());
Kinetics thisK = fillKineticsByAverage(keySet);
if (thisK!=null) kSet.add(thisK);
}
k = ArrheniusKinetics.average(kSet);
if (k==null) return null;
kineticsTemplateLibrary.addKinetics(key,k);
}
return k;
//#]
}
//## operation findClosestRateConstant(Collection)
public Kinetics findClosestRateConstant(LinkedList p_matchedPathSet) {
//#[ operation findClosestRateConstant(Collection)
LinkedHashSet exactTreeNode = new LinkedHashSet();
LinkedHashSet exactKey = new LinkedHashSet();
// deal with the top tree node(leaf)
// if it has a dummy child, at it into the matched path
// put the tree node into the exact tree node set
for (Iterator pathIter = p_matchedPathSet.iterator(); pathIter.hasNext();) {
Stack s = (Stack)pathIter.next();
HierarchyTreeNode n = (HierarchyTreeNode)(s.peek());
if (n.hasDummyChild()) {
DummyLeaf dl = n.getDummyChild();
s.push(dl);
exactTreeNode.add(dl);
exactKey.add(dl.getName());
}
else {
exactTreeNode.add(n);
exactKey.add(n.getElement());
}
}
// find if exact kt exists. if it does, return it.
KineticsTemplate kt = kineticsTemplateLibrary.getKineticsTemplate(exactKey);
int rNum = getReactantNumber();
if (kt!=null) {
return kt.kinetics;
}
Collection allPossibleTreeNodeSet = MathTool.expand(p_matchedPathSet.iterator());
HashSet bestKineticsTemplateSet = new HashSet();
LinkedHashSet bestKineticsSet = new LinkedHashSet();
// find the closest distance
int closest = Integer.MAX_VALUE;
for (Iterator iter = allPossibleTreeNodeSet.iterator(); iter.hasNext(); ) {
LinkedHashSet treeNode = new LinkedHashSet((Collection)iter.next());
LinkedHashSet key = extractKineticsTemplateKey(treeNode);
kt = kineticsTemplateLibrary.getKineticsTemplate(key);
if (kt != null) {
Kinetics k = kt.getKinetics();
int distance = calculateDistance(exactTreeNode,treeNode);
if (distance < closest) {
closest = distance;
bestKineticsTemplateSet.clear();
bestKineticsTemplateSet.add(kt);
bestKineticsSet.clear();
bestKineticsSet.add(k);
}
else if (distance == closest) {
bestKineticsTemplateSet.add(kt);
bestKineticsSet.add(k);
}
}
}
/* if (bestKineticsSet.size() == 0) {
System.out.println("problem with rate constant");
System.out.println(reactionAdjList.productNumber);
System.out.println(reactionAdjList.reactantNumber);
}*/
if (bestKineticsSet.size() == 0) throw new RateConstantNotFoundException();
// get averaged k with the closest distance
Kinetics newK = ArrheniusKinetics.average(bestKineticsSet);
return newK;
}
//## operation findExactRateConstant(Collection)
public Kinetics findExactRateConstant(Collection p_matchedPathSet) {
//#[ operation findExactRateConstant(Collection) \
LinkedHashSet fgc = new LinkedHashSet();
for (Iterator iter = p_matchedPathSet.iterator(); iter.hasNext();) {
Stack s = (Stack)iter.next();
HierarchyTreeNode node = (HierarchyTreeNode)s.peek();
if (node.hasDummyChild()) fgc.add(node.getDummyChild().getName());
else {
Matchable fg = (Matchable)node.getElement();
fgc.add(fg);
}
}
KineticsTemplate kt = kineticsTemplateLibrary.getKineticsTemplate(fgc);
if (kt==null) return null;
else return kt.kinetics;
}
/**
Requires:
Effects: call itsKineticsTemplateLibrary.findKinetics() to find out the kinetics for the structure, return the found kinetics or null if nothing is found.
Modifies:
*/
//## operation findRateConstant(Structure)
public Kinetics[] findRateConstant(Structure p_structure) {
double pT = System.currentTimeMillis();
/*
*If a primary reaction library exists, check the
* current reaction against that list before attempting
* to estimate via searching the tree
*/
Kinetics[] k = null;
if (doesPrimaryKineticLibraryExist()) {
k = getPrimaryKineticRate(p_structure);
}
if (k != null) {
setRateCoefficientSource(k);
p_structure.setDirection(getPrimaryKineticDirection(p_structure));
return k;
}
// look for kinetics in kinetics template libarry
LinkedList reactants = null;
if (isForward()) {
p_structure.setDirection(1);
reactants = p_structure.reactants;
}
else if (isBackward()) {
p_structure.setDirection(-1);
}
else if (isNeutral()) {
boolean thermoConsistence = true;
// in H abstraction, we allow biradical abstract H from a molecule, but the reverse is not allowed
// therefore, such H abs reactions will be all set as forward reaction
// (unless the reverse is also a biradical)
/*
* 18-SEPT-2010
* Recently, members of the Green Group have been having difficulty getting RMG-generated
* mechanisms to converge in PREMIX (CHEMKIN model). One reason for these numerical issues
* is due to small K_eq (thus, when computing k_rev = k_f / K_eq, we are dividing by a very
* small number, potentially, for very endothermic reactions). To help avoid these issues,
* I am removing the reaction family specific rules for H_Abstraction and intra_H_migration
* so that the reaction will always be written in the exothermic direction.
* MRH ([email protected])
*
* 24-SEPT-2010
* Restoring the "if one species has more than one radical, automatically
* assign it as the reactants". It seems RMG's rate coefficient estimates
* for the R. + HOO. --> .OO. + RH direction are not very accurate (ignition delays
* change drastically, running the same condition.txt file).
*/
/* 17-JAN-2011
* Once again removing the "H_Abstraction" code so that the exothermic direction is always favored.
* The observation of 24-SEPT-2010 that the ignition delays change drastically could have been due
* to some other change.
if (name.equals("H_Abstraction")) {
boolean polyRadicalReactant = false;
boolean polyRadicalProduct = false;
Iterator iter = p_structure.reactants.iterator();
while (iter.hasNext()) {
ChemGraph cg = (ChemGraph)iter.next();
int rNum = cg.getRadicalNumber();
if (rNum >= 2) polyRadicalReactant = true;
}
iter = p_structure.products.iterator();
while (iter.hasNext()) {
ChemGraph cg = (ChemGraph)iter.next();
int rNum = cg.getRadicalNumber();
if (rNum >= 2) polyRadicalProduct = true;
}
// If both reactants and products have polyradical species
// then let the exothermic direction win, otherwise
// make sure the polyradical is a reactant.
if (polyRadicalReactant && polyRadicalProduct) {
thermoConsistence = true;
}
else if (polyRadicalReactant) {
thermoConsistence = false;
reactants = p_structure.reactants;
p_structure.setDirection(1);
}
else if (polyRadicalProduct) {
thermoConsistence = false;
p_structure.setDirection(-1);
}
}
*/
if (thermoConsistence) {
Temperature T = new Temperature(298, "K");
// to avoid calculation error's effect, lower the threshold for forward reaction
//if (p_structure.calculateKeq(T)>0.999) {
/*if (p_structure.calculateKeq(T)>0.999 && p_structure.calculateKeq(T) <1.001) {
System.out.println(p_structure.toChemkinString(true));
}*/
if (p_structure.calculateKeq(T)>0.999) {
p_structure.setDirection(1);
reactants = p_structure.reactants;
}
else {
p_structure.setDirection(-1);
}
// for intra h migration, set the ROO. as the forward
/*
I think the reason for this is that our rate estimates
for migration from OH to C. are worse than from CH to O.
(i.e. entirely missing and estimated by inappopriate averaging).
This is a property of the current database and probably shouldn't be
hard-coded like this, but for now I'll leave it. -- rwest
*/
if (name.equals("intra_H_migration")) {
ChemGraph rcg = (ChemGraph)(p_structure.getReactants().next());
HashSet rrad = rcg.getRadicalNode();
Atom rra = (Atom)( (Node) ( (rrad.iterator()).next())).getElement();
ChemGraph pcg = (ChemGraph)(p_structure.getProducts().next());
HashSet prad = pcg.getRadicalNode();
Atom pra = (Atom)( (Node) ( (prad.iterator()).next())).getElement();
if (rra.isOxygen() && pra.isCarbon()) {
p_structure.setDirection(1);
reactants = p_structure.reactants;
}
else if (pra.isOxygen() && rra.isCarbon())
p_structure.setDirection(-1);
}
}
}
else {
throw new InvalidReactionTemplateDirectionException();
}
if (p_structure.isForward()) {
Kinetics kf = null;
LinkedList fg = structureTemplate.getMatchedFunctionalGroup(reactants);
if (fg == null) {
Global.RT_findRateConstant += (System.currentTimeMillis()-pT)/1000/60;
return null;
}
String comments = getKineticsComments(fg);
kf = findExactRateConstant(fg);
if (kf==null) {
kf = findClosestRateConstant(fg);
kf.setSource(name + " estimate: (" + kf.getSource() + ")");
}
else kf.setSource(name + " exact: ");
kf.setComments(comments);
Global.RT_findRateConstant += (System.currentTimeMillis()-pT)/1000/60;
// fix rate constant here
double Hrxn = p_structure.calculateHrxn(new Temperature(298, "K"));
ArrheniusKinetics k_fixed = kf.fixBarrier(Hrxn);
// We must return a list (with one element).
k = new Kinetics[1];
k[0] = k_fixed;
return k;
}
else {
Global.RT_findRateConstant += (System.currentTimeMillis()-pT)/1000/60;
return null;
}
}
/**
In commit 030ff4bd577e8ace9b4f2e023f4a8faf641bb9b2 the function findReverseRateConstant()
was added. It was entire copy of findRateConstant() with one line wrapped in a try/catch block
returning null on exception. Since then, the two functions, maintained separately, have diverged
a little by mistake. Now, this findReverseRateConstant function just calls the findRateConstant() function.
*/
public Kinetics[] findReverseRateConstant(Structure p_structure) {
Kinetics[] k = null;
try{
k = findRateConstant(p_structure);
}
catch (RateConstantNotFoundException e) {
return k;
}
return k;
}
public void setRateCoefficientSource(Kinetics[] k) {
for (int numK=0; numK<k.length; numK++) {
k[numK].setFromPrimaryKineticLibrary(true);
String currentSource = k[numK].getSource();
if (this.direction == -1) {
if (!currentSource.contains(this.reverseReactionTemplate.name))
k[numK].setSource(this.reverseReactionTemplate.name+" "+k[numK].getSource());
}
else {
if (!currentSource.contains(this.name))
k[numK].setSource(this.name+" "+k[numK].getSource());
}
}
}
/**
* Given a structure, function searches the primary reaction library
* to determine if user supplied a set of kinetic parameters for
* this reaction. If so, RMG uses this set of parameters. If not,
* RMG estimates the kinetic parameters by traversing the tree.
*
* @param p_structure: Structure of the reaction
* @return
*/
private Kinetics[] getPrimaryKineticRate(Structure p_structure) {
boolean equivReactants = false;
LinkedHashSet primaryKinLibrary = getPrimaryKinLibrary();
Iterator iter = primaryKinLibrary.iterator();
LinkedList reactants_asdefinedbyRMG = p_structure.getReactantList();
LinkedList products_asdefinedbyRMG = p_structure.getProductList();
while (iter.hasNext()) {
Reaction rxn = (Reaction)iter.next();
LinkedList reactants_asdefinedinPRL = rxn.getReactantList();
/*
* The LinkedList "reactants_asdefinedbyRMG" contains species generated by RMG.
* The LinkedList contains chemgraphs (and species, indirectly).
* The LinkedList "reactants_asdefinedinPRL" contains the species read in by RMG,
* from the user-defined primary reaction library. When reading in the user-
* specified adjacency lists, RMG makes a Species (meaning all resonance
* isomers have been explored / stored).
* Thus, both reactants_asdefinedbyRMG and reactants_asdefinedinPRL have all
* of the resonance isomers defined ... if you know where to look
*/
equivReactants = Structure.isSpeciesListEquivalentToChemGraphListAsChemGraphs(reactants_asdefinedinPRL,reactants_asdefinedbyRMG);
if (equivReactants) {
LinkedList products_asdefinedinPRL = rxn.getProductList();
if (Structure.isSpeciesListEquivalentToChemGraphListAsChemGraphs(products_asdefinedinPRL,products_asdefinedbyRMG)) {
if (rxn instanceof ThirdBodyReaction || rxn instanceof TROEReaction || rxn instanceof LindemannReaction)
Logger.info("RMG is only utilizing the high-pressure limit parameters for PKL reaction: " + rxn.toString());
return rxn.getKinetics();
}
}
}
return null;
}
private int getPrimaryKineticDirection(Structure p_structure) {
boolean equivReactants = false;
LinkedHashSet primaryKinLibrary = getPrimaryKinLibrary();
Iterator iter = primaryKinLibrary.iterator();
LinkedList p_reactants = p_structure.getReactantList();
LinkedList p_products = p_structure.getProductList();
while (iter.hasNext()) {
Reaction rxn = (Reaction)iter.next();
LinkedList reactants = rxn.getReactantList();
equivReactants = Structure.isSpeciesListEquivalentToChemGraphListAsChemGraphs(reactants, p_reactants);
if (equivReactants) {
LinkedList products = rxn.getProductList();
if (Structure.isSpeciesListEquivalentToChemGraphListAsChemGraphs(products,p_products)) {
if (rxn instanceof ThirdBodyReaction || rxn instanceof TROEReaction || rxn instanceof LindemannReaction)
Logger.info("RMG is only utilizing the high-pressure limit parameters for PKL reaction: " + rxn.toString());
return rxn.getStructure().direction;
}
}
}
return -1;
}
private String getKineticsComments(Collection p_matchedPathSet) {
StringBuilder comment = new StringBuilder("[ ");
for (Iterator iter = p_matchedPathSet.iterator(); iter.hasNext();) {
Stack s = (Stack)iter.next();
HierarchyTreeNode node = (HierarchyTreeNode)s.peek();
if (node.hasDummyChild()) comment.append((node.getDummyChild().getName() + " , "));
else {
if (node.getElement() instanceof FunctionalGroup)
comment.append(((FunctionalGroup)node.getElement()).getName() + " , ");
else
comment.append(((FunctionalGroupCollection)node.getElement()).getName() + " , ");
}
}
comment.delete(comment.length()-2, comment.length()); // remove the final comma
comment.append("]");
return comment.toString();
}
//## operation findUnion(String,HashMap)
private void findUnion(String p_name, HashMap p_unRead) {
//#[ operation findUnion(String,HashMap)
HashSet union = (HashSet)p_unRead.get(p_name);
FunctionalGroupCollection fgc = new FunctionalGroupCollection(p_name);
Iterator union_iter = union.iterator();
while (union_iter.hasNext()) {
String fg_name = (String)union_iter.next();
if (p_unRead.containsKey(fg_name)) {
findUnion(fg_name, p_unRead);
}
Matchable fg = (Matchable)fgDictionary.get(fg_name);
if (fg == null)
throw new InvalidFunctionalGroupException("Unknown FunctionalGroup in findUnion(): " + fg_name);
fgc.addFunctionalGroups(fg);
}
fgDictionary.put(p_name,fgc);
p_unRead.remove(p_name);
return;
//#]
}
/**
Requires:
Effects: Return the reversed reaction template of this reaction template if this reaction template's direction is forward. Reverse reaction template in such aspects:
(1) structure template
(2) kinetics template
(3) direction
Note: if the reversereaction template is generated successfully, set this.itsReverseReactionTemplate to this new generated reaction template.
Modifies: this.itsReverseReactionTemplate.
*/
// Argument Stringp_name :
/**
pass in the name of the reverse reaction template
*/
//## operation generateReverseReactionTemplate(String)
public ReactionTemplate generateReverseReactionTemplate(String p_name) {
//#[ operation generateReverseReactionTemplate(String)
// guarantee validity of the template and its direction
if (direction != 1 || !repOk()) {
return null;
}
ReactionTemplate reversetemplate = new ReactionTemplate();
// set direction
reversetemplate.direction = -1;
// set name
reversetemplate.name = p_name;
// set the structure template
reversetemplate.structureTemplate = structureTemplate.generateReverse(reactionAdjList);
// set the reaction adjList
reversetemplate.reactionAdjList = reactionAdjList.generateReverse();
// set the kinetics template library to the forward kinetics template library to keep thermo consistency
reversetemplate.kineticsTemplateLibrary = kineticsTemplateLibrary;
// set itsReverseReactionTemplate to this generated reversetemplate
reversetemplate.reverseReactionTemplate = this;
this.reverseReactionTemplate = reversetemplate;
return reversetemplate;
//#]
}
//## operation getProductNumber()
public int getProductNumber() {
//#[ operation getProductNumber()
return reactionAdjList.getProductNumber();
//#]
}
//## operation getReactantNumber()
public int getReactantNumber() {
//#[ operation getReactantNumber()
return structureTemplate.getReactantNumber();
//#]
}
//## operation getReactantTree()
public Iterator getReactantTree() {
//#[ operation getReactantTree()
return getStructureTemplate().getReactantTree();
//#]
}
//## operation getReactantTreeNumber()
public int getReactantTreeNumber() {
//#[ operation getReactantTreeNumber()
return structureTemplate.getReactantTreeNumber();
//#]
}
//## operation getReactionFromStructure(Structure)
public TemplateReaction getReactionFromStructure(Structure p_structure) {
//#[ operation getReactionFromStructure(Structure)
return (TemplateReaction)reactionDictionaryByStructure.get(p_structure);
//#]
}
//## operation hasOneReactant()
public boolean hasOneReactant() {
//#[ operation hasOneReactant()
return (getReactantNumber() == 1);
//#]
}
//## operation hasTwoReactants()
public boolean hasTwoReactants() {
//#[ operation hasTwoReactants()
return (getReactantNumber() == 2);
//#]
}
//## operation isBackward()
public boolean isBackward() {
//#[ operation isBackward()
return (direction == -1);
//#]
}
//## operation isForward()
public boolean isForward() {
//#[ operation isForward()
return (direction == 1);
//#]
}
//## operation isNeutral()
public boolean isNeutral() {
//#[ operation isNeutral()
return (direction == 0);
//#]
}
//## operation isReverse(ReactionTemplate)
public boolean isReverse(ReactionTemplate p_reactionTemplate) {
//#[ operation isReverse(ReactionTemplate)
if (direction == 0 || reverseReactionTemplate == null) return false;
return reverseReactionTemplate.equals(p_reactionTemplate);
//#]
}
/**
Requires:
Effects: react p_reactant according to this reaction template to form a set of reactions. (generate product according to the reaction adjlist, find out kinetics sccording to the kinticstemplatelibrary). return the set of reactions.
Modifies:
*/
//## operation reactOneReactant(Species)
public LinkedHashSet reactOneReactant(Species p_reactant) {
//#[ operation reactOneReactant(Species)
LinkedList r = new LinkedList();
r.add(p_reactant);
/*HashSet reaction = getReactionSetFromReactant(r);
if (reaction != null)
return reaction;*/
ChemGraph rg;
LinkedHashSet reaction = new LinkedHashSet();
if (!p_reactant.hasResonanceIsomers()) {
// react the main structre
rg = p_reactant.getChemGraph();
reaction = reactOneReactant(rg);
}
else {
// react the resonance isomers
Iterator iter = p_reactant.getResonanceIsomers();
while (iter.hasNext()) {
rg = (ChemGraph)iter.next();
LinkedHashSet more = reactOneReactant(rg);
reaction.addAll(more);
}
}
// put in reactionDictionaryByReactant
//reactionDictionaryByReactant.put(r,reaction);
// return the reaction set
return reaction;
//#]
}
//## operation reactOneReactant(ChemGraph)
protected LinkedHashSet reactOneReactant(ChemGraph p_chemGraph) {
//#[ operation reactOneReactant(ChemGraph)
LinkedHashSet reaction_set = new LinkedHashSet();
// if (name.equals("Intra_R_Add_Endocyclic") && !p_chemGraph.isAcyclic()) return reaction_set; //commented out by gmagoon 7/29/09: according to Sandeep this may be an unneeded artifact of an old bug that may have been addressed with the use of ForbiddenGroups for Intra_R_Add_Endocyclic and Intra_R_Add_Exocyclic; however, it should be kept in mind that when this is commented out, it is probably more likely that one will obtain reactions for which the group identification (and hence kinetics estimates) are not reproducible due to identification of different ring paths in the same molecule
LinkedHashSet allReactionSites = structureTemplate.identifyReactedSites(p_chemGraph,1);
//System.out.println("Species: "+p_chemGraph.toString());
if (allReactionSites.isEmpty()) return reaction_set;
// add present chemgraph into the reactant linked list
LinkedList reactant = new LinkedList();
LinkedList reactantSp = new LinkedList();
reactant.add(p_chemGraph);
reactantSp.add(p_chemGraph.getSpecies());
LinkedHashMap structureMap = new LinkedHashMap();
LinkedHashMap rateMap = new LinkedHashMap();
LinkedHashMap reactionMap = new LinkedHashMap();
for (Iterator iter = allReactionSites.iterator(); iter.hasNext(); ) {
MatchedSite ms = (MatchedSite)iter.next();
HashMap site = ms.getCenter();
int redundancy = ms.getRedundancy();
//System.out.println(ms.toString());
// reset the reacted site for rg in reactant linkedlist
p_chemGraph.resetReactedSite(site);
boolean forbidden = false;
Iterator forbiddenIter = forbiddenStructures.values().iterator();
while (forbiddenIter.hasNext()){
Matchable fg = (Matchable)forbiddenIter.next();
if (p_chemGraph.isSubAtCentralNodes(fg)){
forbidden = true;
break;
}
}
if (forbidden) break;
// react reactant to form a new structure
try {
LinkedList product = reactionAdjList.reactChemGraph(reactant);
LinkedList productSp = new LinkedList();
SpeciesDictionary sd = SpeciesDictionary.getInstance();
for (int i=0; i< product.size(); i++){
String name = null;
if (((ChemGraph)product.get(i)).getSpecies() == null){
Species sp = Species.make(name, ((ChemGraph)product.get(i)));
productSp.add(sp);
}
}
double pt = System.currentTimeMillis();
boolean rpsame = MathTool.isListEquivalent(reactantSp, productSp);
Global.checkReactionReverse = Global.checkReactionReverse + (System.currentTimeMillis()-pt)/1000/60;
if (!rpsame) {
Structure structure = new Structure(reactant,product);
Kinetics[] k = findRateConstant(structure);
Structure structureSp = new Structure(reactantSp, productSp);
structureSp.direction = structure.direction;
structure.setRedundancy(redundancy);
Reaction old_reaction = (Reaction)reactionMap.get(structureSp);
if (old_reaction == null){
TemplateReaction r = TemplateReaction.makeTemplateReaction(structureSp,k, this,structure);
structure = null;
if (r != null)
reactionMap.put(structureSp,r);
}
else {
if (k == null)
old_reaction.addAdditionalKinetics(null,redundancy,false);
else {
for (int i=0; i<k.length; i++) {
old_reaction.addAdditionalKinetics(k[i], redundancy,false);
}
}
//old_reaction.getStructure().increaseRedundancy(redundancy);
structureSp = null;
structure = null;
}
}
}
catch (ForbiddenStructureException e) {
// do the next reaction site
}
catch (InvalidProductNumberException e) {
// do the next reaction site
}
}
for (Iterator mapIter = reactionMap.values().iterator(); mapIter.hasNext(); ) {
Reaction reaction = (Reaction)mapIter.next();
//System.out.println(reaction.toString());
if (!reaction.repOk()) throw new InvalidTemplateReactionException(reaction.toString());
//reaction.getStructure().clearChemGraph();
reaction.setFinalized(true);
reaction_set.add(reaction);
}
return reaction_set;
//#]
}
// ## operation reactTwoReactants(ChemGraph,ChemGraph)
/*protected TemplateReaction calculateForwardRateConstant(ChemGraph chemGraph1, ChemGraph chemGraph2, Structure p_structure) {
//#[ operation reactTwoReactants(ChemGraph,ChemGraph)
ChemGraph r1 = chemGraph1;
ChemGraph r2 = chemGraph2;
if (r1 == r2) {
try{
r2 = ChemGraph.copy(r2);
}
catch (ForbiddenStructureException e) {
return null;
}
}
TemplateReaction reverseReaction = null;
/*TemplateReaction reverseReaction = getReactionFromStructure(p_structure);
if (reverseReaction != null){
if (!reverseReaction.isForward()) throw new InvalidReactionDirectionException();
return reverseReaction;
}
HashSet allReactionSites1 = structureTemplate.identifyReactedSites(r1,1);
HashSet allReactionSites2 = structureTemplate.identifyReactedSites(r2,2);
LinkedList reactant = new LinkedList();
reactant.add(r1);
reactant.add(r2);
HashSet rateSet = new HashSet();
for (Iterator iter1 = allReactionSites1.iterator(); iter1.hasNext(); ) {
MatchedSite ms1 = (MatchedSite)iter1.next();
HashMap site1 = ms1.getCenter();
r1.resetReactedSite(site1);
int redundancy1 = ms1.getRedundancy();
for (Iterator iter2 = allReactionSites2.iterator(); iter2.hasNext(); ) {
MatchedSite ms2 = (MatchedSite)iter2.next();
HashMap site2 = (HashMap)ms2.getCenter();
r2.resetReactedSite(site2);
int redundancy2 = ms2.getRedundancy();
int redundancy = redundancy1*redundancy2;
try {
LinkedList product = reactionAdjList.reactChemGraph(reactant);
SpeciesDictionary sd = SpeciesDictionary.getInstance();
for (int i=0; i< product.size(); i++){
String name = null;
if (((ChemGraph)product.get(i)).getSpecies() == null){
Species sp = Species.make(name, ((ChemGraph)product.get(i)));
}
}
boolean rpsame = MathTool.isListEquivalent(reactant, product);
if (!rpsame) {
Structure structure = new Structure(reactant,product);
if (structure.equals(p_structure)){
Kinetics k = findRateConstant(p_structure);
if (reverseReaction == null){
reverseReaction = TemplateReaction.makeTemplateReaction(p_structure,k,this);
}
else {
//p_structure.increaseRedundancy(redundancy);
reverseReaction.addAdditionalKinetics(k,redundancy);
//structure = null;
}
}
/*else {
SpeciesDictionary sd = SpeciesDictionary.getInstance();
while (!product.isEmpty())
sd.remove(((ChemGraph)product.remove()));
}
}
}
catch (ForbiddenStructureException e) {
// do the next reaction site
}
catch (InvalidProductNumberException e) {
// do the next reaction site
}
catch (InvalidChemGraphException e){
}
}
}
//reverseReaction.getStructure().clearChemGraph();
return reverseReaction;
//#]
}*/
// ## operation reactTwoReactants(ChemGraph,ChemGraph)
protected TemplateReaction calculateForwardRateConstant(ChemGraph p_chemGraph, Structure p_structure) {
//#[ operation reactTwoReactants(ChemGraph,ChemGraph)
TemplateReaction reverseReaction = null;
LinkedHashSet rateSet = new LinkedHashSet();
LinkedHashSet allReactionSites = structureTemplate.identifyReactedSites(p_chemGraph,1);
if (allReactionSites.isEmpty()) return reverseReaction;
// add present chemgraph into the reactant linked list
LinkedList reactant = new LinkedList();
LinkedList reactantSp = new LinkedList();
reactantSp.add(p_chemGraph.getSpecies());
reactant.add(p_chemGraph);
for (Iterator iter = allReactionSites.iterator(); iter.hasNext(); ) {
MatchedSite ms = (MatchedSite)iter.next();
HashMap site = ms.getCenter();
int redundancy = ms.getRedundancy();
// reset the reacted site for rg in reactant linkedlist
p_chemGraph.resetReactedSite(site);
// react reactant to form a new structure
try {
LinkedList product = reactionAdjList.reactChemGraph(reactant);
LinkedList productSp = new LinkedList();
for (int i=0; i< product.size(); i++){
String name = null;
if (((ChemGraph)product.get(i)).getSpecies() == null){
Species sp = Species.make(name, ((ChemGraph)product.get(i)));
productSp.add(sp);
}
}
boolean rpsame = MathTool.isListEquivalent(reactantSp, productSp);
if (!rpsame) {
Structure structure = new Structure(reactant,product);
Structure structureSp = new Structure(reactantSp,productSp);
if (structure.equalsAsChemGraph(p_structure)){
Kinetics[] k = findRateConstant(p_structure);
structureSp.direction = p_structure.direction;
if (reverseReaction == null){
reverseReaction = TemplateReaction.makeTemplateReaction(structureSp,k,this,p_structure);
}
else {
//p_structure.increaseRedundancy(redundancy);
for (int i=0; i<k.length; i++) {
reverseReaction.addAdditionalKinetics(k[i],redundancy,false);
}
}
}
}
}
catch (ForbiddenStructureException e) {
// do the next reaction site
}
catch (InvalidProductNumberException e) {
// do the next reaction site
}
}
//reverseReaction.getStructure().clearChemGraph();
reverseReaction.setFinalized(true);
return reverseReaction;
//#]
}
/**
* reactTwoReactants
* 17-Jun-2009 MRH
* Function "reacts" two reactants (in the form of ChemGraphs).
*
* @param cg1: ChemGraph of species1
* @param rs1: Collection of reactive sites for cg1
* @param cg2: ChemGraph of species2
* @param rs2: Collection of reactive sties for cg2
* @return
*/
protected LinkedHashSet reactTwoReactants(ChemGraph cg1, LinkedHashSet rs1, ChemGraph cg2, LinkedHashSet rs2) {
LinkedHashSet reaction_set = new LinkedHashSet();
if (rs1.isEmpty() || rs2.isEmpty()) return reaction_set;
ChemGraph r1 = cg1;
ChemGraph r2;
if (cg1 == cg2) {
try{
r2 = ChemGraph.copy(cg2);
}
catch (ForbiddenStructureException e) {
return reaction_set;
}
}
else {
r2 = cg2;
}
LinkedList reactant = new LinkedList();
LinkedList reactantSp = new LinkedList();
reactant.add(r1);
reactant.add(r2);
reactantSp.add(r1.getSpecies());
reactantSp.add(r2.getSpecies());
LinkedHashMap structureMap = new LinkedHashMap();
LinkedHashMap rateMap = new LinkedHashMap();
LinkedHashMap reactionMap = new LinkedHashMap();
for (Iterator iter1 = rs1.iterator(); iter1.hasNext(); ) {
MatchedSite ms1 = (MatchedSite)iter1.next();
HashMap site1 = ms1.getCenter();
r1.resetReactedSite(site1);
boolean forbidden1 = false;
Iterator forbiddenIter = forbiddenStructures.values().iterator();
while (forbiddenIter.hasNext()){
Matchable fg = (Matchable)forbiddenIter.next();
if (r1.isSubAtCentralNodes(fg)){
forbidden1 = true;
break;
}
}
if (forbidden1) continue;
int redundancy1 = ms1.getRedundancy();
for (Iterator iter2 = rs2.iterator(); iter2.hasNext(); ) {
MatchedSite ms2 = (MatchedSite)iter2.next();
HashMap site2 = (HashMap)ms2.getCenter();
r2.resetReactedSite(site2);
boolean forbidden2 = false;
forbiddenIter = forbiddenStructures.values().iterator();
while (forbiddenIter.hasNext()){
Matchable fg = (Matchable)forbiddenIter.next();
if (r2.isSubAtCentralNodes(fg)){
forbidden2 = true;
break;
}
}
if (forbidden2) continue;
int redundancy2 = ms2.getRedundancy();
int redundancy = redundancy1*redundancy2;
try {
LinkedList product = reactionAdjList.reactChemGraph(reactant);
LinkedList productSp = new LinkedList();
for (int i=0; i< product.size(); i++){
String name = null;
Species sp = ((ChemGraph)product.get(i)).getSpecies();
if (sp == null){
sp = Species.make(name, ((ChemGraph)product.get(i))); // gets old one it if it already exists, and saves it in the chemgraph
}
productSp.add(sp);
}
double pt = System.currentTimeMillis();
boolean rpsame = MathTool.isListEquivalent(reactantSp, productSp);
Global.checkReactionReverse = Global.checkReactionReverse + (System.currentTimeMillis()-pt)/1000/60;
if (!rpsame) {
Structure structure = new Structure(reactant,product);
Structure structureSp = new Structure(reactantSp,productSp);
Kinetics[] k = findRateConstant(structure);
structureSp.direction = structure.direction;
structure.setRedundancy(redundancy);
Reaction old_reaction = (Reaction)reactionMap.get(structureSp);
if (old_reaction == null){
TemplateReaction r= TemplateReaction.makeTemplateReaction(structureSp,k, this,structure);
if (r != null)
reactionMap.put(structureSp,r);
structure = null;
}
else {
if (k == null)
old_reaction.addAdditionalKinetics(null,redundancy,false);
else {
for (int i=0; i<k.length; i++) {
old_reaction.addAdditionalKinetics(k[i], redundancy,false);
}
}
//old_reaction.getStructure().increaseRedundancy(redundancy);
structure = null;
}
}
}
catch (ForbiddenStructureException e) {
// do the next reaction site
}
catch (InvalidProductNumberException e) {
// do the next reaction site
}
catch (InvalidChemGraphException e){
}
}
}
for (Iterator mapIter = reactionMap.values().iterator(); mapIter.hasNext(); ) {
Reaction reaction = (Reaction)mapIter.next();
//System.out.println(reaction.toString());
if (!reaction.repOk()) throw new InvalidTemplateReactionException(reaction.toString());
//reaction.getStructure().clearChemGraph();
reaction.setFinalized(true);
reaction_set.add(reaction);
}
return reaction_set;
}
/**
Requires:
Effects: read in the reaction templated defined in the pass-in directory
Modifies:
*/
//## operation read(String,String)
public void read(String p_reactionTemplateName, String p_directoryName) {
//#[ operation read(String,String)
String directoryName;
if (!(p_directoryName.endsWith("/"))) {
directoryName = p_directoryName + "/";
}
else {
directoryName = p_directoryName;
}
setName(p_reactionTemplateName);
Logger.info("Reading forward template: "+p_reactionTemplateName);
String ReactionAdjListName = directoryName + "reactionAdjList.txt";
String DictionaryName = directoryName + "dictionary.txt";
String TreeName = directoryName + "tree.txt";
String LibraryName = directoryName + "rateLibrary.txt";
String ForbiddenName = directoryName + "forbiddenGroups.txt";
try {
readFGDictionary(DictionaryName);
readForbiddenStructures(ForbiddenName);
String reverseRTName = readReactionAdjList(ReactionAdjListName);
readTree(TreeName);
readLibrary(LibraryName);
fillKineticsBottomToTop();
if (reverseRTName != null && reverseRTName.compareToIgnoreCase("none")!=0) {
Logger.info("Generating reverse template: "+reverseRTName);
reverseReactionTemplate = generateReverseReactionTemplate(reverseRTName);
reverseReactionTemplate.forbiddenStructures = forbiddenStructures;
}
}
catch (Exception e) {
Logger.logStackTrace(e);
Logger.critical("Error in read in reaction template: " + name);
Logger.critical(e.getMessage());
System.exit(0);
}
return;
//#]
}
public void readForbiddenStructures(String p_fileName) throws IOException {
//#[ operation readFGDictionary(String)
try {
if (!(new File(p_fileName)).exists()) {
// System.out.println("forbiddenStructures file does not exist");
return;
}
FileReader in = new FileReader(p_fileName);
BufferedReader data = new BufferedReader(in);
HashMap unRead = new HashMap();
String fgname = null;
// step 1: read in structure
String line = ChemParser.readMeaningfulLine(data, true);
read: while (line != null) {
StringTokenizer token = new StringTokenizer(line);
fgname = token.nextToken();
data.mark(10000);
line = ChemParser.readMeaningfulLine(data, true);
if (line == null) break read;
line = line.trim();
String prefix = line.substring(0,5);
if (prefix.compareToIgnoreCase("union") == 0) {
HashSet union = ChemParser.readUnion(line);
unRead.put(fgname,union);
}
else {
data.reset();
Graph fgGraph = null;
try {
fgGraph = ChemParser.readFGGraph(data);
}
catch (InvalidGraphFormatException e) {
throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage());
}
if (fgGraph == null)
throw new InvalidFunctionalGroupException(fgname);
FunctionalGroup fg = FunctionalGroup.make(fgname, fgGraph);
Object old = forbiddenStructures.get(fgname);
if (old == null) {
forbiddenStructures.put(fgname,fg);
}
else {
FunctionalGroup oldFG = (FunctionalGroup)old;
if (!oldFG.equals(fg)) throw new ReplaceFunctionalGroupException(fgname);
}
}
line = ChemParser.readMeaningfulLine(data, true);
}
while (!unRead.isEmpty()) {
fgname = (String)(unRead.keySet().iterator().next());
ChemParser.findUnion(fgname,unRead,forbiddenStructures);
}
in.close();
return;
}
catch (Exception e) {
Logger.logStackTrace(e);
Logger.error("Failed to read forbiddenStructures file");
//throw new IOException(e.getMessage());
}
//#]
}
//## operation readFGDictionary(String)
public void readFGDictionary(String p_fileName) throws IOException {
//#[ operation readFGDictionary(String)
try {
FileReader in = new FileReader(p_fileName);
BufferedReader data = new BufferedReader(in);
HashMap unRead = new HashMap();
String fgname = null;
// step 1: read in structure
String line = ChemParser.readMeaningfulLine(data, true);
read: while (line != null) {
StringTokenizer token = new StringTokenizer(line);
fgname = token.nextToken();
if (fgname.toLowerCase().startsWith("others")) {
Logger.verbose(" Skipping dictionary definition of group "+fgname+" because its begins with 'others' and that has special meaning.");
// gobble up the rest
while (line!=null) {
line=ChemParser.readUncommentLine(data);
}
// now get an unblank line
line = ChemParser.readMeaningfulLine(data, true);
continue read;
}
data.mark(10000);
line = ChemParser.readMeaningfulLine(data, true);
if (line == null) break read;
line = line.trim();
if (line.toLowerCase().startsWith("union") || line.startsWith("OR") ) {
HashSet union = ChemParser.readUnion(line);
unRead.put(fgname,union);
}
else {
data.reset();
Graph fgGraph = null;
try {
fgGraph = ChemParser.readFGGraph(data);
}
catch (InvalidGraphFormatException e) {
throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage());
}
if (fgGraph == null)
throw new InvalidFunctionalGroupException(fgname);
FunctionalGroup fg = FunctionalGroup.make(fgname, fgGraph);
Object old = fgDictionary.get(fgname);
if (old == null) {
fgDictionary.put(fgname,fg);
}
else {
FunctionalGroup oldFG = (FunctionalGroup)old;
if (!oldFG.equals(fg)) throw new ReplaceFunctionalGroupException(fgname);
}
}
line = ChemParser.readMeaningfulLine(data, true);
}
while (!unRead.isEmpty()) {
fgname = (String)(unRead.keySet().iterator().next());
ChemParser.findUnion(fgname,unRead,fgDictionary);
}
in.close();
return;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new IOException(e.getMessage());
}
}
//## operation readLibrary(String)
public void readLibrary(String p_fileName) throws IOException, InvalidKineticsFormatException, InvalidFunctionalGroupException {
//#[ operation readLibrary(String)
try {
FileReader in = new FileReader(p_fileName);
BufferedReader data = new BufferedReader(in);
// step 1: read in kinetics format
String line = ChemParser.readMeaningfulLine(data, true);
if (line == null) throw new InvalidKineticsFormatException();
String format;
if (line.compareToIgnoreCase("Arrhenius") == 0) format = "Arrhenius";
else if (line.compareToIgnoreCase("Arrhenius_EP") == 0) format = "Arrhenius_EP";
else throw new InvalidKineticsFormatException("unknown rate constant type: " + line);
// step 2 read in content
kineticsTemplateLibrary = new KineticsTemplateLibrary();
int treeNum = getReactantTreeNumber();
int reactantNum = getReactantNumber();
int keyNum = Math.max(treeNum,reactantNum);
line = ChemParser.readMeaningfulLine(data, true);
while (line != null) {
StringTokenizer token = new StringTokenizer(line);
String ID = token.nextToken();
// read in the names of functional group defining this kinetics
LinkedHashSet fgc = new LinkedHashSet();
for (int i=0; i<keyNum; i++) {
String r = token.nextToken().trim();
Object fg = fgDictionary.get(r);
if (fg == null) {
throw new InvalidKineticsKeyException("unknown fg name: " + r);
}
else fgc.add(fg);
}
// read in the kinetics
Kinetics k;
if (format.equals("Arrhenius")) k = ChemParser.parseArrheniusKinetics(line,keyNum);
else if (format.equals("Arrhenius_EP")) k = ChemParser.parseArrheniusEPKinetics(line,keyNum);
else throw new InvalidKineticsFormatException("Invalid rate constant format: " + line);
/*
* Added by MRH on 24-Jun-2009
* Restoring feature for RMG to choose the best kinetics based on rank
* and valid temperature range. We 'get' the static Temperature variable
* temp4BestKinetics from ReactionModelGenerator and pass it to a new
* addKinetics function, that accepts the Temperature as an input
*/
Temperature firstTempEncountered = ReactionModelGenerator.getTemp4BestKinetics();
kineticsTemplateLibrary.addKinetics(fgc,k,firstTempEncountered);
line = ChemParser.readMeaningfulLine(data, true);
}
in.close();
return;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new IOException("Error reading rate library. The error message is:" + '\n' + e.getMessage());
}
//#]
}
//## operation readReactionAdjList(String)
public String readReactionAdjList(String p_fileName) throws InvalidReactionAdjListFormatException, IOException, NotInDictionaryException {
//#[ operation readReactionAdjList(String)
try {
FileReader in = new FileReader(p_fileName);
BufferedReader data = new BufferedReader(in);
// step 1: read in structure
String line = ChemParser.readMeaningfulLine(data, true);
if (line == null) throw new InvalidReactionAdjListFormatException();
StringTokenizer token = new StringTokenizer(line);
String fgName1 = token.nextToken();
int reactantNum = 1;
String fgName2 = null;
String seperator = token.nextToken();
if (seperator.equals("+")) {
fgName2 = token.nextToken();
seperator = token.nextToken();
reactantNum++;
}
if (!seperator.equals("->")) throw new InvalidReactionAdjListFormatException();
String pName1 = token.nextToken();
int productNum = 1;
// if (token.hasMoreTokens()) {
// seperator = token.nextToken();
// if (seperator.equals("+")) productNum++;
// }
/* Updated by MRH on 1-Jun-2009
ReactionTemplate.java only looked for one or two products.
A. Jalan found a rxn to place into the database with the following recipe:
R1-H + R2-OOH -> R1 + R2-O + H2O
RMG now looks for as many products as the user specifies in the recipe.
*/
while (token.hasMoreTokens()) {
seperator = token.nextToken();
if (seperator.equals("+")) productNum++;
}
// step 2 get reactant structure from dictionary to form structureTemplate
Matchable r1 = (Matchable)fgDictionary.get(fgName1);
if (r1 == null) throw new NotInDictionaryException("During reading reactionAdjList: " + fgName1 + " is not found in functional group dictionary!");
Matchable r2 = null;
if (fgName2 != null) {
r2 = (Matchable)fgDictionary.get(fgName2);
if (r2 == null) throw new NotInDictionaryException("During reading reactionAdjList: " + fgName2 + " is not found in functional group dictionary!");
}
structureTemplate = new StructureTemplate(r1,r2);
// step 3 read in direction and corresponding infor about reverse and thermo consisitence
line = ChemParser.readMeaningfulLine(data, true);
line = line.trim();
int direction = 0;
if (line.compareToIgnoreCase("forward")==0) direction = 1;
else if (line.compareToIgnoreCase("thermo_consistence")==0) direction = 0;
setDirection(direction);
String reverseRT = null;
if (direction == 1) {
// read in reverse reaction family's name
line = ChemParser.readMeaningfulLine(data, true).trim();
StringTokenizer dst = new StringTokenizer(line,":");
String sign = dst.nextToken().trim();
if (!sign.startsWith("reverse")) throw new InvalidReactionAdjListFormatException("Unknown reverse reaction family name!");
reverseRT = dst.nextToken().trim();
}
// step 4: read in actions in reaction template
reactionAdjList = new ReactionAdjList(reactantNum,productNum);
while (line != null) {
while (!line.startsWith("Action")) line = ChemParser.readMeaningfulLine(data, true);
LinkedList actions = ChemParser.readActions(data);
reactionAdjList.setActions(actions);
line = ChemParser.readMeaningfulLine(data, true);
}
in.close();
return reverseRT;
}
catch (IOException e) {
throw new IOException("Reaction AdjList: " + e.getMessage());
}
catch (InvalidActionException e) {
throw new IOException("Reaction AdjList: " + e.getMessage());
}
//#]
}
//## operation readTree(String)
public void readTree(String p_fileName) throws IOException, NotInDictionaryException {
//#[ operation readTree(String)
try {
FileReader in = new FileReader(p_fileName);
BufferedReader data = new BufferedReader(in);
LinkedHashSet treeSet = new LinkedHashSet();
HierarchyTree tree = ChemParser.readHierarchyTree(data, fgDictionary, 1);
while (tree != null) {
treeSet.add(tree);
tree = ChemParser.readHierarchyTree(data, fgDictionary, 1);
}
setReactantTree(treeSet);
in.close();
return;
}
catch (IOException e) {
throw new IOException("kinetics tree");
}
catch (NotInDictionaryException e) {
throw new NotInDictionaryException("kinetics tree reading: "+name+'\n'+ e.getMessage());
}
//#]
}
/**
Check if the present reaction template is valid. things to check:
(1) if the structure template of this reaction template is valid
(2) if the kinetics template of this reaction template is valid
(3) if all the structure templates in kinetics are the subgraph of the structure template of this reaction template
(4) if the sum set of all the structure templates in kinetics is equal to the sturcture template of this reaction template
*/
//## operation repOk()
public boolean repOk() {
//#[ operation repOk()
return true;
//#]
}
//## operation resetReactedSitesBondDissociation(LinkedList)
private void resetReactedSitesBondDissociation(LinkedList p_reactants) {
//#[ operation resetReactedSitesBondDissociation(LinkedList)
if (p_reactants.size() != 2) return;
Iterator iter = p_reactants.iterator();
while (iter.hasNext()) {
Graph g = ((ChemGraph)iter.next()).getGraph();
Node n = g.getCentralNodeAt(2);
if (n != null) {
g.clearCentralNode();
g.setCentralNode(1,n);
}
}
return;
//#]
}
//## operation setReactantTree(HashSet)
public void setReactantTree(LinkedHashSet p_treeSet) {
//#[ operation setReactantTree(HashSet)
structureTemplate.setReactantTree(p_treeSet);
//#]
}
//## operation toString()
public String toString() {
//#[ operation toString()
String s = "Reaction Template Name: " + name + '\n';
s = s + "Direction: ";
if (direction == 1) s = s+"forward" +'\n';
else if (direction == -1) s = s+"backward" +'\n';
else s = s+"unknown" +'\n';
return s;
//#]
}
public int getDirection() {
return direction;
}
public void setDirection(int p_direction) {
direction = p_direction;
}
public HashMap getFgDictionary() {
return fgDictionary;
}
public void setFgDictionary(LinkedHashMap p_fgDictionary) {
fgDictionary = p_fgDictionary;
}
public String getName() {
return name;
}
public void setName(String p_name) {
name = p_name;
}
public KineticsTemplateLibrary getKineticsTemplateLibrary() {
return kineticsTemplateLibrary;
}
public void setKineticsTemplateLibrary(KineticsTemplateLibrary p_KineticsTemplateLibrary) {
kineticsTemplateLibrary = p_KineticsTemplateLibrary;
}
public ReactionAdjList getReactionAdjList() {
return reactionAdjList;
}
public void setReactionAdjList(ReactionAdjList p_ReactionAdjList) {
reactionAdjList = p_ReactionAdjList;
}
public ReactionTemplate getReverseReactionTemplate() {
return reverseReactionTemplate;
}
public StructureTemplate getStructureTemplate() {
return structureTemplate;
}
public void setStructureTemplate(StructureTemplate p_StructureTemplate) {
structureTemplate = p_StructureTemplate;
}
public LinkedHashSet getPrimaryKinLibrary(){
return PrimaryKineticLibrary.getReactionSet();
}
public boolean doesPrimaryKineticLibraryExist() {
if (PrimaryKineticLibrary.size() != 0) return true;
else return false;
}
}
/*********************************************************************
File Path : RMG\RMG\jing\rxn\ReactionTemplate.java
*********************************************************************/
| mit |
venanciolm/afirma-ui-miniapplet_x_x | afirma_ui_miniapplet/src/main/java/com/lowagie/text/pdf/PdfObject.java | 11448 | /*
* $Id: PdfObject.java 3912 2009-04-26 08:38:15Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 Bruno Lowagie
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* 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 Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
package com.lowagie.text.pdf;
import java.io.IOException;
import java.io.OutputStream;
/**
* <CODE>PdfObject</CODE> is the abstract superclass of all PDF objects.
* <P>
* PDF supports seven basic types of objects: Booleans, numbers, strings, names,
* arrays, dictionaries and streams. In addition, PDF provides a null object.
* Objects may be labeled so that they can be referred to by other objects.<BR>
* All these basic PDF objects are described in the 'Portable Document Format
* Reference Manual version 1.3' Chapter 4 (pages 37-54).
*
* @see PdfNull
* @see PdfBoolean
* @see PdfNumber
* @see PdfString
* @see PdfName
* @see PdfArray
* @see PdfDictionary
* @see PdfStream
* @see PdfIndirectReference
*/
public abstract class PdfObject {
// CONSTANTS
/** A possible type of <CODE>PdfObject</CODE> */
static final int BOOLEAN = 1;
/** A possible type of <CODE>PdfObject</CODE> */
static final int NUMBER = 2;
/** A possible type of <CODE>PdfObject</CODE> */
static final int STRING = 3;
/** A possible type of <CODE>PdfObject</CODE> */
static final int NAME = 4;
/** A possible type of <CODE>PdfObject</CODE> */
public static final int ARRAY = 5;
/** A possible type of <CODE>PdfObject</CODE> */
static final int DICTIONARY = 6;
/** A possible type of <CODE>PdfObject</CODE> */
public static final int STREAM = 7;
/** A possible type of <CODE>PdfObject</CODE> */
static final int NULL = 8;
/** A possible type of <CODE>PdfObject</CODE> */
public static final int INDIRECT = 10;
/** An empty string used for the <CODE>PdfNull</CODE>-object and for an empty <CODE>PdfString</CODE>-object. */
static final String NOTHING = "";
/**
* This is the default encoding to be used for converting Strings into
* bytes and vice versa. The default encoding is PdfDocEncoding.
*/
static final String TEXT_PDFDOCENCODING = "PDF";
/** This is the encoding to be used to output text in Unicode. */
public static final String TEXT_UNICODE = "UnicodeBig";
// CLASS VARIABLES
/** The content of this <CODE>PdfObject</CODE> */
protected byte[] bytes;
/** The type of this <CODE>PdfObject</CODE> */
protected int type;
/** Holds the indirect reference. */
private PRIndirectReference indRef;
// CONSTRUCTORS
/**
* Constructs a <CODE>PdfObject</CODE> of a certain <VAR>type</VAR>
* without any <VAR>content</VAR>.
*
* @param type type of the new <CODE>PdfObject</CODE>
*/
protected PdfObject(final int type) {
this.type = type;
}
/**
* Constructs a <CODE>PdfObject</CODE> of a certain <VAR>type</VAR>
* with a certain <VAR>content</VAR>.
*
* @param type type of the new <CODE>PdfObject</CODE>
* @param content content of the new <CODE>PdfObject</CODE> as a
* <CODE>String</CODE>.
*/
protected PdfObject(final int type, final String content) {
this.type = type;
this.bytes = PdfEncodings.convertToBytes(content, null);
}
/**
* Constructs a <CODE>PdfObject</CODE> of a certain <VAR>type</VAR>
* with a certain <VAR>content</VAR>.
*
* @param type type of the new <CODE>PdfObject</CODE>
* @param bytes content of the new <CODE>PdfObject</CODE> as an array of
* <CODE>byte</CODE>.
*/
protected PdfObject(final int type, final byte[] bytes) {
this.bytes = bytes;
this.type = type;
}
// methods dealing with the content of this object
/**
* Writes the PDF representation of this <CODE>PdfObject</CODE> as an
* array of <CODE>byte</CODE>s to the writer.
*
* @param writer for backwards compatibility
* @param os The <CODE>OutputStream</CODE> to write the bytes to.
* @throws IOException
*/
public void toPdf(final PdfWriter writer, final OutputStream os) throws IOException {
if (this.bytes != null) {
os.write(this.bytes);
}
}
/**
* Returns the <CODE>String</CODE>-representation of this
* <CODE>PdfObject</CODE>.
*
* @return a <CODE>String</CODE>
*/
@Override
public String toString() {
if (this.bytes == null) {
return super.toString();
}
return PdfEncodings.convertToString(this.bytes, null);
}
/**
* Gets the presentation of this object in a byte array
*
* @return a byte array
*/
public byte[] getBytes() {
return this.bytes;
}
/**
* Whether this object can be contained in an object stream.
*
* PdfObjects of type STREAM OR INDIRECT can not be contained in an
* object stream.
*
* @return <CODE>true</CODE> if this object can be in an object stream.
* Otherwise <CODE>false</CODE>
*/
boolean canBeInObjStm() {
switch (this.type) {
case NULL:
case BOOLEAN:
case NUMBER:
case STRING:
case NAME:
case ARRAY:
case DICTIONARY:
return true;
case STREAM:
case INDIRECT:
default:
return false;
}
}
/**
* Changes the content of this <CODE>PdfObject</CODE>.
*
* @param content the new content of this <CODE>PdfObject</CODE>
*/
protected void setContent(final String content) {
this.bytes = PdfEncodings.convertToBytes(content, null);
}
// methods dealing with the type of this object
/**
* Returns the type of this <CODE>PdfObject</CODE>.
*
* May be either of:
* - <VAR>NULL</VAR>: A <CODE>PdfNull</CODE>
* - <VAR>BOOLEAN</VAR>: A <CODE>PdfBoolean</CODE>
* - <VAR>NUMBER</VAR>: A <CODE>PdfNumber</CODE>
* - <VAR>STRING</VAR>: A <CODE>PdfString</CODE>
* - <VAR>NAME</VAR>: A <CODE>PdfName</CODE>
* - <VAR>ARRAY</VAR>: A <CODE>PdfArray</CODE>
* - <VAR>DICTIONARY</VAR>: A <CODE>PdfDictionary</CODE>
* - <VAR>STREAM</VAR>: A <CODE>PdfStream</CODE>
* - <VAR>INDIRECT</VAR>: ><CODE>PdfIndirectObject</CODE>
*
* @return The type
*/
public int type() {
return this.type;
}
/**
* Checks if this <CODE>PdfObject</CODE> is of the type
* <CODE>PdfNull</CODE>.
*
* @return <CODE>true</CODE> or <CODE>false</CODE>
*/
public boolean isNull() {
return this.type == NULL;
}
/**
* Checks if this <CODE>PdfObject</CODE> is of the type
* <CODE>PdfBoolean</CODE>.
*
* @return <CODE>true</CODE> or <CODE>false</CODE>
*/
public boolean isBoolean() {
return this.type == BOOLEAN;
}
/**
* Checks if this <CODE>PdfObject</CODE> is of the type
* <CODE>PdfNumber</CODE>.
*
* @return <CODE>true</CODE> or <CODE>false</CODE>
*/
public boolean isNumber() {
return this.type == NUMBER;
}
/**
* Checks if this <CODE>PdfObject</CODE> is of the type
* <CODE>PdfString</CODE>.
*
* @return <CODE>true</CODE> or <CODE>false</CODE>
*/
public boolean isString() {
return this.type == STRING;
}
/**
* Checks if this <CODE>PdfObject</CODE> is of the type
* <CODE>PdfName</CODE>.
*
* @return <CODE>true</CODE> or <CODE>false</CODE>
*/
public boolean isName() {
return this.type == NAME;
}
/**
* Checks if this <CODE>PdfObject</CODE> is of the type
* <CODE>PdfArray</CODE>.
*
* @return <CODE>true</CODE> or <CODE>false</CODE>
*/
public boolean isArray() {
return this.type == ARRAY;
}
/**
* Checks if this <CODE>PdfObject</CODE> is of the type
* <CODE>PdfDictionary</CODE>.
*
* @return <CODE>true</CODE> or <CODE>false</CODE>
*/
public boolean isDictionary() {
return this.type == DICTIONARY;
}
/**
* Checks if this <CODE>PdfObject</CODE> is of the type
* <CODE>PdfStream</CODE>.
*
* @return <CODE>true</CODE> or <CODE>false</CODE>
*/
public boolean isStream() {
return this.type == STREAM;
}
/**
* Checks if this <CODE>PdfObject</CODE> is of the type
* <CODE>PdfIndirectObject</CODE>.
*
* @return <CODE>true</CODE> if this is an indirect object,
* otherwise <CODE>false</CODE>
*/
public boolean isIndirect() {
return this.type == INDIRECT;
}
/**
* Get the indirect reference
*
* @return A <CODE>PdfIndirectReference</CODE>
*/
public PRIndirectReference getIndRef() {
return this.indRef;
}
/**
* Set the indirect reference
*
* @param indRef New value as a <CODE>PdfIndirectReference</CODE>
*/
public void setIndRef(final PRIndirectReference indRef) {
this.indRef = indRef;
}
}
| mit |
GaretJax/pop-analysis-suite | pas/conf/suite_template/contrib/popc_1.3.1beta_xdr/lib/combox_client.cc | 2470 | #include <timer.h>
#include <stdio.h>
#include <signal.h>
#define LOOP 10
#define MSGSIZE 7111
int main(int argc, char **argv)
{
if (argc<2)
{
printf("Usage: combox_client <address> [encoding]\n");
return 1;
}
signal(SIGPIPE, SIG_IGN);
paroc_combox_factory *fact=paroc_combox_factory::GetInstance();
char prot[32];
char *tmp;
if ((tmp=strstr(argv[1],"://"))==NULL)
{
strcpy(prot,"socket");
}
else
{
*tmp=0;
strcpy(prot,argv[1]);
*tmp=':';
}
paroc_combox *client=fact->Create(prot);
if (client==NULL)
{
printf("Error: %s: unknown protocol\n", prot);
return 1;
}
paroc_buffer_factory *bf=client->GetBufferFactory();
paroc_buffer *buffer=bf->CreateBuffer();
paroc_string name;
if (argc>2)
{
name=argv[2];
bf=paroc_buffer_factory_finder::GetInstance()->FindFactory(name);
if (bf==NULL)
{
printf("Error: can not find encoding %s\n", argv[2]);
return 1;
}
}
else bf->GetBufferName(name);
client->Create(0,false);
if (!client->Connect(argv[1]))
{
client->Destroy();
printf("Error: can not connect to %s\n", argv[1]);
return 1;
}
printf("Connected!\n");
//Negotiate protocol...
printf("Setting encoding to %s\n", (const char *)name);
paroc_message_header h1(0,0,0,"Encoding");
int status=-1;
buffer->SetHeader(h1);
buffer->Pack(&status,1);
buffer->Pack(&name,1);
if (!buffer->Send(*client))
{
printf("Error: send buffer\n");
client->Destroy();
return 1;
}
buffer->Reset();
if (!buffer->Recv(*client))
{
printf("Error: receive buffer\n");
client->Destroy();
return 1;
}
buffer->UnPack(&status,1);
if (status==-1)
{
printf("Use encoding: %s\n",(const char *)name);
buffer=bf->CreateBuffer();
buffer->SetHeader(h1);
}
else
{
printf("Encoding %s not supported\n",(const char *)name);
}
status=1;
char buf[MSGSIZE];
int count=0;
int n;
Timer timer;
timer.Start();
for (int i=0;i<LOOP;i++)
{
buffer->Reset();
buffer->Pack(&status,1);
buffer->Pack(buf, MSGSIZE);
if (!buffer->Send(*client))
{
printf("Error: can not send the message\n");
client->Destroy();
return 1;
}
buffer->Reset();
if (!buffer->Recv(*client))
{
printf("Error: can not send the message\n");
client->Destroy();
return 1;
}
}
timer.Stop();
printf("Send %d message of %d bytes each to %s in %g seconds (%g MB/s)\n", LOOP, MSGSIZE,argv[1],timer.Elapsed(),2.0*LOOP*MSGSIZE/(timer.Elapsed()*1024.0*1024.0));
client->Destroy();
return 0;
}
| mit |
lucasbrendel/Badger | Badger/ViewModels/IBadgerDashboardViewModel.cs | 204 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Badger.ViewModels
{
interface IBadgerDashboardViewModel
{
}
}
| mit |
jamro/jsbattle | packages/jsbattle-server/test/unit/services/ScriptStore.spec.js | 6699 | "use strict";
const serviceConfig = require('../../../app/lib/serviceConfig.js');
const { ServiceBroker } = require("moleculer");
const { ValidationError } = require("moleculer").Errors;
const { MoleculerClientError } = require("moleculer").Errors;
const crypto = require("crypto");
const path = require('path');
const createTestToken = (user) => ({
id: (user ? user.id : '') || "123456",
username: (user ? user.username : '') || "amy",
role: (user ? user.role : '') || "user",
})
describe("Test 'ScriptStore' service", () => {
describe("unregistered user", () => {
let broker;
beforeEach(async () => {
serviceConfig.extend({ auth: { admins: [{provider: 'google', username: 'monica83' }] } });
broker = new ServiceBroker(require('../../utils/getLoggerSettings.js')(path.resolve(__dirname, '..', '..'), __filename, expect.getState()));
broker.createService({
name: 'userStore',
actions: {
get: () => ({
username: 'john',
registered: false
})
}
})
const schemaBuilder = require(__dirname + "../../../../app/services/scriptStore/index.js");
broker.createService(schemaBuilder(serviceConfig.data));
await broker.start()
});
afterEach(() => broker.stop());
it('should not create user script', async () => {
const user = {
username: 'john',
role: 'user',
id: '92864'
}
expect(
broker.call('scriptStore.createUserScript', {scriptName: 'alha345'}, {meta: {user: createTestToken(user)}})
).rejects.toThrow(/must finish registration process/)
});
});
describe("registered user", () => {
let broker;
beforeEach(async () => {
serviceConfig.extend({ auth: { admins: [{provider: 'google', username: 'monica83' }] } });
broker = new ServiceBroker({ logger: false });
broker.createService({
name: 'userStore',
actions: {
get: () => ({
username: 'john',
registered: true
})
}
})
const schemaBuilder = require(__dirname + "../../../../app/services/scriptStore/index.js");
broker.createService(schemaBuilder(serviceConfig.data));
await broker.start();
});
afterEach(() => broker.stop());
it('should create user script', async () => {
const user = {
username: 'john',
role: 'user',
id: '92864'
}
let result = await broker.call('scriptStore.createUserScript', {scriptName: 'beta8978'}, {meta: {user: createTestToken(user)}});
expect(result).toHaveProperty('ownerId', user.id);
expect(result).toHaveProperty('ownerName', user.username);
expect(result).toHaveProperty('namespace', 'user');
expect(result).toHaveProperty('id');
expect(result).toHaveProperty('code');
expect(result).toHaveProperty('scriptName');
expect(result).toHaveProperty('createdAt');
expect(result).toHaveProperty('modifiedAt');
});
it('should create hash of code', async () => {
const code = "// some code 34523451";
const codeHash = crypto.createHash('md5').update(code).digest("hex");
const user = {
username: 'john',
role: 'user',
id: '92864',
}
let result = await broker.call('scriptStore.createUserScript', {scriptName: 'beta8978', code: code}, {meta: {user: createTestToken(user)}});
expect(result).toHaveProperty('code', code);
expect(result).toHaveProperty('hash', codeHash);
result = await broker.call('scriptStore.getUserScript', {id: result.id}, {meta: {user: createTestToken(user)}});
expect(result).toHaveProperty('code', code);
expect(result).toHaveProperty('hash', codeHash);
});
it('should list user scripts', async () => {
const user = {
username: 'john',
role: 'user',
id: '92864'
}
await broker.call('scriptStore.createUserScript', {scriptName: 'phi3254'}, {meta: {user: createTestToken(user)}});
await broker.call('scriptStore.createUserScript', {scriptName: 'psi2747'}, {meta: {user: createTestToken(user)}});
await broker.call('scriptStore.createUserScript', {scriptName: 'psi1234'}, {meta: {user: createTestToken(user)}});
let result = await broker.call('scriptStore.listUserScripts', {}, {meta: {user: createTestToken(user)}});
expect(result).toHaveLength(3);
});
it('should update user scripts', async () => {
const newCode = '// new hello world8934572345';
const codeHash = crypto.createHash('md5').update(newCode).digest("hex");
const user = {
username: 'john',
role: 'user',
id: '92864'
}
let script = await broker.call(
'scriptStore.createUserScript',
{
code: '// hello world1235',
scriptName: 'helloScript'
},
{meta: {user: createTestToken(user)}}
);
let updatedScript = await broker.call('scriptStore.updateUserScript', {id: script.id, code: newCode}, {meta: {user: createTestToken(user)}});
expect(updatedScript).toHaveProperty('id', script.id);
expect(updatedScript).toHaveProperty('scriptName', 'helloScript');
expect(updatedScript).toHaveProperty('ownerId', script.ownerId);
expect(updatedScript).toHaveProperty('ownerName', script.ownerName);
expect(updatedScript).toHaveProperty('code', newCode);
expect(updatedScript).toHaveProperty('createdAt', script.createdAt);
expect(updatedScript).toHaveProperty('modifiedAt');
expect(updatedScript).toHaveProperty('hash', codeHash);
});
it('should get user script', async () => {
const user = {
username: 'john',
role: 'user',
id: '92864'
}
let result = await broker.call('scriptStore.createUserScript', {scriptName: 'pi0983'}, {meta: {user: createTestToken(user)}});
result = await broker.call('scriptStore.getUserScript', {id: result.id}, {meta: {user: createTestToken(user)}});
expect(result).toHaveProperty('ownerId', user.id);
expect(result).toHaveProperty('ownerName', user.username);
expect(result).toHaveProperty('namespace', 'user');
expect(result).toHaveProperty('id');
expect(result).toHaveProperty('code');
expect(result).toHaveProperty('scriptName');
expect(result).toHaveProperty('createdAt');
expect(result).toHaveProperty('modifiedAt');
});
it('should delete user script', async () => {
const user = {
username: 'john',
role: 'user',
id: '92864'
}
await broker.call('scriptStore.createUserScript', {scriptName: 'gamma665'}, {meta: {user: createTestToken(user)}});
let result = await broker.call('scriptStore.createUserScript', {scriptName: 'gamma563'}, {meta: {user: createTestToken(user)}});
await broker.call('scriptStore.deleteUserScript', {id: result.id}, {meta: {user: createTestToken(user)}});
result = await broker.call('scriptStore.listUserScripts', {}, {meta: {user: createTestToken(user)}});
expect(result).toHaveLength(1);
});
});
});
| mit |
exercism/xjavascript | exercises/linked-list/linked-list.spec.js | 1821 | var LinkedList = require('./linked-list');
describe('LinkedList', function () {
it('push/pop', function () {
var list = new LinkedList();
list.push(10);
list.push(20);
expect(list.pop()).toBe(20);
expect(list.pop()).toBe(10);
});
xit('push/shift', function () {
var list = new LinkedList();
list.push(10);
list.push(20);
expect(list.shift()).toBe(10);
expect(list.shift()).toBe(20);
});
xit('unshift/shift', function () {
var list = new LinkedList();
list.unshift(10);
list.unshift(20);
expect(list.shift()).toBe(20);
expect(list.shift()).toBe(10);
});
xit('unshift/pop', function () {
var list = new LinkedList();
list.unshift(10);
list.unshift(20);
expect(list.pop()).toBe(10);
expect(list.pop()).toBe(20);
});
xit('example', function () {
var list = new LinkedList();
list.push(10);
list.push(20);
expect(list.pop()).toBe(20);
list.push(30);
expect(list.shift()).toBe(10);
list.unshift(40);
list.push(50);
expect(list.shift()).toBe(40);
expect(list.pop()).toBe(50);
expect(list.shift()).toBe(30);
});
xit('can count its elements', function () {
var list = new LinkedList();
expect(list.count()).toBe(0);
list.push(10);
expect(list.count()).toBe(1);
list.push(20);
expect(list.count()).toBe(2);
});
xit('deletes the last element from the list', function () {
var list = new LinkedList();
list.push(10);
list.push(20);
list.push(30);
list.delete(20);
expect(list.count()).toBe(2);
expect(list.pop()).toBe(30);
expect(list.shift()).toBe(10);
});
xit('deletes the only element', function () {
var list = new LinkedList();
list.push(10);
list.delete(10);
expect(list.count()).toBe(0);
});
});
| mit |
mailru/dbr | condition_test.go | 1898 | package dbr
import (
"testing"
"github.com/mailru/dbr/dialect"
"github.com/stretchr/testify/assert"
)
func TestCondition(t *testing.T) {
for _, test := range []struct {
cond Builder
query string
value []interface{}
}{
{
cond: Eq("col", 1),
query: "`col` = ?",
value: []interface{}{1},
},
{
cond: Eq("col", nil),
query: "`col` IS NULL",
value: nil,
},
{
cond: Eq("col", []int{}),
query: "0",
value: nil,
},
{
cond: Eq("col", map[int]int{}),
query: "0",
value: nil,
},
{
cond: Eq("col", []int{1}),
query: "`col` IN ?",
value: []interface{}{[]int{1}},
},
{
cond: Eq("col", map[int]int{1: 2}),
query: "`col` IN ?",
value: []interface{}{map[int]int{1: 2}},
},
{
cond: Neq("col", 1),
query: "`col` != ?",
value: []interface{}{1},
},
{
cond: Neq("col", nil),
query: "`col` IS NOT NULL",
value: nil,
},
{
cond: Neq("col", []int{}),
query: "1",
value: nil,
},
{
cond: Neq("col", []int{1}),
query: "`col` NOT IN ?",
value: []interface{}{[]int{1}},
},
{
cond: Neq("col", map[int]int{1: 2}),
query: "`col` NOT IN ?",
value: []interface{}{map[int]int{1: 2}},
},
{
cond: Gt("col", 1),
query: "`col` > ?",
value: []interface{}{1},
},
{
cond: Gte("col", 1),
query: "`col` >= ?",
value: []interface{}{1},
},
{
cond: Lt("col", 1),
query: "`col` < ?",
value: []interface{}{1},
},
{
cond: Lte("col", 1),
query: "`col` <= ?",
value: []interface{}{1},
},
{
cond: And(Lt("a", 1), Or(Gt("b", 2), Neq("c", 3))),
query: "(`a` < ?) AND ((`b` > ?) OR (`c` != ?))",
value: []interface{}{1, 2, 3},
},
} {
buf := NewBuffer()
err := test.cond.Build(dialect.MySQL, buf)
assert.NoError(t, err)
assert.Equal(t, test.query, buf.String())
assert.Equal(t, test.value, buf.Value())
}
}
| mit |
JeroenNoten/Laravel-AdminLTE | tests/Helpers/LayoutHelperTest.php | 12661 | <?php
use JeroenNoten\LaravelAdminLte\Helpers\LayoutHelper;
class LayoutHelperTest extends TestCase
{
public function testMakeBodyData()
{
// Test without config.
$data = LayoutHelper::makeBodyData();
$this->assertEquals('', $data);
// Test with default config values.
config([
'adminlte.sidebar_scrollbar_theme' => 'os-theme-light',
'adminlte.sidebar_scrollbar_auto_hide' => 'l',
]);
$data = LayoutHelper::makeBodyData();
$this->assertEquals('', $data);
// Test with non-default 'sidebar_scrollbar_theme' config value.
config([
'adminlte.sidebar_scrollbar_theme' => 'os-theme-dark',
'adminlte.sidebar_scrollbar_auto_hide' => 'l',
]);
$data = LayoutHelper::makeBodyData();
$this->assertStringContainsString('data-scrollbar-theme=os-theme-dark', $data);
// Test with non-default 'sidebar_scrollbar_auto_hide' config value.
config([
'adminlte.sidebar_scrollbar_theme' => 'os-theme-light',
'adminlte.sidebar_scrollbar_auto_hide' => 'm',
]);
$data = LayoutHelper::makeBodyData();
$this->assertStringContainsString('data-scrollbar-auto-hide=m', $data);
// Test with non-default config values.
config([
'adminlte.sidebar_scrollbar_theme' => 'os-theme-dark',
'adminlte.sidebar_scrollbar_auto_hide' => 's',
]);
$data = LayoutHelper::makeBodyData();
$this->assertStringContainsString('data-scrollbar-theme=os-theme-dark', $data);
$this->assertStringContainsString('data-scrollbar-auto-hide=s', $data);
}
public function testMakeBodyClassesWithouConfig()
{
// Test without config.
$data = LayoutHelper::makeBodyClasses();
$this->assertEquals('sidebar-mini', $data);
}
public function testMakeBodyClassesWithSidebarMiniConfig()
{
// Test config 'sidebar_mini' => null.
config(['adminlte.sidebar_mini' => null]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('sidebar-mini', $data);
$this->assertStringNotContainsString('sidebar-mini-md', $data);
$this->assertStringNotContainsString('sidebar-mini-xs', $data);
// Test config 'sidebar_mini' => 'lg'.
config(['adminlte.sidebar_mini' => 'lg']);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('sidebar-mini', $data);
$this->assertStringNotContainsString('sidebar-mini-md', $data);
$this->assertStringNotContainsString('sidebar-mini-xs', $data);
// Test config 'sidebar_mini' => 'md'.
config(['adminlte.sidebar_mini' => 'md']);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('sidebar-mini-md', $data);
$this->assertStringNotContainsString('sidebar-mini-xs', $data);
$this->assertNotRegExp('/sidebar-mini[^-]/', $data);
// Test config 'sidebar_mini' => 'xs'.
config(['adminlte.sidebar_mini' => 'xs']);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('sidebar-mini-xs', $data);
$this->assertStringNotContainsString('sidebar-mini-md', $data);
$this->assertNotRegExp('/sidebar-mini[^-]/', $data);
}
public function testMakeBodyClassesWithSidebarCollapseConfig()
{
// Test config 'sidebar_collapse' => null.
config(['adminlte.sidebar_collapse' => null]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('sidebar-collapse', $data);
// Test config 'sidebar_collapse' => false.
config(['adminlte.sidebar_collapse' => false]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('sidebar-collapse', $data);
// Test config 'sidebar_collapse' => true.
config(['adminlte.sidebar_collapse' => true]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('sidebar-collapse', $data);
}
public function testMakeBodyClassesWithLayoutTopnavConfig()
{
// Test config 'layout_topnav' => null.
config(['adminlte.layout_topnav' => null]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('layout-top-nav', $data);
// Test config 'layout_topnav' => false.
config(['adminlte.layout_topnav' => false]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('layout-top-nav', $data);
// Test config 'layout_topnav' => true.
config(['adminlte.layout_topnav' => true]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('layout-top-nav', $data);
}
public function testMakeBodyClassesWithLayoutBoxedConfig()
{
// Test config 'layout_boxed' => null.
config(['adminlte.layout_boxed' => null]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('layout-boxed', $data);
// Test config 'layout_boxed' => false.
config(['adminlte.layout_boxed' => false]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('layout-boxed', $data);
// Test config 'layout_boxed' => true.
config(['adminlte.layout_boxed' => true]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('layout-boxed', $data);
}
public function testMakeBodyClassesWithRightSidebarConfig()
{
// Test config 'right_sidebar_push' => false.
config(['adminlte.right_sidebar_push' => false]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('control-sidebar-push', $data);
// Test config 'right_sidebar_push' => true, 'right_sidebar' => true.
config([
'adminlte.right_sidebar' => true,
'adminlte.right_sidebar_push' => true,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('control-sidebar-push', $data);
// Test config 'right_sidebar_push' => true, 'right_sidebar' => false.
config([
'adminlte.right_sidebar' => false,
'adminlte.right_sidebar_push' => true,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('control-sidebar-push', $data);
}
public function testMakeBodyClassesWithLayoutFixedSidebarConfig()
{
// Test config 'layout_fixed_sidebar' => null.
config(['adminlte.layout_fixed_sidebar' => null]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('layout-fixed', $data);
// Test config 'layout_fixed_sidebar' => true, 'layout_topnav' => true.
config([
'adminlte.layout_fixed_sidebar' => true,
'adminlte.layout_topnav' => true,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('layout-fixed', $data);
// Test config 'layout_fixed_sidebar' => true, 'layout_topnav' => null.
config([
'adminlte.layout_fixed_sidebar' => true,
'adminlte.layout_topnav' => null,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('layout-fixed', $data);
}
public function testMakeBodyClassesWithLayoutFixedNavbarConfig()
{
// Test config 'layout_fixed_navbar' => null.
config(['adminlte.layout_fixed_navbar' => null]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('layout-navbar-fixed', $data);
// Test config 'layout_fixed_navbar' => true, 'layout_boxed' => true.
config([
'adminlte.layout_fixed_navbar' => true,
'adminlte.layout_boxed' => true,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('layout-navbar-fixed', $data);
// Test config 'layout_fixed_navbar' => true, 'layout_boxed' => null.
config([
'adminlte.layout_fixed_navbar' => true,
'adminlte.layout_boxed' => null,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('layout-navbar-fixed', $data);
// Test config 'layout_fixed_navbar' => ['xs' => true, 'lg' => false],
// 'layout_boxed' => null.
config([
'adminlte.layout_fixed_navbar' => ['xs' => true, 'lg' => false],
'adminlte.layout_boxed' => null,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('layout-navbar-fixed', $data);
$this->assertStringContainsString('layout-lg-navbar-not-fixed', $data);
// Test config 'layout_fixed_navbar' => ['xs' => true, 'foo' => true],
// 'layout_boxed' => null.
config([
'adminlte.layout_fixed_navbar' => ['xs' => true, 'foo' => true],
'adminlte.layout_boxed' => null,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('layout-navbar-fixed', $data);
$this->assertStringNotContainsString('layout-foo-navbar-fixed', $data);
}
public function testMakeBodyClassesWithLayoutFixedFooterConfig()
{
// Test config 'layout_fixed_footer' => null.
config(['adminlte.layout_fixed_footer' => null]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('layout-footer-fixed', $data);
// Test config 'layout_fixed_footer' => true, 'layout_boxed' => true.
config([
'adminlte.layout_fixed_footer' => true,
'adminlte.layout_boxed' => true,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('layout-footer-fixed', $data);
// Test config 'layout_fixed_footer' => true, 'layout_boxed' => null.
config([
'adminlte.layout_fixed_footer' => true,
'adminlte.layout_boxed' => null,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('layout-footer-fixed', $data);
// Test config 'layout_fixed_footer' => ['md' => true, 'lg' => false],
// 'layout_boxed' => null.
config([
'adminlte.layout_fixed_footer' => ['md' => true, 'lg' => false],
'adminlte.layout_boxed' => null,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('layout-md-footer-fixed', $data);
$this->assertStringContainsString('layout-lg-footer-not-fixed', $data);
// Test config 'layout_fixed_footer' => ['md' => true, 'foo' => false],
// 'layout_boxed' => null.
config([
'adminlte.layout_fixed_footer' => ['md' => true, 'foo' => false],
'adminlte.layout_boxed' => null,
]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('layout-md-footer-fixed', $data);
$this->assertStringNotContainsString('layout-foo-footer-not-fixed', $data);
}
public function testMakeBodyClassesWithClassesBodyConfig()
{
// Test config 'classes_body' => custom-body-class.
config(['adminlte.classes_body' => 'custom-body-class']);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('custom-body-class', $data);
// Test config 'classes_body' => 'custom-body-class-1 custom-body-class-2'.
config(['adminlte.classes_body' => 'custom-body-class-1 custom-body-class-2']);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('custom-body-class-1', $data);
$this->assertStringContainsString('custom-body-class-2', $data);
}
public function testMakeBodyClassesWithDarkModeConfig()
{
// Test config 'layout_dark_mode' => null.
config(['adminlte.layout_dark_mode' => null]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringNotContainsString('dark-mode', $data);
// Test config 'layout_dark_mode' => true.
config(['adminlte.layout_dark_mode' => true]);
$data = LayoutHelper::makeBodyClasses();
$this->assertStringContainsString('dark-mode', $data);
}
}
| mit |
dleute/symfony-training | src/Train/MainBundle/Controller/DefaultController.php | 1510 | <?php
namespace Train\MainBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Train\MainBundle\Entity\Product;
class DefaultController extends Controller
{
/**
* @Route("/{name}", name = "hamepage", defaults = { "name" = "sniff" })
*/
public function indexAction($name = "snarf",$page = "myPage")
{
$repository = $this->getDoctrine()->getRepository('MainBundle:Product');
$products = $repository->findAll();
if (!count($products)) {
$product = new Product();
$product->setName('A Foo Bar');
$product->setPrice('19.99');
$product->setDescription('Lorem ipsum dolor');
$em = $this->getDoctrine()->getEntityManager();
$em->persist($product);
$em->flush();
}
$response = $this->render("MainBundle:Default:index.html.twig", array('name' => $name, 'products' => $products));
return $response;
// return array('name' => $name);
}
/**
* @Route("/showproduct/{id}", name = "showproduct")
* @Template()
*/
public function showAction($id)
{
$repository = $this->getDoctrine()->getRepository('MainBundle:Product');
$product = $repository->find($id);
return array('product' => $product);
}
}
| mit |
darindragomirow/DevJobs | DevJobs.Models/Contracts/IDeletable.cs | 283 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DevJobs.Models.Contracts
{
public interface IDeletable
{
bool IsDeleted { get; set; }
DateTime? DeletedOn { get; set; }
}
}
| mit |
Galavantier/doxycotin | src/JSDoxygen.js | 32333 | // Helpful for debug output.
var tablevel = 0;
function tabOutput(output){
var tabs = "";
for (var i = 0; i < tablevel; i++) {
tabs += " ";
};
console.log(tabs + output);
}
/*--------------------------------------------Main------------------------------------------*/
//More intuitive command line params
var cmd = require('commander');
//File System
var fs = require('fs');
//Esprima
var esprima = require('esprima');
// Make output pretty for debugging
var prettyjson = require('prettyjson');
//Facilitates the visitor pattern by creating wrapper objects around the Esprima ast nodes.
var vs = require('./visitorPattern.js');
cmd.version('0.0.1')
.option('-f, --file <file>', 'specify the file to parse (Required)')
.parse(process.argv);
// Command Line error checking.
if(typeof cmd.file == 'undefined' ) {
cmd.help();
}
// Read the file.
var code = fs.readFileSync(cmd.file);
// Parse the file into an Abstract Syntax Tree. Include file location data and comments.
var ast = esprima.parse(code, { loc : true, comment : true } );
var astWrapper = vs.visitorNodeWrapperFactory(ast);
// Phase 1. Find all the contexts.
var globalContext = { type: "globalContext", symbolTable : {}, contexts : [] };
var attrCollector = vs.visitorFactory(
{
attrContext : [],
MemberExpression : function(nodeWrapper) {
var object = nodeWrapper.object.visit(this);
var property = nodeWrapper.property.visit(this);
if(object == '$attrs' || object == 'attrs') {
var unique = true;
this.attrContext.forEach(function(curAttr){
if(property == curAttr) {
unique = false;
}
});
if(unique) {
this.attrContext.push(property);
}
}
},
Literal : function(nodeWrapper) {
return nodeWrapper.node.value;
},
Identifier : function(nodeWrapper) {
return nodeWrapper.node.name;
}
});
var contextVisitor = vs.visitorFactory({
curContext : globalContext,
curModule : null,
CallExpression : function(nodeWrapper) {
//find out what is getting called.
var context = nodeWrapper.callee.visit(this);
if(this.curContext.type == 'functionBodyContext') {
var self = this;
nodeWrapper.arguments.nodes.forEach(function(curArg){
curArg.visit(self);
});
return context;
}
if(typeof context.type != 'undefined') {
if(context.type.search('Context') != -1) {
var myContext = this.curContext;
this.curContext = context;
if(context.type.search('angular') != -1) {
// The first argument of any angular context is the name of the context.
context.name = nodeWrapper.arguments.nodes[0].visit(this);
switch(context.type) {
case 'angularModuleContext' :
// The second argument of an angular module is it's requirements.
context.requirements = nodeWrapper.arguments.nodes[1].visit(this);
this.curModule = context;
break;
case 'angularServiceContext' :
case 'angularFactoryContext' :
var factoryIntrfce = nodeWrapper.arguments.nodes[1].visit(this);
if( nodeWrapper.arguments.nodes[1].node.type == 'ArrayExpression' ) {
context.interfce = factoryIntrfce.pop();
context.requirements = factoryIntrfce;
} else {
context.interfce = factoryIntrfce;
}
break;
case 'angularDirectiveContext' :
var directiveArgs = nodeWrapper.arguments.nodes[1].visit(this);
if( nodeWrapper.arguments.nodes[1].node.type == 'ArrayExpression' ) {
context.params = directiveArgs.pop();
context.requirements = directiveArgs;
} else {
context.params = directiveArgs;
}
break;
case 'angularControllerContext' :
var controllerArgs = nodeWrapper.arguments.nodes[1].visit(this);
if( nodeWrapper.arguments.nodes[1].node.type == 'ArrayExpression' ) {
context.interfce = controllerArgs.pop();
context.requirements = controllerArgs;
} else {
context.interfce = controllerArgs;
}
break;
case 'angularAnimationContext' :
var animationArgs = nodeWrapper.arguments.nodes[1].visit(this);
if( nodeWrapper.arguments.nodes[1].node.type == 'ArrayExpression' ) {
animationArgs.pop();
context.requirements = animationArgs;
} else {
context.requirements = animationArgs;
}
break;
default:
break;
}
this.curContext = myContext;
return this.curModule;
}
}
}
},
MemberExpression : function(nodeWrapper) {
var object = nodeWrapper.object.visit(this);
var property = nodeWrapper.property.visit(this);
if(object == 'angular' && property == 'module') {
// Create a new angular module context
var moduleContext = { type : 'angularModuleContext', location: nodeWrapper.node.loc, contexts : [] };
this.curContext.contexts.push(moduleContext);
return moduleContext;
}
//Try to find the object in the symbol table.
if(this.curContext && typeof this.curContext.symbolTable != 'undefined' && this.curContext.symbolTable.hasOwnProperty(object)) {
object = this.curContext.symbolTable[object];
}
//If this is referencing $scope, and scope has not yet been defined, magically create the $scope object.
else if ( this.curContext && typeof this.curContext.symbolTable != 'undefined' && (object == '$scope' || object == 'scope') ) {
this.curContext.symbolTable[object] = { type : 'jsObjectContext', name : object, members : [] };
object = this.curContext.symbolTable[object];
}
if( typeof object.type != 'undefined' ) {
if( object.type == 'angularModuleContext' ) {
var newContext = { location : nodeWrapper.node.property.loc };
switch(property) {
case 'factory' :
newContext.type = 'angularFactoryContext';
break;
case 'service' :
newContext.type = 'angularServiceContext';
break;
case 'directive' :
newContext.type = 'angularDirectiveContext';
break;
case 'controller' :
newContext.type = 'angularControllerContext';
break;
case 'animation' :
newContext.type = 'angularAnimationContext';
break;
default :
return object + "." + property;
break;
}
object.contexts.push(newContext);
return newContext;
}
else if( object.type == 'jsObjectContext' ) {
var propertyExists = false;
object.members.forEach(function(curMember){
if(typeof curMember.name != 'undefined' && curMember.name == property) {
propertyExists = true;
}
});
if(!propertyExists) {
var objContext = { name : property };
object.members.push(objContext);
return objContext;
}
}
}
return object + "." + property;
},
FunctionDeclaration : function(nodeWrapper) {
var interfce = nodeWrapper.node.type;
if(this.curContext) {
// Change the context to a temporary context that is local to the function itself.
var myContext = this.curContext;
this.curContext = { type : 'functionBodyContext', symbolTable : {} };
var body = nodeWrapper.body.visit(this);
switch(myContext.type) {
case 'globalContext':
// Find the return value of the function and use it to generate the interface of the factory.
var factoryIntrfce = null;
body.forEach(function(curStatement){
if(typeof curStatement.type != 'undefined' && curStatement.type == 'returnContext') {
factoryIntrfce = curStatement.value;
}
});
// Are we a factory (I.E. a constructor of a class), or are we just a regular procedural function.
if(factoryIntrfce && typeof factoryIntrfce.type != 'undefined' && factoryIntrfce.type == 'jsObjectContext') {
interfce = factoryIntrfce;
}
else {
//Try to find the object in the symbol table.
if( typeof this.curContext.symbolTable != 'undefined' && this.curContext.symbolTable.hasOwnProperty(factoryIntrfce) ) {
interfce = this.curContext.symbolTable[factoryIntrfce];
}
else {
var myParams = [];
var self = this;
nodeWrapper.params.nodes.forEach(function(curParam){
myParams.push(curParam.visit(self));
});
interfce = { type : 'jsFunctionContext', returnVal : factoryIntrfce, params : myParams };
}
}
var symbolName = nodeWrapper.id.visit(this);
// add the function the list of contexts
switch (interfce.type) {
case 'jsFunctionContext':
interfce.name = symbolName;
interfce.location = nodeWrapper.node.loc;
myContext.contexts.push(interfce);
break;
case 'jsObjectContext':
var newContext = {
name : symbolName,
type : 'jsFactoryContext',
'interfce' : interfce,
location : nodeWrapper.node.loc
};
myContext.contexts.push(newContext);
break;
default:
break;
}
break;
default:
break;
}
// return the current Context to the global state.
this.curContext = myContext;
}
},
FunctionExpression : function(nodeWrapper) {
var interfce = nodeWrapper.node.type;
if(this.curContext) {
// Change the context to a temporary context that is local to the function itself.
var myContext = this.curContext;
this.curContext = { type : 'functionBodyContext', symbolTable : {} };
switch(myContext.type) {
case 'globalContext':
// Find the return value of the function and use it to generate the interface of the factory.
var factoryIntrfce = null;
var body = nodeWrapper.body.visit(this);
body.forEach(function(curStatement){
if(typeof curStatement.type != 'undefined' && curStatement.type == 'returnContext') {
factoryIntrfce = curStatement.value;
}
});
// Are we a factory (I.E. a constructor of a class), or are we just a regular procedural function.
if(factoryIntrfce && typeof factoryIntrfce.type != 'undefined' && factoryIntrfce.type == 'jsObjectContext') {
interfce = factoryIntrfce;
}
else {
//Try to find the object in the symbol table.
if( typeof this.curContext.symbolTable != 'undefined' && this.curContext.symbolTable.hasOwnProperty(factoryIntrfce) ) {
interfce = this.curContext.symbolTable[factoryIntrfce];
}
else {
var myParams = [];
var self = this;
nodeWrapper.params.nodes.forEach(function(curParam){
myParams.push(curParam.visit(self));
});
interfce = { type : 'jsFunctionContext', returnVal : factoryIntrfce, params : myParams };
}
}
break;
case 'angularServiceContext':
case 'angularFactoryContext':
// If the requirements haven't been determined yet, get them from the function params.
if(typeof myContext.requirements == 'undefined') {
myContext.requirements = [];
var self = this;
nodeWrapper.params.nodes.forEach(function(curParam){
myContext.requirements.push(curParam.visit(self));
});
}
// Find the return value of the function and use it to generate the interface of the factory.
var factoryIntrfce = null;
var body = nodeWrapper.body.visit(this);
body.forEach(function(curStatement){
if(typeof curStatement.type != 'undefined' && curStatement.type == 'returnContext') {
factoryIntrfce = curStatement.value;
}
});
// Determine if we are using an externally defined interface (i.e. a promise object), or if the interface is explicitly defined (i.e. with a jsObjectContext);
if(!factoryIntrfce) {
interfce = null;
} else if(typeof factoryIntrfce.type != 'undefined' && factoryIntrfce.type == 'jsObjectContext') {
interfce = factoryIntrfce;
}
else {
// Try to find the object in the symbol table.
if( typeof this.curContext.symbolTable != 'undefined' && this.curContext.symbolTable.hasOwnProperty(factoryIntrfce) ) {
interfce = this.curContext.symbolTable[factoryIntrfce];
}
else {
interfce = { type : 'externalIntrfce', name : factoryIntrfce };
}
}
break;
case 'angularDirectiveContext':
// The return statement is used to determine all the params of a directive.
var returnVal = null;
var body = nodeWrapper.body.visit(this);
body.forEach(function(curStatement){
if(typeof curStatement.type != 'undefined' && curStatement.type == 'returnContext') {
returnVal = curStatement.value;
}
});
if(returnVal) {
// @TODO: get the scope object and parse the link function for $attrs. Combine into to the params object.
var link = null;
var scope = null;
returnVal.members.forEach(function(curMember){
if(curMember.name == 'scope') { scope = curMember.value; }
if(curMember.name == 'link') { link = curMember.value; }
});
var params = []
if(scope) {
scope.members.forEach(function(curMember){
params.push(curMember.name);
});
}
nodeWrapper.visitAllChildren(attrCollector);
link = attrCollector.attrContext;
if(link.length > 0) {
params = params.concat(link);
}
interfce = params;
}
break;
case 'angularControllerContext':
var body = nodeWrapper.body.visit(this);
var scopeContext = {};
if( this.curContext.symbolTable.hasOwnProperty('$scope') ) {
scopeContext = this.curContext.symbolTable.$scope;
}
else if ( this.curContext.symbolTable.hasOwnProperty('scope') ) {
scopeContext = this.curContext.symbolTable.scope;
}
interfce = scopeContext;
break;
case 'functionBodyContext':
var body = nodeWrapper.body.visit(this);
/*console.log(this.curContext.symbolTable.$scope);
console.log(myContext);*/
var scopeContext = null;
if( this.curContext.symbolTable.hasOwnProperty('$scope') ) {
scopeContext = this.curContext.symbolTable.$scope;
} else if ( this.curContext.symbolTable.hasOwnProperty('scope') ) {
scopeContext = this.curContext.symbolTable.scope;
}
var parentScopeContext = null;
if( myContext.symbolTable.hasOwnProperty('$scope') ) {
parentScopeContext = myContext.symbolTable.$scope;
} else if ( myContext.symbolTable.hasOwnProperty('scope') ) {
parentScopeContext = myContext.symbolTable.scope;
}
if( scopeContext && parentScopeContext ) {
parentScopeContext.members = parentScopeContext.members.concat(scopeContext.members);
// Only keep unique members
var unique = [];
var uniqueObjs = [];
for (var i = 0; i < parentScopeContext.members.length; i++) {
if ( unique.indexOf(parentScopeContext.members[i].name) == -1) {
unique.push(parentScopeContext.members[i].name);
uniqueObjs.push(parentScopeContext.members[i]);
}
}
parentScopeContext.members = uniqueObjs;
}
default:
var params = [];
var self = this;
nodeWrapper.params.nodes.forEach(function(curParam){
params.push(curParam.visit(self));
});
interfce = params;
break;
}
// return the current Context to the global state.
this.curContext = myContext;
}
return interfce;
},
ArrayExpression : function(nodeWrapper) {
var elems = [];
var self = this;
nodeWrapper.elements.nodes.forEach(function(curElem){
elems.push(curElem.visit(self));
});
return elems;
},
BlockStatement : function(nodeWrapper) {
var statements = [];
var self = this;
nodeWrapper.body.nodes.forEach(function(curStatement){
statements.push(curStatement.visit(self));
});
return statements;
},
ReturnStatement : function(nodeWrapper) {
var returnContext = { type : 'returnContext' };
returnContext.value = nodeWrapper.argument.visit(this);
return returnContext;
},
ObjectExpression : function(nodeWrapper) {
var objContext = { type : "jsObjectContext", members : [] };
// Parse the properties of the object.
var self = this;
nodeWrapper.properties.nodes.forEach(function(curProperty){
var propertyContext = curProperty.visit(self);
objContext.members.push(propertyContext);
});
return objContext;
},
Property : function(nodeWrapper) {
if(nodeWrapper.node.kind == 'init') {
var propName = nodeWrapper.key.visit(this);
var objContext = { name : propName, type : nodeWrapper.node.value.type, location: nodeWrapper.node.loc };
var val = nodeWrapper.value.visit(this);
if(objContext.type == 'FunctionExpression') {
objContext.params = val;
} else {
objContext.value = val;
}
return objContext;
}
},
VariableDeclarator : function(nodeWrapper) {
// Everytime we declare a new variable, add it to the symbol table along with the object representing it's context or value.
if(this.curContext && typeof this.curContext.symbolTable != 'undefined') {
var symbolName = nodeWrapper.id.visit(this);
this.curContext.symbolTable[symbolName] = (nodeWrapper.node.init) ? nodeWrapper.init.visit(this) : null;
// If we are in the global context and this is a function, add it the list of contexts
if(typeof this.curContext.type != 'undefined' && this.curContext.type == 'globalContext' && this.curContext.symbolTable[symbolName] != null && typeof this.curContext.symbolTable[symbolName].type != 'undefined') {
switch (this.curContext.symbolTable[symbolName].type) {
case 'jsFunctionContext':
this.curContext.symbolTable[symbolName].name = symbolName;
this.curContext.symbolTable[symbolName].location = nodeWrapper.node.loc;
this.curContext.contexts.push(this.curContext.symbolTable[symbolName]);
break;
case 'jsObjectContext':
var newContext = {
name : symbolName,
type : 'jsFactoryContext',
interfce : this.curContext.symbolTable[symbolName],
location : nodeWrapper.node.loc
};
this.curContext.contexts.push(newContext);
break;
default:
break;
}
}
}
},
AssignmentExpression : function(nodeWrapper) {
if(nodeWrapper.node.operator == '=') {
var objContext = nodeWrapper.left.visit(this);
objContext.type = nodeWrapper.node.right.type;
objContext.location = nodeWrapper.node.loc;
var val = nodeWrapper.right.visit(this);
if(objContext.type == 'FunctionExpression') {
objContext.params = val;
} else {
objContext.value = val;
}
return objContext;
}
},
Literal : function(nodeWrapper) {
return nodeWrapper.node.value;
},
Identifier : function(nodeWrapper) {
return nodeWrapper.node.name;
},
default : function(nodeWrapper) {
nodeWrapper.visitAllChildren(this);
return nodeWrapper.node.type;
}
});
astWrapper.visitAllChildren(contextVisitor);
// Phase 2. Match up all the contexts with the comment blocks
function matchComments(context) {
// Match the comment to the context.
if(typeof context.location != 'undefined') {
ast.comments.forEach(function(curComment, index){
if(curComment.type == "Block") {
if( (curComment.loc.end.line + 1) == context.location.start.line ) {
context.docBlock = ast.comments.splice(index, 1 );
}
}
});
}
// Recursively match comments of child contexts.
if(typeof context.interfce != 'undefined' && context.interfce && typeof context.interfce.members != 'undefined') {
context.interfce.members.forEach(function(member){
matchComments(member);
});
}
if(typeof context.contexts != 'undefined') {
context.contexts.forEach(function(childContext){
matchComments(childContext);
});
}
}
matchComments(globalContext);
// Phase 3. Output the resulting datastructure as a PHP like skeleton file that is readable by Doxygen.
function renderContext(curContext, tablevel) {
var output = '';
var tabs = '';
if(typeof tablevel == 'undefined') { tablevel = 0; }
for (var i = 0; i < tablevel; i++) {
tabs += ' ';
};
// This is a class.
if( typeof curContext.interfce != 'undefined' ) {
if( typeof curContext.docBlock != 'undefined' ) {
var wargingMsg = (curContext.interfce == null) ? '<strong>WARNGING!</strong> No interface could be parsed from this class. This could indicate a programming error. <img src="http://www.r-bloggers.com/wp-content/uploads/2010/04/vader-fail1.jpg" />' : false;
output += renderDocBlock(curContext.docBlock[0].value, tabs, wargingMsg);
}
var angularType = null;
switch( curContext.type ) {
case 'angularControllerContext' :
angularType = 'Controller';
break;
case 'angularFactoryContext' :
angularType = 'Factory';
break;
case 'angularServiceContext' :
angularType = 'Service';
break;
default :
break;
}
output += tabs + 'class ' + curContext.name;
if( !curContext.interfce ) {
output += '\n' + tabs + '{' + '\n';
} else {
if( curContext.interfce.type == 'externalIntrfce' ) {
// This class inherits from some external Class.
output += ' extends ' + curContext.interfce.name
if(angularType) { output += ' , angular.' + angularType; }
output += '\n' + tabs + '{' + '\n';
} else if( curContext.interfce.type == 'jsObjectContext' ) {
if(angularType) { output += ' extends angular.' + angularType; }
output += '\n' + tabs + '{' + '\n';
// Sort the interface members so that functions all come last
curContext.interfce.members.sort(function( a, b ){
if( typeof a.params != 'undefined' && typeof b.params == 'undefined' ) {
return 1;
} else if ( typeof a.params == 'undefined' && typeof b.params != 'undefined' ) {
return -1;
} else {
return 0;
}
});
// Recurse into each class member.
tablevel++;
curContext.interfce.members.forEach(function(curMember) {
output += renderContext(curMember, tablevel);
});
}
}
output += tabs + '}' + '\n\n';
} else if( typeof curContext.params != 'undefined' ) {
// This is a function.
var renderParams = function() {
var output = '';
if(curContext.params.length > 0) {
curContext.params.forEach(function(curParam){
output += ' ' + '' + curParam + ' ,';
});
output = output.substring(0, output.length - 1);
}
return output;
};
var renderFunction = function() {
var output = '';
if( typeof curContext.docBlock != 'undefined' ) {
output += renderDocBlock(curContext.docBlock[0].value, tabs );
}
output += tabs + 'public function ' + curContext.name + ' (' + renderParams() + ')' + '\n' + tabs + '{' + '\n' + tabs + '}' + '\n\n';
return output;
}
if( curContext.type == 'angularDirectiveContext' ) {
output += tabs + 'class ' + curContext.name.replace(/-/g,'_') + ' extends angular.Directive' + '\n' + tabs + '{' + '\n';
tabs += tabs;
output += renderFunction();
tabs = tabs.substring(0, (tabs.length / 2) );
output += tabs + '}' + '\n\n';
} else {
output += renderFunction();
}
} else if ( curContext.type == 'angularAnimationContext' ) {
if( typeof curContext.docBlock != 'undefined' ) {
output += renderDocBlock(curContext.docBlock[0].value, tabs );
}
output += tabs + 'class ' + curContext.name.replace(/-/g,'_') + ' extends angular.Animation' + '\n' + tabs + '{' + '\n';
output += tabs + '}' + '\n\n';
} else if( curContext.type == 'angularModuleContext' ) {
// Angular Modules are interpreted as a namespace.
if( typeof curContext.docBlock != 'undefined' ) {
output += renderDocBlock(curContext.docBlock[0].value, tabs);
}
output += 'namespace ' + curContext.name + ';' + '\n\n';
tablevel++;
} else if ( curContext.type == 'globalContext' ) {
//Don't print anything.
} else {
// Ignore anything that starts with a $, because it is probably a special function or object from Angular or JQuery.
if(curContext.name.indexOf('$') != 0) {
// Treat anything else as a public attribute.
if( typeof curContext.docBlock != 'undefined' ) {
output += renderDocBlock(curContext.docBlock[0].value, tabs);
}
// @TODO: determine the type.
output += tabs + 'public ' + '' + curContext.name + ';' + '\n\n';
}
}
if( typeof curContext.contexts != 'undefined' ) {
// Recurse to the children contexts.
curContext.contexts.forEach(function(childContext){
output += renderContext(childContext, tablevel);
});
}
return output;
};
function renderDocBlock(docString, prefix, warningMsg) {
var output = '';
output += prefix + '/*';
var docArr = docString.split('\n');
docArr.forEach(function(curLine, index){
if(index > 0) {
output += prefix + ' ';
}
output += curLine.trim() + '\n';
});
output = output.substring(0, output.length - 1);
if(warningMsg) {
output += '*\n' + prefix + ' * <i>' + warningMsg + '</i>\n';
}
output += prefix + ' */' + '\n';
return output;
}
//console.log(prettyjson.render(globalContext));
console.log('<?php');
console.log(renderContext(globalContext));
console.log('?>'); | mit |
ciena-frost/ember-frost-bunsen | addon/components/array-container.js | 11913 | import {utils} from 'bunsen-core'
const {getLabel} = utils
import Ember from 'ember'
const {Component, get, isPresent, typeOf} = Ember
import computed, {readOnly} from 'ember-computed-decorators'
import {HookMixin} from 'ember-hook'
import {singularize} from 'ember-inflector'
import PropTypeMixin, {PropTypes} from 'ember-prop-types'
import _ from 'lodash'
import layout from 'ember-frost-bunsen/templates/components/frost-bunsen-array-container'
const {keys} = Object
/**
* Finds the index of an item in an array based on the bunsen ID's of the item and its containing array
*
* @param {String} arrayId Bunsen ID of the array
* @param {String} itemId Bunsen ID of the item in the array
* @returns {String} Index of array item (as a string)
*/
function itemIndex (arrayId, itemId) {
return itemId.slice(arrayId.length + 1).split('.')[0]
}
/**
* Recursively clears empty objects based on a path
*
* @param {Object} object Hash containing object
* @param {String[]} path Array of path segments to the desired value to clear
* @param {Number} pathIndex Index of the path segment to use as a key
* @returns {Boolean} True if a key was deleted from the passed in object
*/
function clearSubObject (object, path, pathIndex) {
const key = path[pathIndex]
if (path.length < pathIndex + 2) {
delete object[key]
return true
}
const subObj = object[key]
const didClear = clearSubObject(subObj, path, pathIndex + 1)
if (didClear && keys(subObj).length <= 0) {
delete object[key]
return true
}
return false
}
export default Component.extend(HookMixin, PropTypeMixin, {
// == Component Properties ===================================================
classNames: ['frost-bunsen-array-container', 'frost-bunsen-section'],
layout,
// == State Properties =======================================================
propTypes: {
bunsenId: PropTypes.string.isRequired,
bunsenModel: PropTypes.object.isRequired,
bunsenView: PropTypes.object.isRequired,
cellConfig: PropTypes.object.isRequired,
compact: PropTypes.bool,
errors: PropTypes.object.isRequired,
formDisabled: PropTypes.bool,
formValue: PropTypes.oneOfType([
PropTypes.EmberObject,
PropTypes.object
]),
getRootProps: PropTypes.func,
onChange: PropTypes.func.isRequired,
onError: PropTypes.func.isRequired,
readOnly: PropTypes.bool,
registerForFormValueChanges: PropTypes.func,
renderers: PropTypes.oneOfType([
PropTypes.EmberObject,
PropTypes.object
]),
required: PropTypes.bool,
showAllErrors: PropTypes.bool,
unregisterForFormValueChanges: PropTypes.func,
value: PropTypes.object
},
getDefaultProps () {
return {
compact: false,
formValue: Ember.Object.create({}),
readOnly: false
}
},
// == Computed Properties ====================================================
@readOnly
@computed('bunsenId', 'cellConfig', 'bunsenModel')
/**
* Get label for cell
* @param {String} bunsenId - bunsen ID for array (represents path in bunsenModel)
* @param {Object} cellConfig - cell config
* @param {BunsenModel} bunsenModel - bunsen model
* @returns {String} label
*/
addLabel (bunsenId, cellConfig, bunsenModel) {
const prefix = 'Add '
let label = get(cellConfig, 'label')
if (label) {
label = `${singularize(label)}`
} else {
const renderLabel = getLabel(label, bunsenModel, bunsenId)
label = `${singularize(renderLabel).toLowerCase()}`
}
return `${prefix}${label}`
},
@readOnly
@computed('formDisabled', 'cellConfig')
disabled (formDisabled, cellConfig) {
return formDisabled || get(cellConfig, 'disabled')
},
@readOnly
@computed('cellConfig')
inline (cellConfig) {
const inline = get(cellConfig, 'arrayOptions.inline')
return inline === undefined || inline === true
},
@readOnly
@computed('bunsenModel', 'cellConfig', 'inline', 'maxItemsReached')
showAddButton (bunsenModel, cellConfig, inline, maxItemsReached) {
// If we've reached max items don't allow more to be added
if (maxItemsReached) {
return false
}
if (Array.isArray(bunsenModel.items) && !isPresent(bunsenModel.additionalItems)) {
return false
}
return inline && !get(cellConfig, 'arrayOptions.autoAdd')
},
@readOnly
@computed('bunsenModel.maxItems', 'value', 'bunsenId')
maxItemsReached (maxItems, value, bunsenId) {
if (value && maxItems) {
return get(value, bunsenId).length >= maxItems
}
return false
},
@readOnly
@computed('cellConfig', 'readOnly')
/**
* Whether or not array items can be sorted by user
* @param {Object} cellConfig - cell config
* @param {Boolean} readOnly - whether or not form is read only
* @returns {Boolean} whether or not sorting is enabled
*/
sortable (cellConfig, readOnly) {
return (
readOnly !== true &&
get(cellConfig, 'arrayOptions.sortable') === true
)
},
@readOnly
@computed('bunsenModel')
itemsModel (model) {
const itemModels = model.items
if (Array.isArray(itemModels)) {
return model.additionalItems
}
return itemModels
},
@readOnly
@computed('bunsenId', 'readOnly', 'value', 'bunsenModel', 'cellConfig.arrayOptions.itemCell')
/* eslint-disable complexity */
items (bunsenId, readOnly, value, bunsenModel, cellConfig) {
if (typeOf(value) === 'object' && 'asMutable' in value) {
value = value.asMutable({deep: true})
}
const items = get(value || {}, bunsenId) || []
if (
readOnly !== true &&
this.get('cellConfig.arrayOptions.autoAdd') === true
) {
items.push(this._getEmptyItem())
}
if (Array.isArray(bunsenModel.items)) {
return items.slice(bunsenModel.items.length)
}
return items
},
/* eslint-enable complexity */
@readOnly
@computed('bunsenId', 'bunsenModel', 'value')
startingIndex (bunsenId, bunsenModel, value) {
const items = bunsenModel.items
if (Array.isArray(items)) {
return items.length
}
return 0
},
@readOnly
@computed('bunsenModel')
tupleItems (model) {
if (Array.isArray(model.items)) {
return model.items
}
},
// == Functions ==============================================================
/* eslint-disable complexity */
_getEmptyItem (model) {
const type = model ? model.type
: this.get('bunsenModel.items.type') || this.get('bunsenModel.additionalItems.type')
switch (type) {
case 'array':
return []
case 'boolean':
return false
case 'integer':
case 'number':
return NaN
case 'object':
return {}
case 'string':
return ''
}
},
/* eslint-enable complexity */
_handleArrayChange (bunsenId, value, autoAdd) {
const clearingValue = [undefined, null, ''].indexOf(value) !== -1
if (autoAdd && clearingValue) {
return
// TODO: implement functionality
}
this.onChange(bunsenId, value)
},
/* eslint-disable complexity */
_handleObjectChange (bunsenId, value, autoAdd) {
const clearingValue = [undefined, null, ''].includes(value)
if (autoAdd && clearingValue) {
const arrayPath = this.get('bunsenId')
const itemPathBits = bunsenId.replace(`${arrayPath}.`, '').split('.')
const itemIndex = parseInt(itemPathBits.splice(0, 1)[0], 10)
const itemPath = `${arrayPath}.${itemIndex}`
const item = this.get(`value.${itemPath}`)
const itemCopy = _.cloneDeep(item)
let key = itemPathBits.pop()
// If property is not not nested go ahead and clear it
if (itemPathBits.length === 0) {
delete itemCopy[key]
bunsenId = bunsenId.replace(`.${key}`, '')
// If property is nested further down clear it and remove any empty parent items
} else {
clearSubObject(itemCopy, itemPathBits, 0)
}
if (keys(itemCopy).length === 0) {
this.send('removeItem', itemIndex)
return
}
const subPathLen = itemPath.length === 0 ? 0 : itemPath.length + 1
const relativePath = bunsenId.slice(subPathLen)
value = get(itemCopy, relativePath)
}
this.onChange(bunsenId, value)
},
/* eslint-enable complexity */
_handlePrimitiveChange (bunsenId, value, autoAdd) {
if (this._isItemEmpty(value)) {
const arrayPath = this.get('bunsenId')
const itemPathBits = bunsenId.replace(`${arrayPath}.`, '').split('.')
const itemIndex = parseInt(itemPathBits.splice(0, 1)[0], 10)
this.send('removeItem', itemIndex)
return
}
this.onChange(bunsenId, value)
},
/* eslint-disable complexity */
_isItemEmpty (item) {
const type = this.get('bunsenModel.items.type')
switch (type) {
case 'array':
return item.length !== 0
case 'boolean':
return [undefined, null].indexOf(item) !== -1
case 'integer':
case 'number':
return isNaN(item) || item === null
case 'object':
return [undefined, null].indexOf(item) !== -1 || keys(item).length === 0
case 'string':
return [undefined, null, ''].indexOf(item) !== -1
}
},
/* eslint-enable complexity */
/**
* Initialze state of cell
*/
init () {
this._super(...arguments)
},
/**
* Method called by parent when formValue changes
* @param {Object} newValue - the new formValue
*/
formValueChanged (newValue) {
const bunsenId = this.get('bunsenId')
const newItems = get(newValue || {}, bunsenId)
const oldItems = get(this.get('value') || {}, bunsenId)
if (!_.isEqual(oldItems, newItems)) {
this.notifyPropertyChange('value')
}
this.set('formValue', newValue)
},
itemType (itemId) {
return this.get('bunsenModel.items.type') ||
this.get(`bunsenModel.items.${itemIndex(this.get('bunsenId'), itemId)}.type`) ||
this.get('bunsenModel.additionalItems.type')
},
// == Actions ================================================================
actions: {
/**
* Add an empty item then focus on it after it's been rendererd
*/
addItem () {
const bunsenId = this.get('bunsenId')
const newItem = this._getEmptyItem()
const value = this.get('value')
const items = get(value || {}, bunsenId) || []
const index = Math.max(items.length, this.get('bunsenModel.items.length') || 0)
this.onChange(`${bunsenId}.${index}`, newItem)
},
/* eslint-disable complexity */
handleChange (bunsenId, value) {
const autoAdd = this.get('cellConfig.arrayOptions.autoAdd')
const type = this.itemType(bunsenId)
switch (type) {
case 'array':
this._handleArrayChange(bunsenId, value, autoAdd)
break
case 'boolean':
case 'integer':
case 'number':
case 'string':
this._handlePrimitiveChange(bunsenId, value, autoAdd)
break
case 'object':
this._handleObjectChange(bunsenId, value, autoAdd)
break
}
},
/* eslint-enable complexity */
/**
* Remove an item
* @param {Number} index - index of item to remove
*/
removeItem (index) {
const bunsenId = this.get('bunsenId')
const value = this.get('value')
const items = get(value || {}, bunsenId) || []
const newValue = items.slice(0, index).concat(items.slice(index + 1))
// since the onChange mechanism doesn't allow for removing things
// we basically need to re-set the whole array
this.onChange(bunsenId, newValue)
},
/**
* Reorder items in array
* @param {Array} reorderedItems - reordered items
*/
reorderItems (reorderedItems) {
const bunsenId = this.get('bunsenId')
this.onChange(bunsenId, reorderedItems)
}
}
})
| mit |
connor557/rubymine | lib/server/map.rb | 3331 | module Server
module Map
# Represents a single chunk of the Minecraft map. Note that +x+ points
# south, +z+ points west, and +y+ points upwards.
class Chunk
# @return the start position of the region, in world block coordinates
#
# @example Find which chunk is affected
# ChunkX = X >> 4
# ChunkY = Y >> 7
# ChunkZ = Z >> 4
attr_reader :x, :y, :z
# @example which local block in the chunk to start at
# StartX = X & 15
# StartY = Y & 127 (not always 0!)
# StartZ = Z & 15
attr_reader :size_x, :size_y, :size_z
# @return [Array] the blocks located within this chunk in a one-dimensional
# array
#
# @example Access the block at point [x, z, y]
# index = y + (z * (Size_Y+1)) + (x * (Size_Y+1) * (Size_Z+1))
attr_reader :blocks
def initialize(x, y, z, size_x, size_y, size_z, blocks)
@x, @y, @z = x, y, z
@size_x, @size_y, @size_z = size_x, size_y, size_z
@blocks = blocks
end
# @return [String] the zlib deflated byte data, ready to be sent to the client
def to_bytes
buffer = IO::Buffer.new
# The block type array
@blocks.each do |block|
buffer.put_byte block.type
end
# The block metadata array
@blocks.each_slice(2) do |blocks|
buffer.put_byte((blocks[0].metadata << 4) + blocks[1].metadata)
end
# The block light array
@blocks.each_slice(2) do |blocks|
buffer.put_byte((blocks[0].light << 4) + blocks[1].light)
end
# The block sky light array
@blocks.each_slice(2) do |blocks|
buffer.put_byte((blocks[0].sky_light << 4) + blocks[1].sky_light)
end
Zlib::Deflate.deflate buffer.data
end
def self.generate_test_data
chunks = []
(-16..16).step(16).each do |x|
(-16..16).step(16).each do |z|
chunks << generate_test_data_for(x, z)
end
end
chunks
end
# TODO: load map data from a file, or generate a real map
def self.generate_test_data_for(x, z)
blocks = []
size_x = 15
size_z = 15
size_y = 127
(0..size_x).each do |x|
(0..size_z).each do |z|
# Set the floor layer to stone
(0..1).each do |y|
index = y + (z * (size_y+1)) + (x * (size_y+1) * (size_z+1))
blocks[index] = Block.new 1, 0, 0, 0
end
# Set everything above that to air
(2..size_y).each do |y|
index = y + (z * (size_y+1)) + (x * (size_y+1) * (size_z+1))
blocks[index] = Block.new 0, 0, 0, 0
end
end
end
chunk = Chunk.new x, 0, z, size_x, size_y, size_z, blocks
end
end
class Block
# @return [Fixnum] the block type; air or water for instance
attr_reader :type
# TODO: what is this?
attr_reader :metadata
# TODO: what is this?
attr_reader :light
# TODO: what is this?
attr_reader :sky_light
def initialize(type, metadata, light, sky_light)
@type, @metadata, @light, @sky_light = type, metadata, light, sky_light
end
end
end
end
| mit |
EemeliSyynimaa/picross | engine/graphics.py | 314 | # -*- coding: utf-8 -*-
from pyglet.gl import *
def scale_image(image, width, height):
image.get_texture()
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
gl.GL_NEAREST)
image.width = width
image.height = height
return image
| mit |
sindresorhus/gravatar-url | index.test-d.ts | 1241 | import {expectType, expectError} from 'tsd';
import gravatarUrl from './index.js';
expectType<string>(gravatarUrl('[email protected]'));
expectType<string>(gravatarUrl('[email protected]', {default: '404'}));
expectType<string>(gravatarUrl('[email protected]', {default: 'blank'}));
expectType<string>(
gravatarUrl('[email protected]', {default: 'identicon'})
);
expectType<string>(gravatarUrl('[email protected]', {default: 'mm'}));
expectType<string>(
gravatarUrl('[email protected]', {default: 'monsterid'})
);
expectType<string>(gravatarUrl('[email protected]', {default: 'retro'}));
expectType<string>(gravatarUrl('[email protected]', {default: 'wavatar'}));
expectType<string>(
gravatarUrl('[email protected]', {default: 'https://example.com'})
);
expectType<string>(gravatarUrl('[email protected]', {size: 200}));
expectType<string>(gravatarUrl('[email protected]', {rating: 'g'}));
expectType<string>(gravatarUrl('[email protected]', {rating: 'pg'}));
expectType<string>(gravatarUrl('[email protected]', {rating: 'r'}));
expectType<string>(gravatarUrl('[email protected]', {rating: 'x'}));
expectError(gravatarUrl('[email protected]', {rating: 'foo'}));
| mit |
xixizhang96/Example | myweb/demo/demo备注.php | 16508 | <?php
error_reporting(0);
define("IObit","IObit");
if (@!$include){
$pResUrl = './';
$pRootUrl = '../../../';
}
include $pRootUrl.'include/common.inc.php';
//指定ref参数 以下两种模式根据情况选其一
if (empty($_GET['ref'])) $_GET['ref'] = ''; //指定ref参数 可覆盖
//$_GET['ref'] = ''; //指定ref参数 不可覆盖
//创建浮点计算,取 购买人数 及 剩余礼品数,根据情况选择使用
function microtime_float(){
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
// 已购买人数
// 需要精确到某个值时,先输出 ceil(microtime_float()*1000/20000) 再 由此结果计算需要减去的量
$buyNum = ceil(microtime_float()*1000/20000) - 69041325;
$buyNum = number_format($buyNum); //以分号隔开数字
// 在学要变化的标签内这样调用: <?php echo $buyNum; ? > 复制的时候记到php符号的后结束符号?和 >之间要把空格删掉
if(!empty($_GET['action'])&&($_GET['action']=='getPacks')){ //让购买人数自动增加
echo $buyNum;
exit();
}
// 剩余礼品数
$packsNum = ceil(microtime_float()*2000/20000);
$packsNum = 360-($packsNum%360);
if ($_GET['action'] == 'getPacks'){
echo $packsNum;
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Title</title>
<meta name="Copyright" content="IObit">
<link rel="icon" href="<?php echo $pRootUrl; ?>tpl/img/favicon.ico" mce_href="<?php echo $pRootUrl; ?>tpl/img/favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="<?php echo $pRootUrl; ?>tpl/img/favicon.ico" mce_href="<?php echo $pRootUrl; ?>tpl/img/favicon.ico" type="image/x-icon">
<!-- 引用字体 -->
<link rel="stylesheet" href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,600'>
<!-- 规定了使用哪种字体的话,这里的名字也要相应的变化 -->
<!-- <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700"> -->
<link href="<?php echo $pResUrl; ?>style/style.css" rel="stylesheet">
<?php echo $gJavascript['public'];?>
<?php echo $gJavascript['head']; ?>
<script>
//剩余礼物数量 (记得删除掉中文字符)
function decreasingPacks() {
$.ajax({
type: "GET",
url: "index.php", //要求为String类型的参数,(默认为当前页地址)发送请求的地址(新建页面的地址)
data: "action=getPacks&r=" + Math.random(), //要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式。get请求中将附加在url后
success: function(packs) { //请求成功时,执行此回调函数,其中packs为自定义参数,返回的是上面的$packsNum;
//alert(packs);
$('.packsNum').html(packs);
setTimeout('decreasingPacks()', 10000);
}
});
}
setTimeout('decreasingPacks()', 10000);
</script>
</head>
<body>
<script type="text/javascript" src="<?php echo $pRootUrl; ?>tpl/js/stats.js"></script>
<!-- header start -->
<div class="header">
<div class="wrapper">
<a class="logo" href="http://www.iobit.com" target="_blank">
<img src="<?php echo $pResUrl; ?>images/logo.png" alt="IObit" onclick="goTarget($('#compare'),140)">
</a>
<!-- time -->
<ul id="countdown" class="countdown">
<li>00</li>
<li>00</li>
<li>00</li>
<li>000</li>
</ul>
</div>
</div>
<!-- header end -->
<!-- container start -->
<div class="container">
<!-- user-rev start -->
<div class="user-rev" id="user">
<h2>User Review</h2>
<dl>
<dt><h4>"I'm really happy I upgraded, it puts my mind at ease and does all the work"</h4></dt>
<dd>
"The Advanced-System Care Pro keeps my computer well cleaned. Not only that, their customer service is excellent. They persevered with courteous help until I was able to solve my problem of sending a gift of this ASC service to another person. This is evidence of a good company."
</dd>
</dl>
<dl class="show">
<dt><h4>"Cleaned up Spyware and Malware My antivirus lets slip through"</h4></dt>
<dd>
"We used to use up to a dozen different programs to keep our machines running smoothly and keep the bad guys out. It took hours every week to maintain security and performance. Now, with Advanced System Care Pro, everything is in one place and it takes us just a few minutes every couple of days to do the same jobs with much more confidence."
</dd>
</dl>
<dl>
<dt><h4>"It takes care of everything in the background"</h4></dt>
<dd>
"Advanced System Care Pro has proved to be a trusted tool, automatically improving performance and security in a simple interface and with a great support. I recommend it to all my Family and friends."
</dd>
</dl>
<dl>
<dt><h4>My system has never run better.</h4></dt>
<dd>
In my opinion, IObit's ASC Pro is the best maintenance application available for the Windows user, providing excellent value and function in both its shareware and freeware versions. IObit provides expert technical support that is competent, knowledgeable and responsive, adding significant value to their products and services for their customers.
</dd>
</dl>
<ul class="users">
<li>
<img src="<?php echo $pResUrl; ?>images/jane_mcclain.jpg" alt="Jane McClain">
<sapn>Jane McClain</sapn>
<span>2014</span>
</li>
<li class="current">
<img src="<?php echo $pResUrl; ?>images/bob.jpg" alt="Bob Bassett">
<span>Bob Bassett</span>
<span>2014</span>
</li>
<li>
<img src="<?php echo $pResUrl; ?>images/almir.jpg" alt="Almir Romboli Tavares">
<span>Almir Romboli Tavares</span>
<span>2014</span>
</li>
<li>
<img src="<?php echo $pResUrl; ?>images/gordon.jpg" alt="Gordon Griswold">
<span>Gordon Griswold</span>
<span>2014</span>
</li>
</ul>
</div>
<!-- user-rev end -->
<!-- comparison start -->
<div class="comparison wrapper" id="compare">
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<thead>
<tr>
<th class="text" colspan="2">
Bekijk wat de pro versie voor u kan betekenen:
</th>
<th class="itemb">
<strong>Driver Booster 3 Free</strong>
</th>
<th class="itema">
<b>Driver Booster 3 Pro</b>
<a class="tbbuybtn btngs" href="http://www.iobit.com/buy.php?product=nl-db3sd&ref=nl_db3sdpurchase1604&refs=nl_purchase_db" onclick="ga('send', 'event', 'dbbuy', 'buy', 'dbpurchase1604-nl');">
Koop Nu
</a>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="icons" width="45"><img src="<?php echo $pResUrl; ?>images/icon_01.png"></td>
<td class="virtue">Scan & Identificeer Automatisch Verouderde, Missende & Onjuiste
Drivers</td>
<td class="itemb"><span class="mark-icons blue">√</span></td>
<td class="itema"><span class="mark-icons orange">√</span></td>
</tr>
<tr>
<td class="icons"><img src="<?php echo $pResUrl; ?>images/icon_02.png"></td>
<td class="virtue">Download & Update Verouderde Drivers met 1-klik</td>
<td class="itemb"><span class="mark-icons blue">√</span></td>
<td class="itema"><span class="mark-icons orange">√</span></td>
</tr>
<tr>
<td class="icons"><img src="<?php echo $pResUrl; ?>images/icon_03.png"></td>
<td class="virtue">Ontgrendel Driver Update Snelheids Limiet</td>
<td class="itemb"></td>
<td class="itema"><span class="mark-icons orange">√</span></td>
</tr>
<tr>
<td class="icons"><img src="<?php echo $pResUrl; ?>images/icon_04.png"></td>
<td class="virtue">Prioriteit voor het Updaten van Zeer Verouderde & Zeldzame Drivers</td>
<td class="itemb"></td>
<td class="itema"><span class="mark-icons orange">√</span></td>
</tr>
<tr>
<td class="icons"><img src="<?php echo $pResUrl; ?>images/icon_05.png"></td>
<td class="virtue">Reduceer het Vastlopen & Crashes van het Systeem voor Betere Prestaties</td>
<td class="itemb"></td>
<td class="itema"><span class="mark-icons orange">√</span></td>
</tr>
<tr>
<td class="icons"><img src="<?php echo $pResUrl; ?>images/icon_06.png"></td>
<td class="virtue">Auto Driver Download & Installatie wanneer het Systeem in ruststand
staat</td>
<td class="itemb"></td>
<td class="itema"><span class="mark-icons orange">√</span></td>
</tr>
<tr>
<td class="icons"><img src="<?php echo $pResUrl; ?>images/icon_07.png"></td>
<td class="virtue">Automatische Back-up van alle Drivers voor Veilig Herstel</td>
<td class="itemb"></td>
<td class="itema"><span class="mark-icons orange">√</span></td>
</tr>
<tr>
<td class="icons"><img src="<?php echo $pResUrl; ?>images/icon_08.png"></td>
<td class="virtue">Prioriteit voor het updaten van Game Componenten voor betere Game Ervaring</td>
<td class="itemb"></td>
<td class="itema"><span class="mark-icons orange">√</span></td>
</tr>
<tr>
<td class="icons"><img src="<?php echo $pResUrl; ?>images/icon_09.png"></td>
<td class="virtue">Automatische Update naar de laatste Versie</td>
<td class="itemb"></td>
<td class="itema"><span class="mark-icons orange">√</span></td>
</tr>
<tr>
<td class="icons"><img src="<?php echo $pResUrl; ?>images/icon_10.png"></td>
<td class="virtue">Gratis 24/7 Technische Ondersteuning op Aanvraag</td>
<td class="itemb"></td>
<td class="itema"><span class="mark-icons orange">√</span></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="2"></th>
<th class="itemb">
<strong>Driver Booster 3 Free</strong>
<span>Uw huidige versie</span>
</th>
<th class="itema">
<b>Driver Booster 3 Pro</b>
<a class="tbbuybtn btngs" href="http://www.iobit.com/buy.php?product=nl-db3sd&ref=nl_db3sdpurchase1604&refs=nl_purchase_db" onclick="ga('send', 'event', 'dbbuy', 'buy', 'dbpurchase1604-nl');">
Koop Nu
</a>
</th>
</tr>
</tfoot>
</table>
</div>
<!-- comparison end -->
<!-- annotation start -->
<dl class="annotation border-bottom">
<dt>N.B.</dt>
<dd>1*Ces programmes de promotion sont modifiables sans préavis, à tout moment et à notre seule discrétion.</dd>
<dd>2*.Les données peuvent varier en fonction de différents systèmes ou ordinateurs.</dd>
</dl>
<!-- annotation end -->
</div>
<!-- container end -->
<!-- footer start -->
<div class="footer">Copyright © 2005 - <?php echo date('Y')?> IObit. All Rights Reserved</div><!-- 注意书写规范 <?php echo date('Y')?> -->
<!-- footer end -->
<!-- 如需要使用google翻译,引用下面一段,否则删除 -->
<?php echo $gJavascript['foot']; ?>
<script>
//userreview
$(".users li").mouseover(function(event) {
var num = $(this).index();
$(".users li").eq(num).addClass('active').siblings().removeClass('active');
$(".user_rev .content>dl").eq(num).addClass('active').siblings().removeClass('active');
});
function switchover(name,clickname,active,contname) {
$(name).on(clickname,function(){
var num = $(this).index();
$(name).eq(num).addClass(active).siblings().removeClass(active);
$(contname).eq(num).addClass(active).siblings().removeClass(active);
});
}
//floatlayer
$(window).on('scroll', function () {
var scrollHeight = $(".header .buybtn:last").offset().top;
if ($(window).scrollTop() > scrollHeight) {
$('#floatlayer').addClass('on');
}else {
$('#floatlayer').removeClass('on');
}
});
function showFloat(subject,target){
var scrollHeight = $(subject).height();
if ($(window).scrollTop() > scrollHeight) {
$(target).addClass('on');
} else {
$(target).removeClass('on');
}
}
//(http://localhost/purchase.rs.iobit.com/2016/asc/maysalede/index.php)
$(".center-banner .infor li").mouseover(function(event) {
var num = $(this).index();
var dataName = $(this).attr("data-name");
var dataUrl = $(".banner").find("[data-num=\'" + dataName + "\'] .buybtn").attr("href");
var price = $(this).find(".price").text();
var offer = $(this).find(".offer-price").text();
$(".center-banner .infor li").eq(num).addClass('active').siblings().removeClass('active');
$(".center-banner .centerbtn").attr("href",dataUrl);
$(".center-banner .buy").find("#all").text(price);
$(".center-banner .buy").find("#offer").text(offer);
});
//同时选中链接(参照febsalebde文件)(记得删除掉中文字符)
$("[data-name^='pc']").on("click",function(){ //data-name属性以pc开始的所有标签
var dataName = $(this).attr("data-name");
var dataUrl = $(this).attr("data-url");
$("[data-name=\'" + dataName + "\']").addClass("active"); // \'--代表一个单引号(撇号)字符
$("[data-name^='pc']:not([data-name=\'" + dataName + "\'])").removeClass("active");
$(".header .buybtn, .floatlayer .buybtn").attr("href",dataUrl);
return false;
});
$(".floatlayer .right dd").click(function(){
$(this).addClass("currt").siblings().removeClass("currt");
$(".floatlayer .buybtn").attr('href',$(this).attr("data-url"));
$(".floatlayer .buybtn").attr('onclick',$(this).find('span.choose').attr("data-event"));
});
//页面中的指定局部跳转链接 (记得删除掉中文字符)
function goTarget(target,yoffset) {
if(!yoffset) yoffset = 0;
var Theigth = target.offset().top - yoffset;
$("html, body").animate({scrollTop: Theigth}, 'slow');
}
// function goTarget(target) {
// var Theigth = target.offset().top;
// $("html, body").animate({scrollTop: Theigth}, 'slow');
// }
/* 比如跳转到对比表 href="javascript:;" onclick="goTarget($('#compare'),140)" href="javascript:;" onclick="goTarget($('#compare'))" */
//count down
function cycleCountdown(){
var startTimestamp = MApp(2.2).datetime.getTimestamp('2013-11-27 22:17:00');
var datetime = MApp(2.2).datetime.getCycleCountdown(startTimestamp, 4);
d = MApp(2.2).packages.zeroize(datetime[0], 2);
h = MApp(2.2).packages.zeroize(datetime[1], 2);
i = MApp(2.2).packages.zeroize(datetime[2], 2);
s = MApp(2.2).packages.zeroize(datetime[3], 2);
mi = MApp(2.2).packages.zeroize(datetime[4], 3);
//mi = MApp(2.2).packages.zeroize(datetime[4], 3).substr(0,2); 截取两位数字
//写法一
//$("#counttime li").eq(0).html(h).end().eq(1).html(i).end().eq(2).html(s).end().eq(3).html(mi);
//$("#floatlayer .right dd span").eq(0).html(h).end().eq(1).html(i).end().eq(2).html(s).end().eq(3).html(mi + "Ms");
//写法二
document.getElementById('countdown').innerHTML = '<li>'+h+'<span>Uur</span><span class="colon">:</span>'+'</li><li>'+ i+'<span>Min</span><span class="colon">:</span>'+'</li><li>'+ s+'<span>Sec</span><span class="colon">:</span>'+'</li><li class="last">'+ mi+'</li>'+'<li><sup>*</sup></li>';
//setTimeout('cycleCountdown()', 1);
setTimeout('cycleCountdown()', 1);
}
cycleCountdown();
//以小数点来间隔数字
function strFormat(str) {
return str.replace(/,/g, '.');
}
$(function() {
$('.buy-num').html(strFormat($('.buy-num').html()));
});
</script>
</body>
</html> | mit |
ministryofjustice/apvs-internal-web | test/unit/services/domain/test-claim-deduction.js | 1422 | const ClaimDeduction = require('../../../../app/services/domain/claim-deduction')
const ValidationError = require('../../../../app/services/errors/validation-error')
const expect = require('chai').expect
const deductionTypeEnum = require('../../../../app/constants/deduction-type-enum')
let claimDeduction
describe('services/domain/claim-deduction', function () {
const VALID_DEDUCTION_TYPE = deductionTypeEnum.HC3_DEDUCTION
const VALID_AMOUNT = '10'
it('should construct a domain object given valid input', function () {
claimDeduction = new ClaimDeduction(VALID_DEDUCTION_TYPE, VALID_AMOUNT)
expect(claimDeduction.deductionType).to.equal(VALID_DEDUCTION_TYPE)
expect(claimDeduction.amount).to.equal(VALID_AMOUNT)
})
it('should return isRequired error for decision if deductionType is empty', function () {
try {
claimDeduction = new ClaimDeduction('', VALID_AMOUNT)
} catch (e) {
expect(e).to.be.instanceof(ValidationError)
expect(e.validationErrors.deductionType[0]).to.equal('A deduction type is required')
}
})
it('should return isRequired error for decision if amount is empty or zero', function () {
try {
claimDeduction = new ClaimDeduction(VALID_DEDUCTION_TYPE, '')
} catch (e) {
expect(e).to.be.instanceof(ValidationError)
expect(e.validationErrors.deductionAmount[0]).to.equal('A deduction amount is required')
}
})
})
| mit |
kamalmahmudi/sia | src/main/java/id/ac/itb/model/PengaturanSemester.java | 9240 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package id.ac.itb.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author billysusanto
*/
@Entity
@Table(name = "pengaturan_semester")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "PengaturanSemester.findAll", query = "SELECT p FROM PengaturanSemester p"),
@NamedQuery(name = "PengaturanSemester.findByIdSemester", query = "SELECT p FROM PengaturanSemester p WHERE p.idSemester = :idSemester"),
@NamedQuery(name = "PengaturanSemester.findByTglAwalBukaKelas", query = "SELECT p FROM PengaturanSemester p WHERE p.tglAwalBukaKelas = :tglAwalBukaKelas"),
@NamedQuery(name = "PengaturanSemester.findByTglAkhirBukaKelas", query = "SELECT p FROM PengaturanSemester p WHERE p.tglAkhirBukaKelas = :tglAkhirBukaKelas"),
@NamedQuery(name = "PengaturanSemester.findByTglAwalFrs", query = "SELECT p FROM PengaturanSemester p WHERE p.tglAwalFrs = :tglAwalFrs"),
@NamedQuery(name = "PengaturanSemester.findByTglAkhirFrs", query = "SELECT p FROM PengaturanSemester p WHERE p.tglAkhirFrs = :tglAkhirFrs"),
@NamedQuery(name = "PengaturanSemester.findByTglAwalPrs", query = "SELECT p FROM PengaturanSemester p WHERE p.tglAwalPrs = :tglAwalPrs"),
@NamedQuery(name = "PengaturanSemester.findByTglAkhirPrs", query = "SELECT p FROM PengaturanSemester p WHERE p.tglAkhirPrs = :tglAkhirPrs"),
@NamedQuery(name = "PengaturanSemester.findByTglAwalInputNilai", query = "SELECT p FROM PengaturanSemester p WHERE p.tglAwalInputNilai = :tglAwalInputNilai"),
@NamedQuery(name = "PengaturanSemester.findByTglAkhirInputNilai", query = "SELECT p FROM PengaturanSemester p WHERE p.tglAkhirInputNilai = :tglAkhirInputNilai"),
@NamedQuery(name = "PengaturanSemester.findByCreatedBy", query = "SELECT p FROM PengaturanSemester p WHERE p.createdBy = :createdBy"),
@NamedQuery(name = "PengaturanSemester.findByCreatedAt", query = "SELECT p FROM PengaturanSemester p WHERE p.createdAt = :createdAt"),
@NamedQuery(name = "PengaturanSemester.findByUpdatedBy", query = "SELECT p FROM PengaturanSemester p WHERE p.updatedBy = :updatedBy"),
@NamedQuery(name = "PengaturanSemester.findByUpdatedAt", query = "SELECT p FROM PengaturanSemester p WHERE p.updatedAt = :updatedAt")})
public class PengaturanSemester extends AbstractModel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id_semester")
private Integer idSemester;
@Basic(optional = false)
@NotNull
@Column(name = "tgl_awal_buka_kelas")
@Temporal(TemporalType.DATE)
private Date tglAwalBukaKelas;
@Basic(optional = false)
@NotNull
@Column(name = "tgl_akhir_buka_kelas")
@Temporal(TemporalType.DATE)
private Date tglAkhirBukaKelas;
@Basic(optional = false)
@NotNull
@Column(name = "tgl_awal_frs")
@Temporal(TemporalType.DATE)
private Date tglAwalFrs;
@Basic(optional = false)
@NotNull
@Column(name = "tgl_akhir_frs")
@Temporal(TemporalType.DATE)
private Date tglAkhirFrs;
@Basic(optional = false)
@NotNull
@Column(name = "tgl_awal_prs")
@Temporal(TemporalType.DATE)
private Date tglAwalPrs;
@Basic(optional = false)
@NotNull
@Column(name = "tgl_akhir_prs")
@Temporal(TemporalType.DATE)
private Date tglAkhirPrs;
@Basic(optional = false)
@NotNull
@Column(name = "tgl_awal_input_nilai")
@Temporal(TemporalType.DATE)
private Date tglAwalInputNilai;
@Basic(optional = false)
@NotNull
@Column(name = "tgl_akhir_input_nilai")
@Temporal(TemporalType.DATE)
private Date tglAkhirInputNilai;
@Basic(optional = false)
@NotNull
@Column(name = "created_by")
private int createdBy;
@Basic(optional = false)
@NotNull
@Column(name = "created_at")
@Temporal(TemporalType.DATE)
private Date createdAt;
@Column(name = "updated_by")
private Integer updatedBy;
@Column(name = "updated_at")
@Temporal(TemporalType.DATE)
private Date updatedAt;
public PengaturanSemester() {
}
public PengaturanSemester(Integer idSemester) {
this.idSemester = idSemester;
}
public PengaturanSemester(Integer idSemester, Date tglAwalBukaKelas, Date tglAkhirBukaKelas, Date tglAwalFrs, Date tglAkhirFrs, Date tglAwalPrs, Date tglAkhirPrs, Date tglAwalInputNilai, Date tglAkhirInputNilai, int createdBy, Date createdAt) {
this.idSemester = idSemester;
this.tglAwalBukaKelas = tglAwalBukaKelas;
this.tglAkhirBukaKelas = tglAkhirBukaKelas;
this.tglAwalFrs = tglAwalFrs;
this.tglAkhirFrs = tglAkhirFrs;
this.tglAwalPrs = tglAwalPrs;
this.tglAkhirPrs = tglAkhirPrs;
this.tglAwalInputNilai = tglAwalInputNilai;
this.tglAkhirInputNilai = tglAkhirInputNilai;
this.createdBy = createdBy;
this.createdAt = createdAt;
}
public Integer getIdSemester() {
return idSemester;
}
public void setIdSemester(Integer idSemester) {
this.idSemester = idSemester;
}
public Date getTglAwalBukaKelas() {
return tglAwalBukaKelas;
}
public void setTglAwalBukaKelas(Date tglAwalBukaKelas) {
this.tglAwalBukaKelas = tglAwalBukaKelas;
}
public Date getTglAkhirBukaKelas() {
return tglAkhirBukaKelas;
}
public void setTglAkhirBukaKelas(Date tglAkhirBukaKelas) {
this.tglAkhirBukaKelas = tglAkhirBukaKelas;
}
public Date getTglAwalFrs() {
return tglAwalFrs;
}
public void setTglAwalFrs(Date tglAwalFrs) {
this.tglAwalFrs = tglAwalFrs;
}
public Date getTglAkhirFrs() {
return tglAkhirFrs;
}
public void setTglAkhirFrs(Date tglAkhirFrs) {
this.tglAkhirFrs = tglAkhirFrs;
}
public Date getTglAwalPrs() {
return tglAwalPrs;
}
public void setTglAwalPrs(Date tglAwalPrs) {
this.tglAwalPrs = tglAwalPrs;
}
public Date getTglAkhirPrs() {
return tglAkhirPrs;
}
public void setTglAkhirPrs(Date tglAkhirPrs) {
this.tglAkhirPrs = tglAkhirPrs;
}
public Date getTglAwalInputNilai() {
return tglAwalInputNilai;
}
public void setTglAwalInputNilai(Date tglAwalInputNilai) {
this.tglAwalInputNilai = tglAwalInputNilai;
}
public Date getTglAkhirInputNilai() {
return tglAkhirInputNilai;
}
public void setTglAkhirInputNilai(Date tglAkhirInputNilai) {
this.tglAkhirInputNilai = tglAkhirInputNilai;
}
public int getCreatedBy() {
return createdBy;
}
public void setCreatedBy(int createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Integer getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(Integer updatedBy) {
this.updatedBy = updatedBy;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idSemester != null ? idSemester.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PengaturanSemester)) {
return false;
}
PengaturanSemester other = (PengaturanSemester) object;
if ((this.idSemester == null && other.idSemester != null) || (this.idSemester != null && !this.idSemester.equals(other.idSemester))) {
return false;
}
return true;
}
@Override
public String toString() {
return "id.ac.itb.model.PengaturanSemester[ idSemester=" + idSemester + " ]";
}
@Override
@JsonIgnore
public String getName() {
return "" + this.idSemester;
}
@Override
@JsonIgnore
public String getPkUrl() {
return "" + this.idSemester;
}
}
| mit |
ljharb/node-comments | test/samples/2.multi.js | 143 | /* nested multiline comment /**
here is a line with tabs
here is a line with spaces
*/ var hereIsAVar = 7; /* and a single line comment */
| mit |
EvgenyOrekhov/Clean-Feed-for-VK.com | src/popup.js | 2581 | import { init } from "actus";
import defaultActions from "actus-default-actions";
import defaultSettings from "./defaultSettings.json";
function addClickHandlers(actions) {
const map = {
"is-disabled": actions["is-disabled"].toggle,
groups: actions.toggleGroups,
mygroups: actions.mygroups.toggle,
people: actions.people.toggle,
external_links: actions.toggleExternalLinks,
links: actions.links.toggle,
apps: actions.apps.toggle,
instagram: actions.instagram.toggle,
video: actions.video.toggle,
group_share: actions.group_share.toggle,
mem_link: actions.mem_link.toggle,
event_share: actions.event_share.toggle,
wall_post_more: actions.wall_post_more.toggle,
likes: actions.likes.toggle,
comments: actions.comments.toggle,
};
Object.entries(map).forEach(([name, action]) => {
document.querySelector(`[name=${name}]`).addEventListener("click", action);
});
}
const actions = {
toggleGroups: (ignore, state) => ({
...state,
groups: !state.groups,
mygroups: false,
people: false,
}),
toggleExternalLinks: (ignore, state) => ({
...state,
external_links: !state.external_links,
links: false,
}),
};
/* eslint-disable fp/no-mutation, no-param-reassign */
function updatePage({ state: settings }) {
const checkboxes = document.querySelectorAll("input");
checkboxes.forEach((checkbox) => {
checkbox.checked = settings[checkbox.name];
if (checkbox.name !== "is-disabled") {
checkbox.disabled = settings["is-disabled"];
}
});
document
.querySelector("#mygroups-label")
.classList.toggle("hidden", !settings.groups);
document
.querySelector("#people-label")
.classList.toggle("hidden", !settings.groups);
document
.querySelector("#links-label")
.classList.toggle("hidden", settings.external_links);
}
/* eslint-enable fp/no-mutation, no-param-reassign */
function saveSettings({ state: settings }) {
chrome.storage.sync.set(settings);
}
function applySettings({ state: settings }) {
chrome.tabs.query(
{
currentWindow: true,
active: true,
},
function sendMessage([tab]) {
chrome.runtime.sendMessage({
tabId: tab.id,
action: "execute",
settings,
});
}
);
}
chrome.storage.sync.get((settings) => {
const boundActions = init([
defaultActions(defaultSettings),
{
state: { ...defaultSettings, ...settings },
actions,
subscribers: [updatePage, saveSettings, applySettings],
},
]);
addClickHandlers(boundActions);
});
| mit |
shepherdwind/css-hot-loader | examples/ts-example/webpack.config.js | 2312 | const webpack = require('webpack'); // webpack itself
const path = require('path'); // nodejs dependency when dealing with paths
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const tslintConfig = require('./tslint.json');
const AutoPrefixer = require('autoprefixer');
let config = { // config object
mode: 'development',
entry: {
output: './src/App.ts', // entry file
},
output: { // output
path: path.resolve(__dirname, 'dist'), // ouput path
filename: '[name].js',
},
module: {
rules: [
{
test : /\.ts$/,
exclude : /(node_modules|Gulptasks)/,
enforce : 'pre',
use : [
{
loader : 'ts-loader',
options : {
transpileOnly : true
}
},
{
loader : `tslint-loader`,
options : tslintConfig
}
]
},
{
test : /\.(css|sass|scss)$/,
exclude : /node_modules/,
use : [
'css-hot-loader',
MiniCssExtractPlugin.loader,
{
loader : 'css-loader',
options : {
constLoaders : 1,
minimize : true
}
},
{
loader : 'clean-css-loader',
options : {
compatibility : 'ie8',
debug : true,
level : {
2 : {
all : true
}
}
}
},
{
loader : 'postcss-loader',
options : {
plugins : loader => [
AutoPrefixer({
browsers : ['last 2 versions'],
cascade : false
})
]
}
},
{
loader : 'fast-sass-loader',
options : {
includePaths : [
'node_modules',
'src',
]
}
}
]
},
] // end rules
},
plugins: [ // webpack plugins
new MiniCssExtractPlugin('[name].css'),
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
hot: true,
},
devtool: 'eval-source-map', // enable devtool for better debugging experience
}
module.exports = config;
| mit |
rickdberg/database | odp_data_age_depth.py | 1287 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 5 16:14:54 2016
@author: rickdberg
# File loader to create table in MySQL database with original headers from single csv file
"""
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
# Connect to database
engine = create_engine("mysql://root:neogene227@localhost/iodp_compiled")
table = 'age_depth'
##### File group info #####
filename = 'age_depth_101_190.txt'
site_table = 'site_info'
data = pd.read_csv(r'C:\Users\rickdberg\Documents\UW Projects\Magnesium uptake\Data\100-312\Original files\{}'.format(filename), sep="\t", header=0, skiprows=None, encoding='windows-1252')
data.columns = ('leg', 'site', 'hole', 'source', 'depth', 'age', 'type')
data['age'] = np.multiply(data['age'], 1000000)
data = data.applymap(str)
data = data.loc[:,['leg', 'site', 'hole', 'depth', 'age', 'type', 'source']]
sql = """SELECT distinct site_key, site FROM {}; """.format(site_table)
site_keys = pd.read_sql(sql, engine)
full_data = pd.merge(site_keys, data, how = 'inner', on = ['site'])
full_data = full_data.loc[:,['site_key', 'leg', 'site', 'hole', 'depth', 'age', 'type', 'source']]
### Send to database and autoincrement age_depth_key
full_data.to_sql(table, con=engine, if_exists = 'append', index=False)
# eof
| mit |
davidakachaos/little-tw-helper | units/ram.rb | 291 | # Represents a ram
class Ram < Unit
WOOD = 300
CLAY = 200
IRON = 200
POPULATION = 5
ATTACK = 2
DEF_INF = 20
DEF_HORSE = 50
DEF_ARCH = 20
SPEED = 30
CARRY = 0
BUILD_REQ = { workshop: 1 }
def building_time_factor
village.buildings[:workshop].time_factor
end
end
| mit |
chaddanna/d1-baseball | conference-overview.php | 22332 | <?php require 'header.php'; ?>
<div id="wrap" class="container conference-overview">
<div class="player-header">
<div class="team-logo pull-left">
<img src="img/sec-logo.png" alt="" data-rjs="2">
</div>
<div class="team-header-left">
<h1 class="team-title">Southeastern Conference</h1>
<select name="team" class="mobile-hidden">
<option value="lsu">Conferences</option>
</select>
</div>
<div class=" pull-right">
<div class="score-board pull-right">
<section class="title">
Conference Ratings
</section>
<div class="rpi"><span>RPI</span>2</div>
<div class="epi"><span>EPI</span>2</div>
<div class="elo"><span>ELO</span>2</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<?php require 'sidebar.php'; ?>
<main>
<div class="content">
<section class="data-table">
<section class="filters">
<h3>Conference Standings</h3>
</section>
<div class="table-group">
<h4>Eastern Division</h4>
<table>
<thead>
<tr>
<td>Team</td>
<td>Record</td>
<td>Win %</td>
<td>Overall</td>
<td>Overall %</td>
<td>RPI</td>
<td>vs RPI Top 50</td>
</tr>
</thead>
<tbody>
<tr>
<td class="team"><a href="#"><img src="img/team-logos/southcarolina-logo.png" alt="" data-rjs="2"/> South Carolina</a></td>
<td>20-9</td>
<td>.690</td>
<td>46-18</td>
<td>.719</td>
<td>13</td>
<td>12-14</td>
</tr>
<tr>
<td class="team"><a href="#"><img src="img/team-logos/southcarolina-logo.png" alt="" data-rjs="2"/> South Carolina</a></td>
<td>20-9</td>
<td>.690</td>
<td>46-18</td>
<td>.719</td>
<td>13</td>
<td>12-14</td>
</tr>
<tr>
<td class="team"><a href="#"><img src="img/team-logos/southcarolina-logo.png" alt="" data-rjs="2"/> South Carolina</a></td>
<td>20-9</td>
<td>.690</td>
<td>46-18</td>
<td>.719</td>
<td>13</td>
<td>12-14</td>
</tr>
<tr>
<td class="team"><a href="#"><img src="img/team-logos/southcarolina-logo.png" alt="" data-rjs="2"/> South Carolina</a></td>
<td>20-9</td>
<td>.690</td>
<td>46-18</td>
<td>.719</td>
<td>13</td>
<td>12-14</td>
</tr>
</tbody>
</table>
</div>
<div class="table-group">
<h4>Western Division</h4>
<table>
<thead>
<tr>
<td>Team</td>
<td>Record</td>
<td>Win %</td>
<td>Overall</td>
<td>Overall %</td>
<td>RPI</td>
<td>vs RPI Top 50</td>
</tr>
</thead>
<tbody>
<tr>
<td class="team"><a href="#"><img src="img/team-logos/southcarolina-logo.png" alt="" data-rjs="2"/> South Carolina</a></td>
<td>20-9</td>
<td>.690</td>
<td>46-18</td>
<td>.719</td>
<td>13</td>
<td>12-14</td>
</tr>
<tr>
<td class="team"><a href="#"><img src="img/team-logos/southcarolina-logo.png" alt="" data-rjs="2"/> South Carolina</a></td>
<td>20-9</td>
<td>.690</td>
<td>46-18</td>
<td>.719</td>
<td>13</td>
<td>12-14</td>
</tr>
<tr>
<td class="team"><a href="#"><img src="img/team-logos/southcarolina-logo.png" alt="" data-rjs="2"/> South Carolina</a></td>
<td>20-9</td>
<td>.690</td>
<td>46-18</td>
<td>.719</td>
<td>13</td>
<td>12-14</td>
</tr>
<tr>
<td class="team"><a href="#"><img src="img/team-logos/southcarolina-logo.png" alt="" data-rjs="2"/> South Carolina</a></td>
<td>20-9</td>
<td>.690</td>
<td>46-18</td>
<td>.719</td>
<td>13</td>
<td>12-14</td>
</tr>
</tbody>
</table>
</div>
</section>
<section class="data-table score-set">
<div class="filters clearfix">
<h3>Today's Schedule</h3>
<div class="pull-right"><a href="#">Full Schedule</a></div>
</div>
<div class="row clearfix">
<div class="score-set-item pull-left half">
<div>
<table>
<thead>
<tr>
<td>FRIDAY, AUGUST 5</td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20LSUSEC.png" alt=""/> 8 LSU</td>
<td>8:00 PM</td>
</tr>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20AlabamaSEC.png" alt=""/> Alabama</td>
<td></td>
</tr>
</tbody>
</table>
<div class="footer clearfix">
<div class="pull-left">
<a href="#">Preview</a>
</div>
<div class="pull-right">
<a href="#">SECN</a>
</div>
</div>
</div>
</div>
<div class="score-set-item pull-left half">
<div>
<table>
<thead>
<tr>
<td>FRIDAY, AUGUST 5</td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20LSUSEC.png" alt=""/> 8 LSU</td>
<td>8:00 PM</td>
</tr>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20AlabamaSEC.png" alt=""/> Alabama</td>
<td></td>
</tr>
</tbody>
</table>
<div class="footer clearfix">
<div class="pull-left">
<a href="#">Preview</a>
</div>
<div class="pull-right">
<a href="#">SECN</a>
</div>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="score-set-item pull-left half">
<div>
<table>
<thead>
<tr>
<td>FRIDAY, AUGUST 5</td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20LSUSEC.png" alt=""/> 8 LSU</td>
<td>8:00 PM</td>
</tr>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20AlabamaSEC.png" alt=""/> Alabama</td>
<td></td>
</tr>
</tbody>
</table>
<div class="footer clearfix">
<div class="pull-left">
<a href="#">Preview</a>
</div>
<div class="pull-right">
<a href="#">SECN</a>
</div>
</div>
</div>
</div>
<div class="score-set-item pull-left half">
<div>
<table>
<thead>
<tr>
<td>FRIDAY, AUGUST 5</td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20LSUSEC.png" alt=""/> 8 LSU</td>
<td>8:00 PM</td>
</tr>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20AlabamaSEC.png" alt=""/> Alabama</td>
<td></td>
</tr>
</tbody>
</table>
<div class="footer clearfix">
<div class="pull-left">
<a href="#">Preview</a>
</div>
<div class="pull-right">
<a href="#">SECN</a>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="data-table score-set">
<div class="filters clearfix">
<h3>Yesterday's Schedule</h3>
</div>
<div class="row clearfix">
<div class="score-set-item pull-left half">
<div>
<table>
<thead>
<tr>
<td>FRIDAY, AUGUST 5</td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20LSUSEC.png" alt=""/> 8 LSU</td>
<td>8:00 PM</td>
</tr>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20AlabamaSEC.png" alt=""/> Alabama</td>
<td></td>
</tr>
</tbody>
</table>
<div class="footer clearfix">
<div class="pull-left">
<a href="#">Preview</a>
</div>
<div class="pull-right">
<a href="#">SECN</a>
</div>
</div>
</div>
</div>
<div class="score-set-item pull-left half">
<div>
<table>
<thead>
<tr>
<td>FRIDAY, AUGUST 5</td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20LSUSEC.png" alt=""/> 8 LSU</td>
<td>8:00 PM</td>
</tr>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20AlabamaSEC.png" alt=""/> Alabama</td>
<td></td>
</tr>
</tbody>
</table>
<div class="footer clearfix">
<div class="pull-left">
<a href="#">Preview</a>
</div>
<div class="pull-right">
<a href="#">SECN</a>
</div>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="score-set-item pull-left half">
<div>
<table>
<thead>
<tr>
<td>FRIDAY, AUGUST 5</td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20LSUSEC.png" alt=""/> 8 LSU</td>
<td>8:00 PM</td>
</tr>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20AlabamaSEC.png" alt=""/> Alabama</td>
<td></td>
</tr>
</tbody>
</table>
<div class="footer clearfix">
<div class="pull-left">
<a href="#">Preview</a>
</div>
<div class="pull-right">
<a href="#">SECN</a>
</div>
</div>
</div>
</div>
<div class="score-set-item pull-left half">
<div>
<table>
<thead>
<tr>
<td>FRIDAY, AUGUST 5</td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20LSUSEC.png" alt=""/> 8 LSU</td>
<td>8:00 PM</td>
</tr>
<tr>
<td>
<img src="img/team-logos/Kendall%20Rogers%20-%20AlabamaSEC.png" alt=""/> Alabama</td>
<td></td>
</tr>
</tbody>
</table>
<div class="footer clearfix">
<div class="pull-left">
<a href="#">Preview</a>
</div>
<div class="pull-right">
<a href="#">SECN</a>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="data-table">
<h3>South Conference Leaders</h3>
<div class="clearfix row">
<div class="half pull-left">
<div>
<table>
<thead>
<tr>
<td></td>
<td>Player</td>
<td>Batting Average</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>2</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>3</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="half pull-left">
<div>
<table>
<thead>
<tr>
<td></td>
<td>Player</td>
<td>Homeruns</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="clearfix row">
<div class="half pull-left">
<div>
<table>
<thead>
<tr>
<td></td>
<td>Player</td>
<td>Batting Average</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>2</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>3</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="half pull-left">
<div>
<table>
<thead>
<tr>
<td></td>
<td>Player</td>
<td>Homeruns</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="clearfix row">
<div class="half pull-left">
<div>
<table>
<thead>
<tr>
<td></td>
<td>Player</td>
<td>Batting Average</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>2</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>3</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="half pull-left">
<div>
<table>
<thead>
<tr>
<td></td>
<td>Player</td>
<td>Homeruns</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
<tr>
<td>1</td>
<td><a href="#">Ryan Scott, UALR</a></td>
<td>.435</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>
<section class="more-stories data-table">
<div class="filters">
<h3>Southeastern Conference Headlines</h3>
</div>
<div class="more-stories-item clearfix row">
<figure>
<a href="#"><img src="img/more-stories1.png" alt="" data-rjs="2"/></a>
</figure>
<div class="stories-content">
<a href="#"><h3>Stat Roundup: March 15 Top Performers</h3></a>
<span>D1 Baseball Staff - March 15, 2016</span>
<p>
Bobby Dalbec homered twice and earned the save to lead Arizona past New Mexico, headlining the Tuesday individual leaderboard.
</p>
</div>
</div>
<div class="more-stories-item clearfix row">
<figure>
<a href="#"><img src="img/more-stories2.png" alt="" data-rjs="2"/></a>
</figure>
<div class="stories-content">
<a href="#"><h3>Sorenson: Super Tuesday Winners & Losers</h3></a>
<span>Eric Sorenson - March 15, 2016</span>
<p>
With a lot of nearby rivals facing each other, Super Tuesday in college baseball was a hard fought battle of familiar foes on the diamond.
</p>
</div>
</div>
<div class="more-stories-item clearfix row">
<figure>
<a href="#"><img src="img/more-stories3.png" alt="" data-rjs="2"/></a>
</figure>
<div class="stories-content">
<a href="#"><h3>GSA Spotlight: Virginia’s Matt Thaiss</h3></a>
<span>Aaron Fitt - March 15, 2016</span>
<p>
Matt Thaiss is the emotional leader for the reigning national champion Cavaliers, and he's worked hard to become one of the best all-around catchers in college baseball.
</p>
</div>
</div>
<div class="more-stories-item clearfix row">
<figure>
<a href="#"><img src="img/more-stories4.png" alt="" data-rjs="2"/></a>
</figure>
<div class="stories-content">
<a href="#"><h3>Week 4 Power Rankings: Relief Pitchers</h3></a>
<span>D1 Baseball Staff - March 15, 2016</span>
<p>
Ryan Hendrix has been dominant over the first month for Texas A&M, moving him to the top of our power rankings for relievers.
</p>
</div>
</div>
<div class="button-container">
<a href="#" class="read-more">Read More</a>
</div>
</section>
</div>
</main>
<div class="clearfix"></div>
</div>
<?php require 'footer.php'; ?>
| mit |
kostyakch/rhino | src/Application/BackBundle/Controller/HelpController.php | 271 | <?php
namespace Application\BackBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class HelpController extends Controller {
public function indexAction($folder='content') {
return $this->render('BackBundle:Help:index.html.twig');
}
}
| mit |
ccpgames/eve-metrics | web2py/gluon/contrib/login_methods/gae_google_account.py | 1069 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of web2py Web Framework (Copyrighted, 2007-2009).
Developed by Massimo Di Pierro <[email protected]>.
License: GPL v2
Thanks to Hans Donner <[email protected]> for GaeGoogleAccount.
"""
from google.appengine.api import users
class GaeGoogleAccount(object):
"""
Login will be done via Google's Appengine login object, instead of web2py's
login form.
Include in your model (eg db.py)::
from gluon.contrib.login_methods.gae_google_account import \
GaeGoogleAccount
auth.settings.login_form=GaeGoogleAccount()
"""
def login_url(self, next="/"):
return users.create_login_url(next)
def logout_url(self, next="/"):
return users.create_logout_url(next)
def get_user(self):
user = users.get_current_user()
if user:
return dict(nickname=user.nickname(), email=user.email(),
user_id=user.user_id(), source="google account")
| mit |
kalinmarkov/SoftUni | JS Core/JS Fundamentals/02. Lab - Control-Flow Logic/8. Fruit or Vegetable.js | 511 | function food(word) {
switch (word) {
case 'banana':
case 'apple':
case 'kiwi':
case 'cherry':
case 'lemon':
case 'grapes':
case 'peach':
console.log('fruit');
break;
case 'tomato':
case 'cucumber':
case 'pepper':
case 'onion':
case 'parsley':
case 'garlic':
console.log('vegetable');
break;
default:
console.log('unknown');
}
}
| mit |
ScreenBasedSimulator/ScreenBasedSimulator2 | src/main/java/mil/tatrc/physiology/datamodel/bind/CircuitCalculatorData.java | 1184 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.12.09 at 06:16:52 PM EST
//
package mil.tatrc.physiology.datamodel.bind;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CircuitCalculatorData complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="CircuitCalculatorData">
* <complexContent>
* <extension base="{uri:/mil/tatrc/physiology/datamodel}ObjectData">
* <sequence>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CircuitCalculatorData")
public class CircuitCalculatorData
extends ObjectData
{
}
| mit |
madeso/prettygood | dotnet/Tagger/AutoTagger.Designer.py | 9616 | namespace Tagger
{
partial class AutoTagger
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dTags = new BrightIdeasSoftware.FastObjectListView();
this.dFileName = new System.Windows.Forms.TextBox();
this.olvcArtist = new BrightIdeasSoftware.OLVColumn();
this.olvcTitle = new BrightIdeasSoftware.OLVColumn();
this.olvcAlbum = new BrightIdeasSoftware.OLVColumn();
this.olvcTrackNumber = new BrightIdeasSoftware.OLVColumn();
this.olvcGenre = new BrightIdeasSoftware.OLVColumn();
this.olvcYear = new BrightIdeasSoftware.OLVColumn();
this.olvcComments = new BrightIdeasSoftware.OLVColumn();
this.olvcIsCover = new BrightIdeasSoftware.OLVColumn();
this.olvcIsRemix = new BrightIdeasSoftware.OLVColumn();
this.olvcTotalTracks = new BrightIdeasSoftware.OLVColumn();
this.olvcScore = new BrightIdeasSoftware.OLVColumn();
this.olvcPattern = new BrightIdeasSoftware.OLVColumn();
this.dIncludeInvalid = new System.Windows.Forms.CheckBox();
this.olvcMessage = new BrightIdeasSoftware.OLVColumn();
((System.ComponentModel.ISupportInitialize)(this.dTags)).BeginInit();
this.SuspendLayout();
//
// dTags
//
this.dTags.AllColumns.Add(this.olvcTrackNumber);
this.dTags.AllColumns.Add(this.olvcArtist);
this.dTags.AllColumns.Add(this.olvcTitle);
this.dTags.AllColumns.Add(this.olvcAlbum);
this.dTags.AllColumns.Add(this.olvcTotalTracks);
this.dTags.AllColumns.Add(this.olvcPattern);
this.dTags.AllColumns.Add(this.olvcScore);
this.dTags.AllColumns.Add(this.olvcGenre);
this.dTags.AllColumns.Add(this.olvcYear);
this.dTags.AllColumns.Add(this.olvcMessage);
this.dTags.AllColumns.Add(this.olvcComments);
this.dTags.AllColumns.Add(this.olvcIsCover);
this.dTags.AllColumns.Add(this.olvcIsRemix);
this.dTags.AllowColumnReorder = true;
this.dTags.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dTags.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.F2Only;
this.dTags.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvcTrackNumber,
this.olvcArtist,
this.olvcTitle,
this.olvcAlbum,
this.olvcTotalTracks,
this.olvcPattern,
this.olvcScore,
this.olvcGenre,
this.olvcYear,
this.olvcMessage,
this.olvcComments,
this.olvcIsCover,
this.olvcIsRemix});
this.dTags.FullRowSelect = true;
this.dTags.Location = new System.Drawing.Point(12, 38);
this.dTags.Name = "dTags";
this.dTags.ShowGroups = false;
this.dTags.Size = new System.Drawing.Size(859, 242);
this.dTags.TabIndex = 0;
this.dTags.UseAlternatingBackColors = true;
this.dTags.UseCompatibleStateImageBehavior = false;
this.dTags.View = System.Windows.Forms.View.Details;
this.dTags.VirtualMode = true;
this.dTags.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.dTags_MouseDoubleClick);
//
// dFileName
//
this.dFileName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dFileName.Location = new System.Drawing.Point(103, 12);
this.dFileName.Name = "dFileName";
this.dFileName.ReadOnly = true;
this.dFileName.Size = new System.Drawing.Size(768, 20);
this.dFileName.TabIndex = 1;
//
// olvcArtist
//
this.olvcArtist.AspectName = "tag.Artist";
this.olvcArtist.Text = "Artist";
//
// olvcTitle
//
this.olvcTitle.AspectName = "tag.Title";
this.olvcTitle.Text = "Title";
//
// olvcAlbum
//
this.olvcAlbum.AspectName = "tag.Album";
this.olvcAlbum.Text = "Album";
//
// olvcTrackNumber
//
this.olvcTrackNumber.AspectName = "tag.TrackNumber";
this.olvcTrackNumber.Text = "#";
//
// olvcGenre
//
this.olvcGenre.AspectName = "tag.Genre";
this.olvcGenre.Text = "Genre";
//
// olvcYear
//
this.olvcYear.AspectName = "tag.Year";
this.olvcYear.Text = "Year";
//
// olvcComments
//
this.olvcComments.AspectName = "tag.Comments";
this.olvcComments.Text = "Comments";
this.olvcComments.Width = 127;
//
// olvcIsCover
//
this.olvcIsCover.AspectName = "tag.IsCover";
this.olvcIsCover.Text = "cover?";
//
// olvcIsRemix
//
this.olvcIsRemix.AspectName = "tag.IsRemix";
this.olvcIsRemix.Text = "remix?";
//
// olvcTotalTracks
//
this.olvcTotalTracks.AspectName = "tag.TotalTracks";
this.olvcTotalTracks.Text = "Total tracks";
this.olvcTotalTracks.Width = 88;
//
// olvcScore
//
this.olvcScore.AspectName = "Score";
this.olvcScore.IsEditable = false;
this.olvcScore.Text = "Score";
this.olvcScore.Width = 48;
//
// olvcPattern
//
this.olvcPattern.AspectName = "extractor.logic";
this.olvcPattern.IsEditable = false;
this.olvcPattern.Text = "Pattern";
//
// dIncludeInvalid
//
this.dIncludeInvalid.AutoSize = true;
this.dIncludeInvalid.Location = new System.Drawing.Point(12, 14);
this.dIncludeInvalid.Name = "dIncludeInvalid";
this.dIncludeInvalid.Size = new System.Drawing.Size(85, 17);
this.dIncludeInvalid.TabIndex = 2;
this.dIncludeInvalid.Text = "Also invalid?";
this.dIncludeInvalid.UseVisualStyleBackColor = true;
this.dIncludeInvalid.CheckedChanged += new System.EventHandler(this.dIncludeInvalid_CheckedChanged);
//
// olvcMessage
//
this.olvcMessage.AspectName = "Message";
this.olvcMessage.Text = "Message";
this.olvcMessage.Width = 99;
//
// AutoTagger
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(883, 292);
this.Controls.Add(this.dIncludeInvalid);
this.Controls.Add(this.dFileName);
this.Controls.Add(this.dTags);
this.Name = "AutoTagger";
this.Text = "AutoTagger";
((System.ComponentModel.ISupportInitialize)(this.dTags)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private BrightIdeasSoftware.FastObjectListView dTags;
private System.Windows.Forms.TextBox dFileName;
private BrightIdeasSoftware.OLVColumn olvcArtist;
private BrightIdeasSoftware.OLVColumn olvcTitle;
private BrightIdeasSoftware.OLVColumn olvcAlbum;
private BrightIdeasSoftware.OLVColumn olvcTrackNumber;
private BrightIdeasSoftware.OLVColumn olvcGenre;
private BrightIdeasSoftware.OLVColumn olvcYear;
private BrightIdeasSoftware.OLVColumn olvcComments;
private BrightIdeasSoftware.OLVColumn olvcIsCover;
private BrightIdeasSoftware.OLVColumn olvcIsRemix;
private BrightIdeasSoftware.OLVColumn olvcTotalTracks;
private BrightIdeasSoftware.OLVColumn olvcScore;
private BrightIdeasSoftware.OLVColumn olvcPattern;
private System.Windows.Forms.CheckBox dIncludeInvalid;
private BrightIdeasSoftware.OLVColumn olvcMessage;
}
} | mit |
ISO-tech/sw-d8 | web/2005-2/549/549_13_CinderellaMan.php | 6313 | <html>
<head>
<title>
Seabiscuit in boxing gloves
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>
</head>
<body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0">
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td>
<td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?>
</td></tr></table>
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="18" bgcolor="FFCC66"></td>
<td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td>
<td width="18"></td>
<td width="480" valign="top">
<?php include "../../legacy-includes/BodyInsert.htmlf" ?>
<font face="Times New Roman, Times, serif" size="4"><i>Cinderella Man</i> movie doesn't cut it</font><br>
<font face="Times New Roman, Times, serif" size="5"><b>Seabiscuit in boxing gloves</b></font><p>
<font face="Times New Roman, Times, serif" size="2"><b>Review by Dave Zirin</b></font><font face="Arial, Helvetica, sans-serif" size="2"> | June 24, 2005 | Page 13</font><p>
<font face="Arial, Helvetica, sans-serif" size="2"><b><i>Cinderella Man,</b></i> directed by Ron Howard, starring Russell Crowe and Renée Zellweger.</font><p>
<font face="Times New Roman, Times, serif" size="3">"WHEN OUR country was on its knees, he brought America to his feet." So goes the tagline for Ron Howard's Depression-era boxing film <i>Cinderella Man </i>starring Russell Crowe.<p>
<i>Cinderella Man </i>has been compared to <i>Seabiscuit, </i>both stories of plucky sports underdogs that triumphed during the Great Depression. The comparison is apt, and not just because Crowe's James J. Braddock mopes around with the same blank hangdog expression as that horse.<p>
Like the insipid Seabiscuit, the entire big budget biopic comes off as yet another Hollywood effort to sweeten the story of the 1930s. And like <i>Seabiscuit, Cinderella Man </i>sees the Depression as a time for beautifully photographed poverty, and, in the words of reviewer Jami Bernard, "good for teaching values."<p>
Beyond that, all one would learn from <i>Cinderella Man </i>is that the Great Depression was really depressing.<p>
In reality, the 1930s was a time of not only poverty but also mass resistance, as strikes swept the South and shut down the cities of San Francisco, Toledo, Ohio, and Minneapolis. It was a time when many of the reforms on the chopping block today, like Social Security, were won in struggle.<p>
It was a time when revolution in the U.S. was on the table as hundreds of thousands of people attempted to offer an alternative to the barbarisms of capitalism. As Depression-era sports writer Lester Rodney put it, "In the 1930s, if you weren't some kind of radical, Communist, socialist, or Trotskyist, you were considered brain-dead, and you probably were!"<p>
Just about everyone in <i>Cinderella Man </i>wears their brain-deadness like a medal of honor, passively enduring poverty as if they had just received red, white and blue lobotomies.<p>
The only hint of the other side of the Depression in <i>Cinderella Man </i>is Braddock's dockworker buddy Mike Wilson (played by Paddy Considine). Mike believes in the power of protest, but he's also portrayed as a drunk who gets the speech from his wife where she says, "You can save the world, but not your family!"<p>
Renée Zellweger, as Crowe's spouse Mae, complements Mike's wife, as the typical sexist sports-movie female character, fretting with every fight and being forced to say lines like, "You are the champion of my heart, James J. Braddock!"<p>
The film is also shamefully simplistic and even slanderous in its portrayal of the heavyweight champion at the time Max Baer. Baer was a hulking, brutal fighter who had two opponents die in the ring.<br>
But <i>Cinderella Man </i>reduces Baer to a one-dimensional stock villain, a perfect counterpart for Crowe's paper-thin stock hero. As played by Craig Bierko, Baer struts around with a psychotic gleam in his eye, as if he would enjoy nothing more than killing Braddock and spitting on his grave. In one scene, he looks at Mae and says, "Nice! Too bad she'll be a widow."<p>
In reality, Baer was devastated and nearly destroyed by the ring deaths that occurred at his hands, as any non-sociopath would be. <p>
Also, Baer was a complex figure who fought against the Nazi favorite Max Schmeling with a Star of David embroidered on his trunks. To see Howard's movie, one would think the only symbol Baer favored would be a pentagram.<p>
But the real tragedy of the film is its treatment of Braddock. Crowe does what he can with a terrible script, but it says everything about the film that it closes before the actual ending of Braddock's fight career, a 1937 8th round knockout at the hands of Joe Louis.<p>
Louis, the first African American heavyweight champ since Jack Johnson, was a symbol of hope for both African Americans and the left wing of the radicalizing working class.<p>
To have portrayed his fight with Braddock would have meant dealing with complex issues of how boxing, in a violent society, has acted as a deeply symbolic morality play about the ability of people--especially people of color--to succeed and stand triumphant.<p>
It would have meant trying to understand why some people who would have rooted for the underdog Braddock against Baer, would have bitterly opposed him against Louis.<p>
But the filmmakers could care less about these complicated dimensions of either the period or the sport. Their job in <i>Cinderella Man </i>is to take complex characters and turn them into stick figures, easily consumed and easily forgotten.<p>
At that task, they have succeeded admirably.<p>
[For people really interested in the James J. Braddock story, read the just-released Jeremy Schaap book also called <i>Cinderella Man‚ </i>and--blessedly--not connected to the film.]<p>
<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>
<td width="12"></td>
<td width="108" valign="top">
<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>
</td>
</tr>
</table>
</body>
</html>
| mit |
Azure/azure-sdk-for-python | sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2021_01_01/operations/_blob_services_operations.py | 13580 | # coding=utf-8
# --------------------------------------------------------------------------
# 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.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class BlobServicesOperations(object):
"""BlobServicesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.storage.v2021_01_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list(
self,
resource_group_name, # type: str
account_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.BlobServiceItems"]
"""List blob services of storage account. It returns a collection of one object named default.
:param resource_group_name: The name of the resource group within the user's subscription. The
name is case insensitive.
:type resource_group_name: str
:param account_name: The name of the storage account within the specified resource group.
Storage account names must be between 3 and 24 characters in length and use numbers and
lower-case letters only.
:type account_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either BlobServiceItems or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.storage.v2021_01_01.models.BlobServiceItems]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BlobServiceItems"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-01-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('BlobServiceItems', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices'} # type: ignore
def set_service_properties(
self,
resource_group_name, # type: str
account_name, # type: str
parameters, # type: "_models.BlobServiceProperties"
**kwargs # type: Any
):
# type: (...) -> "_models.BlobServiceProperties"
"""Sets the properties of a storage account’s Blob service, including properties for Storage
Analytics and CORS (Cross-Origin Resource Sharing) rules.
:param resource_group_name: The name of the resource group within the user's subscription. The
name is case insensitive.
:type resource_group_name: str
:param account_name: The name of the storage account within the specified resource group.
Storage account names must be between 3 and 24 characters in length and use numbers and
lower-case letters only.
:type account_name: str
:param parameters: The properties of a storage account’s Blob service, including properties for
Storage Analytics and CORS (Cross-Origin Resource Sharing) rules.
:type parameters: ~azure.mgmt.storage.v2021_01_01.models.BlobServiceProperties
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BlobServiceProperties, or the result of cls(response)
:rtype: ~azure.mgmt.storage.v2021_01_01.models.BlobServiceProperties
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BlobServiceProperties"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-01-01"
blob_services_name = "default"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.set_service_properties.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
'BlobServicesName': self._serialize.url("blob_services_name", blob_services_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'BlobServiceProperties')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('BlobServiceProperties', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
set_service_properties.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/{BlobServicesName}'} # type: ignore
def get_service_properties(
self,
resource_group_name, # type: str
account_name, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.BlobServiceProperties"
"""Gets the properties of a storage account’s Blob service, including properties for Storage
Analytics and CORS (Cross-Origin Resource Sharing) rules.
:param resource_group_name: The name of the resource group within the user's subscription. The
name is case insensitive.
:type resource_group_name: str
:param account_name: The name of the storage account within the specified resource group.
Storage account names must be between 3 and 24 characters in length and use numbers and
lower-case letters only.
:type account_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BlobServiceProperties, or the result of cls(response)
:rtype: ~azure.mgmt.storage.v2021_01_01.models.BlobServiceProperties
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BlobServiceProperties"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-01-01"
blob_services_name = "default"
accept = "application/json"
# Construct URL
url = self.get_service_properties.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
'BlobServicesName': self._serialize.url("blob_services_name", blob_services_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('BlobServiceProperties', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_service_properties.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/{BlobServicesName}'} # type: ignore
| mit |
MicroPyramid/Django-CRM | accounts/migrations/0005_auto_20190212_1334.py | 1498 | # Generated by Django 2.1.5 on 2019-02-12 08:04
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("contacts", "0002_auto_20190212_1334"),
("leads", "0004_auto_20190212_1334"),
("accounts", "0004_account_status"),
]
operations = [
migrations.RemoveField(
model_name="account",
name="assigned_to",
),
migrations.RemoveField(
model_name="account",
name="teams",
),
migrations.AddField(
model_name="account",
name="contacts",
field=models.ManyToManyField(
related_name="account_contacts", to="contacts.Contact"
),
),
migrations.AddField(
model_name="account",
name="leads",
field=models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="account_leads",
to="leads.Lead",
),
),
migrations.AlterField(
model_name="account",
name="created_by",
field=models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="account_created_by",
to=settings.AUTH_USER_MODEL,
),
),
]
| mit |
PeterPalmer/SvgSpinner | SvgSpinner/Scripts/raphael.d.ts | 13860 | // Type definitions for Raphael 2.1
// Project: http://raphaeljs.com
// Definitions by: https://github.com/CheCoxshall
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
interface BoundingBox {
x: number;
y: number;
x2: number;
y2: number;
width: number;
height: number;
}
interface RaphaelAnimation {
delay(delay: number): RaphaelAnimation;
repeat(repeat: number): RaphaelAnimation;
}
interface RaphaelFont {
}
interface RaphaelElement {
animate(params: { [key: string]: any; }, ms: number, easing?: string, callback?: Function): RaphaelElement;
animate(animation: RaphaelAnimation): RaphaelElement;
animateWith(el: RaphaelElement, anim: RaphaelAnimation, params: any, ms: number, easing?: string, callback?: Function): RaphaelElement;
animateWith(el: RaphaelElement, anim: RaphaelAnimation, animation: RaphaelAnimation): RaphaelElement;
attr(attrName: string, value: any): RaphaelElement;
attr(params: { [key: string]: any; }): RaphaelElement;
attr(attrName: string): any;
attr(attrNames: string[]): any[];
click(handler: Function): RaphaelElement;
clone(): RaphaelElement;
data(key: string): any;
data(key: string, value: any): RaphaelElement;
dblclick(handler: Function): RaphaelElement;
drag(onmove: (dx: number, dy: number, x: number, y: number, event: DragEvent) =>{ }, onstart: (x: number, y: number, event: DragEvent) =>{ }, onend: (DragEvent) =>{ }, mcontext?: any, scontext?: any, econtext?: any): RaphaelElement;
getBBox(isWithoutTransform?: boolean): BoundingBox;
glow(glow?: { width?: number; fill?: boolean; opacity?: number; offsetx?: number; offsety?: number; color?: string; }): RaphaelSet;
hide(): RaphaelElement;
hover(f_in: Function, f_out: Function, icontext?: any, ocontext?: any): RaphaelElement;
id: string;
insertAfter(): RaphaelElement;
insertBefore(): RaphaelElement;
isPointInside(x: number, y: number): boolean;
isVisible(): boolean;
matrix: RaphaelMatrix;
mousedown(handler: Function): RaphaelElement;
mousemove(handler: Function): RaphaelElement;
mouseout(handler: Function): RaphaelElement;
mouseover(handler: Function): RaphaelElement;
mouseup(handler: Function): RaphaelElement;
next: RaphaelElement;
node: Element;
onDragOver(f: Function): RaphaelElement;
paper: RaphaelPaper;
pause(anim?: RaphaelAnimation): RaphaelElement;
prev: RaphaelElement;
raphael: RaphaelStatic;
remove();
removeData(key?: string): RaphaelElement;
resume(anim?: RaphaelAnimation): RaphaelElement;
setTime(anim: RaphaelAnimation);
setTime(anim: RaphaelAnimation, value: number): RaphaelElement;
show(): RaphaelElement;
status(): { anim: RaphaelAnimation; status: number; }[];
status(anim: RaphaelAnimation): number;
status(anim: RaphaelAnimation, value: number): RaphaelElement;
stop(anim?: RaphaelAnimation): RaphaelElement;
toBack(): RaphaelElement;
toFront(): RaphaelElement;
touchcancel(handler: Function): RaphaelElement;
touchend(handler: Function): RaphaelElement;
touchmove(handler: Function): RaphaelElement;
touchstart(handler: Function): RaphaelElement;
transform(): string;
transform(tstr: string): RaphaelElement;
unclick(handler? ): RaphaelElement;
undblclick(handler? ): RaphaelElement;
undrag(): RaphaelElement;
unhover(): RaphaelElement;
unhover(f_in, f_out): RaphaelElement;
unmousedown(handler? ): RaphaelElement;
unmousemove(handler? ): RaphaelElement;
unmouseout(handler? ): RaphaelElement;
unmouseover(handler? ): RaphaelElement;
unmouseup(handler? ): RaphaelElement;
untouchcancel(handler? ): RaphaelElement;
untouchend(handler? ): RaphaelElement;
untouchmove(handler? ): RaphaelElement;
untouchstart(handler? ): RaphaelElement;
}
interface RaphaelPath extends RaphaelElement {
getPointAtLength(length: number): { x: number; y: number; alpha: number; };
getSubpath(from: number, to: number): string;
getTotalLength(): number;
}
interface RaphaelSet {
clear();
exclude(element: RaphaelElement): boolean;
forEach(callback: Function, thisArg?: any): RaphaelSet;
pop(): RaphaelElement;
push(...RaphaelElement: any[]): RaphaelElement;
splice(index: number, count: number): RaphaelSet;
splice(index: number, count: number, ...insertion: RaphaelElement[]): RaphaelSet;
length: number;
[key: number]: RaphaelElement;
animate(params: { [key: string]: any; }, ms: number, easing?: string, callback?: Function): RaphaelElement;
animate(animation: RaphaelAnimation): RaphaelElement;
animateWith(el: RaphaelElement, anim: RaphaelAnimation, params: any, ms: number, easing?: string, callback?: Function): RaphaelElement;
animateWith(el: RaphaelElement, anim: RaphaelAnimation, animation: RaphaelAnimation): RaphaelElement;
attr(attrName: string, value: any): RaphaelElement;
attr(params: { [key: string]: any; }): RaphaelElement;
attr(attrName: string): any;
attr(attrNames: string[]): any[];
click(handler: Function): RaphaelElement;
clone(): RaphaelElement;
data(key: string): any;
data(key: string, value: any): RaphaelElement;
dblclick(handler: Function): RaphaelElement;
drag(onmove: (dx: number, dy: number, x: number, y: number, event: DragEvent) =>{ }, onstart: (x: number, y: number, event: DragEvent) =>{ }, onend: (DragEvent) =>{ }, mcontext?: any, scontext?: any, econtext?: any): RaphaelElement;
getBBox(isWithoutTransform?: boolean): BoundingBox;
glow(glow?: { width?: number; fill?: boolean; opacity?: number; offsetx?: number; offsety?: number; color?: string; }): RaphaelSet;
hide(): RaphaelElement;
hover(f_in: Function, f_out: Function, icontext?: any, ocontext?: any): RaphaelElement;
id: string;
insertAfter(): RaphaelElement;
insertBefore(): RaphaelElement;
isPointInside(x: number, y: number): boolean;
isVisible(): boolean;
matrix: RaphaelMatrix;
mousedown(handler: Function): RaphaelElement;
mousemove(handler: Function): RaphaelElement;
mouseout(handler: Function): RaphaelElement;
mouseover(handler: Function): RaphaelElement;
mouseup(handler: Function): RaphaelElement;
next: RaphaelElement;
onDragOver(f: Function): RaphaelElement;
paper: RaphaelPaper;
pause(anim?: RaphaelAnimation): RaphaelElement;
prev: RaphaelElement;
raphael: RaphaelStatic;
remove();
removeData(key?: string): RaphaelElement;
resume(anim?: RaphaelAnimation): RaphaelElement;
setTime(anim: RaphaelAnimation);
setTime(anim: RaphaelAnimation, value: number): RaphaelElement;
show(): RaphaelElement;
status(): { anim: RaphaelAnimation; status: number; }[];
status(anim: RaphaelAnimation): number;
status(anim: RaphaelAnimation, value: number): RaphaelElement;
stop(anim?: RaphaelAnimation): RaphaelElement;
toBack(): RaphaelElement;
toFront(): RaphaelElement;
touchcancel(handler: Function): RaphaelElement;
touchend(handler: Function): RaphaelElement;
touchmove(handler: Function): RaphaelElement;
touchstart(handler: Function): RaphaelElement;
transform(): string;
transform(tstr: string): RaphaelElement;
unclick(handler? ): RaphaelElement;
undblclick(handler? ): RaphaelElement;
undrag(): RaphaelElement;
unhover(): RaphaelElement;
unhover(f_in, f_out): RaphaelElement;
unmousedown(handler? ): RaphaelElement;
unmousemove(handler? ): RaphaelElement;
unmouseout(handler? ): RaphaelElement;
unmouseover(handler? ): RaphaelElement;
unmouseup(handler? ): RaphaelElement;
untouchcancel(handler? ): RaphaelElement;
untouchend(handler? ): RaphaelElement;
untouchmove(handler? ): RaphaelElement;
untouchstart(handler? ): RaphaelElement;
}
interface RaphaelMatrix {
add(a: number, b: number, c: number, d: number, e: number, f: number, matrix: RaphaelMatrix): RaphaelMatrix;
clone(): RaphaelMatrix;
invert(): RaphaelMatrix;
rotate(a: number, x: number, y: number);
scale(x: number, y?: number, cx?: number, cy?: number);
split(): { dx: number; dy: number; scalex: number; scaley: number; shear: number; rotate: number; isSimple: boolean; };
toTransformString(): string;
translate(x: number, y: number);
x(x: number, y: number);
y(x: number, y: number);
}
interface RaphaelPaper {
add(JSON): RaphaelSet;
bottom: RaphaelElement;
canvas: Element;
circle(x: number, y: number, r: number): RaphaelElement;
clear();
defs: Element;
ellipse(x: number, y: number, rx: number, ry: number): RaphaelElement;
forEach(callback: number, thisArg: any): RaphaelStatic;
getById(id: number): RaphaelElement;
getElementByPoint(x: number, y: number): RaphaelElement;
getElementsByPoint(x: number, y: number): RaphaelSet;
getFont(family: string, weight?: string, style?: string, stretch?: string): RaphaelFont;
getFont(family: string, weight?: number, style?: string, stretch?: string): RaphaelFont;
height: number;
image(src: string, x: number, y: number, width: number, height: number): RaphaelElement;
path(pathString?: string): RaphaelPath;
print(x: number, y: number, str: string, font: RaphaelFont, size?: number, origin?: string, letter_spacing?: number): RaphaelPath;
rect(x: number, y: number, width: number, height: number, r?: number): RaphaelElement;
remove();
renderfix();
safari();
set(elements?: RaphaelElement[]): RaphaelSet;
setFinish();
setSize(width: number, height: number);
setStart();
setViewBox(x: number, y: number, w: number, h: number, fit: boolean);
text(x: number, y: number, text: string): RaphaelElement;
top: RaphaelElement;
width: number;
}
interface RaphaelStatic {
(container: HTMLElement, width: number, height: number, callback?: Function): RaphaelPaper;
(container: string, width: number, height: number, callback?: Function): RaphaelPaper;
(x: number, y: number, width: number, height: number, callback?: Function): RaphaelPaper;
(all: Array, callback?: Function): RaphaelPaper;
(onReadyCallback?: Function): RaphaelPaper;
angle(x1: number, y1: number, x2: number, y2: number, x3?: number, y3?: number): number;
animation(params: any, ms: number, easing?: string, callback?: Function): RaphaelAnimation;
bezierBBox(p1x: number, p1y: number, c1x: number, c1y: number, c2x: number, c2y: number, p2x: number, p2y: number): { min: { x: number; y: number; }; max: { x: number; y: number; }; };
bezierBBox(bez: Array): { min: { x: number; y: number; }; max: { x: number; y: number; }; };
color(clr: string): { r: number; g: number; b: number; hex: string; error: boolean; h: number; s: number; v: number; l: number; };
createUUID(): string;
deg(deg: number): number;
easing_formulas: any;
el: any;
findDotsAtSegment(p1x: number, p1y: number, c1x: number, c1y: number, c2x: number, c2y: number, p2x: number, p2y: number, t: number): { x: number; y: number; m: { x: number; y: number; }; n: { x: number; y: number; }; start: { x: number; y: number; }; end: { x: number; y: number; }; alpha: number; };
fn: any;
format(token: string, ...parameters: any[]): string;
fullfill(token: string, json: JSON): string;
//getColor {
// (value?: number): string;
// reset();
//};
getPointAtLength(path: string, length: number): { x: number; y: number; alpha: number; };
getRGB(colour: string): { r: number; g: number; b: number; hex: string; error: boolean; };
getSubpath(path: string, from: number, to: number): string;
getTotalLength(path: string): number;
hsb(h: number, s: number, b: number): string;
hsb2rgb(h: number, s: number, v: number): { r: number; g: number; b: number; hex: string; };
hsl(h: number, s: number, l: number): string;
hsl2rgb(h: number, s: number, l: number): { r: number; g: number; b: number; hex: string; };
is(o: any, type: string): boolean;
isBBoxIntersect(bbox1: string, bbox2: string): boolean;
isPointInsideBBox(bbox: string, x: number, y: number): boolean;
isPointInsidePath(path: string, x: number, y: number): boolean;
matrix(a: number, b: number, c: number, d: number, e: number, f: number): RaphaelMatrix;
ninja();
parsePathString(pathString: string): string[];
parsePathString(pathString: string[]): string[];
parseTransformString(TString: string): string[];
parseTransformString(TString: string[]): string[];
path2curve(pathString: string): string[];
path2curve(pathString: string[]): string[];
pathBBox(path: string): BoundingBox;
pathIntersection(path1: string, path2: string): { x: number; y: number; t1: number; t2: number; segment1: number; segment2: number; bez1: Array; bez2: Array; }[];
pathToRelative(pathString: string): string[];
pathToRelative(pathString: string[]): string[];
rad(deg: number): number;
registerFont(font: RaphaelFont): RaphaelFont;
rgb(r: number, g: number, b: number): string;
rgb2hsb(r: number, g: number, b: number): { h: number; s: number; b: number; };
rgb2hsl(r: number, g: number, b: number): { h: number; s: number; l: number; };
setWindow(newwin: Window);
snapTo(values: number, value: number, tolerance?: number): number;
snapTo(values: number[], value: number, tolerance?: number): number;
st: any;
svg: boolean;
toMatrix(path: string, transform: string): RaphaelMatrix;
toMatrix(path: string, transform: string[]): RaphaelMatrix;
transformPath(path: string, transform: string): string;
transformPath(path: string, transform: string[]): string;
type: string;
vml: boolean;
}
declare var Raphael: RaphaelStatic;
| mit |
arquio/apollo-server | packages/apollo-server-koa/src/koaApollo.ts | 1981 | import * as koa from 'koa';
import {
GraphQLOptions,
HttpQueryError,
runHttpQuery,
} from 'apollo-server-core';
import * as GraphiQL from 'apollo-server-module-graphiql';
export interface KoaGraphQLOptionsFunction {
(ctx: koa.Context): GraphQLOptions | Promise<GraphQLOptions>;
}
export interface KoaHandler {
(req: any, next): void;
}
export function graphqlKoa(
options: GraphQLOptions | KoaGraphQLOptionsFunction,
): KoaHandler {
if (!options) {
throw new Error('Apollo Server requires options.');
}
if (arguments.length > 1) {
throw new Error(
`Apollo Server expects exactly one argument, got ${arguments.length}`,
);
}
return (ctx: koa.Context): Promise<void> => {
return runHttpQuery([ctx], {
method: ctx.request.method,
options: options,
query:
ctx.request.method === 'POST' ? ctx.request.body : ctx.request.query,
}).then(
gqlResponse => {
ctx.set('Content-Type', 'application/json');
ctx.body = gqlResponse;
},
(error: HttpQueryError) => {
if ('HttpQueryError' !== error.name) {
throw error;
}
if (error.headers) {
Object.keys(error.headers).forEach(header => {
ctx.set(header, error.headers[header]);
});
}
ctx.status = error.statusCode;
ctx.body = error.message;
},
);
};
}
export interface KoaGraphiQLOptionsFunction {
(ctx: koa.Context): GraphiQL.GraphiQLData | Promise<GraphiQL.GraphiQLData>;
}
export function graphiqlKoa(
options: GraphiQL.GraphiQLData | KoaGraphiQLOptionsFunction,
) {
return (ctx: koa.Context) => {
const query = ctx.request.query;
return GraphiQL.resolveGraphiQLString(query, options, ctx).then(
graphiqlString => {
ctx.set('Content-Type', 'text/html');
ctx.body = graphiqlString;
},
error => {
ctx.status = 500;
ctx.body = error.message;
},
);
};
}
| mit |
calonso-conabio/buscador | app/lib/taxon_describers/conabio.rb | 566 | module TaxonDescribers
class Conabio < Base
def self.describer_name
'CONABIO'
end
def self.describe(taxon)
if cat = taxon.scat
page = conabio_service.search(cat.catalogo_id)
if page.blank?
TaxonDescribers::ConabioViejo.describe(taxon)
else
page
end
else # Consulta en las fichas viejas
TaxonDescribers::ConabioViejo.describe(taxon)
end
end
private
def conabio_service
@conabio_service=New_Conabio_Service.new(:timeout => 20)
end
end
end | mit |
xingoxu/works | index-src/js/nextpageajax.js | 1549 | /**
* @author xingo
* @date 2016-03-07 version 0.1
* @description 首页无限向下加载
* @update
*
*/
define([], function() {
var limitHeight = 200;
var getCurrentPage = function() {
return $('#page-nav').children('.current').text();
};
var taskid = 0;
var processing = false;
var handler = function() {
clearTimeout(taskid);
if (processing) {
return;
}
taskid = setTimeout(function() {
processing = true;
//check if on the bottom
var restHeight = $(document).height() - $(document).scrollTop() - $(window).height();
if (restHeight > limitHeight) {
processing = false;
return;
}
//check if is the last page
var currentPage = parseInt(getCurrentPage(), 10);
if (currentPage >= $('#page-nav').children('.page-number:last').text()) {
processing = false;
return;
}
$('.loading-circle').show();
$.get('page/' + (currentPage + 1) + '/')
.done(function(data, textstatus, jqxhr) {
$nextPageArticle = $(data).find('.body-wrap').children();
$('#page-nav').remove();
$('.loading-circle').hide().remove();
$('.body-wrap').append($nextPageArticle);
processing = false;
})
.fail(function() {
$('.loading-circle').children('.fail-message').show()
.siblings().hide();
});
}, 300);
};
var bind = function() {
$(window).scroll(handler);
};
var remove = function() {
$(window).unbind('scroll', handler);
};
return {
init: function() {
bind();
},
bind: bind,
remove: remove,
handler: handler
};
}); | mit |
dcturner/tk_relic | js/relics/relic.js | 687 | Relic = {};
Relic['shaders'] = [];
relic_update = function() {};
Relic.RelicScene = function(name) {
// collada
_this = this;
this.name = name;
this.ready = false;
// COLLADA
this.relicLoader = new THREE.ColladaLoader();
this.relicLoader.load("relicAssets/carbon/geo/main.dae", function(geo) {
_this.relicConfig = new Relic.RelicConfig(geo);
console.log("relic >> " + name + " >> created");
_this.ready = true;
});
// this.relicLoader = new THREE.OBJLoader();
//
// this.relicLoader.load(
// 'relicAssets/carbon/geo/blend.obj',
// function ( object ) {
// _this.relicConfig = new Relic.RelicConfig(object);
// }
// );
this.update = function() {}
}
| mit |
gumblex/zhconv | docs/conf.py | 9825 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# zhconv documentation build configuration file, created by
# sphinx-quickstart on Tue Jan 17 19:18:49 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'zhconv'
copyright = '2017, Dingyuan Wang'
author = 'Dingyuan Wang'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.4.1'
# The full version, including alpha/beta/rc tags.
release = '1.4.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'zh_CN'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = 'zhconv v1.2.1'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
# html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'zhconvdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'zhconv.tex', 'zhconv Documentation',
'Dingyuan Wang', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# It false, will not define \strong, \code, itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'zhconv', 'zhconv Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'zhconv', 'zhconv Documentation',
author, 'zhconv', 'Converts between Simplified and Traditional Chinese.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []
# If false, no module index is generated.
#
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
| mit |
paulvickery/hypothesis-testing-calculator | Android/HypothesisTestingAndroid/Properties/AssemblyInfo.cs | 1024 | using System.Reflection;
using System.Runtime.CompilerServices;
using Android.App;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("HypothesisTestingAndroid")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("James")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit |
redPanther/hyperion.ng | src/hyperiond/main.cpp | 8877 | #include <cassert>
#include <csignal>
#include <unistd.h>
#include <stdlib.h>
#ifndef __APPLE__
/* prctl is Linux only */
#include <sys/prctl.h>
#endif
#include <exception>
#include <QCoreApplication>
#include <QApplication>
#include <QLocale>
#include <QFile>
#include <QString>
#include <QResource>
#include <QDir>
#include <QStringList>
#include <QSystemTrayIcon>
#include "HyperionConfig.h"
#include <utils/Logger.h>
#include <utils/FileUtils.h>
#include <webconfig/WebConfig.h>
#include <commandline/Parser.h>
#include <commandline/IntOption.h>
#ifdef ENABLE_X11
#include <X11/Xlib.h>
#endif
#include "hyperiond.h"
#include "systray.h"
using namespace commandline;
#define PERM0664 QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther | QFileDevice::WriteOwner | QFileDevice::WriteGroup
void signal_handler(const int signum)
{
if(signum == SIGCHLD)
{
// only quit when a registered child process is gone
// currently this feature is not active ...
return;
}
QCoreApplication::quit();
// reset signal handler to default (in case this handler is not capable of stopping)
signal(signum, SIG_DFL);
}
void startNewHyperion(int parentPid, std::string hyperionFile, std::string configFile)
{
pid_t childPid = fork(); // child pid should store elsewhere for later use
if ( childPid == 0 )
{
sleep(3);
execl(hyperionFile.c_str(), hyperionFile.c_str(), "--parent", QString::number(parentPid).toStdString().c_str(), configFile.c_str(), NULL);
exit(0);
}
}
QCoreApplication* createApplication(int &argc, char *argv[])
{
bool isGuiApp = false;
bool forceNoGui = false;
// command line
for (int i = 1; i < argc; ++i)
{
if (qstrcmp(argv[i], "--desktop") == 0)
{
isGuiApp = true;
}
else if (qstrcmp(argv[i], "--service") == 0)
{
isGuiApp = false;
forceNoGui = true;
}
}
// on osx/windows gui always available
#if defined(__APPLE__) || defined(__WIN32__)
isGuiApp = true && ! forceNoGui;
#else
if (!forceNoGui)
{
// if x11, then test if xserver is available
#ifdef ENABLE_X11
Display* dpy = XOpenDisplay(NULL);
if (dpy != NULL)
{
XCloseDisplay(dpy);
isGuiApp = true;
}
#endif
}
#endif
if (isGuiApp)
{
QApplication* app = new QApplication(argc, argv);
app->setApplicationDisplayName("Hyperion");
return app;
}
QCoreApplication* app = new QCoreApplication(argc, argv);
app->setApplicationName("Hyperion");
app->setApplicationVersion(HYPERION_VERSION);
return app;
}
int main(int argc, char** argv)
{
setenv("AVAHI_COMPAT_NOWARN", "1", 1);
// initialize main logger and set global log level
Logger* log = Logger::getInstance("MAIN");
Logger::setLogLevel(Logger::WARNING);
// Initialising QCoreApplication
QScopedPointer<QCoreApplication> app(createApplication(argc, argv));
bool isGuiApp = (qobject_cast<QApplication *>(app.data()) != 0 && QSystemTrayIcon::isSystemTrayAvailable());
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGABRT, signal_handler);
signal(SIGCHLD, signal_handler);
signal(SIGPIPE, signal_handler);
// force the locale
setlocale(LC_ALL, "C");
QLocale::setDefault(QLocale::c());
Parser parser("Hyperion Daemon");
parser.addHelpOption();
BooleanOption & versionOption = parser.add<BooleanOption>(0x0, "version", "Show version information");
IntOption & parentOption = parser.add<IntOption> ('p', "parent", "pid of parent hyperiond"); // 2^22 is the max for Linux
BooleanOption & silentOption = parser.add<BooleanOption>('s', "silent", "do not print any outputs");
BooleanOption & verboseOption = parser.add<BooleanOption>('v', "verbose", "Increase verbosity");
BooleanOption & debugOption = parser.add<BooleanOption>('d', "debug", "Show debug messages");
parser.add<BooleanOption>(0x0, "desktop", "show systray on desktop");
parser.add<BooleanOption>(0x0, "service", "force hyperion to start as console service");
Option & exportConfigOption = parser.add<Option> (0x0, "export-config", "export default config to file");
Option & exportEfxOption = parser.add<Option> (0x0, "export-effects", "export effects to given path");
parser.addPositionalArgument("config-files", QCoreApplication::translate("main", "Configuration file"), "config.file");
parser.process(*qApp);
QStringList configFiles = parser.positionalArguments();
int logLevelCheck = 0;
if (parser.isSet(silentOption))
{
Logger::setLogLevel(Logger::OFF);
logLevelCheck++;
}
if (parser.isSet(verboseOption))
{
Logger::setLogLevel(Logger::INFO);
logLevelCheck++;
}
if (parser.isSet(debugOption))
{
Logger::setLogLevel(Logger::DEBUG);
logLevelCheck++;
}
if (logLevelCheck > 1)
{
Error(log, "aborting, because options --silent --verbose --debug can't used together");
return 0;
}
if (parser.isSet(versionOption))
{
std::cout
<< "Hyperion Ambilight Deamon (" << getpid() << ")" << std::endl
<< "\tVersion : " << HYPERION_VERSION << " (" << HYPERION_BUILD_ID << ")" << std::endl
<< "\tBuild Time: " << __DATE__ << " " << __TIME__ << std::endl;
return 0;
}
if (parser.isSet(exportEfxOption))
{
Q_INIT_RESOURCE(EffectEngine);
QDir directory(":/effects/");
QDir destDir(exportEfxOption.value(parser));
if (directory.exists() && destDir.exists())
{
std::cout << "extract to folder: " << std::endl;
QStringList filenames = directory.entryList(QStringList() << "*", QDir::Files, QDir::Name | QDir::IgnoreCase);
QString destFileName;
foreach (const QString & filename, filenames)
{
destFileName = destDir.dirName()+"/"+filename;
if (QFile::exists(destFileName))
{
QFile::remove(destFileName);
}
std::cout << "Extract: " << filename.toStdString() << " ... ";
if (QFile::copy(QString(":/effects/")+filename, destFileName))
{
QFile::setPermissions(destFileName, PERM0664 );
std::cout << "ok" << std::endl;
}
else
{
std::cout << "error, aborting" << std::endl;
return 1;
}
}
return 0;
}
Error(log, "can not export to %s",exportEfxOption.getCString(parser));
return 1;
}
// handle default config file
if (configFiles.size() == 0)
{
QString hyperiond_path = QDir::homePath();
QString hyperiond_config = hyperiond_path+"/.hyperion.config.json";
QFileInfo hyperiond_pathinfo(hyperiond_path);
if ( ! hyperiond_pathinfo.isWritable() && ! QFile::exists(hyperiond_config) )
{
QFileInfo hyperiond_fileinfo(argv[0]);
hyperiond_config = hyperiond_fileinfo.absolutePath()+"/hyperion.config.json";
}
configFiles.append(hyperiond_config);
Info(log, "No config file given. Standard config file used: %s", QSTRING_CSTR(configFiles[0]));
}
bool exportDefaultConfig = false;
bool exitAfterExportDefaultConfig = false;
QString exportConfigFileTarget;
if (parser.isSet(exportConfigOption))
{
exportDefaultConfig = true;
exitAfterExportDefaultConfig = true;
exportConfigFileTarget = exportConfigOption.value(parser);
}
else if ( ! QFile::exists(configFiles[0]) )
{
exportDefaultConfig = true;
exportConfigFileTarget = configFiles[0];
Warning(log, "Your configuration file does not exist. hyperion writes default config");
}
if (exportDefaultConfig)
{
Q_INIT_RESOURCE(resource);
QDir().mkpath(FileUtils::getDirName(exportConfigFileTarget));
if (QFile::copy(":/hyperion_default.config",exportConfigFileTarget))
{
QFile::setPermissions(exportConfigFileTarget, PERM0664 );
Info(log, "export complete.");
if (exitAfterExportDefaultConfig) return 0;
}
else
{
Error(log, "error while export to %s", QSTRING_CSTR(exportConfigFileTarget) );
return 1;
}
}
if (configFiles.size() > 1)
{
Warning(log, "You provided more than one config file. Hyperion will use only the first one");
}
int parentPid = parser.value(parentOption).toInt();
if (parentPid > 0 )
{
Info(log, "hyperiond client, parent is pid %d", parentPid);
#ifndef __APPLE__
prctl(PR_SET_PDEATHSIG, SIGHUP);
#endif
}
HyperionDaemon* hyperiond = nullptr;
try
{
hyperiond = new HyperionDaemon(configFiles[0], qApp);
hyperiond->run();
}
catch (std::exception& e)
{
Error(log, "Hyperion Daemon aborted:\n %s", e.what());
}
int rc = 1;
WebConfig* webConfig = nullptr;
try
{
webConfig = new WebConfig(qApp);
// run the application
if (isGuiApp)
{
Info(log, "start systray");
QApplication::setQuitOnLastWindowClosed(false);
SysTray tray(hyperiond, webConfig->getPort());
tray.hide();
rc = (qobject_cast<QApplication *>(app.data()))->exec();
}
else
{
rc = app->exec();
}
Info(log, "Application closed with code %d", rc);
}
catch (std::exception& e)
{
Error(log, "Hyperion aborted:\n %s", e.what());
}
// delete components
delete webConfig;
delete hyperiond;
Logger::deleteInstance();
return rc;
}
| mit |
RaynaldM/autohelp | AutoHelp/Helpers/DocServiceFactory.cs | 573 | using System;
using System.Web.Configuration;
using System.Web.Hosting;
using AutoHelp.domain.Services;
namespace AutoHelp.Helpers
{
public static class DocServiceFactory
{
public static DocServices CreatServices()
{
// get value from web config
var assemblyPath = WebConfigurationManager.AppSettings.Get("AssemblyDirectory");
assemblyPath = HostingEnvironment.MapPath(String.IsNullOrWhiteSpace(assemblyPath) ? "~/App_Data" : assemblyPath);
return new DocServices(assemblyPath);
}
}
}
| mit |
blakmatrix/node-zendesk | lib/client/ticketaudits.js | 769 | //TicketAudits.js: Client for the zendesk API.
var util = require('util'),
Client = require('./client').Client;
var TicketAudits = exports.TicketAudits = function (options) {
this.jsonAPINames = [ 'audits', 'audit' ];
this.sideLoadMap = [
{ field: 'author_id', name: 'author', dataset: 'users'},
{ field: 'ticket_id', name: 'ticket', dataset: 'tickets' }
];
Client.call(this, options);
};
// Inherit from Client base object
util.inherits(TicketAudits, Client);
// ######################################################## TicketAudits
// ====================================== Listing TicketAudits
TicketAudits.prototype.list = function (ticketID, cb) {
return this.requestAll('GET', ['tickets', ticketID, 'audits'], cb);//all?
};
| mit |
jonathanlee46/online-connect | db/migrate/201506010000_create_users.rb | 202 | class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :password_hash
t.string :email
t.timestamps
end
end
end
| mit |
BePark/laravel-confirm | src/Services/ConfirmService.php | 1478 | <?php
namespace BePark\Libs\Confirm\Services;
use BePark\Libs\Confirm\ValueObjects\ConfirmMessage;
use Illuminate\Http\Request;
/**
* Allow to play in an easier way with confirmation
*/
class ConfirmService
{
/**
* Ask people to confirm their choice, using url (and get) instead of form (and post)
* @param ConfirmMessage $message
* @param null|string $title
* @return \Illuminate\Contracts\View\Factory
*/
public function confirmByUrl(ConfirmMessage $message, string $title = null)
{
return view('common.confirm_url', [
'_page' => ['title' => trans($title ?? $message->getTitle())],
'confirm' => $message,
]);
}
/**
* Validate that the confirmation is well done.
*
* @param Request $request
* @param callable|null $callback the callback to call if it's valid
* @return bool
*/
public function isConfirmedByUrl(Request $request, callable $callback = null): bool
{
if ($request->get('confirm', false))
{
if ($callback)
{
$callback($request);
}
return true;
}
return false;
}
/**
* Ask people to confirm their choice, using form (and post) instead of url (and get)
* @param ConfirmMessage $message
* @param null|string $title
* @return \Illuminate\Contracts\View\Factory
*/
public function confirmByForm(ConfirmMessage $message, string $title = null)
{
return view('common.confirm_form', [
'_page' => ['title' => trans($title ?? $message->getTitle())],
'confirm' => $message,
]);
}
}
| mit |
github/codeql | javascript/ql/test/library-tests/frameworks/EventEmitter/tst.js | 1228 | var emitter = require('events').EventEmitter;
var em = new emitter();
// Splitting different channels
em.addListener('FirstEvent', function (first) {});
em.on('SecondEvent', function (second) {});
em.emit('FirstEvent', 'FirstData');
em.emit('SecondEvent', 'SecondData');
// Splitting different emitters.
var em2 = new emitter();
em2.addListener('FirstEvent', function (otherFirst) {});
em2.emit('FirstEvent', 'OtherFirstData');
// Chaining.
var em3 = new emitter();
em3.on("foo", (foo) => {}).on("bar", (bar) => {});
em3.emit("foo", "foo");
em3.emit("bar", "bar");
// Returning a value does not work here.
var em4 = new emitter();
em3.on("bla", (event) => {
event.returnValue = "foo"
});
em3.emit("bla", "blab");
class MyEventEmitter extends emitter {};
var em4 = new MyEventEmitter();
em4.on("blab", (x) => {});
em4.emit("blab", "BOH");
class ExtendsMyCustomEmitter extends MyEventEmitter{}
var em5 = new ExtendsMyCustomEmitter();
em5.on("yibity", (x) => {});
em5.emit("yibity", "yabity");
var process = require('process');
process.addListener('FirstEvent', function (first) {});
process.on('SecondEvent', function (second) {});
process.emit('FirstEvent', 'FirstData');
process.emit('SecondEvent', 'SecondData');
| mit |
Lansoweb/request-id | src/RequestId.php | 3242 | <?php
declare(strict_types=1);
namespace LosMiddleware\RequestId;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use function array_merge;
use function assert;
use function in_array;
use function is_int;
use function is_string;
final class RequestId implements MiddlewareInterface
{
public const HEADER_NAME = 'X-Request-Id';
/** @var array<array-key,mixed> */
private array $options;
/** @param array<array-key,mixed> $options */
public function __construct(array $options = [])
{
$this->options = array_merge([
'uuid' => false,
'uuid_version' => 4,
'uuid_ns' => null,
'uuid_name' => null,
'allow_override' => false,
'header_name' => self::HEADER_NAME,
], $options);
if (
! is_int($this->options['uuid_version']) ||
! in_array($this->options['uuid_version'], [1, 3, 4, 5, 6])
) {
throw new InvalidArgumentException('Uuid version must be 1, 3, 4, 5 or 6');
}
if (
($this->options['uuid_version'] === 3 || $this->options['uuid_version'] === 5) &&
(empty($this->options['uuid_ns']) || empty($this->options['uuid_name']))
) {
throw new InvalidArgumentException('Uuid versions 3 and 5 requires uuid_ns and uuid_name');
}
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$uuid = '';
$headerName = $this->options['header_name'];
assert(is_string($headerName));
if ($this->options['allow_override'] || ! $request->hasHeader($headerName)) {
$uuid = $this->generateId();
$request = $request->withHeader($headerName, (string) $uuid);
} elseif ($request->hasHeader($headerName)) {
$uuid = $request->getHeader($headerName)[0];
}
$response = $handler->handle($request);
if (! empty($uuid)) {
$response = $response->withHeader($headerName, (string) $uuid);
}
return $response;
}
private function generateId(): UuidInterface
{
if (is_string($this->options['uuid']) && Uuid::isValid($this->options['uuid'])) {
return Uuid::fromString($this->options['uuid']);
}
$version = (int) $this->options['uuid_version'];
switch ($version) {
case 1:
return Uuid::uuid1();
case 3:
case 5:
$ns = $this->options['uuid_ns'];
$name = $this->options['uuid_name'];
assert(is_string($ns));
assert(is_string($name));
if ($version === 3) {
return Uuid::uuid3($ns, $name);
}
return Uuid::uuid5($ns, $name);
case 6:
return Uuid::uuid6();
default:
return Uuid::uuid4();
}
}
}
| mit |
rug-compling/hmm-reps | inference/hmm_splitmerge.py | 2891 | import logging
import numpy as np
from util.log_domain import logzero, sselogsum
__author__ = 'sim'
class HMMsplitmerge:
# @profile
def get_loss(self, N, forward, backward, ll, norm_emission_counts):
"""
:param forward: forward trellis
:param backward: backward trellis
:param ll: log likelihood of the current sequence
:param emission_scores: for access to state posteriors needed for weighting backward merges
:param N: number of split states
"""
logger = logging.getLogger(__name__)
loss_seq = np.zeros(N / 2) # there are N/2 possible merges
assert forward.shape[1] == N
n_merge = 0
# iterate over possible merges
for i in range(len(loss_seq)):
i_merge = i + n_merge
# prepare trellis
#forward_merge = np.zeros((forward.shape[0], forward.shape[1]-1), 'f') + logzero()
forward_to_merge = forward[:, i_merge:i_merge + 2]
sum_split_forward = np.zeros((forward.shape[0], 1), 'f') + logzero()
for row_n, row in enumerate(forward_to_merge):
# sum split states
sum_split_forward[row_n] = sselogsum(row)
forward_merge = np.hstack((forward[:, :i_merge], sum_split_forward, forward[:, i_merge + 2:]))
backward_to_merge = backward[:, i_merge:i_merge + 2]
sum_split_backward = np.zeros((backward.shape[0], 1), 'f') + logzero()
# incorporate weights for each element (Petrov 2009, p. 89)
# weights are normalized emission counts
# accumulated from state posteriors over all sequences
assert backward.shape[1] == N
backward_to_merge += norm_emission_counts[i_merge:i_merge + 2]
for row_n, row in enumerate(backward_to_merge):
# sum weighted split states
sum_split_backward[row_n] = sselogsum(row)
backward_merge = np.hstack((backward[:, :i_merge], sum_split_backward, backward[:, i_merge + 2:]))
ll_merged_positions = np.zeros(forward_merge.shape[0], 'f') + logzero()
fb_merge = forward_merge + backward_merge
for row_n, row in enumerate(fb_merge):
ll_merged_positions[row_n] = sselogsum(row)
# likelihood for one merge at all t's
#for row_n in range(forward_merge.shape[0]):
# ll_merged_positions[row_n] = sselogsum(forward_merge[row_n] + backward_merge[row_n])
# get loss (difference in likelihoods)
#assert np.all(ll_merged_positions < ll)
#assert np.all((ll_merged_positions < ll).astype(int) |
# (np.isclose(ll_merged_positions, ll, rtol=0.01)).astype(int))
loss_seq[i] = (ll_merged_positions - ll).sum()
n_merge += 1
return loss_seq | mit |
ikatyang/dts-element | src/types/array-type.ts | 910 | import * as ts from 'typescript';
import { IType } from '../collections';
import { ElementKind } from '../constants';
import {
create_element,
is_element,
IElement,
IElementOptions,
} from '../element';
import { transform } from '../transform';
export interface IArrayTypeOptions extends IElementOptions {
type: IType;
}
export interface IArrayType
extends IElement<ElementKind.ArrayType>,
IArrayTypeOptions {}
export const create_array_type = (options: IArrayTypeOptions): IArrayType => ({
...create_element(ElementKind.ArrayType),
...options,
});
export const is_array_type = (value: any): value is IArrayType =>
is_element(value) && value.kind === ElementKind.ArrayType;
/**
* @hidden
*/
export const transform_array_type = (
element: IArrayType,
path: IElement<any>[],
) =>
ts.createArrayTypeNode(
/* elementType */ transform(element.type, path) as ts.TypeNode,
);
| mit |
flesire/ontrack | ontrack-extension-jenkins/src/main/java/net/nemerosa/ontrack/extension/jenkins/JenkinsConfiguration.java | 2123 | package net.nemerosa.ontrack.extension.jenkins;
import lombok.Data;
import net.nemerosa.ontrack.model.support.UserPasswordConfiguration;
import net.nemerosa.ontrack.model.form.Form;
import net.nemerosa.ontrack.model.form.Password;
import net.nemerosa.ontrack.model.form.Text;
import net.nemerosa.ontrack.model.support.ConfigurationDescriptor;
import java.util.function.Function;
import static net.nemerosa.ontrack.model.form.Form.defaultNameField;
@Data
public class JenkinsConfiguration implements UserPasswordConfiguration<JenkinsConfiguration> {
private final String name;
private final String url;
private final String user;
private final String password;
public static Form form() {
return Form.create()
.with(defaultNameField())
.url()
.with(Text.of("user").label("User").length(16).optional())
.with(Password.of("password").label("Password").length(40).optional());
}
@Override
public JenkinsConfiguration obfuscate() {
return new JenkinsConfiguration(
name,
url,
user,
""
);
}
public Form asForm() {
return form()
.with(defaultNameField().readOnly().value(name))
.fill("url", url)
.fill("user", user)
.fill("password", "");
}
@Override
public JenkinsConfiguration withPassword(String password) {
return new JenkinsConfiguration(
name,
url,
user,
password
);
}
@Override
public ConfigurationDescriptor getDescriptor() {
return new ConfigurationDescriptor(name, name);
}
@Override
public JenkinsConfiguration clone(String targetConfigurationName, Function<String, String> replacementFunction) {
return new JenkinsConfiguration(
targetConfigurationName,
replacementFunction.apply(url),
replacementFunction.apply(user),
password
);
}
}
| mit |
dmillerw/MineLua | src/main/java/me/dmillerw/minelua/lib/mapping/FieldMapping.java | 884 | package me.dmillerw.minelua.lib.mapping;
/**
* @author dmillerw
*/
public class FieldMapping {
public final String owner;
public final String name;
public FieldMapping(String owner, String name) {
this.owner = owner;
this.name = name;
}
@Override
public String toString() {
return "{owner: " + owner + ", name: " + name + "}";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FieldMapping that = (FieldMapping) o;
if (!name.equals(that.name)) return false;
if (!owner.equals(that.owner)) return false;
return true;
}
@Override
public int hashCode() {
int result = owner.hashCode();
result = 31 * result + name.hashCode();
return result;
}
}
| mit |
lszhu/saleSys | client/templates/order/disposal.js | 24269 | Template.orderDisposalItem.helpers({
disposalSummary: function() {
var data = Template.currentData();
//console.log('disposal: ', JSON.stringify(data));
var disposal = _.extend(data.disposal, {
delivery: data.delivery,
capital: data.capital
});
return createMessageContent(disposal);
},
formatDate: formatDate,
formatTime: formatTime
});
Template.orderDisposalItem.onRendered(function () {
var detail = this.find('.order-disposal-item > .panel');
$(detail).hide();
});
Template.orderDisposalItem.events({
'click .open-detail': function (e, t) {
e.preventDefault();
var target = $(e.target);
var detail = t.find('.order-disposal-item > .panel');
detail = $(detail);
if (detail.hasClass('hide-me')) {
detail.removeClass('hide-me');
detail.fadeIn('normal');
target.find('.fa-caret-down')
.removeClass('fa-caret-down')
.addClass('fa-caret-up');
} else {
detail.slideUp('normal', function () {
detail.addClass('hide-me');
target.find('.fa-caret-up')
.removeClass('fa-caret-up')
.addClass('fa-caret-down');
});
}
}
});
Template.editOrder.onCreated(function () {
Session.set('editOrderSubmitErrors', {});
// 必须保证当前模板上下文数据不是未定义,参考路由配置
var currentData = Template.currentData();
currentData._filteredManagersListener = new Tracker.Dependency();
currentData._filteredManagers = [{}];
currentData.getManagers = function () {
currentData._filteredManagersListener.depend();
return currentData._filteredManagers;
};
// 特权用户必须能查看当前部门所有账号(订单主管)列表
if (isSuperUser()) {
var stationId = currentData.stationId || Meteor.user().stationId;
var query = stationId ? {stationId: stationId} : {};
currentData._filteredManagers = Meteor.users.find(query).fetch();
currentData._filteredManagersListener.changed();
//console.log('filtered managerList: ' +
// JSON.stringify(currentData.getManagers()));
// 如果返回结果为空数组则表明当前的登录账号与所查询订单不在同一个部门
// 此时需要继续运行下面的代码
if (currentData._filteredManagers.length > 0) {
return;
}
}
if (currentData.managerId) {
Meteor.call('getNameById', currentData.managerId,
function (error, result) {
currentData._filteredManagersListener.depend();
if (error) {
currentData._filteredManagers = [{
_id: currentData.managerId,
profile: {name: '未知'}
}];
} else {
currentData._filteredManagers = [{
_id: currentData.managerId,
profile: {name: result}
}];
}
currentData._filteredManagersListener.changed();
//console.log('filtered managerList: ' +
// JSON.stringify(currentData.getManagers()));
});
}
});
Template.editOrder.onRendered(function() {
$('.edit-order input[name=deadline]').datepicker({
format: "yyyy-mm-dd",
language: "zh-CN",
//todayBtn: true,
orientation: 'top left',
autoclose: true
});
});
Template.editOrder.events({
'change .edit-order select[name=stationId]': function (e) {
var managers = Meteor.users.find({stationId: $(e.target).val()}).fetch();
var currentData = Template.currentData() || {};
managers.unshift({});
currentData._filteredManagers = managers;
currentData._filteredManagersListener.changed();
},
'change .edit-order input[name=deadline]': function (e) {
var target = $(e.target);
var t = target.val().split('-');
var time = new Date(t[0], t[1] - 1, t[2]);
if (time.toString() == 'Invalid Date') {
throwError('交货截至日期填写有误!');
time = 0;
} else {
time = time.getTime();
}
target.data('time', time);
}
});
Template.editOrder.helpers({
hasError: function (field) {
return !!Session.get('editOrderSubmitErrors')[field] ?
'has-error' : '';
},
isSelected: function (u, v) {
return u == v ? 'selected' : '';
},
time: function (d) {
return d && d.getTime() ? d.getTime() : 0;
},
formatDate: formatDate
});
Template.orderDisposalDetail.helpers({
selectionItem: function () {
return {
disposalTypes: [
{name: ''}, {name: '备货'}, {name: '发货'}, {name: '收货'},
{name: '换货'}, {name: '退货'}, {name: '收款'}, {name: '付款'},
{name: '退款'}, {name: '维修'}, {name: '报废'}
],
goodsTypes: [
{name: ''}, {name: '出库'}, {name: '入库'},
{name: '换货'}, {name: '报废'}, {name: '其它'}
],
accountTypes: [
{name: ''}, {name: '收入现金'}, {name: '收入支票'}, {name: '支出'}
],
capitalTypes: [
{name: ''}, {name: '销售'}, {name: '采购'},
{name: '维护'}, {name: '日常开销'}
]
};
},
orderDisposalId: function() {
var data = Template.currentData();
if (!data || !data.disposal) {
return '单据号无效';
}
var index = data.index;
var timestamp = data.disposal.timestamp;
var order = Orders.findOne();
var code = order ? order.code : '';
return orderDisposalId(code, timestamp, index);
},
isSelected: function (attr) {
var selection = Template.parentData();
selection = selection && selection.disposal && selection.disposal.type;
//console.log('selection: ' + selection);
return attr == selection ? 'selected' : '';
},
isSelectedDelivery: function (attr) {
//console.log('this.name: ' + this.name);
var data = Template.parentData();
//console.log('delivery data: ' + JSON.stringify(data.delivery));
data = data && data.delivery;
return data && data.type == attr ? 'selected' : '';
},
isSelectedCapital: function (attr) {
var data = Template.parentData();
//console.log('disposal data: ' + JSON.stringify(data));
var capital = data && data.capital;
//capital && console.log('capital: ' + JSON.stringify(capital));
return capital && capital.type == attr ? 'selected' : '';
},
isSelectedAccount: function (attr) {
var data = Template.parentData();
data = data ? data.capital : null;
//console.log('account data: ' + JSON.stringify(data));
if (!data || !data.money || !data.money.value) {
return '' == attr ? 'selected' : '';
} else if (data.money.value < 0) {
return '支出' == attr ? 'selected' : '';
}
return '收入' + data.money.type == attr ? 'selected' : '';
},
getOrderInfo: function() {
console.log('order disposal: ' + JSON.stringify(Template.currentData()));
//console.log('data: ' + JSON.stringify(this));
var data = Template.currentData();
return data || {};
},
absolute: function (v) {
return isNaN(v) ? '' : Math.abs(v);
},
hasError: function (field) {
var data = Template.currentData();
var index = data && data.index;
if (isNaN(index)) {
return;
}
//console.log('index: ' + index);
var errors = Session.get('orderDisposalDetailSubmitErrors')[++index];
return errors && errors[field] ? 'has-error' : '';
},
managerId: function () {
return Meteor.userId();
},
managerName: function () {
var user = Meteor.user();
return user && user.profile.name;
},
time: function (d) {
return d && d.getTime() ? d.getTime() : 0;
},
formatDate: formatDate
});
Template.orderDisposalDetail.onCreated(function () {
Session.set('orderDisposalDetailSubmitErrors', []);
});
Template.orderDisposalDetail.onRendered(function() {
// 初始化日期选择插件
$('.order-disposal-detail input[name=timestamp]').datepicker({
format: "yyyy-mm-dd",
language: "zh-CN",
todayBtn: true,
orientation: 'top left',
autoclose: true
});
});
Template.orderDisposalDetail.events({
// 根据用户输入的时间更新DOM附件数据
'change [name=timestamp]': function (e) {
var t = $(e.target);
var d = t && t.val() && t.val().split('-');
// 如果手工设定的日期,则假设时间为下午6点(通常为下班时间)
// 另外添加一个随机的毫秒数(用于区别每次不同修改)
var ms = Math.floor(Math.random() * 1000);
var time = (new Date(d[0], d[1] - 1, d[2], 18, 0, 0, ms));
time = (time.toString() == 'Invalid Date') ? 0 : time.getTime();
t.data('time', time);
},
// 用于显示货物清单
'click .open-goods-list': function (e, t) {
e.preventDefault();
// 首先必须确认已选择货物操作类型
var sel = $(e.target).parent().children('select');
if (!sel || !sel.val()) {
return throwError('请先指定货物操作类型论');
}
var data = Template.currentData();
var index = data && data.index;
var hot = getGoodsListHot(index + 1);
// 获取小三角形图标,用于随后改变放置方向
var caret = $(e.currentTarget).find('i.fa');
var show = $(t.find('.goods-list > .grid'));
if (show.hasClass('hidden')) {
caret.removeClass('fa-caret-down');
caret.addClass('fa-caret-up');
show.removeClass('hidden');
hot && hot.render();
} else {
show.addClass('hidden');
caret.removeClass('fa-caret-up');
caret.addClass('fa-caret-down');
}
},
// 资金金额不能为负数,如果输入负数,自动转为其绝对值
'change [name=capitalValue]': function (e) {
var t = $(e.target);
var value = t.val();
console.log('value: ' + value);
if (isNaN(value)) {
t.val('');
} else if (value < 0) {
t.val(-value);
}
},
// 保存订单的当前处理内容
'click .fa-check': function (e, t) {
e.preventDefault();
//console.log('clicked, data is: ' + JSON.stringify(hot.getData()));
var data = Template.currentData();
var capitalId = '';
var deliveryId = '';
if (data && data.disposal) {
capitalId = data.disposal.capitalId ? data.disposal.capitalId : '';
deliveryId = data.disposal.deliveryId ? data.disposal.deliveryId : '';
}
var orderId = data && data.orderId;
var order = Orders.findOne(orderId);
if (!orderId || !order) {
return throwError('未指定有效订单');
}
var index = data && data.hasOwnProperty('index') ? data.index : -1;
if (isNaN(index) || index < -1) {
return throwError('订单处理索引号有误');
}
//console.log('disposal detail data: ' + JSON.stringify(data));
console.log('orderId is: ' + orderId);
console.log('index is: ' + index);
console.log('保存当前订单处理');
var disposal = t.find('.order-disposal-detail');
var disposalData = getDisposalInfo(disposal);
if (disposalData.delivery.type) {
disposalData.delivery.product = trimGoodsList(getGoodsList(index + 1));
}
data = {
disposal: disposalData,
orderId: orderId,
index: index,
capitalId: capitalId,
deliveryId: deliveryId,
partnerId: order.customer,
stationId: order.stationId
};
//console.log('disposal data: ' + JSON.stringify(data));
var errors = validateOrderDisposal(data.disposal);
console.log('index: ' + index);
signalOrderDisposalError(index + 1, errors);
//Session.set('orderDisposalDetailSubmitErrors', errors);
if (errors.err) {
return throwError(getErrorMessage(errors));
}
Meteor.call('orderDisposalUpdate', data, function (err) {
if (err) {
return throwError(err.reason);
}
//console.log('index: ' + index);
if (index == -1) {
// 清空并隐藏订单处理部分
clearDisposalInfo(disposal, index);
$(disposal).find('.goods-list > .grid').addClass('hidden');
$(disposal).find('.open-goods-list > .fa')
.removeClass('fa-caret-up').addClass('fa-caret-down');
// 此处操作了父级模板的DOM
$('#order-disposal-detail').fadeOut('normal', function () {
$(this).addClass('hide-me');
});
} else {
var hot = getGoodsListHot(index + 1);
hot && hot.render();
}
});
},
// 删除订单的当前处理内容
'click .tools > .fa-trash-o': function (e, t) {
e.preventDefault();
var data = Template.currentData();
var orderId = data && data.orderId;
var index = data && data.hasOwnProperty('index') ? data.index : -2;
if (!orderId || index < -1) {
return throwError('订单信息指定错误');
} else if (index == -1) {
console.log('index: ' + index);
// 清除当前编辑的信息
clearDisposalInfo(t.find('.order-disposal-detail'));
return;
}
// 删除前需要用户确认
if (!confirm('确认要删除本处理信息')) {
return;
}
// 保存最后一个订单处理条目的展开状态,用于删除条目后的恢复
var lastOne = $('.order-disposal-item > .panel.panel-default')
.last().hasClass('hide-me');
Meteor.call('orderDisposalRemove', orderId, index, function (err) {
if (err) {
return throwError(err.reason);
}
clearOrderDisposalGoodsLists(index + 1);
updateGoodsListForRemoval(index + 1);
shiftHiddenItem(index, lastOne);
console.log('remove goods table id: ' + index);
});
}
});
Template.orderDisposal.onCreated(function () {
// 当打开特定Id的订单失败(比如对于Id的订单不存在)时进入创建订单详情页面
var data = Template.currentData();
//console.log('data: ' + JSON.stringify(data));
if (!data.order || !data.order._id) {
Router.go('/order');
}
});
Template.orderDisposal.onDestroyed(function () {
clearOrderDisposalGoodsLists();
});
Template.orderDisposal.onRendered(function () {
// 刚加载订单处理页面时不显示订单处理的表单
$('#order-disposal-detail').hide();
});
Template.orderDisposal.helpers({
currentTime: function() {
var t = new Date();
var y = t.getFullYear();
var m = t.getMonth() + 1;
m = m < 10 ? '0' + m : m;
var d = t.getDate();
d = d < 10 ? '0' + d : d;
var h = t.getHours();
h = h < 10 ? '0' + h : h;
var mm = t.getMinutes();
mm = mm < 10 ? '0' + mm : mm;
var s = t.getSeconds();
s = s < 10 ? '0' + s : s;
return y + '年' + m + '月' + d + '日 ' + h + ':' + mm + ':' + s;
},
// 为每个处理内容关联上索引号并按时间排序,同时插入对应资金收支和货物处理信息
indexDisposal: function () {
var data = Template.currentData();
var orderId = data && data.order && data.order._id;
var disposal = data && data.order && data.order.disposal;
if (!disposal) {
return;
}
data = [];
for (var i = 0; i < disposal.length; i++) {
data.push({
index: i,
orderId: orderId,
disposal: disposal[i],
capital: Capitals.findOne(disposal[i].capitalId),
delivery: Deliveries.findOne(disposal[i].deliveryId)
});
}
data.sort(function (a, b) {
return a.disposal.timestamp.valueOf() - b.disposal.timestamp.valueOf();
});
//console.log('disposal data: ' + JSON.stringify(data));
return data;
}
});
Template.orderDisposal.events({
// 添加订单处理记录
'click .order-tool .add-disposal': function (e) {
console.log('添加订单处理记录');
e.preventDefault();
var data = Template.currentData();
if (!data || !data.order || !data.order._id) {
throwError('请先填写并保存订单基本信息');
//alert('请先保存订单基本信息!');
return;
}
var disposal = $('#order-disposal-detail');
// 确保首次显示页面时是隐藏的
if (disposal.hasClass('hidden')) {
disposal.removeClass('hidden');
disposal.hide();
}
if (disposal.hasClass('hide-me')) {
disposal.removeClass('hide-me');
disposal.fadeIn('normal', function () {
// 设置订单处理日期时间
disposal.find('[name=timestamp]')
.val(formatDate(new Date))
.data('time', Date.now());
});
} else {
disposal.fadeOut('normal', function () {
disposal.addClass('hide-me');
});
}
},
// 保存订单基本信息及处理记录
'click .order-tool .save-all': function (e, t) {
e.preventDefault();
var orderInfo = getOrderInfo(t.find('.edit-order'));
// 如果含有hidden类表示隐藏了订单处理部分,提交时也相应忽略这部分
var disposal = t.find('#order-disposal-detail');
var disposalInfo = {};
var $disposal = $(disposal);
if (!$disposal.hasClass('hide-me')) {
disposalInfo = getDisposalInfo(disposal);
disposalInfo.delivery.product = trimGoodsList(getGoodsList(0));
//console.log('upload disposal data: ' + JSON.stringify(disposalInfo));
disposalInfo.index = $disposal.data('index');
}
var order = _.extend(orderInfo, {disposal: disposalInfo});
//console.log('order: ' + JSON.stringify(order));
var errors = validateOrderBase(order);
Session.set('editOrderSubmitErrors', errors);
if (errors.err) {
return throwError(getErrorMessage(errors));
}
// 如果当前加载了订单,则获取对应id,当前为订单更新操作
var data = Template.currentData();
data = data && data.order;
var orderId = data && data._id ? data._id : '';
if (orderId) {
Meteor.call('orderUpdate', orderId, order, function (err) {
if (err) {
return throwError(err.reason);
}
if (disposalInfo.index >= 0) {
return;
}
// 清空并隐藏订单处理部分
clearDisposalInfo(disposal, -1);
$(disposal).find('.goods-list > .grid').addClass('hidden');
$(disposal).find('.open-goods-list > .fa')
.removeClass('fa-caret-up').addClass('fa-caret-down');
$disposal.fadeOut('normal', function () {
$disposal.addClass('hide-me');
});
});
} else {
Meteor.call('orderInsert', order, function (err, orderId) {
if (err) {
return throwError(err.reason);
}
// 转到当前保存订单的处理界面
Router.go('/order/' + orderId);
});
}
},
// 打印预览订单基本信息及处于显示状态的处理记录
'click .print-preview': function (e) {
e.preventDefault();
// 为了兼容IE浏览器,注意一定加上个全局变量window
window.print();
console.log('打印预览订单基本信息及处理记录');
},
// 删除当前订单基本信息及处理记录
'click .order-tool .remove-order': function (e) {
console.log('删除当前订单基本信息及处理记录');
e.preventDefault();
// 获取对应数据库条目Id
var _id = this.order && this.order._id;
console.log('_id: ' + _id);
if (!confirm('你确实要删除该订单的所有相关信息吗?')) {
return;
}
Meteor.call('orderRemove', _id, function (err) {
//if (err) {
// return throwError(err.reason);
//}
//Router.go('/order');
err ? throwError(err.reason) : Router.go('/order');
});
}
});
function clearDisposalInfo(target, index) {
var t = target ? $(target) : $('#order-disposal-detail');
//t = $('#order-disposal-detail');
var d = new Date();
t.find('[name=timestamp]').val(formatDate(d));
t.find('[name=timestamp]').data('time', d.getTime());
t.find('[name=disposalType]').val('');
//t.find('[name=managerId]').val('');
t.find('[name=disposalComment]').val('');
t.find('[name=goodsType]').val('');
t.find('[name=goodsComment]').val('');
t.find('[name=capitalType]').val('');
t.find('[name=accountType]').val('');
t.find('[name=capitalComment]').val('');
t.find('[name=capitalValue]').val('');
//t.find('[name=currency]').val('');
if (index == -1) {
clearGoodsList(index + 1);
}
}
function getDisposalInfo(target) {
var t = $(target);
var info = {
timestamp: t.find('[name=timestamp]').data('time'),
type: t.find('[name=disposalType]').val(),
managerId: t.find('[name=managerId]').val(),
comment: t.find('[name=disposalComment]').val(),
delivery: {
type: t.find('[name=goodsType]').val(),
comment: t.find('[name=goodsComment]').val()
},
capital: {
type: t.find('[name=capitalType]').val(),
comment: t.find('[name=capitalComment]').val()
}
};
// 存在delivery.type说明delivery内容有效,分析并添加具体内容
//if (info.delivery.type) {
// info.delivery.product = getGoodsList(t.find('.delivery .grid'));
//}
var accountType = t.find('[name=accountType]').val();
console.log('disposal account type: ' + accountType);
var value = parseFloat(t.find('[name=capitalValue]').val());
value = value ? value : 0;
var money = {
currency: t.find('[name=currency]').val(),
// 默认值用于通过服务端验证
value: value,
type: ''
};
if (accountType == '收入现金') {
money.value = +value;
money.type = '现金';
} else if (accountType == '收入支票') {
money.value = +value;
money.type = '支票';
} else if (accountType == '支出') {
money.value = -value;
money.type = '现金';
}
info.capital.money = money;
// 如果订单处理时间值未定义则设为0以满足校验
if (!info.timestamp) {
info.timestamp = 0;
}
return info;
}
// 从订单处理的商品列表中返回数据列表
function getGoodsList(index) {
console.log('index: ' + index);
if (!orderDisposalDetailGoodsLists.hasOwnProperty(index)) {
return [];
}
var hot = orderDisposalDetailGoodsLists[index].hot;
return hot.getData() || [];
}
function clearGoodsList(index) {
if (!orderDisposalDetailGoodsLists.hasOwnProperty(index)) {
return [];
}
var hot = orderDisposalDetailGoodsLists[index].hot;
hot.loadData([[], []]);
}
function getOrderInfo(target) {
var t = $(target);
var info = {
code: t.find('[name=code]').val(),
type: t.find('[name=type]').val(),
status: t.find('[name=status]').val(),
// 后面需对customer进一步处理
customer: t.find('[name=customerNameOrId]'),
address: t.find('[name=address]').val(),
phone: t.find('[name=phone]').val(),
deadline: parseInt(t.find('[name=deadline]').data('time')),
stationId: t.find('[name=stationId]').val(),
managerId: t.find('[name=managerId]').val(),
comment: t.find('[name=comment]').val()
};
// 设置customer,如果显示名称和保存的id值不一致,则说明名称编辑过,采用该值
// 否则保存对应客户Id(通过下拉按钮选择的客户)
var customer = Customers.findOne(info.customer.data('customer-id'));
if (customer && customer.name == info.customer.val()) {
info.customer = customer._id;
} else {
info.customer = info.customer.val();
}
// 如果期限(deadline)未定义则指定为0,以满足校验
if (!info.deadline) {
info.deadline = 0;
}
return info;
}
function shiftHiddenItem(index, lastOne) {
if (index < 0) {
return;
}
var items = $('.order-disposal-item > .panel.panel-default');
var carets = $('.order-disposal-item .open-detail > .fa');
var len = items.length;
// 如果删除的是最后一个,则无需进行任何操作
if (index >= len) {
console.log('删除最后一个处理条目');
return;
}
for (var i = index + 1; i < len; i++) {
if (items.eq(i) && items.eq(i).hasClass('hide-me')) {
items.eq(i - 1).addClass('hide-me').hide();
carets.eq(i - 1).addClass('fa-caret-down').removeClass('fa-caret-up');
} else {
items.eq(i - 1).removeClass('hide-me').show();
carets.eq(i - 1).removeClass('fa-caret-down').addClass('fa-caret-up');
}
}
if (lastOne) {
items.last().addClass('hide-me').hide();
carets.eq(i - 1).addClass('fa-caret-down').removeClass('fa-caret-up');
} else {
items.last().removeClass('hide-me').show();
carets.eq(i - 1).removeClass('fa-caret-down').addClass('fa-caret-up');
}
} | mit |
alphagov/notifications-api | tests/app/dao/test_uploads_dao.py | 14177 | from datetime import datetime, timedelta
from freezegun import freeze_time
from app.dao.uploads_dao import (
dao_get_uploaded_letters_by_print_date,
dao_get_uploads_by_service_id,
)
from app.models import JOB_STATUS_IN_PROGRESS, LETTER_TYPE
from tests.app.db import (
create_job,
create_notification,
create_service,
create_service_contact_list,
create_service_data_retention,
create_template,
)
def create_uploaded_letter(letter_template, service, status='created', created_at=None):
return create_notification(
template=letter_template,
to_field="file-name",
status=status,
reference="dvla-reference",
client_reference="file-name",
one_off=True,
created_by_id=service.users[0].id,
created_at=created_at
)
def create_uploaded_template(service):
return create_template(
service,
template_type=LETTER_TYPE,
template_name='Pre-compiled PDF',
subject='Pre-compiled PDF',
content="",
hidden=True,
postage="second",
)
@freeze_time("2020-02-02 14:00") # GMT time
def test_get_uploads_for_service(sample_template):
create_service_data_retention(sample_template.service, 'sms', days_of_retention=9)
contact_list = create_service_contact_list()
# Jobs created from contact lists should be filtered out
create_job(sample_template, contact_list_id=contact_list.id)
job = create_job(sample_template, processing_started=datetime.utcnow())
letter_template = create_uploaded_template(sample_template.service)
letter = create_uploaded_letter(letter_template, sample_template.service)
other_service = create_service(service_name="other service")
other_template = create_template(service=other_service)
other_job = create_job(other_template, processing_started=datetime.utcnow())
other_letter_template = create_uploaded_template(other_service)
create_uploaded_letter(other_letter_template, other_service)
uploads_from_db = dao_get_uploads_by_service_id(job.service_id).items
other_uploads_from_db = dao_get_uploads_by_service_id(other_job.service_id).items
assert len(uploads_from_db) == 2
assert uploads_from_db[0] == (
None,
'Uploaded letters',
1,
'letter',
None,
letter.created_at.replace(hour=17, minute=30, second=0, microsecond=0),
None,
letter.created_at.replace(hour=17, minute=30, second=0, microsecond=0),
None,
'letter_day',
None,
)
assert uploads_from_db[1] == (
job.id,
job.original_file_name,
job.notification_count,
'sms',
9,
job.created_at,
job.scheduled_for,
job.processing_started,
job.job_status,
"job",
None,
)
assert len(other_uploads_from_db) == 2
assert other_uploads_from_db[0] == (
None,
'Uploaded letters',
1,
'letter',
None,
letter.created_at.replace(hour=17, minute=30, second=0, microsecond=0),
None,
letter.created_at.replace(hour=17, minute=30, second=0, microsecond=0),
None,
"letter_day",
None,
)
assert other_uploads_from_db[1] == (other_job.id,
other_job.original_file_name,
other_job.notification_count,
other_job.template.template_type,
7,
other_job.created_at,
other_job.scheduled_for,
other_job.processing_started,
other_job.job_status,
"job",
None)
assert uploads_from_db[1] != other_uploads_from_db[1]
@freeze_time("2020-02-02 18:00")
def test_get_uploads_for_service_groups_letters(sample_template):
letter_template = create_uploaded_template(sample_template.service)
# Just gets into yesterday’s print run
create_uploaded_letter(letter_template, sample_template.service, created_at=(
datetime(2020, 2, 1, 17, 29, 59)
))
# Yesterday but in today’s print run
create_uploaded_letter(letter_template, sample_template.service, created_at=(
datetime(2020, 2, 1, 17, 30)
))
# First thing today
create_uploaded_letter(letter_template, sample_template.service, created_at=(
datetime(2020, 2, 2, 0, 0)
))
# Just before today’s print deadline
create_uploaded_letter(letter_template, sample_template.service, created_at=(
datetime(2020, 2, 2, 17, 29, 59)
))
# Just missed today’s print deadline
create_uploaded_letter(letter_template, sample_template.service, created_at=(
datetime(2020, 2, 2, 17, 30)
))
uploads_from_db = dao_get_uploads_by_service_id(sample_template.service_id).items
assert [
(upload.notification_count, upload.created_at)
for upload in uploads_from_db
] == [
(1, datetime(2020, 2, 3, 17, 30)),
(3, datetime(2020, 2, 2, 17, 30)),
(1, datetime(2020, 2, 1, 17, 30)),
]
def test_get_uploads_does_not_return_cancelled_jobs_or_letters(sample_template):
create_job(sample_template, job_status='scheduled')
create_job(sample_template, job_status='cancelled')
letter_template = create_uploaded_template(sample_template.service)
create_uploaded_letter(letter_template, sample_template.service, status='cancelled')
assert len(dao_get_uploads_by_service_id(sample_template.service_id).items) == 0
def test_get_uploads_orders_by_created_at_desc(sample_template):
letter_template = create_uploaded_template(sample_template.service)
upload_1 = create_job(sample_template, processing_started=datetime.utcnow(),
job_status=JOB_STATUS_IN_PROGRESS)
upload_2 = create_job(sample_template, processing_started=datetime.utcnow(),
job_status=JOB_STATUS_IN_PROGRESS)
create_uploaded_letter(letter_template, sample_template.service, status='delivered')
results = dao_get_uploads_by_service_id(service_id=sample_template.service_id).items
assert [
(result.id, result.upload_type) for result in results
] == [
(None, 'letter_day'),
(upload_2.id, 'job'),
(upload_1.id, 'job'),
]
def test_get_uploads_orders_by_processing_started_desc(sample_template):
days_ago = datetime.utcnow() - timedelta(days=3)
upload_1 = create_job(sample_template, processing_started=datetime.utcnow() - timedelta(days=1),
created_at=days_ago,
job_status=JOB_STATUS_IN_PROGRESS)
upload_2 = create_job(sample_template, processing_started=datetime.utcnow() - timedelta(days=2),
created_at=days_ago,
job_status=JOB_STATUS_IN_PROGRESS)
results = dao_get_uploads_by_service_id(service_id=sample_template.service_id).items
assert len(results) == 2
assert results[0].id == upload_1.id
assert results[1].id == upload_2.id
@freeze_time("2020-10-27 16:15") # GMT time
def test_get_uploads_orders_by_processing_started_and_created_at_desc(sample_template):
letter_template = create_uploaded_template(sample_template.service)
days_ago = datetime.utcnow() - timedelta(days=4)
create_uploaded_letter(letter_template, service=letter_template.service)
upload_2 = create_job(sample_template, processing_started=datetime.utcnow() - timedelta(days=1),
created_at=days_ago,
job_status=JOB_STATUS_IN_PROGRESS)
upload_3 = create_job(sample_template, processing_started=datetime.utcnow() - timedelta(days=2),
created_at=days_ago,
job_status=JOB_STATUS_IN_PROGRESS)
create_uploaded_letter(letter_template, service=letter_template.service,
created_at=datetime.utcnow() - timedelta(days=3))
results = dao_get_uploads_by_service_id(service_id=sample_template.service_id).items
assert len(results) == 4
assert results[0].id is None
assert results[1].id == upload_2.id
assert results[2].id == upload_3.id
assert results[3].id is None
@freeze_time('2020-04-02 14:00') # Few days after the clocks go forward
def test_get_uploads_only_gets_uploads_within_service_retention_period(sample_template):
letter_template = create_uploaded_template(sample_template.service)
create_service_data_retention(sample_template.service, 'sms', days_of_retention=3)
days_ago = datetime.utcnow() - timedelta(days=4)
upload_1 = create_uploaded_letter(letter_template, service=letter_template.service)
upload_2 = create_job(
sample_template, processing_started=datetime.utcnow() - timedelta(days=1), created_at=days_ago,
job_status=JOB_STATUS_IN_PROGRESS
)
# older than custom retention for sms:
create_job(
sample_template, processing_started=datetime.utcnow() - timedelta(days=5), created_at=days_ago,
job_status=JOB_STATUS_IN_PROGRESS
)
upload_3 = create_uploaded_letter(
letter_template, service=letter_template.service, created_at=datetime.utcnow() - timedelta(days=3)
)
# older than retention for sms but within letter retention:
upload_4 = create_uploaded_letter(
letter_template, service=letter_template.service, created_at=datetime.utcnow() - timedelta(days=6)
)
# older than default retention for letters:
create_uploaded_letter(
letter_template, service=letter_template.service, created_at=datetime.utcnow() - timedelta(days=8)
)
results = dao_get_uploads_by_service_id(service_id=sample_template.service_id).items
assert len(results) == 4
# Uploaded letters get their `created_at` shifted time of printing
# 17:30 BST == 16:30 UTC
assert results[0].created_at == upload_1.created_at.replace(hour=16, minute=30, second=0, microsecond=0)
# Jobs keep their original `created_at`
assert results[1].created_at == upload_2.created_at.replace(hour=14, minute=00, second=0, microsecond=0)
# Still in BST here…
assert results[2].created_at == upload_3.created_at.replace(hour=16, minute=30, second=0, microsecond=0)
# Now we’ve gone far enough back to be in GMT
# 17:30 GMT == 17:30 UTC
assert results[3].created_at == upload_4.created_at.replace(hour=17, minute=30, second=0, microsecond=0)
@freeze_time('2020-02-02 14:00')
def test_get_uploads_is_paginated(sample_template):
letter_template = create_uploaded_template(sample_template.service)
create_uploaded_letter(
letter_template, sample_template.service, status='delivered',
created_at=datetime.utcnow() - timedelta(minutes=3),
)
create_job(
sample_template, processing_started=datetime.utcnow() - timedelta(minutes=2),
job_status=JOB_STATUS_IN_PROGRESS,
)
create_uploaded_letter(
letter_template, sample_template.service, status='delivered',
created_at=datetime.utcnow() - timedelta(minutes=1),
)
create_job(
sample_template, processing_started=datetime.utcnow(),
job_status=JOB_STATUS_IN_PROGRESS,
)
results = dao_get_uploads_by_service_id(sample_template.service_id, page=1, page_size=1)
assert results.per_page == 1
assert results.total == 3
assert len(results.items) == 1
assert results.items[0].created_at == datetime.utcnow().replace(hour=17, minute=30, second=0, microsecond=0)
assert results.items[0].notification_count == 2
assert results.items[0].upload_type == 'letter_day'
results = dao_get_uploads_by_service_id(sample_template.service_id, page=2, page_size=1)
assert len(results.items) == 1
assert results.items[0].created_at == datetime.utcnow().replace(hour=14, minute=0, second=0, microsecond=0)
assert results.items[0].notification_count == 1
assert results.items[0].upload_type == 'job'
def test_get_uploads_returns_empty_list(sample_service):
items = dao_get_uploads_by_service_id(sample_service.id).items
assert items == []
@freeze_time('2020-02-02 14:00')
def test_get_uploaded_letters_by_print_date(sample_template):
letter_template = create_uploaded_template(sample_template.service)
# Letters for the previous day’s run
for _ in range(3):
create_uploaded_letter(
letter_template, sample_template.service, status='delivered',
created_at=datetime.utcnow().replace(day=1, hour=17, minute=29, second=59)
)
# Letters from yesterday that rolled into today’s run
for _ in range(30):
create_uploaded_letter(
letter_template, sample_template.service, status='delivered',
created_at=datetime.utcnow().replace(day=1, hour=17, minute=30, second=0)
)
# Letters that just made today’s run
for _ in range(30):
create_uploaded_letter(
letter_template, sample_template.service, status='delivered',
created_at=datetime.utcnow().replace(hour=17, minute=29, second=59)
)
# Letters that just missed today’s run
for _ in range(3):
create_uploaded_letter(
letter_template, sample_template.service, status='delivered',
created_at=datetime.utcnow().replace(hour=17, minute=30, second=0)
)
result = dao_get_uploaded_letters_by_print_date(
sample_template.service_id,
datetime.utcnow(),
)
assert result.total == 60
assert len(result.items) == 50
assert result.has_next is True
assert result.has_prev is False
result = dao_get_uploaded_letters_by_print_date(
sample_template.service_id,
datetime.utcnow(),
page=10,
page_size=2,
)
assert result.total == 60
assert len(result.items) == 2
assert result.has_next is True
assert result.has_prev is True
| mit |
machine-intelligence/rl-teacher-atari | human-feedback-api/human_feedback_site/urls.py | 912 | from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
import human_feedback_api.views
# Examples:
# url(r'^$', 'human_comparison_site.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
urlpatterns = [
url(r'^$', human_feedback_api.views.index, name='index'),
url(r'^experiments/(.*)/list$', human_feedback_api.views.list_comparisons, name='list'),
url(r'^comparisons/(.*)$', human_feedback_api.views.show_comparison, name='show_comparison'),
url(r'^experiments/(.*)/ajax_response', human_feedback_api.views.ajax_response, name='ajax_response'),
url(r'^experiments/(.*)$', human_feedback_api.views.respond, name='responses'),
url(r'^admin/', include(admin.site.urls)),
url(r'^tree/(.*)$', human_feedback_api.views.tree, name='tree_viewer'),
url(r'^clips/(.*)$', human_feedback_api.views.all_clips, name='all_clips'),
]
| mit |
frankydoge/blok | src/bloks/Grid/Row.js | 1120 | import React from 'react'
import PropTypes from 'prop-types'
import cx from 'classnames'
import '../../blok.css'
const Row = (props) => {
const {
children,
className,
color,
font,
size,
tag,
textAlign
} = props
var rowClass = cx ({
'row': true,
[`color-background-${color}`]: color,
[`font-family-${font}`]: font,
[`font-size-${size}`]: size,
[`text-align-${textAlign}`]: textAlign,
[`${className}`]: className
})
const ElementTag = `${props.tag}`
return (
<ElementTag className={rowClass}>
{props.children}
</ElementTag>
)
}
Row.propTypes = {
/* Add Custom Content */
children: PropTypes.node,
/* Add Custom Classes */
className: PropTypes.string,
/* Set The Color Scheme - REPLACE WITH THEME */
color: PropTypes.string,
/* Set The Font Type */
font: PropTypes.string,
/* Set The Size Of The Font */
size: PropTypes.string,
/* Set The Tag For The Element */
tag: PropTypes.string,
/* Set The Alignment Of The Text */
textAlign: PropTypes.string
}
Row.defaultProps = {
tag: 'div'
}
export default Row | mit |
jcummings/MarshallU-Wordpress-Roots-Theme | functions.php | 1338 | <?php
/**
* Roots includes
*/
require_once locate_template('/lib/utils.php'); // Utility functions
require_once locate_template('/lib/init.php'); // Initial theme setup and constants
require_once locate_template('/lib/sidebar.php'); // Sidebar class
require_once locate_template('/lib/config.php'); // Configuration
//require_once locate_template('/lib/activation.php'); // Theme activation
require_once locate_template('/lib/cleanup.php'); // Cleanup
require_once locate_template('/lib/nav.php'); // Custom nav modifications
require_once locate_template('/lib/comments.php'); // Custom comments modifications
require_once locate_template('/lib/rewrites.php'); // URL rewriting for assets
require_once locate_template('/lib/htaccess.php'); // HTML5 Boilerplate .htaccess
require_once locate_template('/lib/widgets.php'); // Sidebars and widgets
require_once locate_template('/lib/scripts.php'); // Scripts and stylesheets
require_once locate_template('/lib/custom.php'); // Custom functions
require_once locate_template('/lib/hooks.php'); // Custom Hooks
require_once locate_template('/lib/custom-install.php' ); // MU Custom Install
require_once locate_template('/lib/theme-options.php' ); // MU Custom Theme Options | mit |
cy6erskunk/2pane-github-diff | dist/js/diff.min.js | 21660 | (function(content_before, content_after, diff_model) {
/* jshint unused: false */
var DOM = {
addClassToNode: function (node, className) {
if (node && className) {
if (node.classList) {
node.classList.add(className);
} else if ( ! (new RegExp('(^| +)' + className +'( +|$)')).test(node.className)) {
node.className += (node.className.length ? ' ' : '') + className;
}
}
return this;
},
addTextContent: function(node, text) {
node['textContent' in document.body ? 'textContent' : 'innerText'] = text;
return this;
},
bindEvent: function (node, evt, fn) {
if (node.addEventListener) {
node.addEventListener(evt, fn, false);
} else if (node.attachEvent) {
node.attachEvent('on' + evt, fn);
}
return this;
},
getHead: function () {
if ( ! this._head) {
this._head = document.head || document.getElementsByTagName('head')[0];
}
return this._head;
},
target: function(eventObj) {
return eventObj.target || eventObj.srcElement;
}
};
/**
* @typedef {lineObject}
*
* @property {int} [number] - lineNumber
* @property {string} [text] - line of code
* @property {lineType} [type] - any of DiffData#types
*/
/**
* @class DiffData
*
* @method getLines
* @method getNthDiffFirstLineNumber
* @method getLinesCount
*
*/
function DiffData(before, after, diffModel) {
if (! this instanceof DiffData) {
return new DiffData(before, after, diffModel);
}
this.diffModel = diffModel;
this
._initDiffData(before, after)
._setDiffStartLines();
return this;
}
var dataProto = DiffData.prototype;
dataProto.types = {
ADD_LEFT: '+_',
ADD_RIGHT: '_+',
REMOVE_LEFT: '-_',
REMOVE_RIGHT: '_-',
CHANGE: '#'
};
/**
* returns up to `count` lines of code
* @param {int} start - becomes 0 if not an int or < 0
* @param {int} [count]
* @return {lineObject[]}
*/
dataProto.getLines = function (start, count) {
var end = this.length,
result;
start = parseInt(start, 10) || 0;
if (start < 0) {
start = 0;
}
if (count) {
end = Math.min(start + count, this.length);
}
result = {
before: this.before.slice(start, end),
after: this.after.slice(start, end),
};
if (result.before.length !== result.after.length) {
throw new Error('DiffData#getLines returned different number of lines');
}
result.length = result.before.length;
return result;
};
/**
* @param {int} [diffIndex = 0] - zero-based diff index
*
* @return {int|null}
*/
dataProto.getNthDiffFirstLineNumber = function (diffIndex) {
/* jshint camelcase: false */
diffIndex = parseInt(diffIndex, 10) || 0;
if (typeof this._diffStartLines[diffIndex] === 'undefined') {
return null;
}
return this._diffStartLines[diffIndex];
};
dataProto.getLinesCount = function () {
return this.length;
};
dataProto._initDiffData = function (before, after) {
var self = this,
_processData = function(data, isRight) {
var _diffModel = self.diffModel.slice(),
_specialLines = {
type: null,
lines: 0
},
diff = _diffModel.shift(),
_addSpecialLines = function (type, count) {
var specialLines = [];
for (var i = 0; i < count; i += 1) {
specialLines.push({
type: type
});
}
return specialLines;
};
return data.reduce(function (head, currentValue, index) {
/* jshint camelcase: false */
var lineNumber = index,
type = null;
if (isRight) {
while(diff && (lineNumber > diff.after_line_number)) {
diff = _diffModel.shift();
}
} else {
while(diff && (lineNumber > diff.before_line_number)) {
diff = _diffModel.shift();
}
}
if (diff) {
if (isRight) {
if (diff.after_line_number === lineNumber) {
// добавление
if (! diff.before_line_count) {
_specialLines.lines = diff.after_line_count;
_specialLines.type = self.types.ADD_RIGHT;
// удаление
} else if (! diff.after_line_count) {
head = head.concat(_addSpecialLines(self.types.REMOVE_RIGHT, diff.before_line_count));
// изменение
} else if (diff.before_line_count) {
_specialLines.lines = diff.after_line_count;
_specialLines.type = self.types.CHANGE;
}
}
} else {
if (diff.before_line_number === lineNumber) {
// добавление
if (! diff.before_line_count) {
head = head.concat(_addSpecialLines(self.types.ADD_LEFT, diff.after_line_count));
// удаление
} else if (! diff.after_line_count) {
_specialLines.lines = diff.before_line_count;
_specialLines.type = self.types.REMOVE_LEFT;
// изменение
} else if (diff.after_line_count) {
_specialLines.lines = diff.before_line_count;
_specialLines.type = self.types.CHANGE;
}
}
}
}
if (_specialLines && _specialLines.lines && ! type) {
type = _specialLines.type;
_specialLines.lines -= 1;
}
head.push({
number: lineNumber,
text: currentValue,
type: type
});
return head;
}, []);
};
this.before = _processData(before);
this.after = _processData(after, true);
if (this.before.length !== this.after.length) {
throw new Error('#before and #after have different lengths!');
}
this.length = this.before.length;
return this;
};
dataProto._setDiffStartLines = function () {
var startLines = [],
addition = 0;
this.diffModel.forEach(function(diff) {
/* jshint camelcase: false */
startLines.push(diff.before_line_number + addition);
if ( !diff.before_line_count) {
addition += Math.max(diff.before_line_count, diff.after_line_count);
}
});
this._diffStartLines = startLines;
return this;
};
/* global DOM: false */
/**
* @class DiffView
*
* @method init
*
* @method displayPanels
* @method clearPanels
* @method addLineToTarget
* @method scroll
*
* @method _processOptions
* @method _hideLoader
* @method _determineLineHeight
* @method _getPanels
* @method _setLinesCount
* @method _setNumbersWidth
* @method _bindHandlers
* @method _addCodeToTarget
* @method _removeLines
* @method _scrollUp
* @method _scrollDown
* @method _scrollToFirstLine
* @method _positionPseudoScroll
* @method _addOverView
*
**/
function DiffView(diffData) {
if (! this instanceof DiffView) {
return new DiffView(diffData);
}
this.diffData = diffData;
}
/*
/---start of loaded data----\
\
===> hiddenLines.before
/
----start of visible area---/=\==> firstLine
\
=> linesInPanel
/
----end of visible area-----\-/
\
===> hiddenLines.after
/
\---end of loaded data------/
*/
var viewProto = DiffView.prototype;
viewProto.init = function (options) {
return this
._processOptions(options)
._hideLoader()
._determineLineHeight()
._setNumbersWidth()
._getPanels()
._setLinesCount()
._bindHandlers()
._addOverview();
};
viewProto._processOptions = function (options) {
var o = {
loaderSelector: '.loader-wrapper',
panelSelector: '.wrapper',
leftPanelSelector: '.wrapper_left',
rightPanelSelector: '.wrapper_right',
lineWrapper: {
cls: 'line-wrapper',
tag: 'div'
},
lineNumber: {
cls: 'line-number',
tag: 'span'
},
lineText: {
cls: 'line-text',
tag: 'span'
},
diffAddClass: 'green',
diffDelClass: 'red',
diffChangeClass: 'yellow',
MIN_HIDDEN_LINES_COUNT: 200,
overviewSelector: '.overview',
overviewChild: {
cls: 'overview__diff',
height: 10
},
pseudoScrollSelector: '.overview-wrapper .position'
};
if (options) {
Object.keys(o).forEach(function (name) {
if (options.hasOwnProperty(name)) {
o[name] = options[name];
}
});
}
this.o = o;
return this;
};
/**
* @param {int} [firstLine] - first visible line in panel
* (in case when there's not enough lines to fill the panel
* it may be decreased)
*/
viewProto.displayPanels = function (firstLine) {
var totalLineNumber = this.diffData.getLinesCount(),
dataSlices;
this.firstLine = typeof firstLine !== 'undefined'?
// check if first line is not greater then total number of lines
Math.min(parseInt(firstLine, 10) || 0, totalLineNumber) :
this.firstLine;
// make sure that last visible line is not greater than total number of lines
if (this.firstLine + this.linesInPanel > totalLineNumber) {
this.firstLine = totalLineNumber - this.linesInPanel + 1;
}
this.hiddenLines.before = Math.min(this.firstLine - 1, this.hiddenLines.max);
this.hiddenLines.after = Math.min(totalLineNumber - (this.firstLine + this.linesInPanel - 1), this.hiddenLines.max);
this.lineCount = this.linesInPanel + this.hiddenLines.before + this.hiddenLines.after;
dataSlices = this.diffData.getLines(this.firstLine - this.hiddenLines.before - 1, this.lineCount);
this.stopScrolling = false;
this._addCodeToTarget(dataSlices.before, this.leftPanel);
this._addCodeToTarget(dataSlices.after, this.rightPanel);
this._scrollToFirstLine();
this._positionPseudoScroll(this.firstLine);
return this;
};
viewProto.clearPanels = function () {
this.leftPanel.innerHTML = this.rightPanel.innerHTML = '';
this.stopScrolling = true;
return this;
};
/**
* adds line of code to target Node
* @param {Node} target
* @param {lineObject} lineObject - lineObject described in DiffData
*/
viewProto.addLineToTarget = function (target, lineObject) {
var lineElem = document.createElement(this.o.lineWrapper.tag),
numberElem = document.createElement(this.o.lineNumber.tag),
textElem = document.createElement(this.o.lineText.tag),
_class, _number, _text,
_addLine = function () {
DOM.addClassToNode(lineElem, _class);
DOM.addTextContent(numberElem, _number || lineObject.number);
DOM.addTextContent(textElem, _text || lineObject.text || ' ');
};
DOM.addClassToNode(lineElem, this.o.lineWrapper.cls);
DOM.addClassToNode(numberElem, this.o.lineNumber.cls);
DOM.addClassToNode(textElem, this.o.lineText.cls);
switch (lineObject.type) {
case this.diffData.types.ADD_LEFT:
_class = this.o.diffAddClass;
_number = '+';
break;
case this.diffData.types.ADD_RIGHT:
_class = this.o.diffAddClass;
break;
case this.diffData.types.REMOVE_RIGHT:
_class = this.o.diffDelClass;
_number = '-';
break;
case this.diffData.types.REMOVE_LEFT:
_class = this.o.diffDelClass;
break;
case this.diffData.types.CHANGE:
_class = this.o.diffChangeClass;
break;
}
_addLine();
lineElem.appendChild(numberElem);
lineElem.appendChild(textElem);
target.appendChild(lineElem);
return this;
};
viewProto.scroll = function (lineNumber) {
if (lineNumber < this.firstLine - this.hiddenLines.before / 2 &&
this.hiddenLines.before >= this.hiddenLines.max) {
this._scrollUp(lineNumber);
} else if (lineNumber > this.firstLine + (this.linesInPanel + this.hiddenLines.after)/ 2 &&
this.hiddenLines.after >= this.hiddenLines.max) {
this._scrollDown(lineNumber);
}
return this;
};
viewProto._hideLoader = function () {
document.querySelector(this.o.loaderSelector).style.display = 'none';
return this;
};
viewProto._determineLineHeight = function () {
var testLineWrapper = document.createElement(this.o.lineWrapper.tag),
rect;
testLineWrapper.style.position = 'absolute';
testLineWrapper.style.left = '-9999px';
this.addLineToTarget(testLineWrapper, { text: 'TEST', number: 1});
document.body.appendChild(testLineWrapper);
// @TODO take into account margins
rect = testLineWrapper.firstChild.getBoundingClientRect();
this.lineHeight = rect.height || (rect.bottom - rect.top);
document.body.removeChild(testLineWrapper);
return this;
};
viewProto._getPanels = function () {
this.panels = document.querySelectorAll(this.o.panelSelector);
this.leftPanel = document.querySelector(this.o.leftPanelSelector);
this.rightPanel = document.querySelector(this.o.rightPanelSelector);
return this;
};
viewProto._setLinesCount = function () {
// @TODO paddings?
var panelHeight = this.leftPanel.clientHeight;
this.linesInPanel = Math.ceil(panelHeight / this.lineHeight);
this.hiddenLines = {
max: Math.max(this.o.MIN_HIDDEN_LINES_COUNT, 2 * this.linesInPanel)
};
this.hiddenLines.before = this.hiddenLines.after = this.hiddenLines.max;
this.lineCount = this.linesInPanel + this.hiddenLines.before + this.hiddenLines.after;
this.firstLine = 0;
return this;
};
viewProto._setNumbersWidth = function () {
var styleElem = document.createElement('style'),
css = '.' + this.o.lineNumber.cls + '{width:' + (this.diffData.getLinesCount() + '').length + 'em;}';
styleElem.setAttribute('type', 'text/css');
if (styleElem.styleSheet) { // IE
styleElem.styleSheet.cssText = css;
} else {
styleElem.appendChild(document.createTextNode(css));
}
DOM.getHead().appendChild(styleElem);
return this;
};
viewProto._addCodeToTarget = function (data, target, prepend) {
var _docFrag = document.createDocumentFragment(),
self = this;
data.forEach(function(v) {
self.addLineToTarget(_docFrag, v);
});
if (prepend) {
target.insertBefore(_docFrag, target.firstChild);
} else {
target.appendChild(_docFrag);
}
return this;
};
viewProto._removeLines = function(type, count) {
[this.leftPanel, this.rightPanel].forEach(function (parent) {
for (var i = 0; i < count; i += 1) {
if (parent[type + 'Child']) {
parent.removeChild(parent[type + 'Child']);
}
}
});
return this;
};
viewProto._scrollUp = function(lineNumber) {
var linesToReceive = Math.abs(this.firstLine - lineNumber),
dataSlices = this.diffData.getLines(lineNumber - this.hiddenLines.before, linesToReceive),
linesReceived = dataSlices.length,
linesToRemove = linesReceived,
delta;
if (lineNumber < this.hiddenLines.before) {
this.hiddenLines.before = lineNumber;
}
if (this.hiddenLines.after < this.hiddenLines.max) {
delta = this.hiddenLines.max - this.hiddenLines.after;
this.hiddenLines.after += Math.min(delta, linesToRemove);
linesToRemove -= Math.min(delta, linesToRemove);
}
this._removeLines('last', linesToRemove);
this._addCodeToTarget(dataSlices.before, this.leftPanel, true);
this._addCodeToTarget(dataSlices.after, this.rightPanel, true);
this.firstLine = lineNumber;
this.hiddenLines.before -= linesToReceive - linesReceived;
this._scrollToFirstLine();
return this;
};
viewProto._scrollDown = function (lineNumber) {
var linesToReceive = Math.abs(this.firstLine - lineNumber),
dataSlices = this.diffData.getLines(this.firstLine + this.linesInPanel + this.hiddenLines.after, linesToReceive),
linesReceived = dataSlices.length,
linesToRemove = linesReceived,
delta;
if (this.hiddenLines.before < this.hiddenLines.max) {
delta = this.hiddenLines.max - this.hiddenLines.before;
this.hiddenLines.before += Math.min(delta, linesToRemove);
linesToRemove -= Math.min(delta, linesToRemove);
}
this._removeLines('first', linesToRemove);
this._addCodeToTarget(dataSlices.before, this.leftPanel);
this._addCodeToTarget(dataSlices.after, this.rightPanel);
this.firstLine = lineNumber;
this.hiddenLines.after -= linesToReceive - linesReceived;
this._scrollToFirstLine();
return this;
};
viewProto._bindHandlers = function () {
var self = this;
DOM.bindEvent(this.leftPanel, 'scroll', function (e) {
var currentLineNumber = self.firstLine - self.hiddenLines.before + Math.floor(DOM.target(e).scrollTop / self.lineHeight);
if ( ! self.stopScrolling) {
self.scroll(currentLineNumber);
self.rightPanel.scrollTop = DOM.target(e).scrollTop;
self.rightPanel.scrollLeft = DOM.target(e).scrollLeft;
}
self._positionPseudoScroll(currentLineNumber);
});
DOM.bindEvent(this.rightPanel, 'scroll', function (e) {
if ( ! self.stopScrolling) {
self.leftPanel.scrollTop = DOM.target(e).scrollTop;
self.leftPanel.scrollLeft = DOM.target(e).scrollLeft;
}
});
return this;
};
/**
* scrolls to this.firstLine
*/
viewProto._scrollToFirstLine = function () {
this.leftPanel.scrollTop = (this.hiddenLines.before + 1) * this.lineHeight;
// TODO: update linesInPanel on resize
return this;
};
viewProto._positionPseudoScroll = function (currentLineNumber) {
var pseudoScrollElem = document.querySelector(this.o.pseudoScrollSelector),
overviewHeight = (document.querySelector(this.o.overviewSelector)).clientHeight;
// minimal height of pseudoScrollElem = 10px
pseudoScrollElem.style.top = (Math.floor(currentLineNumber / this.diffData.getLinesCount() * overviewHeight) - 5) + 'px';
pseudoScrollElem.style.height = (Math.max(10, Math.floor(this.leftPanel.clientHeight / this.leftPanel.scrollHeight * overviewHeight)) )+ 'px';
return this;
};
viewProto._addOverview = function () {
var self = this,
overviewElem = document.querySelector(this.o.overviewSelector),
reducedLength = this.diffData.getLinesCount() / overviewElem.clientHeight,
dataAttr = 'data-diff';
this.diffData.diffModel.map(function (diff) {
/* jshint camelcase: false */
var color = diff.before_line_count && diff.after_line_count ? 'yellow' :
diff.before_line_count && !diff.after_line_count ? 'red' : 'green';
return {
color: color,
lineNumber: diff.before_line_number,
top: Math.floor(Math.min(diff.before_line_number, diff.after_line_number) / reducedLength)
};
}).forEach(function (diff, index, array) {
var elem = document.createElement('diff');
DOM.addClassToNode(elem, self.o.overviewChild.cls);
elem.setAttribute(dataAttr, index);
elem.style.top = diff.top + 'px';
if (array[index - 1] && diff.top - array[index - 1].top < self.o.overviewChild.height) {
diff.top += self.o.overviewChild.height - diff.top + array[index - 1].top;
elem.style.top = diff.top + 'px';
}
elem.style.backgroundColor = diff.color;
overviewElem.appendChild(elem);
});
DOM.bindEvent(overviewElem, 'click', function (e) {
var target = DOM.target(e);
if (target.getAttribute('data-diff')) {
self
.clearPanels()
.displayPanels(self.diffData.getNthDiffFirstLineNumber(target.getAttribute(dataAttr)));
}
});
};
/* global DiffData: false, DiffView: false, diff_model: false, content_before: false, content_after: false */
/* jshint camelcase: false */
var diffData = new DiffData(content_before.split('\n'), content_after.split('\n'), diff_model),
diffView = new DiffView(diffData);
diffView.init();
diffView.displayPanels(diffData.getNthDiffFirstLineNumber());
})(content_before, content_after, diff_model);
| mit |
leifos/simiir | simiir/query_generators/single_reversed_tri_interleaved_generator.py | 1404 | from ifind.common.query_ranker import QueryRanker
from ifind.common.query_generation import SingleQueryGeneration
from simiir.query_generators.base_generator import BaseQueryGenerator
from query_generators.single_term_generator_reversed import SingleTermQueryGeneratorReversed
from query_generators.tri_term_generator import TriTermQueryGenerator
class SingleReversedTriInterleavedQueryGenerator(BaseQueryGenerator):
"""
Takes the SingleTermGeneratorReversed and the TriTermGenerator, and interleaves like [Single,Tri,Single,Tri,Single,Tri...]
"""
def __init__(self, stopword_file, background_file=[]):
super(SingleReversedTriInterleavedQueryGenerator, self).__init__( stopword_file, background_file=background_file)
self.__single = SingleTermQueryGeneratorReversed( stopword_file, background_file)
self.__tri = TriTermQueryGenerator(stopword_file, background_file)
def generate_query_list(self, search_context):
"""
Given a Topic object, produces a list of query terms that could be issued by the simulated agent.
"""
topic = search_context.topic
single_queries = self.__single.generate_query_list(search_context)
tri_queries = self.__tri.generate_query_list(search_context)
interleaved_queries = [val for pair in zip(single_queries, tri_queries) for val in pair]
return interleaved_queries
| mit |
twistor/flysystem-stream-wrapper | src/Flysystem/Exception/TriggerErrorException.php | 311 | <?php
namespace Twistor\Flysystem\Exception;
use League\Flysystem\Exception;
class TriggerErrorException extends Exception
{
protected $defaultMessage;
public function formatMessage($function)
{
return sprintf($this->message ? $this->message : $this->defaultMessage, $function);
}
}
| mit |
jehovahsays/hiddenwiki | examples/chat/node_modules/php-embed/src/node_php_jsserver_class.cc | 6153 | // This is a thin wrapper object to allow javascript to call
// php_register_variable_* inside an initialization callback.
// Copyright (c) 2015 C. Scott Ananian <[email protected]>
#include "src/node_php_jsserver_class.h"
extern "C" {
#include "main/php.h"
#include "main/php_variables.h"
#include "Zend/zend.h"
#include "Zend/zend_exceptions.h"
}
#include "src/macros.h"
#include "src/values.h"
using node_php_embed::node_php_jsserver;
/* Class entries */
zend_class_entry *php_ce_jsserver;
/*Object handlers */
static zend_object_handlers node_php_jsserver_handlers;
/* Constructors and destructors */
static void node_php_jsserver_free_storage(
void *object,
zend_object_handle handle TSRMLS_DC) {
TRACE(">");
node_php_jsserver *c = reinterpret_cast<node_php_jsserver *>(object);
zend_object_std_dtor(&c->std TSRMLS_CC);
zval_ptr_dtor(&(c->track_vars_array));
efree(object);
TRACE("<");
}
static zend_object_value node_php_jsserver_new(zend_class_entry *ce TSRMLS_DC) {
TRACE(">");
zend_object_value retval;
node_php_jsserver *c;
c = reinterpret_cast<node_php_jsserver *>(ecalloc(1, sizeof(*c)));
zend_object_std_init(&c->std, ce TSRMLS_CC);
retval.handle = zend_objects_store_put(
c, nullptr,
(zend_objects_free_object_storage_t) node_php_jsserver_free_storage,
nullptr TSRMLS_CC);
retval.handlers = &node_php_jsserver_handlers;
TRACE("<");
return retval;
}
void node_php_embed::node_php_jsserver_create(zval *res, zval *track_vars_array
TSRMLS_DC) {
TRACE(">");
object_init_ex(res, php_ce_jsserver);
node_php_jsserver *c = reinterpret_cast<node_php_jsserver *>
(zend_object_store_get_object(res TSRMLS_CC));
c->track_vars_array = track_vars_array;
Z_ADDREF_P(c->track_vars_array);
TRACE("<");
}
/* Methods */
#define FETCH_OBJ_ELSE(method, this_ptr, defaultValue) \
node_php_jsserver *obj = reinterpret_cast<node_php_jsserver *> \
(zend_object_store_get_object(this_ptr TSRMLS_CC))
#define FETCH_OBJ(method, this_ptr) FETCH_OBJ_ELSE(method, this_ptr, )
#define PARSE_PARAMS(method, ...) \
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, __VA_ARGS__) == \
FAILURE) { \
zend_throw_exception(zend_exception_get_default(TSRMLS_C), \
"bad args to " #method, 0 TSRMLS_CC); \
return; \
} \
FETCH_OBJ(method, this_ptr)
ZEND_BEGIN_ARG_INFO_EX(node_php_jsserver_get_args, 0, 1/*return by ref*/, 1)
ZEND_ARG_INFO(0, member)
ZEND_END_ARG_INFO()
PHP_METHOD(JsServer, __get) {
TRACE(">");
zval *member;
PARSE_PARAMS(__get, "z/", &member);
convert_to_string(member);
zval_ptr_dtor(&return_value);
zval **retval;
if (FAILURE ==
zend_symtable_find(Z_ARRVAL_P(obj->track_vars_array),
Z_STRVAL_P(member), Z_STRLEN_P(member) + 1,
reinterpret_cast<void**>(&retval))) {
*return_value_ptr = return_value = EG(uninitialized_zval_ptr);
} else {
*return_value_ptr = return_value = *retval;
}
Z_ADDREF_P(return_value);
TRACE("<");
}
ZEND_BEGIN_ARG_INFO_EX(node_php_jsserver_set_args, 0, 0, 2)
ZEND_ARG_INFO(0, member)
ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()
PHP_METHOD(JsServer, __set) {
zval *member; zval *zv;
TRACE(">");
PARSE_PARAMS(__set, "z/z/", &member, &zv);
node_php_embed::ZVal value(zv ZEND_FILE_LINE_CC);
convert_to_string(member);
// This is the whole point of this class!
php_register_variable_ex(Z_STRVAL_P(member), value.Transfer(TSRMLS_C),
obj->track_vars_array TSRMLS_CC);
RETVAL_BOOL(true);
TRACE("<");
}
#define STUB_METHOD(name) \
PHP_METHOD(JsServer, name) { \
TRACE(">"); \
zend_throw_exception( \
zend_exception_get_default(TSRMLS_C), \
"Can't directly construct, serialize or unserialize JsServer.", \
0 TSRMLS_CC); \
TRACE("<"); \
RETURN_FALSE; \
}
/* NOTE: We could also override node_php_jsserver_handlers.get_constructor
* to throw an exception when invoked, but doing so causes the
* half-constructed object to leak -- this seems to be a PHP bug. So
* we'll define magic __construct methods instead. */
STUB_METHOD(__construct)
STUB_METHOD(__sleep)
STUB_METHOD(__wakeup)
static const zend_function_entry node_php_jsserver_methods[] = {
PHP_ME(JsServer, __construct, nullptr,
ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
PHP_ME(JsServer, __sleep, nullptr,
ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
PHP_ME(JsServer, __wakeup, nullptr,
ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
PHP_ME(JsServer, __get, node_php_jsserver_get_args,
ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
PHP_ME(JsServer, __set, node_php_jsserver_set_args,
ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
PHP_MINIT_FUNCTION(node_php_jsserver_class) {
TRACE("> PHP_MINIT_FUNCTION");
zend_class_entry ce;
/* JsServer class */
INIT_CLASS_ENTRY(ce, "Js\\Server", node_php_jsserver_methods);
php_ce_jsserver = zend_register_internal_class(&ce TSRMLS_CC);
php_ce_jsserver->ce_flags |= ZEND_ACC_FINAL;
php_ce_jsserver->create_object = node_php_jsserver_new;
/* JsServer handlers */
memcpy(&node_php_jsserver_handlers, zend_get_std_object_handlers(),
sizeof(zend_object_handlers));
node_php_jsserver_handlers.clone_obj = nullptr;
node_php_jsserver_handlers.cast_object = nullptr;
node_php_jsserver_handlers.get_property_ptr_ptr = nullptr;
TRACE("< PHP_MINIT_FUNCTION");
return SUCCESS;
}
| mit |
adam-boduch/coyote | app/Repositories/Contracts/CurrencyRepositoryInterface.php | 226 | <?php
namespace Coyote\Repositories\Contracts;
interface CurrencyRepositoryInterface extends RepositoryInterface
{
/**
* @param string $currency
* @return float
*/
public function latest($currency);
}
| mit |
CedricDumont/NMemory.Next | Main/Source/NMemory/Services/AnonymousTypeKeyInfoService.cs | 2915 | // ----------------------------------------------------------------------------------
// <copyright file="AnonymousTypeKeyInfoService.cs" company="NMemory Team">
// Copyright (C) NMemory Team
//
// 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.
// </copyright>
// ----------------------------------------------------------------------------------
namespace NMemory.Services
{
using System;
using System.Linq.Expressions;
using System.Reflection;
using NMemory.Common;
using NMemory.Indexes;
using NMemory.Services.Contracts;
public class AnonymousTypeKeyInfoService : IKeyInfoService
{
public bool TryCreateKeyInfo<TEntity, TKey>(
Expression<Func<TEntity, TKey>> keySelector,
out IKeyInfo<TEntity, TKey> result) where TEntity : class
{
if (!ReflectionHelper.IsAnonymousType(typeof(TKey)))
{
result = null;
return false;
}
IKeyInfoHelper helper = AnonymousTypeKeyInfo<TEntity, TKey>.KeyInfoHelper;
MemberInfo[] members;
if (!helper.TryParseKeySelectorExpression(keySelector.Body, true, out members))
{
result = null;
return false;
}
result = new AnonymousTypeKeyInfo<TEntity, TKey>(members);
return true;
}
public bool TryCreateKeyInfoHelper(
Type keyType,
out IKeyInfoHelper result)
{
if (!ReflectionHelper.IsAnonymousType(keyType))
{
result = null;
return false;
}
result = new AnonymousTypeKeyInfoHelper(keyType);
return true;
}
}
}
| mit |
JGL/Reactickles3 | docs/TouchDemonstration/sketch.js | 867 | function setup() {
createCanvas(windowWidth,windowHeight); //make a fullscreen canvas, thanks to: http://codepen.io/grayfuse/pen/wKqLGL
ellipseMode(RADIUS); //https://p5js.org/reference/#/p5/ellipseMode draw with a radius rather than a width
}
function draw() {
background(0); //black background
stroke('red'); //draw circles outlines in red
fill('red'); //draw circles filled in red
var circleRadius = 50;
ellipse(mouseX, mouseY, circleRadius, circleRadius); //just to prove i'm drawing and updating!
print("The number of touches is " + touches.length);
for (var i = 0; i < touches.length-1; i++) { //for each of the elements in the touches array
var xPosition = touches[i].x;
var yPosition = touches[i].y;
ellipse(xPosition, yPosition, circleRadius); // https://p5js.org/reference/#/p5/ellipse and https://p5js.org/reference/#/p5/ellipseMode
}
}
| mit |
andreabiggi/bivsg | src/Acme/ProvaBundle/AcmeProvaBundle.php | 126 | <?php
namespace Acme\ProvaBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AcmeProvaBundle extends Bundle
{
}
| mit |
scala-rules/rule-engine | engine-core/src/main/scala/org/scalarules/facts/facts.scala | 1351 | package org.scalarules.facts
import org.scalarules.engine.{ErrorEvaluation, Evaluation, ListFactEvaluation, SingularFactEvaluation}
import scala.language.existentials
trait Fact[+A] {
def name: String
def description: String
def toEval: Evaluation[A]
def valueType: String
override def toString: String = name
}
case class SingularFact[+A](name: String, description: String = "", valueType: String = "") extends Fact[A] {
def toEval: Evaluation[A] = new SingularFactEvaluation(this)
}
case class ListFact[+A](name: String, description: String = "", valueType: String = "") extends Fact[List[A]] {
def toEval: Evaluation[List[A]] = new ListFactEvaluation[A](this)
}
case object OriginFact extends Fact[Nothing] {
def name: String = "___meta___OriginFact___meta___"
def description: String = "Meta-fact used in graph construction"
def toEval: Evaluation[Nothing] = new ErrorEvaluation("The OriginFact is a meta-fact used in graph construction to indicate top-level constant evaluations")
def valueType: String = "Nothing"
}
case class SynthesizedFact[+A](factOriginalFact: Fact[Any], synthesizedPostfix: String, description: String = "", valueType: String = "") extends Fact[A] {
def name: String = factOriginalFact.name + "_" + synthesizedPostfix
def toEval: Evaluation[A] = new SingularFactEvaluation[A](this)
}
| mit |
alexyz/vcswatcher | src/vcsw/RepositoryJTable.java | 4397 | package vcsw;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.RowSorter.SortKey;
import javax.swing.table.*;
import vcsw.Main;
import vcsw.Repository;
import static vcsw.Main.*;
public class RepositoryJTable extends JTable {
public static final Color tableBackgroundColour = UIManager.getDefaults().getColor("Table.background");
public static final Color favouriteBackgroundColour = new Color(224, 224, 224);
public static final Font tableFont = UIManager.getDefaults().getFont("Table.font");
public static final Font favouriteFont = tableFont.deriveFont(Font.BOLD);
public RepositoryJTable () {
super(new RepositoryTableModel());
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed (MouseEvent e) {
popup(e);
}
@Override
public void mouseReleased (MouseEvent e) {
popup(e);
}
@Override
public void mouseClicked (MouseEvent e) {
click(e);
}
});
setAutoCreateRowSorter(true);
getRowSorter().setSortKeys(Arrays.asList(new SortKey(0, SortOrder.ASCENDING)));
TableColumn c = getColumnModel().getColumn(0);
c.setPreferredWidth(160);
}
@Override
public RepositoryTableModel getModel () {
return (RepositoryTableModel) super.getModel();
}
private void click (MouseEvent e) {
println("table mouse click");
if (e.getClickCount() >= 2) {
int r = rowAtPoint(e.getPoint());
if (r >= 0) {
int r2 = convertRowIndexToModel(r);
final Repository rep = getModel().getRepository(r2);
rep.command(Repository.Command.REFRESH);
}
}
}
/**
* show right click menu for given mouse event
*/
private void popup (MouseEvent e) {
if (!e.isPopupTrigger()) {
return;
}
{
int r = rowAtPoint(e.getPoint());
int c = columnAtPoint(e.getPoint());
if (!(r >= 0 && c >= 0)) {
return;
}
if (!isCellSelected(r, c)) {
clearSelection();
addRowSelectionInterval(r, r);
addColumnSelectionInterval(c, c);
}
}
int[] rows = getSelectedRows();
final List<Repository> reps = new ArrayList<>();
final List<Repository.Command> cmds = new ArrayList<>();
for (int row : rows) {
int modelRow = convertRowIndexToModel(row);
Repository rep = getModel().getRepository(modelRow);
reps.add(rep);
for (Repository.Command cmd : rep.getCommands()) {
if (!cmds.contains(cmd)) {
cmds.add(cmd);
}
}
}
println("popup on " + reps);
JPopupMenu menu = new JPopupMenu("Commands");
for (final Repository.Command cmd : cmds) {
JMenuItem mi = new JMenuItem(cmd.name);
mi.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
for (final Repository rep : reps) {
Main.commandLater(rep, cmd);
}
}
});
menu.add(mi);
}
menu.show(this, e.getX(), e.getY());
}
@Override
public String getToolTipText (MouseEvent e) {
int r = rowAtPoint(e.getPoint());
int c = columnAtPoint(e.getPoint());
if (r >= 0 && c >= 0) {
int r2 = convertRowIndexToModel(r);
int c2 = convertColumnIndexToModel(c);
String t = getModel().getToolTipAt(r2, c2);
if (t != null && t.length() > 0) {
if (t.contains("\n")) {
return "<html>" + t.replace("\n", "<br>") + "</html>";
} else {
return t;
}
}
}
return null;
}
@Override
public Component prepareRenderer (TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
if (comp instanceof JComponent) {
JComponent jComp = (JComponent) comp;
int r2 = convertRowIndexToModel(row);
int c2 = convertColumnIndexToModel(col);
boolean selected = getSelectionModel().isSelectedIndex(row);
if (!selected) {
// if there isn't a cell specific colour, use a row specific one
Color bg = getModel().getBackgroundAt(r2, c2);
jComp.setBackground(bg != null ? bg : tableBackgroundColour);
}
jComp.setFont(tableFont);
}
return comp;
}
@Override
protected JTableHeader createDefaultTableHeader () {
return new JTableHeader(columnModel) {
@Override
public String getToolTipText (MouseEvent e) {
Point p = e.getPoint();
int c = columnModel.getColumnIndexAtX(p.x);
int c2 = columnModel.getColumn(c).getModelIndex();
return getModel().getColumnToolTip(c2);
}
};
}
}
| mit |
yurri92/MPLS-inventory-management | MPLSinventory/ip_address_tools.py | 1735 | import sys
PYTHON2 = sys.version_info[0] < 3
if PYTHON2:
from ipaddr import IPv4Network, IPv4Address
class IPv4Interface(IPv4Network):
# def __init__(self, config):
# super(IPv4Interface, self).__init__(config)
@property
def network(self):
return IPv4Network(self)
else:
from ipaddress import IPv4Network, IPv4Address, IPv4Interface
""" ip_address.py module that acts resolves differences between the ipaddr (python2) and ipaddress (python3) modules.
In ipaddr (python2) a IPv4Network can be a single host address within a network (i.e. 10.0.1.20/24).
In ipaddress (python3) a IPv4Network must be the network address (i.e. 10.0.1.0/24)
The ipaddress module has a IPv4Interface object that can be a single host with a network (i.e. 10.0.1.20/24).
The IPv4Interface cannot be used to verify if an IP address is in a network:
>>> IPv4Address('10.0.1.1') in IPv4Interface('10.0.1.20/24')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'IPv4Interface' is not iterable
The IPv4Interface object as a network attribute that returns the IPv4Network:
>>> IPv4Interface('10.0.1.20/24').network
IPv4Network('10.0.1.0/24')
>>> IPv4Address('10.0.1.1') in IPv4Interface('10.0.1.20/20').network
True
"""
# def ip_address(address):
# return IPv4Address(address)
# def ip_network(address):
# if PYTHON2:
# return IPv4Network(address)
# else:
# return IPv4Interface(address)
# def ip_in_network(ip_address, ip_network):
# if PYTHON2:
# return ip_address in ip_network
# else:
# return ip_address in ip_network.network
| mit |
JunichiIto/ruby-for-beginners | test/samples_test.rb | 7312 | require 'minitest/autorun'
class SamplesTest < Minitest::Test
def assert_syntax(code)
# http://stackoverflow.com/a/18749289/1058763
stderr = $stderr
$stderr.reopen(IO::NULL)
RubyVM::InstructionSequence.compile(code)
$stderr.reopen(stderr)
assert true
end
def test_samples
assert_syntax <<-RUBY
class Person
def hello
puts 'hello'
end
end
RUBY
assert_syntax <<-RUBY
class UserProfile
# phoneNumber のようなキャメルケースの引数名・変数名はNG
def initialize(name, phone_number)
@name = name
@phone_number = phone_number
end
# firstName のようなキャメルケースのメソッド名はNG
def first_name
@name.split(' ').first
end
end
RUBY
assert_syntax <<-RUBY
# upcase() と書くことは少ない
'hello'.upcase # => 'HELLO'
# puts('hello') でも良いが、丸括弧は省略されることが多い
puts 'hello'
RUBY
def fizz_buzz(n)
if n % 5 == 0 && n % 3 == 0
'Fizz Buzz'
elsif n % 3 == 0
'Fizz'
elsif n % 5 == 0
'Buzz'
else
n
end
end
assert_equal 1, fizz_buzz(1)
assert_equal 2, fizz_buzz(2)
assert_equal 'Fizz', fizz_buzz(3)
assert_equal 4, fizz_buzz(4)
assert_equal 'Buzz', fizz_buzz(5)
assert_equal 'Fizz Buzz', fizz_buzz(15)
assert_syntax <<-RUBY
def go_to_school
today = Date.today
if today.saturday? || today.sunday?
# 土曜日と日曜日は何もせずメソッドを抜ける
return
end
self.get_up
self.eat_breakfast
# 処理が続く...
end
RUBY
assert_syntax <<-RUBY
# userが管理者でなければ通知を送る
if !user.admin?
send_notification_to(user)
end
# 上の条件分岐をunlessで置き換える
unless user.admin?
send_notification_to(user)
end
# if と同様、後ろに置くこともできる
send_notification_to(user) unless user.admin?
RUBY
assert_syntax <<-RUBY
# 普通の if を使った場合
if user.age < 20
puts 'お酒は20歳になってから!'
end
# if 修飾子を使った場合
puts 'お酒は20歳になってから!' if user.age < 20
RUBY
assert_syntax <<-RUBY
# is_admin よりも admin? のように ? で終わらせる方がベター
def admin?
self.role == 'admin'
end
RUBY
assert_output "実行されます\n" * 2 do
if false
puts '実行されません'
end
if nil
puts '実行されません'
end
if true
puts '実行されます'
end
if 0
puts '実行されます'
end
end
def hello(name)
# "Hello, " + name + "!" ではなく、式展開を使う
"Hello, #{name}!"
end
result = hello 'Alice'
assert_equal 'Hello, Alice!', result
assert_output "yen\nyen\n" do
currencies = { 'japan' => 'yen', 'america' => 'dollar', 'italy' => 'euro' }
currencies['india'] = 'rupee'
puts currencies['japan'] # => 'yen'
# ハッシュのキーにシンボルを使う
currencies = { japan: 'yen', america: 'dollar', italy: 'euro' }
currencies[:india] = 'rupee'
puts currencies[:japan] # => 'yen'
end
assert_output "apple\nmelon\nbanana\n" * 2 do
fruits = ['apple', 'melon', 'banana']
# 繰り返し処理は each メソッドを使うのが一般的
fruits.each do |fruit|
puts fruit
end
# 単純な繰り返し処理で for ループが登場することはまずない
for fruit in fruits
puts fruit
end
end
assert_output "8\n9\na\nb\nc\n" * 2 do
numbers = [8, 9, 10, 11, 12]
hex_numbers = []
numbers.each do |n|
hex_numbers << n.to_s(16)
end
puts hex_numbers # => ['8', '9', 'a', 'b', 'c']
numbers = [8, 9, 10, 11, 12]
hex_numbers = numbers.map do |n|
n.to_s(16)
end
puts hex_numbers # => ['8', '9', 'a', 'b', 'c']
end
assert_output "1\n3\n5\n" * 2 do
numbers = [1, 2, 3, 4, 5]
odd_numbers = []
numbers.each do |n|
if n.odd?
odd_numbers << n
end
end
puts odd_numbers # => [1, 3, 5]
numbers = [1, 2, 3, 4, 5]
odd_numbers = numbers.select do |n|
n.odd?
end
puts odd_numbers # => [1, 3, 5]
odd_numbers = numbers.select do |n| n.odd? end
odd_numbers = numbers.select { |n| n.odd? }
odd_numbers = numbers.select(&:odd?)
end
assert_output "109\n109\n" do
numbers = [98, 90, 109, 94, 102]
target = nil
numbers.each do |n|
if n > 100
target = n
break
end
end
puts target # => 109
numbers = [98, 90, 109, 94, 102]
target = numbers.find { |n| n > 100 }
puts target # => 109
end
assert_syntax <<-RUBY
# userはnilの可能性があるのでガード条件を付ける
unless user.nil?
user.say 'Hello!'
end
# userがnilでも気にせずにsayメソッドを呼び出せる
user&.say 'Hello!'
RUBY
items = {
fruits: {
apple: {
price: 100
},
banana: {
price: 50
},
}
}
assert_output "100\n50\n" do
puts items[:fruits][:apple][:price] # => 100
puts items[:fruits][:banana][:price] # => 50
end
assert_raises(NoMethodError) do
puts items[:fruits][:melon][:price] # :melonというキーが無いので [:price] を呼ぶとエラー
end
assert_output "100\n50\n\n" do
puts items.dig(:fruits, :apple, :price) # => 100
puts items.dig(:fruits, :banana, :price) # => 50
puts items.dig(:fruits, :melon, :price) # => nil
end
matrix = [
[
[1, 2, 3]
],
[
# 空
],
[
[100, 200, 300]
]
]
# 添え字を使う場合
assert_output "3\n300\n" do
puts matrix[0][0][2] # => 3
puts matrix[2][0][2] # => 300
end
assert_raises(NoMethodError) do
puts matrix[1][0][2] # => matrix[1][0]が nil なので[2]を呼ぶとエラー
end
# digを使う場合
assert_output "3\n\n300\n" do
puts matrix.dig(0, 0, 2) # => 3
puts matrix.dig(1, 0, 2) # => nil
puts matrix.dig(2, 0, 2) # => 300
end
assert_output "12\namerica\ndollar\n" do
# 配列で find を使う
numbers = [11, 12, 13, 14, 15]
target = numbers.find { |n| n % 3 == 0 }
puts target # => 12
assert_equal 12, target
assert numbers.method(:find).to_s =~ /Enumerable/
# ハッシュで find を使う
currencies = { japan: 'yen', america: 'dollar', italy: 'euro' }
target = currencies.find { |key, value| value == 'dollar' }
puts target # => [:america, 'dollar']
assert_equal [:america, 'dollar'], target
assert currencies.method(:find).to_s =~ /Enumerable/
end
end
end | mit |
luhmann/redis-casper | logger.js | 691 |
var winston = require('winston');
var logger = new winston.Logger({
transports: [
new winston.transports.File({
level: 'info',
filename: './logs/all-logs.log',
handleExceptions: true,
json: true,
maxsize: 5242880, //5MB
maxFiles: 5,
colorize: false
}),
new winston.transports.Console({
level: 'debug',
handleExceptions: true,
json: false,
colorize: true
})
],
exitOnError: false
});
module.exports = logger;
module.exports.stream = {
write: function(message, encoding){
logger.info(message);
}
}; | mit |
edbiler/BazaarCorner | module/janrain/include/phpfox.class.php | 451 | <?php
/**
* [PHPFOX_HEADER]
*/
defined('PHPFOX') or exit('NO DICE!');
/**
*
*
* @copyright [PHPFOX_COPYRIGHT]
* @author Raymond_Benc
* @package Phpfox_Module
* @version $Id: phpfox.class.php 2628 2011-05-25 13:06:52Z Raymond_Benc $
*/
class Module_Janrain
{
public static $aDevelopers = array(
array(
'name' => 'Raymond_Benc',
'website' => 'www.phpfox.com'
)
);
public static $aTables = array(
'janrain'
);
}
?> | mit |
Pietervdw/sageone-api-wrapper | src/SageOneApi.Tests/AccountTests.cs | 1119 | using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SageOneApi.Models;
namespace SageOneApi.Tests
{
[TestClass]
public class AccountTests : TestBase
{
[TestMethod]
public void GetAllAccounts()
{
var accounts = Api.AccountRequest.Get(true);
}
[TestMethod]
public void GetAllAccountsByCategory()
{
var accounts = Api.AccountRequest.GetByCategory(1);
}
[TestMethod]
public void GetAccount()
{
int accountId = 0;
var account = Api.AccountRequest.Get(accountId);
}
[TestMethod]
public void SaveAccount()
{
var account = new Account();
account.Name = "Other Other Sales 1";
account.Category = new Category { ID = 1 };
var newaccount = Api.AccountRequest.Save(account);
}
[TestMethod]
public void DeleteAccount()
{
int accountId = 7769427;
var result = Api.AccountRequest.Delete(accountId);
}
}
} | mit |
oswaldderiemaecker/feed-io | src/FeedIo/Rule/ModifiedSince.php | 1184 | <?php
/*
* This file is part of the feed-io package.
*
* (c) Alexandre Debril <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FeedIo\Rule;
use FeedIo\Feed\NodeInterface;
use FeedIo\DateRuleAbstract;
class ModifiedSince extends DateRuleAbstract
{
const NODE_NAME = 'pubDate';
/**
* @param NodeInterface $node
* @param \DOMElement $element
* @return $this
*/
public function setProperty(NodeInterface $node, \DOMElement $element)
{
$node->setLastModified($this->getDateTimeBuilder()->convertToDateTime($element->nodeValue));
return $this;
}
/**
* creates the accurate DomElement content according to the $item's property
*
* @param \DomDocument $document
* @param NodeInterface $node
* @return \DomElement
*/
public function createElement(\DomDocument $document, NodeInterface $node)
{
return $document->createElement(
$this->getNodeName(),
$node->getLastModified()->format($this->getDefaultFormat())
);
}
}
| mit |
himulawang/observer | js/store/db_store.js | 1164 | /**
* Created by ila on 5/24/2015.
*/
"use strict"
class DBStore {
static exportDB() {
let waitList = [];
let data = {};
return localforage.keys().then(function(keys) {
keys.forEach(function(key) {
let promiseChild = new Promise(function(resolve, reject) {
localforage.getItem(key).then(function(v) {
data[key] = v;
resolve(data);
});
});
waitList.push(promiseChild);
});
return new Promise(function(resolve, reject) {
return Promise.all(waitList).then(function() {
resolve(data);
});
})
});
}
static importDB(data) {
var waitList = [];
for(let key in data) {
let promiseChild = new Promise(function(resolve, reject) {
localforage.setItem(key, data[key]).then(function() {
resolve();
});
});
waitList.push(promiseChild);
}
return Promise.all(waitList);
}
}
| mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highstock/config/PlotOptionsParetoPathfinderMarker.scala | 5373 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highstock]]
*/
package com.highstock.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>plotOptions-pareto-pathfinder-marker</code>
*/
@js.annotation.ScalaJSDefined
class PlotOptionsParetoPathfinderMarker extends com.highcharts.HighchartsGenericObject {
/**
* <p>Enable markers for the connectors.</p>
* @since 6.2.0
*/
val enabled: js.UndefOr[Boolean] = js.undefined
/**
* <p>Horizontal alignment of the markers relative to the points.</p>
* @since 6.2.0
*/
val align: js.UndefOr[String] = js.undefined
/**
* <p>Vertical alignment of the markers relative to the points.</p>
* @since 6.2.0
*/
val verticalAlign: js.UndefOr[String] = js.undefined
/**
* <p>Whether or not to draw the markers inside the points.</p>
* @since 6.2.0
*/
val inside: js.UndefOr[Boolean] = js.undefined
/**
* <p>Set the line/border width of the pathfinder markers.</p>
* @since 6.2.0
*/
val lineWidth: js.UndefOr[Double] = js.undefined
/**
* <p>Set the radius of the pathfinder markers. The default is
* automatically computed based on the algorithmMargin setting.</p>
* <p>Setting marker.width and marker.height will override this
* setting.</p>
* @since 6.2.0
*/
val radius: js.UndefOr[Double] = js.undefined
/**
* <p>Set the width of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.</p>
* @since 6.2.0
*/
val width: js.UndefOr[Double] = js.undefined
/**
* <p>Set the height of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.</p>
* @since 6.2.0
*/
val height: js.UndefOr[Double] = js.undefined
/**
* <p>Set the color of the pathfinder markers. By default this is the
* same as the connector color.</p>
* @since 6.2.0
*/
val color: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>Set the line/border color of the pathfinder markers. By default
* this is the same as the marker color.</p>
* @since 6.2.0
*/
val lineColor: js.UndefOr[String | js.Object] = js.undefined
}
object PlotOptionsParetoPathfinderMarker {
/**
* @param enabled <p>Enable markers for the connectors.</p>
* @param align <p>Horizontal alignment of the markers relative to the points.</p>
* @param verticalAlign <p>Vertical alignment of the markers relative to the points.</p>
* @param inside <p>Whether or not to draw the markers inside the points.</p>
* @param lineWidth <p>Set the line/border width of the pathfinder markers.</p>
* @param radius <p>Set the radius of the pathfinder markers. The default is. automatically computed based on the algorithmMargin setting.</p>. <p>Setting marker.width and marker.height will override this. setting.</p>
* @param width <p>Set the width of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p>
* @param height <p>Set the height of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p>
* @param color <p>Set the color of the pathfinder markers. By default this is the. same as the connector color.</p>
* @param lineColor <p>Set the line/border color of the pathfinder markers. By default. this is the same as the marker color.</p>
*/
def apply(enabled: js.UndefOr[Boolean] = js.undefined, align: js.UndefOr[String] = js.undefined, verticalAlign: js.UndefOr[String] = js.undefined, inside: js.UndefOr[Boolean] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, radius: js.UndefOr[Double] = js.undefined, width: js.UndefOr[Double] = js.undefined, height: js.UndefOr[Double] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined): PlotOptionsParetoPathfinderMarker = {
val enabledOuter: js.UndefOr[Boolean] = enabled
val alignOuter: js.UndefOr[String] = align
val verticalAlignOuter: js.UndefOr[String] = verticalAlign
val insideOuter: js.UndefOr[Boolean] = inside
val lineWidthOuter: js.UndefOr[Double] = lineWidth
val radiusOuter: js.UndefOr[Double] = radius
val widthOuter: js.UndefOr[Double] = width
val heightOuter: js.UndefOr[Double] = height
val colorOuter: js.UndefOr[String | js.Object] = color
val lineColorOuter: js.UndefOr[String | js.Object] = lineColor
com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsParetoPathfinderMarker {
override val enabled: js.UndefOr[Boolean] = enabledOuter
override val align: js.UndefOr[String] = alignOuter
override val verticalAlign: js.UndefOr[String] = verticalAlignOuter
override val inside: js.UndefOr[Boolean] = insideOuter
override val lineWidth: js.UndefOr[Double] = lineWidthOuter
override val radius: js.UndefOr[Double] = radiusOuter
override val width: js.UndefOr[Double] = widthOuter
override val height: js.UndefOr[Double] = heightOuter
override val color: js.UndefOr[String | js.Object] = colorOuter
override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter
})
}
}
| mit |
prasetyaningyudi/layangsworo | application/views/instansi_rekam_view.php | 806 | <!-- content goes here -->
<div class="my-content">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-brown">
<div class="panel-heading">
<div class="panel-title">Rekam Instansi</div>
</div>
<div class="panel-body">
<form action="" id="instansiform" method="post" class="form-horizontal">
<fieldset>
<div class="form-group">
<label for="instansi" class="col-sm-2">Nama Instansi:<br></label>
<div class="col-sm-10">
<input class="form-control" id="instansi" type="text" name="instansi" value="" placeholder="nama instansi" required>
</div>
</div>
<input type="submit" name="submit" value="Submit" class="btn btn-default btn-lg">
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div> | mit |
mactookmyname/ttn-imdbot | src/data/omdb.js | 2230 | import request from 'request-promise';
import _ from 'lodash';
import { SERIES_DURATION } from '../config';
import stripYear from '../utils/stripYear';
import getTitle from './titles';
/**
* Attemps to get imdb info based on the following logic:
* 1. exact title match yields one result
* 2. exact type (series, movie) yields one result
* 3. whichever title has the nearest duration to the ttn metadata
**/
const getOmdb = async (video) => {
// Removes trailing year names on title which causes api lookup to fail
const name = _.flow([stripYear, _.trim, getTitle])(video.name);
// Searches specifically for series instead of movie for shorter durations
const type = video.duration < SERIES_DURATION ? 'series' : 'movie';
const omdbOptions = {
uri: 'http://www.omdbapi.com/?',
json: true,
};
const omdbSearch = {
...omdbOptions,
qs: {
s: name,
},
};
const getById = ({ imdbID }) => request({ ...omdbOptions, qs: { i: imdbID } });
// Strip special chars which throw off matching, e.g. WALL-E vs WALL·E
const stripNonAlphanumeric = (input) => input.replace(/\W/g, '');
const matchTitle = (results) => (
_.filter(results.Search, (r) => _.eq(
stripNonAlphanumeric(_.toLower(r.Title)),
stripNonAlphanumeric(_.toLower(name))
))
);
const durationDiff = (runtime) => Math.abs((parseInt(runtime, 10) * 60) - video.duration);
// search for all titles
const searchResults = await request(omdbSearch);
if (searchResults.Error) {
throw new Error('Error from OMDB endpoint');
}
const exactTitles = matchTitle(searchResults);
if (exactTitles.length === 0) {
throw new Error(`No exact matches found: ['${video.name}' not found in results of [${_.map(searchResults.Search, (r) => r.Title)}]]`);
} else if (exactTitles.length === 1) {
return getById(_.head(exactTitles));
}
const exactTypes = _.filter(exactTitles, { Type: type });
if (exactTypes.length === 1) {
return getById(_.head(exactTypes));
}
const allMatches = await Promise.all(_.map(exactTypes, getById));
return _.reduce(allMatches, (acc, val) => (
durationDiff(acc.Runtime) < durationDiff(val.Runtime) ? acc : val
));
};
export default getOmdb;
| mit |
Ullfis/aurelia-mdc-bridge | dist/native-modules/button/icon-toggle/icon-toggle.js | 3626 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { inject, bindable, bindingMode, customElement } from 'aurelia-framework';
import { getLogger } from 'aurelia-logging';
import { MDCIconToggle } from '@material/icon-toggle';
import * as util from '../../util';
var MdcIconToggle = (function () {
function MdcIconToggle(element) {
this.element = element;
this.iconOn = 'star';
this.iconOff = 'star_border';
this.ariaLabelOn = 'On label';
this.ariaLabelOff = 'Off label';
this.disabled = false;
this.on = false;
this.tabindex = 0;
this.log = getLogger('mdc-icon-toggle');
}
MdcIconToggle.prototype.bind = function () { };
MdcIconToggle.prototype.unbind = function () { };
MdcIconToggle.prototype.attached = function () {
this.mdcIconToggle = new MDCIconToggle(this.elementI);
this.elementI.addEventListener('MDCIconToggle:change', this.raiseEvent.bind(this));
this.disabledChanged(this.disabled);
};
MdcIconToggle.prototype.detached = function () {
this.elementI.removeEventListener('MDCIconToggle:change', this.raiseEvent.bind(this));
this.mdcIconToggle.destroy();
};
MdcIconToggle.prototype.raiseEvent = function () {
this.on = this.mdcIconToggle.on;
util.fireEvent(this.element, 'on-toggle', this.on);
};
MdcIconToggle.prototype.onChanged = function (newValue) {
this.mdcIconToggle.on = util.getBoolean(newValue);
};
MdcIconToggle.prototype.disabledChanged = function (newValue) {
this.mdcIconToggle.disabled = util.getBoolean(newValue);
};
__decorate([
bindable({ defaultBindingMode: bindingMode.oneTime }),
__metadata("design:type", Object)
], MdcIconToggle.prototype, "iconOn", void 0);
__decorate([
bindable({ defaultBindingMode: bindingMode.oneTime }),
__metadata("design:type", Object)
], MdcIconToggle.prototype, "iconOff", void 0);
__decorate([
bindable({ defaultBindingMode: bindingMode.oneTime }),
__metadata("design:type", Object)
], MdcIconToggle.prototype, "ariaLabelOn", void 0);
__decorate([
bindable({ defaultBindingMode: bindingMode.oneTime }),
__metadata("design:type", Object)
], MdcIconToggle.prototype, "ariaLabelOff", void 0);
__decorate([
bindable({ defaultBindingMode: bindingMode.oneWay }),
__metadata("design:type", Object)
], MdcIconToggle.prototype, "disabled", void 0);
__decorate([
bindable({ defaultBindingMode: bindingMode.twoWay }),
__metadata("design:type", Object)
], MdcIconToggle.prototype, "on", void 0);
MdcIconToggle = __decorate([
customElement('mdc-icon-toggle'),
inject(Element),
__metadata("design:paramtypes", [Element])
], MdcIconToggle);
return MdcIconToggle;
}());
export { MdcIconToggle };
| mit |
portchris/NaturalRemedyCompany | src/app/code/community/Ess/M2ePro/Model/Connector/Connection/Response/Message.php | 1657 | <?php
/*
* @author M2E Pro Developers Team
* @copyright M2E LTD
* @license Commercial use is forbidden
*/
class Ess_M2ePro_Model_Connector_Connection_Response_Message extends Ess_M2ePro_Model_Response_Message
{
const SENDER_KEY = 'sender';
const CODE_KEY = 'code';
const SENDER_SYSTEM = 'system';
const SENDER_COMPONENT = 'component';
protected $_sender = null;
protected $_code = null;
//########################################
public function initFromResponseData(array $responseData)
{
parent::initFromResponseData($responseData);
$this->_sender = $responseData[self::SENDER_KEY];
$this->_code = $responseData[self::CODE_KEY];
}
public function initFromPreparedData($text, $type, $sender = NULL, $code = NULL)
{
parent::initFromPreparedData($text, $type);
$this->_sender = $sender;
$this->_code = $code;
}
//########################################
public function asArray()
{
return array_merge(
parent::asArray(), array(
self::SENDER_KEY => $this->_sender,
self::CODE_KEY => $this->_code,
)
);
}
//########################################
public function isSenderSystem()
{
return $this->_sender == self::SENDER_SYSTEM;
}
public function isSenderComponent()
{
return $this->_sender == self::SENDER_COMPONENT;
}
//########################################
public function getCode()
{
return $this->_code;
}
//########################################
} | mit |
solzimer/nsyslog | test/test_shm.js | 433 | const cluster = require('../lib/cluster');
if(cluster.isMaster) {
const Shm = require('../lib/shm');
cluster.fork("./test_shm.js",[]);
setTimeout(()=>{
Shm.hpush('fork','flow1',{data:'data1'});
Shm.hpush('fork','flow1',{data:'data2'});
Shm.hpush('fork','flow1',{data:'data3'});
},1000);
}
else {
const Shm = require('../lib/shm');
setInterval(()=>{
let res = Shm.hget('fork','flow1');
console.log(res);
},1000);
}
| mit |
julianh2o/Podbase | app/util/Stopwatch.java | 2136 | // Copyright 2013 Julian Hartline <[email protected]>
//
// This code is available under the MIT license.
// See the LICENSE file for details.
package util;
import java.io.File;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import access.AccessType;
import services.ImportExportService;
import services.PathService;
import services.PermissionService;
import models.DatabaseImage;
import models.Project;
import models.ProjectVisibleImage;
import models.User;
public class Stopwatch {
HashMap<String,Record> records;
public Stopwatch() {
records = new HashMap<String,Record>();
}
public void clear() {
records.clear();
}
public void start(String name) {
if (records.containsKey(name)) {
Record rec = records.get(name);
rec.start();
} else {
records.put(name, new Record());
}
}
public void stop(String name) {
if (!records.containsKey(name)) throw new RuntimeException("invalid stopwatch key! "+name);
records.get(name).stop();
}
public double getAverageTime(String name) {
if (!records.containsKey(name)) throw new RuntimeException("invalid stopwatch key! "+name);
Record r = records.get(name);
double averageTime = (double)r.totalTime / (double)r.totalEnds;
return averageTime;
}
public String getAverageTimeS(String name) {
return String.format("%2f", getAverageTime(name));
}
public String toString() {
StringBuffer sb = new StringBuffer();
for (Entry<String,Record> entry : records.entrySet()) {
Record r = entry.getValue();
double averageTime = (double)r.totalTime / (double)r.totalEnds;
sb.append(entry.getKey() + ": " + averageTime +"ms\n");
}
return sb.toString();
}
private class Record {
long totalTime;
int totalEnds;
long lastStart;
public Record() {
totalTime = 0;
totalEnds = 0;
start();
}
public void start() {
lastStart = System.currentTimeMillis();
}
public void stop() {
long delta = System.currentTimeMillis() - lastStart;
totalEnds++;
totalTime += delta;
}
}
} | mit |
cuikangyi/alipay_cash_register_server | Application/YunfuApi/Controller/DeviceController.class.php | 1841 | <?php
/**
* Created by PhpStorm.
* User: Kangyi
* Date: 2015/1/17
* Time: 11:30
*/
namespace YunfuApi\Controller;
use Think\Controller;
class DeviceController extends Controller{
public function index(){
$result['is_success'] = 'F';
$result['error_msg'] = '弃用';
returnXml($result);
exit();
if(!IS_POST){
$result['is_success'] = 'F';
$result['error_msg'] = '请求失败';
returnXml($result);
}
$device_no = I('device_no');
$username = I('username');
$device_name = I('device_name');
if(!$device_no){
$result['is_success'] = 'F';
$result['error_msg'] = '机器码为空';
returnXml($result);
}
if(!$username){
$result['is_success'] = 'F';
$result['error_msg'] = '用户名为空';
returnXml($result);
}
if(!$device_name){
$result['is_success'] = 'F';
$result['error_msg'] = '设备名称为空';
returnXml($result);
}
$user = M('user')->where(array('username'=>$username))->find();
if(!$user){
$result['is_success'] = 'F';
$result['error_msg'] = '用户名不存在';
returnXml($result);
}else{
$uid = $user['id'];
}
$device = M('device')->where(array('device_no'=>$device_no))->find();
$data['uid'] = $uid;
$data['device_name'] = $device_name;
$data['status'] = 0;
if($device){
M('device')->where(array('id'=>$device['id']))->save($data);
}else{
$data['device_no'] = $device_no;
M('device')->data($data)->add();
}
$result['is_success'] = 'T';
returnXml($result);
}
} | mit |
ManifestWebDesign/dabl-query | src/DBManager.php | 4298 | <?php
/**
* @link https://github.com/ManifestWebDesign/DABL
* @link http://manifestwebdesign.com/redmine/projects/dabl
* @author Manifest Web Design
* @license MIT License
*/
namespace Dabl\Query;
use Dabl\Adapter\DABLPDO;
use PDOException;
use RuntimeException;
/**
* Database Management class. Handles connections to multiple databases.
*
* {@example libraries/dabl/DBManager_description_1.php}
*
* @package dabl
*/
class DBManager {
private static $connections = array();
private static $parameters = array();
private function __construct() {
}
private function __clone() {
}
/**
* Get the database connections.
* All database handles returned will be connected.
*
* @return DABLPDO[]
*/
static function getConnections() {
foreach (self::$parameters as $name => $params) {
self::connect($name);
}
return self::$connections;
}
/**
* Get the names of all known database connections.
*
* @return string[]
*/
static function getConnectionNames() {
return array_keys(self::$parameters);
}
/**
* Get the connection for $db_name. The returned object will be
* connected to its database.
*
* @param String $connection_name
* @return DABLPDO
* @throws PDOException If the connection fails
*/
static function getConnection($connection_name = null) {
if (null === $connection_name) {
$keys = array_keys(self::$parameters);
$connection_name = reset($keys);
}
if (!@$connection_name) {
return null;
}
return self::connect($connection_name);
}
/**
* Add connection information to the manager. This will not
* connect the database endpoint until it is requested from the
* manager.
*
* @param string $connection_name Name for the connection
* @param array $connection_params Parameters for the connection
*/
static function addConnection($connection_name, $connection_params) {
self::$parameters[$connection_name] = $connection_params;
}
/**
* Get the parameters for a given connection name
*
* @param $connection_name
* @return mixed
*/
static function getParameters($connection_name) {
if (!array_key_exists($connection_name, self::$parameters)) {
throw new RuntimeException("Configuration for database '$connection_name' not loaded");
}
return self::$parameters[$connection_name];
}
/**
* @param $connection_name
* @param $key
* @param $value
*/
static function setParameter($connection_name, $key, $value) {
self::$parameters[$connection_name][$key] = $value;
}
/**
* Get the specified connection parameter from the given DB
* connection.
*
* @param string $connection_name
* @param string $key
* @return string|null
* @throws RuntimeException
*/
static function getParameter($connection_name, $key) {
// don't reveal passwords through this interface
if ('password' === $key) {
throw new RuntimeException('DB::password is private');
}
if (!array_key_exists($connection_name, self::$parameters)) {
throw new RuntimeException("Configuration for database '$connection_name' not loaded");
}
return @self::$parameters[$connection_name][$key];
}
/**
* (Re-)connect to the database connection named $key.
*
* @access private
* @since 2010-10-29
* @param string $connection_name Connection name
* @return DABLPDO Database connection
* @throws PDOException If the connection fails
*/
private static function connect($connection_name) {
if (array_key_exists($connection_name, self::$connections)) {
return self::$connections[$connection_name];
}
if (!array_key_exists($connection_name, self::$parameters)) {
throw new RuntimeException('Connection "' . $connection_name . '" has not been set');
}
$conn = DABLPDO::connect(self::$parameters[$connection_name]);
return (self::$connections[$connection_name] = $conn);
}
/**
* Disconnect from the database connection named $key.
*
* @param string $connection_name Connection name
* @return void
*/
static function disconnect($connection_name) {
self::$connections[$connection_name] = null;
unset(self::$connections[$connection_name]);
}
/**
* Clears parameters and references to all connections
*/
static function clearConnections() {
self::$connections = array();
self::$parameters = array();
}
}
| mit |
uwoseis/zephyr | zephyr/middleware/fields.py | 4782 | from __future__ import print_function, unicode_literals, division, absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
import numpy as np
import scipy.sparse as sp
from ..backend import BaseModelDependent
import SimPEG
class HelmFields(SimPEG.Fields.Fields):
"""Fancy Field Storage for frequency domain problems
u[:,'phi', freqInd] = phi
print u[src0,'phi']
"""
knownFields = {'u': 'N'}
aliasFields = None
dtype = np.complex128
def startup(self):
pass
def _storageShape(self, loc):
nP = {'CC': self.mesh.nC,
'N': self.mesh.nN,
'F': self.mesh.nF,
'E': self.mesh.nE}[loc]
nSrc = self.survey.nSrc
nFreq = self.survey.nfreq
return (nP, nSrc, nFreq)
def _indexAndNameFromKey(self, key, accessType):
if type(key) is not tuple:
key = (key,)
if len(key) == 1:
key += (None,)
if len(key) == 2:
key += (slice(None,None,None),)
assert len(key) == 3, 'must be [Src, fieldName, freqs]'
srcTestList, name, freqInd = key
name = self._nameIndex(name, accessType)
srcInd = self._srcIndex(srcTestList)
return (srcInd, freqInd), name
def _correctShape(self, name, ind, deflate=False):
srcInd, freqInd = ind
if name in self.knownFields:
loc = self.knownFields[name]
else:
loc = self.aliasFields[name][1]
nP, total_nSrc, total_nF = self._storageShape(loc)
nSrc = np.ones(total_nSrc, dtype=bool)[srcInd].sum()
nF = np.ones(total_nF, dtype=bool)[freqInd].sum()
shape = nP, nSrc, nF
if deflate:
shape = tuple([s for s in shape if s > 1])
if len(shape) == 1:
shape = shape + (1,)
return shape
def _setField(self, field, val, name, ind):
srcInd, freqInd = ind
shape = self._correctShape(name, ind)
if SimPEG.Utils.isScalar(val):
field[:,srcInd,freqInd] = val
return
if val.size != np.array(shape).prod():
print('val.size: %r'%(val.size,))
print('np.array(shape).prod(): %r'%(np.array(shape).prod(),))
raise ValueError('Incorrect size for data.')
correctShape = field[:,srcInd,freqInd].shape
field[:,srcInd,freqInd] = val.reshape(correctShape, order='F')
def _getField(self, name, ind):
srcInd, freqInd = ind
if name in self._fields:
out = self._fields[name][:,srcInd,freqInd]
else:
# Aliased fields
alias, loc, func = self.aliasFields[name]
if type(func) is str:
assert hasattr(self, func), 'The alias field function is a string, but it does not exist in the Fields class.'
func = getattr(self, func)
pointerFields = self._fields[alias][:,srcInd,freqInd]
pointerShape = self._correctShape(alias, ind)
pointerFields = pointerFields.reshape(pointerShape, order='F')
freqII = np.arange(self.survey.nfreq)[freqInd]
srcII = np.array(self.survey.srcList)[srcInd]
srcII = srcII.tolist()
if freqII.size == 1:
pointerShapeDeflated = self._correctShape(alias, ind, deflate=True)
pointerFields = pointerFields.reshape(pointerShapeDeflated, order='F')
out = func(pointerFields, srcII, freqII)
else: #loop over the frequencies
nF = pointerShape[2]
out = list(range(nF))
for i, FIND_i in enumerate(freqII):
fieldI = pointerFields[:,:,i]
if fieldI.shape[0] == fieldI.size:
fieldI = SimPEG.Utils.mkvc(fieldI, 2)
out[i] = func(fieldI, srcII, FIND_i)
if out[i].ndim == 1:
out[i] = out[i][:,np.newaxis,np.newaxis]
elif out[i].ndim == 2:
out[i] = out[i][:,:,np.newaxis]
out = np.concatenate(out, axis=2)
shape = self._correctShape(name, ind, deflate=True)
return out.reshape(shape, order='F')
def __repr__(self):
shape = self._storageShape('N')
attrs = {
'name': self.__class__.__name__,
'id': id(self),
'nFields': len(self.knownFields) + len(self.aliasFields),
'nN': shape[0],
'nSrc': shape[1],
'nFreq': shape[2],
}
return '<%(name)s container at 0x%(id)x: %(nFields)d fields, with N shape (%(nN)d, %(nSrc)d, %(nFreq)d)>'%attrs
| mit |
toanphuoc/tkvacation_client | js/controller/tours_controller.js | 160 | app.controller('DestinationTourController', ['$scope', '$routeParams', function ($scope, $routeParams) {
var id = $routeParams.desId;
console.log(id);
}]); | mit |
linpaul2004/JavaWorkspace | Lab0513/src/chapter12/MyThread.java | 354 | package chapter12;
public class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
while (true) {
System.out.println("Helo! I am " + name);
try {
Thread.sleep((long) Math.random() * 2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| mit |
FireEngineRed/framework | src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php | 23422 | <?php
namespace Illuminate\Foundation\Testing\Concerns;
use Closure;
use Exception;
use Illuminate\Support\Str;
use InvalidArgumentException;
use Illuminate\Http\UploadedFile;
use Symfony\Component\DomCrawler\Form;
use Symfony\Component\DomCrawler\Crawler;
use Illuminate\Foundation\Testing\HttpException;
use PHPUnit_Framework_ExpectationFailedException as PHPUnitException;
trait InteractsWithPages
{
/**
* The DomCrawler instance.
*
* @var \Symfony\Component\DomCrawler\Crawler
*/
protected $crawler;
/**
* Nested crawler instances used by the "within" method.
*
* @var array
*/
protected $subCrawlers = [];
/**
* All of the stored inputs for the current page.
*
* @var array
*/
protected $inputs = [];
/**
* All of the stored uploads for the current page.
*
* @var array
*/
protected $uploads = [];
/**
* Visit the given URI with a GET request.
*
* @param string $uri
* @return $this
*/
public function visit($uri)
{
return $this->makeRequest('GET', $uri);
}
/**
* Make a request to the application and create a Crawler instance.
*
* @param string $method
* @param string $uri
* @param array $parameters
* @param array $cookies
* @param array $files
* @return $this
*/
protected function makeRequest($method, $uri, $parameters = [], $cookies = [], $files = [])
{
$uri = $this->prepareUrlForRequest($uri);
$this->call($method, $uri, $parameters, $cookies, $files);
$this->clearInputs()->followRedirects()->assertPageLoaded($uri);
$this->currentUri = $this->app->make('request')->fullUrl();
$this->crawler = new Crawler($this->response->getContent(), $uri);
$this->subCrawlers = [];
return $this;
}
/**
* Make a request to the application using the given form.
*
* @param \Symfony\Component\DomCrawler\Form $form
* @param array $uploads
* @return $this
*/
protected function makeRequestUsingForm(Form $form, array $uploads = [])
{
$files = $this->convertUploadsForTesting($form, $uploads);
return $this->makeRequest(
$form->getMethod(), $form->getUri(), $this->extractParametersFromForm($form), [], $files
);
}
/**
* Extract the parameters from the given form.
*
* @param \Symfony\Component\DomCrawler\Form $form
* @return array
*/
protected function extractParametersFromForm(Form $form)
{
parse_str(http_build_query($form->getValues()), $parameters);
return $parameters;
}
/**
* Follow redirects from the last response.
*
* @return $this
*/
protected function followRedirects()
{
while ($this->response->isRedirect()) {
$this->makeRequest('GET', $this->response->getTargetUrl());
}
return $this;
}
/**
* Clear the inputs for the current page.
*
* @return $this
*/
protected function clearInputs()
{
$this->inputs = [];
$this->uploads = [];
return $this;
}
/**
* Assert that the current page matches a given URI.
*
* @param string $uri
* @return $this
*/
protected function seePageIs($uri)
{
$this->assertPageLoaded($uri = $this->prepareUrlForRequest($uri));
$this->assertEquals(
$uri, $this->currentUri, "Did not land on expected page [{$uri}].\n"
);
return $this;
}
/**
* Assert that a given page successfully loaded.
*
* @param string $uri
* @param string|null $message
* @return void
*
* @throws \Illuminate\Foundation\Testing\HttpException
*/
protected function assertPageLoaded($uri, $message = null)
{
$status = $this->response->getStatusCode();
try {
$this->assertEquals(200, $status);
} catch (PHPUnitException $e) {
$message = $message ?: "A request to [{$uri}] failed. Received status code [{$status}].";
$responseException = isset($this->response->exception)
? $this->response->exception : null;
throw new HttpException($message, null, $responseException);
}
}
/**
* Narrow the test content to a specific area of the page.
*
* @param string $element
* @param \Closure $callback
* @return $this
*/
public function within($element, Closure $callback)
{
$this->subCrawlers[] = $this->crawler()->filter($element);
$callback();
array_pop($this->subCrawlers);
}
/**
* Get the current crawler according to the test context.
*
* @return \Symfony\Component\DomCrawler\Crawler
*/
protected function crawler()
{
return ! empty($this->subCrawlers)
? end($this->subCrawlers)
: $this->crawler;
}
/**
* Get the HTML from the current context or the full response.
*
* @return string
*/
protected function html()
{
return $this->crawler()
? $this->crawler()->html()
: $this->response->getContent();
}
/**
* Get the plain text from the current context or the full response.
*
* @return string
*/
protected function text()
{
return $this->crawler()
? $this->crawler()->text()
: strip_tags($this->response->getContent());
}
/**
* Get the escaped text pattern.
*
* @param string $text
* @return string
*/
protected function getEscapedPattern($text)
{
$rawPattern = preg_quote($text, '/');
$escapedPattern = preg_quote(e($text), '/');
return $rawPattern == $escapedPattern
? $rawPattern : "({$rawPattern}|{$escapedPattern})";
}
/**
* Assert that a given string is seen on the current HTML.
*
* @param string $text
* @param bool $negate
* @return $this
*/
protected function see($text, $negate = false)
{
$method = $negate ? 'assertNotRegExp' : 'assertRegExp';
$pattern = $this->getEscapedPattern($text);
$this->$method("/$pattern/i", $this->html());
return $this;
}
/**
* Assert that a given string is not seen on the current HTML.
*
* @param string $text
* @return $this
*/
protected function dontSee($text)
{
return $this->see($text, true);
}
/**
* Assert that a given string is seen on the current text.
*
* @param string $text
* @param bool $negate
* @return $this
*/
protected function seeText($text, $negate = false)
{
$method = $negate ? 'assertNotRegExp' : 'assertRegExp';
$pattern = $this->getEscapedPattern($text);
$this->$method("/$pattern/i", $this->text());
return $this;
}
/**
* Assert that a given string is not seen on the current text.
*
* @param string $text
* @return $this
*/
protected function dontSeeText($text)
{
return $this->seeText($text, true);
}
/**
* Assert that a given string is seen inside an element.
*
* @param string $element
* @param string $text
* @param bool $negate
* @return $this
*/
public function seeInElement($element, $text, $negate = false)
{
if ($negate) {
return $this->dontSeeInElement($element, $text);
}
$this->assertTrue(
$this->hasInElement($element, $text),
"Element [$element] should contain the expected text [{$text}]"
);
return $this;
}
/**
* Assert that a given string is not seen inside an element.
*
* @param string $element
* @param string $text
* @return $this
*/
public function dontSeeInElement($element, $text)
{
$this->assertFalse(
$this->hasInElement($element, $text),
"Element [$element] should not contain the expected text [{$text}]"
);
return $this;
}
/**
* Check if the page contains text within the given element.
*
* @param string $element
* @param string $text
* @return bool
*/
protected function hasInElement($element, $text)
{
$elements = $this->crawler()->filter($element);
$pattern = $this->getEscapedPattern($text);
foreach ($elements as $element) {
$element = new Crawler($element);
if (preg_match("/$pattern/i", $element->html())) {
return true;
}
}
return false;
}
/**
* Assert that a given link is seen on the page.
*
* @param string $text
* @param string|null $url
* @return $this
*/
public function seeLink($text, $url = null)
{
$message = "No links were found with expected text [{$text}]";
if ($url) {
$message .= " and URL [{$url}]";
}
$this->assertTrue($this->hasLink($text, $url), "{$message}.");
return $this;
}
/**
* Assert that a given link is not seen on the page.
*
* @param string $text
* @param string|null $url
* @return $this
*/
public function dontSeeLink($text, $url = null)
{
$message = "A link was found with expected text [{$text}]";
if ($url) {
$message .= " and URL [{$url}]";
}
$this->assertFalse($this->hasLink($text, $url), "{$message}.");
return $this;
}
/**
* Check if the page has a link with the given $text and optional $url.
*
* @param string $text
* @param string|null $url
* @return bool
*/
protected function hasLink($text, $url = null)
{
$links = $this->crawler()->selectLink($text);
if ($links->count() == 0) {
return false;
}
// If the URL is null, we assume the developer only wants to find a link
// with the given text regardless of the URL. So, if we find the link
// we will return true now. Otherwise, we look for the given URL.
if ($url == null) {
return true;
}
$absoluteUrl = $this->addRootToRelativeUrl($url);
foreach ($links as $link) {
$linkHref = $link->getAttribute('href');
if ($linkHref == $url || $linkHref == $absoluteUrl) {
return true;
}
}
return false;
}
/**
* Add a root if the URL is relative (helper method of the hasLink function).
*
* @param string $url
* @return string
*/
protected function addRootToRelativeUrl($url)
{
if (! Str::startsWith($url, ['http', 'https'])) {
return $this->app->make('url')->to($url);
}
return $url;
}
/**
* Assert that an input field contains the given value.
*
* @param string $selector
* @param string $expected
* @return $this
*/
public function seeInField($selector, $expected)
{
$this->assertSame(
$expected, $this->getInputOrTextAreaValue($selector),
"The field [{$selector}] does not contain the expected value [{$expected}]."
);
return $this;
}
/**
* Assert that an input field does not contain the given value.
*
* @param string $selector
* @param string $value
* @return $this
*/
public function dontSeeInField($selector, $value)
{
$this->assertNotSame(
$this->getInputOrTextAreaValue($selector), $value,
"The input [{$selector}] should not contain the value [{$value}]."
);
return $this;
}
/**
* Assert that the given checkbox is selected.
*
* @param string $selector
* @return $this
*/
public function seeIsChecked($selector)
{
$this->assertTrue(
$this->isChecked($selector),
"The checkbox [{$selector}] is not checked."
);
return $this;
}
/**
* Assert that the given checkbox is not selected.
*
* @param string $selector
* @return $this
*/
public function dontSeeIsChecked($selector)
{
$this->assertFalse(
$this->isChecked($selector),
"The checkbox [{$selector}] is checked."
);
return $this;
}
/**
* Assert that the expected value is selected.
*
* @param string $selector
* @param string $expected
* @return $this
*/
public function seeIsSelected($selector, $expected)
{
$this->assertEquals(
$expected, $this->getSelectedValue($selector),
"The field [{$selector}] does not contain the selected value [{$expected}]."
);
return $this;
}
/**
* Assert that the given value is not selected.
*
* @param string $selector
* @param string $value
* @return $this
*/
public function dontSeeIsSelected($selector, $value)
{
$this->assertNotEquals(
$value, $this->getSelectedValue($selector),
"The field [{$selector}] contains the selected value [{$value}]."
);
return $this;
}
/**
* Get the value of an input or textarea.
*
* @param string $selector
* @return string
*
* @throws \Exception
*/
protected function getInputOrTextAreaValue($selector)
{
$field = $this->filterByNameOrId($selector, ['input', 'textarea']);
if ($field->count() == 0) {
throw new Exception("There are no elements with the name or ID [$selector].");
}
$element = $field->nodeName();
if ($element == 'input') {
return $field->attr('value');
}
if ($element == 'textarea') {
return $field->text();
}
throw new Exception("Given selector [$selector] is not an input or textarea.");
}
/**
* Get the selected value of a select field or radio group.
*
* @param string $selector
* @return string|null
*
* @throws \Exception
*/
protected function getSelectedValue($selector)
{
$field = $this->filterByNameOrId($selector);
if ($field->count() == 0) {
throw new Exception("There are no elements with the name or ID [$selector].");
}
$element = $field->nodeName();
if ($element == 'select') {
return $this->getSelectedValueFromSelect($field);
}
if ($element == 'input') {
return $this->getCheckedValueFromRadioGroup($field);
}
throw new Exception("Given selector [$selector] is not a select or radio group.");
}
/**
* Get the selected value from a select field.
*
* @param \Symfony\Component\DomCrawler\Crawler $field
* @return string|null
*
* @throws \Exception
*/
protected function getSelectedValueFromSelect(Crawler $field)
{
if ($field->nodeName() !== 'select') {
throw new Exception('Given element is not a select element.');
}
foreach ($field->children() as $option) {
if ($option->hasAttribute('selected')) {
return $option->getAttribute('value');
}
}
return;
}
/**
* Get the checked value from a radio group.
*
* @param \Symfony\Component\DomCrawler\Crawler $radioGroup
* @return string|null
*
* @throws \Exception
*/
protected function getCheckedValueFromRadioGroup(Crawler $radioGroup)
{
if ($radioGroup->nodeName() !== 'input' || $radioGroup->attr('type') !== 'radio') {
throw new Exception('Given element is not a radio button.');
}
foreach ($radioGroup as $radio) {
if ($radio->hasAttribute('checked')) {
return $radio->getAttribute('value');
}
}
return;
}
/**
* Return true if the given checkbox is checked, false otherwise.
*
* @param string $selector
* @return bool
*
* @throws \Exception
*/
protected function isChecked($selector)
{
$checkbox = $this->filterByNameOrId($selector, "input[type='checkbox']");
if ($checkbox->count() == 0) {
throw new Exception("There are no checkbox elements with the name or ID [$selector].");
}
return $checkbox->attr('checked') !== null;
}
/**
* Click a link with the given body, name, or ID attribute.
*
* @param string $name
* @return $this
*
* @throws \InvalidArgumentException
*/
protected function click($name)
{
$link = $this->crawler()->selectLink($name);
if (! count($link)) {
$link = $this->filterByNameOrId($name, 'a');
if (! count($link)) {
throw new InvalidArgumentException(
"Could not find a link with a body, name, or ID attribute of [{$name}]."
);
}
}
$this->visit($link->link()->getUri());
return $this;
}
/**
* Fill an input field with the given text.
*
* @param string $text
* @param string $element
* @return $this
*/
protected function type($text, $element)
{
return $this->storeInput($element, $text);
}
/**
* Check a checkbox on the page.
*
* @param string $element
* @return $this
*/
protected function check($element)
{
return $this->storeInput($element, true);
}
/**
* Uncheck a checkbox on the page.
*
* @param string $element
* @return $this
*/
protected function uncheck($element)
{
return $this->storeInput($element, false);
}
/**
* Select an option from a drop-down.
*
* @param string $option
* @param string $element
* @return $this
*/
protected function select($option, $element)
{
return $this->storeInput($element, $option);
}
/**
* Attach a file to a form field on the page.
*
* @param string $absolutePath
* @param string $element
* @return $this
*/
protected function attach($absolutePath, $element)
{
$this->uploads[$element] = $absolutePath;
return $this->storeInput($element, $absolutePath);
}
/**
* Submit a form using the button with the given text value.
*
* @param string $buttonText
* @return $this
*/
protected function press($buttonText)
{
return $this->submitForm($buttonText, $this->inputs, $this->uploads);
}
/**
* Submit a form on the page with the given input.
*
* @param string $buttonText
* @param array $inputs
* @param array $uploads
* @return $this
*/
protected function submitForm($buttonText, $inputs = [], $uploads = [])
{
$this->makeRequestUsingForm($this->fillForm($buttonText, $inputs), $uploads);
return $this;
}
/**
* Fill the form with the given data.
*
* @param string $buttonText
* @param array $inputs
* @return \Symfony\Component\DomCrawler\Form
*/
protected function fillForm($buttonText, $inputs = [])
{
if (! is_string($buttonText)) {
$inputs = $buttonText;
$buttonText = null;
}
return $this->getForm($buttonText)->setValues($inputs);
}
/**
* Get the form from the page with the given submit button text.
*
* @param string|null $buttonText
* @return \Symfony\Component\DomCrawler\Form
*
* @throws \InvalidArgumentException
*/
protected function getForm($buttonText = null)
{
try {
if ($buttonText) {
return $this->crawler()->selectButton($buttonText)->form();
}
return $this->crawler()->filter('form')->form();
} catch (InvalidArgumentException $e) {
throw new InvalidArgumentException(
"Could not find a form that has submit button [{$buttonText}]."
);
}
}
/**
* Store a form input in the local array.
*
* @param string $element
* @param string $text
* @return $this
*/
protected function storeInput($element, $text)
{
$this->assertFilterProducesResults($element);
$element = str_replace('#', '', $element);
$this->inputs[$element] = $text;
return $this;
}
/**
* Assert that a filtered Crawler returns nodes.
*
* @param string $filter
* @return void
*
* @throws \InvalidArgumentException
*/
protected function assertFilterProducesResults($filter)
{
$crawler = $this->filterByNameOrId($filter);
if (! count($crawler)) {
throw new InvalidArgumentException(
"Nothing matched the filter [{$filter}] CSS query provided for [{$this->currentUri}]."
);
}
}
/**
* Filter elements according to the given name or ID attribute.
*
* @param string $name
* @param array|string $elements
* @return \Symfony\Component\DomCrawler\Crawler
*/
protected function filterByNameOrId($name, $elements = '*')
{
$name = str_replace('#', '', $name);
$id = str_replace(['[', ']'], ['\\[', '\\]'], $name);
$elements = is_array($elements) ? $elements : [$elements];
array_walk($elements, function (&$element) use ($name, $id) {
$element = "{$element}#{$id}, {$element}[name='{$name}']";
});
return $this->crawler()->filter(implode(', ', $elements));
}
/**
* Convert the given uploads to UploadedFile instances.
*
* @param \Symfony\Component\DomCrawler\Form $form
* @param array $uploads
* @return array
*/
protected function convertUploadsForTesting(Form $form, array $uploads)
{
$files = $form->getFiles();
$names = array_keys($files);
$files = array_map(function (array $file, $name) use ($uploads) {
return isset($uploads[$name])
? $this->getUploadedFileForTesting($file, $uploads, $name)
: $file;
}, $files, $names);
return array_combine($names, $files);
}
/**
* Create an UploadedFile instance for testing.
*
* @param array $file
* @param array $uploads
* @param string $name
* @return \Illuminate\Http\UploadedFile
*/
protected function getUploadedFileForTesting($file, $uploads, $name)
{
return new UploadedFile(
$file['tmp_name'], basename($uploads[$name]), $file['type'], $file['size'], $file['error'], true
);
}
}
| mit |
cleentfaar/CLTriggerBundle | Tests/DependencyInjection/ExtensionTest.php | 615 | <?php
namespace CL\Bundle\TriggerBundle\Tests\DependencyInjection;
use CL\Bundle\TriggerBundle\DependencyInjection\CLTriggerExtension;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;
class ExtensionTest extends AbstractExtensionTestCase
{
/**
* @test
*/
public function testParameters()
{
$this->load();
//$this->assertContainerBuilderHasParameter('apple', 'pear');
}
/**
* {@inheritdoc}
*/
protected function getContainerExtensions()
{
return array(
new CLTriggerExtension()
);
}
}
| mit |
angry-glass-studios/notation-android | scripts/support/test.rb | 425 | def build_test_database
puts "Building test database"
unless File.exist?("#{DATABASE_TEST_PATH}")
system "mkdir -p #{DATABASE_TEST_PATH}"
end
if File.exist?("#{DATABASE_TEST_PATH}/#{DATABASE_NAME}")
system "rm #{DATABASE_TEST_PATH}/#{DATABASE_NAME}"
end
Dir["#{DATABASE_PATH}/sc*"].each {|file|
next if file == '.' or file == '..'
system "touch #{DATABASE_TEST_PATH}/#{DATABASE_NAME}"
}
end
| mit |
katyaeka2710/python2017005 | account/migrations/0001_initial.py | 3176 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-26 19:03
from __future__ import unicode_literals
from django.db import migrations, models
import django_countries.fields
import localflavor.us.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.CreateModel(
name='EcommerceUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(help_text='Email address', max_length=255, unique=True, verbose_name='Email address')),
('first_name', models.CharField(help_text='First name', max_length=75, verbose_name='First name')),
('last_name', models.CharField(help_text='Last name', max_length=75, verbose_name='Last name')),
('phone_number', models.CharField(max_length=30, verbose_name='phone number')),
('date_joined', models.DateTimeField(auto_now=True, verbose_name='date joined')),
('is_active', models.BooleanField(default=True)),
('is_admin', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Account',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('business_name', models.CharField(blank=True, max_length=100, verbose_name='Business Name')),
('name', models.CharField(max_length=100, verbose_name='Name')),
('address_1', models.CharField(max_length=100, verbose_name='Address Line 1')),
('address_2', models.CharField(blank=True, max_length=100, verbose_name='Address Line 2')),
('city', models.CharField(max_length=100, verbose_name='City')),
('state', localflavor.us.models.USStateField()),
('zip_code', localflavor.us.models.USZipCodeField()),
('country', django_countries.fields.CountryField(max_length=2)),
],
),
]
| mit |
TypesInCode/jTemplates | src/Node/boundNode.types.ts | 1088 | import { Injector } from "../Utils/injector";
import { IDestroyable } from "../Utils/utils.types";
import { NodeRefType } from "./nodeRef";
import { INodeRef, INodeRefBase } from "./nodeRef.types";
export type FunctionOr<T> = {(...args: Array<any>): T | Promise<T> } | T;
export type NodeRefEvents = {
[name: string]: {(...args: Array<any>): void}
}
export interface NodeDefinition<T = any, E = any> {
type: any;
namespace: string;
props?: FunctionOr<{[name: string]: any}>;
attrs?: FunctionOr<{[name: string]: string}>;
on?: FunctionOr<NodeRefEvents>;
}
export interface BoundNodeFunctionParam {
props?: FunctionOr<{[name: string]: any}>;
attrs?: FunctionOr<{[name: string]: string}>;
on?: FunctionOr<NodeRefEvents>;
}
export interface IBoundNodeBase extends INodeRefBase {
nodeDef: BoundNodeFunctionParam;
lastProperties: any;
lastEvents: {[name: string]: any};
setProperties: boolean;
setAttributes: boolean;
setEvents: boolean;
}
export interface IBoundNode extends IBoundNodeBase {
type: NodeRefType.BoundNode;
} | mit |