repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
skyrbe/amruthDistillery | src/components/posts_new.js | 2111 | import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { createPost } from '../actions';
class PostsNew extends Component {
renderField(field) {
const { meta: { touched, error } } = field;
const className = `form-group ${touched && error ? 'has-danger' : ''}`;
return (
<div className={className}>
<label>{field.label}</label>
<input
className="form-control"
type="text"
{...field.input}
/>
<div className="text-help">
{touched ? error : ''}
</div>
</div>
);
}
onSubmit(values) {
this.props.createPost(values, () => {
this.props.history.push('/');
});
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field
label="Title For Post"
name="title"
component={this.renderField}
/>
<Field
label="Categories"
name="categories"
component={this.renderField}
/>
<Field
label="Post Content"
name="content"
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Submit</button>
<Link to="/" className="btn btn-danger">Cancel</Link>
</form>
);
}
}
function validate(values) {
// console.log(values) -> { title: 'asdf', categories: 'asdf', content: 'asdf' }
const errors = {};
// Validate the inputs from 'values'
if (!values.title) {
errors.title = "Enter a title";
}
if (!values.categories) {
errors.categories = 'Enter some categories';
}
if (!values.content) {
errors.content = 'Enter some content';
}
// If errors is empty, the form is fine to submit
// If errors has *any* properties, redux form assumes form is invalid
return errors;
}
export default reduxForm({
validate,
form: 'PostsNewForm'
})(
connect(null,{ createPost })(PostsNew)
);
| mit |
AmbientIT/react-training | webpack.config.js | 1697 | /*eslint-disable*/
'use strict';
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
const ENV = require('yargs').argv.env || 'development';
module.exports = webpackMerge.smart(require(`./webpack/${ENV}`), {
resolve: {
extensions: ['.jsx', '.js', '.json'],
modules: ['node_modules'],
},
module: {
rules: [
{
enforce: 'pre',
test: /\.jsx|.js$/,
exclude: /node_modules/,
loaders: ['eslint-loader', 'source-map-loader'],
},
{
test: /\.jsx|.js$/,
exclude: /node_modules/,
loader: "babel",
query: {
presets: [ 'es2015-native-modules', 'stage-0', 'react' ]
}
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
},
{
test: /\.(gif|png|jpe?g)$/i,
loader: 'file?name=dist/images/[name].[ext]'
},
{
test: /\.woff2?$/,
loader: 'url?name=dist/fonts/[name].[ext]&limit=10000&mimetype=application/font-woff'
},
{
test: /\.(ttf|eot|svg)$/,
loader: 'file?name=dist/fonts/[name].[ext]'
}
]
},
plugins: [
new CopyWebpackPlugin([{
from: 'src/assets',
to: ''
}]),
new HtmlWebpackPlugin({
template: path.resolve(process.cwd(), 'src/index.html'),
inject: 'body'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': `"${ENV}"`
}
})
]
})
| mit |
BVJin/personalWebsite | config/strategies/local.js | 857 | 'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
User = require('mongoose').model('User');
module.exports = function() {
// Use local strategy
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
User.findOne({
username: username
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
console.log("No User Found");
return done(null, false, {
message: 'Unknown user or invalid password'
});
}
if (!user.authenticate(password)) {
console.log("Password is wrong");
return done(null, false, {
message: 'Unknown user or invalid password'
});
}
return done(null, user);
});
}
));
};
| mit |
websoftwares/adr | views/index/browse.html.php | 137 | <html>
<title><?= $data["title"];?></title>
<body>
<h1><?= $data["title"];?></h1>
<div><?=$data["body"];?></div>
</body>
</html>
| mit |
takuya-takeuchi/Demo | WPF.Python4/Python/Python.py | 270 | from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True) | mit |
kra3/simple-workQ | task.py | 214 | # _*_ coding: utf-8 _*_
from simpleq.jobs import SimpleJobQueue
__author__ = 'Arun KR (@kra3)'
jq = SimpleJobQueue()
@jq.subscribe_to('sum_2_nums')
def sum_numbers(data):
return data['num1'] + data['num2']
| mit |
soniar4i/Alood | src/Alood/ExtranetBundle/Tests/Controller/DefaultControllerTest.php | 403 | <?php
namespace Alood\ExtranetBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/hello/Fabien');
$this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
}
}
| mit |
sammler/sammler-strategy-github | src/api/config/config.js | 415 | module.exports = {
COLLECTION_PREFIX: 'github~~',
FIELD_CREATED_AT: 's5r_created_at',
FIELD_UPDATED_AT: 's5r_updated_at',
COLLECTION_PROFILES: 'profiles',
COLLECTION_PROFILE_HISTORY: 'profile-history',
COLLECTION_PROFILE_FOLLOWERS_HISTORY: 'profile-followers-history',
COLLECTION_USERS: 'users',
COLLECTION_USER_STARRED: 'user-starred',
COLLECTION_USER_STARRED_HISTORY: 'user-starred-history'
};
| mit |
ekline/zed5 | Build/Fabricate/manifest.py | 1501 | ## LICENSE_BEGIN
#
# MIT License
#
# SPDX:MIT
#
# https://spdx.org/licenses/MIT
#
# See LICENSE.txt file in the top level directory.
#
## LICENSE_END
import logging
import os
from Fabricate import util
class ManifestReader(object):
"""The class that reads Manifest files and invokes the builder.
"""
MAX_AUTO_DEPENDENCY_ITERATIONS = 1000
def __init__(self, builder):
self._builder = builder
def FindAllManifests(self, where=None):
def IsManifest(fullname):
return (os.path.basename(fullname) == 'Manifest')
return sorted(util.MatchingFileGenerator(IsManifest, directory=where))
def LoadManifestFromString(self, body, filename=None):
if filename is None:
filename = '<string>'
# A custom dict for the local names.
l = {
# Factory methods for use within the Manifest:
'binary': self._builder.BuildBinary,
'generic': self._builder.BuildGenericTarget,
'library': self._builder.BuildLibrary,
'test': self._builder.BuildTest,
}
exec(compile(body, filename, 'exec'), l)
def LoadManifestFile(self, filename):
logging.debug("Loading manifest file '%s'" % filename)
return self.LoadManifestFromString(
open(filename).read(), filename=filename)
def LoadAllManifestFiles(self, where=None):
for m in self.FindAllManifests(where):
self.LoadManifestFile(m)
| mit |
MlleDelphine/formper | src/Formation/AdminBundle/Tests/Controller/DefaultControllerTest.php | 404 | <?php
namespace Formation\AdminBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/hello/Fabien');
$this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
}
}
| mit |
tonyqtian/quora-simi | util/model_eval.py | 8062 | '''
Created on Mar 18, 2017
@author: tonyq
'''
import logging
import six
from collections import OrderedDict, Iterable
from keras.callbacks import Callback
import matplotlib.pyplot as plt
from numpy import around, mean, equal, squeeze, ndarray
from random import randint
logger = logging.getLogger(__name__)
judgeInfo = {False:'Incorect', True:''}
class PlotPic(Callback):
def __init__(self, args, out_dir, timestr, metric):
self.out_dir = out_dir
self.metric = metric
self.val_metric = 'val_' + metric
self.timestr = timestr
self.losses = []
self.accs = []
self.val_accs = []
self.val_losses = []
def on_epoch_end(self, epoch, logs={}):
self.losses.append(logs.get('loss'))
self.val_losses.append(logs.get('val_loss'))
self.accs.append(logs.get(self.metric))
self.val_accs.append(logs.get(self.val_metric))
self.plothem()
return
def plothem(self):
training_epochs = [i+1 for i in range(len(self.losses))]
plt.plot(training_epochs, self.losses, 'b', label='Train Loss')
plt.plot(training_epochs, self.val_losses, 'g', label='Valid Loss')
plt.legend()
plt.xlabel('epochs')
plt.savefig(self.out_dir + '/' + self.timestr + 'TrainLoss.png')
plt.close()
plt.plot(training_epochs, self.accs, 'r.', label='Train Metric')
plt.plot(training_epochs, self.val_accs, 'y.', label='Valid Metric')
plt.legend()
plt.xlabel('epochs')
plt.savefig(self.out_dir + '/' + self.timestr + 'TrainAcc.png')
plt.close()
class Evaluator(Callback):
def __init__(self, args, out_dir, timestr, metric, test_x, test_y, reVocab):
self.out_dir = out_dir
self.test_x = test_x
self.test_y = test_y
self.best_score = 0
self.best_epoch = 0
self.batch_size = args.eval_batch_size
self.metric = metric
self.val_metric = 'val_' + metric
self.timestr = timestr
self.losses = []
self.accs = []
self.val_accs = []
self.val_losses = []
self.test_losses = []
self.test_accs = []
self.test_precisions = []
self.plot = args.plot
self.evl_pred = args.show_evl_pred
self.save_model = args.save_model
self.reVocab = reVocab
def eval(self, model, epoch):
self.test_loss, self.test_metric = model.evaluate(self.test_x, self.test_y, batch_size=self.batch_size)
self.test_losses.append(self.test_loss)
self.test_accs.append(self.test_metric)
self.print_info(epoch, self.test_loss, self.test_metric)
if self.evl_pred:
pred = model.predict(self.test_x, batch_size=self.batch_size)
preds = squeeze(pred)
precision = mean(equal(self.test_y, around(preds)).astype(int))
self.test_precisions.append(precision)
idx = randint(0, len(self.test_y)//2 )
self.print_pred([ self.test_x[0][idx:idx+self.evl_pred], self.test_x[1][idx:idx+self.evl_pred] ],
preds[idx:idx+self.evl_pred], self.test_y[idx:idx+self.evl_pred])
# if self.save_model:
# if self.test_loss < self.best_score:
# self.best_score = self.test_loss
# self.best_epoch = epoch
# self.model.save_weights(self.out_dir + '/' + self.timestr + 'best_model_weights.h5', overwrite=True)
# self.print_best()
def on_epoch_end(self, epoch, logs={}):
self.losses.append(logs.get('loss'))
self.val_losses.append(logs.get('val_loss'))
self.accs.append(logs.get(self.metric))
self.val_accs.append(logs.get(self.val_metric))
self.eval(self.model, epoch+1)
if self.plot:
self.plothem()
return
def plothem(self):
training_epochs = [i+1 for i in range(len(self.losses))]
plt.plot(training_epochs, self.losses, 'b', label='Train Loss')
plt.plot(training_epochs, self.val_losses, 'g', label='Valid Loss')
plt.plot(training_epochs, self.test_losses, 'k', label='Test Loss')
plt.legend()
plt.xlabel('epochs')
plt.savefig(self.out_dir + '/' + self.timestr + 'TrainTestLoss.png')
plt.close()
plt.plot(training_epochs, self.accs, 'r.', label='Train Metric')
plt.plot(training_epochs, self.val_accs, 'y.', label='Valid Metric')
plt.plot(training_epochs, self.test_accs, 'c.', label='Test Metric')
plt.legend()
plt.xlabel('epochs')
plt.savefig(self.out_dir + '/' + self.timestr + 'TrainTestAcc.png')
plt.close()
def print_pred(self, infers, preds, reals):
for (infr0, infr1, pred, real) in zip(infers[0], infers[1], preds, reals):
infr_line1 = []
for strin in infr0:
if not strin == 0:
infr_line1.append(self.reVocab[int(strin)])
infr_line2 = []
for strin in infr1:
if not strin == 0:
infr_line2.append(self.reVocab[int(strin)])
logger.info('[Test] ')
logger.info('[Test] Q1: %s ' % ' '.join(infr_line1))
logger.info('[Test] Q2: %s ' % ' '.join(infr_line2))
try:
logger.info('[Test] True: %d Pred %d (%.4f) %s ' %
(real, around(pred), pred, judgeInfo[real==around(pred)]) )
except ValueError:
logger.info('[Test] True: %d Pred %f ' % (real, pred) )
def print_info(self, epoch, logloss, acc):
logger.info('[Test] Epoch: %i Test Loss: %.4f Test Accuracy: %.4f%%' % (epoch, logloss, 100*acc))
logger.info('[Test] ----------------------------------------------------- ')
def print_best(self):
logger.info('[Test] ')
logger.info('[Test] Best @ Epoch %i: Log Loss: %.4f' % (self.best_epoch, self.best_score))
logger.info('[Test] ')
class TrainLogger(Callback):
"""Callback that streams epoch results to a csv file.
Supports all values that can be represented as a string,
including 1D iterables such as np.ndarray.
# Example
```python
csv_logger = CSVLogger('training.log')
model.fit(X_train, Y_train, callbacks=[csv_logger])
```
# Arguments
filename: filename of the csv file, e.g. 'run/log.csv'.
separator: string used to separate elements in the csv file.
append: True: append if file exists (useful for continuing
training). False: overwrite existing file,
"""
def __init__(self):
self.logger = logger
self.keys = None
def on_epoch_end(self, epoch, logs=None):
logs = logs or {}
def handle_value(k):
is_zero_dim_ndarray = isinstance(k, ndarray) and k.ndim == 0
if isinstance(k, six.string_types):
return k
elif isinstance(k, Iterable) and not is_zero_dim_ndarray:
return '"[%s]"' % (', '.join(map(str, k)))
else:
return k
if self.model.stop_training:
# We set NA so that csv parsers do not fail for this last epoch.
logs = dict([(k, logs[k]) if k in logs else (k, 'NA') for k in self.keys])
self.keys = sorted(logs.keys())
row_dict = OrderedDict({'epoch': epoch})
row_dict.update((key, handle_value(logs[key])) for key in self.keys)
outputlist = []
for ky, vl in row_dict.items():
if ky == 'epoch':
outputlist.append("%s %d" % (ky, vl))
elif ky.endswith('acc'):
outputlist.append("%s %.2f%%" % (ky, vl*100))
else:
outputlist.append("%s %.4f" % (ky, vl))
self.logger.info(" | ".join(outputlist)) | mit |
cherniavskii/material-ui | packages/material-ui-icons/src/WbAuto.js | 389 | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M6.85 12.65h2.3L8 9l-1.15 3.65zM22 7l-1.2 6.29L19.3 7h-1.6l-1.49 6.29L15 7h-.76C12.77 5.17 10.53 4 8 4c-4.42 0-8 3.58-8 8s3.58 8 8 8c3.13 0 5.84-1.81 7.15-4.43l.1.43H17l1.5-6.1L20 16h1.75l2.05-9H22zm-11.7 9l-.7-2H6.4l-.7 2H3.8L7 7h2l3.2 9h-1.9z" /></g>
, 'WbAuto');
| mit |
Superbalist/php-money | src/MockCurrencyConversionService.php | 712 | <?php
namespace Superbalist\Money;
class MockCurrencyConversionService extends BaseCurrencyConversionService
{
/**
* @return string
*/
public function getName()
{
return 'Mock';
}
/**
* @param Currency $currency
*
* @return array
*/
public function getConversionRatesTable(Currency $currency)
{
switch ($currency->getCode()) {
case 'USD':
return [
'USD' => '1',
'ZAR' => '12.07682',
];
default: // ZAR
return [
'USD' => '0.082776',
'ZAR' => '1',
];
}
}
}
| mit |
luiseduardobrito/static-web-cluster | client/app.js | 9735 | (function(window){
//////////////////////////////////////////////////////////
// //
// Application Configurations //
// //
//////////////////////////////////////////////////////////
var appConfig = {
state: "production",
development: {
api: {
host: "localhost",
port: 3000
},
modules: ["user"],
// show info logs
log: true
},
testing: {
api: {
host: "localhost",
port: 3000
},
modules: ["user"],
// show info logs
log: true
},
production: {
api: {
host: "localhost",
port: 3000
},
modules: ["user", "error"]
}
}
var clientConfig = {
tags: {
// tag that specify the element content
container: "data-container",
}
}
//////////////////////////////////////////////////////////
// //
// Framework Core - try not to edit... //
// //
//////////////////////////////////////////////////////////
var Client = function($, _) {
if(!clientConfig) {
throw new Error("No client configuration available...");
}
var exports = {};
var render = function(ctrl, data, cb) {
if(!ctrl || !ctrl.length)
throw new Error("No controller specified");
else if(ctrl.indexOf("javascript:") == 0)
return;
else if(ctrl[0] == "#") {
location.hash = ctrl
return;
}
else if(ctrl == "/" || ctrl[0] == '/')
var uri = ctrl;
else
var uri = "/" + ctrl;
data = data || null;
cb = cb || function(){};
var tag = "[" + clientConfig.tags.container + "='controllers']";
var _ctrl = ctrl;
$(tag).parent().load(uri +" "+ tag, data, function(data){
bindings(tag);
history.pushState('', uri || _ctrl, uri);
sandbox.broadcast.publish("controller/ready");
})
}; exports.render = render;
var publish = function(event, data) {
$("[data-subscribe='"+event+"']").each(function(){
var action = $(this).attr("data-action") || "(function(){})();";
(new Function("data", "with(this) { try {" + action + "} catch(e){ throw e; } }")).call(this, data || {});
});
}; exports.publish = publish;
var redirect = function(url) {
document.location.replace(url);
}; exports.redirect = redirect;
var bindings = function(tag){
$("a").each(function(){
if(!$(this).attr("href") || !$(this).attr("href").length)
$(this).attr("href", "javascript:;");
});
$(tag + " form[data-module][data-method]").on("submit", function(e){
e.preventDefault();
sandbox.broadcast.publish("module/call", {
module: $(this).attr("data-module"),
method: $(this).attr("data-method")
});
});
$(tag + " a[data-module][data-method]").on("click", function(e){
e.preventDefault();
sandbox.broadcast.publish("module/call", {
module: $(this).attr("data-module"),
method: $(this).attr("data-method")
});
});
$(tag + " a").on("click", function(e){
e.preventDefault();
if($(this).attr("data-module")
&& $(this).attr("data-method")) {
return false;
}
else
core.client.render($(this).attr("href"));
return false;
})
$("[data-event][data-on]").each(function(){
$(this).on($(this).attr("data-on") || "", function(e){
if(e && e.preventDefault) e.preventDefault();
var evt = $(this).attr("data-event");
var pub = $(this).attr("data-pub") || "return null";
pub = JSON.parse.call(this, pub);
window.sandbox.broadcast.publish(evt, pub);
return false;
});
});
}
var init = function(){
exports.util = _;
var tag = "[" + clientConfig.tags.container + "='controllers']";
bindings(tag);
$(window).on("hashchange", function(){
sandbox.broadcast.publish("hash/" + location.hash.replace("#", ""), {
hash: location.hash
});
});
exports = $.extend($, exports);
return exports;
}
return init();
}
var Core = function(config) {
var exports = {
log: {},
config: config,
client: new Client($, _)
};
// wrap logger
function info(msg) {
if(!config.log)
return;
if(toString.call(msg) == toString.call("str"))
console.log("info: " + msg);
else
console.log(msg);
};
exports.log.info = info;
// wrap logger
function error(msg) {
console.error(msg);
};
exports.log.error = error;
String.prototype.replaceAll = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, function(c){return "\\" + c;}), "g"+(ignore?"i":"")), str2);
};
function init() {
// run unit test
info("core initialized successfully...")
return exports;
}
return init();
}
var Sandbox = function(core) {
var exports = {
modules: core.config.modules,
selector: $
};
var subscribers = {
any: [] // event type: subscribers
};
var once = {
any: [] // event type: subscribers
};
var broadcast = {
subscribe: function (type, fn) {
type = type || 'any';
if (typeof subscribers[type] === "undefined") {
subscribers[type] = [];
}
subscribers[type].push(fn);
},
once: function (type, fn) {
type = type || 'any';
if (typeof once[type] === "undefined") {
once[type] = [];
}
once[type].push(fn);
},
unsubscribe: function (type, fn) {
this.visitSubscribers('unsubscribe', fn, type);
},
publish: function (type, publication) {
this.visitSubscribers('publish', publication, type);
if(core && core.client)
core.client.publish(type, publication);
},
visitSubscribers: function (action, arg, type) {
var pubtype = type || 'any';
s = subscribers[pubtype] || [];
max = s.length;
for (var i = 0; i < max; i += 1) {
if (action === 'publish') {
s[i](arg);
} else {
if (s[i] === arg) {
s.splice(i, 1);
}
}
}
o = once[pubtype] || [];
max = o.length;
while(o.length) {
var cb = o.pop();
if (action === 'publish') {
cb(arg);
o.splice(i, 1);
}
}
}
}; exports.broadcast = broadcast;
var Api = function(config) {
function _this (uri, data, methods) {
this._uri = uri;
this._data = data;
this._methods = methods || {
success: function(){},
error: function(){
throw new Error("Uncaught problem with API connection");
}
};
};
_this.prototype.success = function(fn) {
this._methods["success"] = fn;
return this;
};
_this.prototype.error = function(fn) {
this._methods["error"] = fn;
return this;
};
_this.prototype.get = function() {
var connection_url = "http://" + config.api.host;
connection_url += ":" + config.api.port + "/api/";
data = this._data || {};
var __this = this;
$.get(connection_url + this._uri, data, function(data) {
if(!data) {
var cb = __this._methods["error"] ||
cb();
}
var response = toString.call(data) == toString.call("str") ?
JSON.parse(data) : data;
if(!response) {
var cb = __this._methods["error"] || function(){};
cb(response);
}
else if(response.result
&& response.result == "success") {
var cb = __this._methods["success"] || function(){};
cb(response);
}
else if(response.result
&& response.result == "error") {
var cb = __this._methods["error"] || function(){};
cb(response);
}
else {
var cb = __this._methods["error"] || function(){};
cb(response);
}
});
return this;
};
return _this;
}; exports.api = function(url, data){
// TODO: improve API wrapper
var obj = new Api(core.config);
return new obj(url, data);
};
function init() {
if(location.hash) {
core.client.render(location.hash);
}
core.log.info("sandbox initialized successfully...")
return exports;
}
return init();
};
window.Application = function(sandbox) {
var exports = {};
var modules = {};
var queue = {};
function start(name) {
modules[name] = modules[name].init(sandbox);
}; exports.start = start;
function startAll() {
for(var k in modules)
start(k);
core.log.info("app started successfully")
}; exports.startAll = startAll;
function stop(name) {
modules[name] = modules[name] = {};
modules[k].destroy = modules[k].destroy || function(){};
modules[k].destroy();
modules[k] = null;
return true;
}; exports.stop = stop;
function stopAll() {
for(var k in modules)
stop(k)
core.log.info("app stopped successfully");
return true;
}; exports.stopAll = stopAll;
function register(name) {
if(window[name + "_module"]) {
var m = window[name + "_module"];
modules[name] = new m(sandbox);
return true;
}
else
return false;
};
function init() {
for(var i = 0; i < sandbox.modules.length; i++)
if(!register(sandbox.modules[i]))
core.log.error("Module not found: " + sandbox.modules[i])
sandbox.broadcast.subscribe("module/call", function(data) {
if(!modules[data.module])
throw new Error("Module not found: " + data.module)
else if(!modules[data.module][data.method])
throw new Error("Method '" + data.method+"' not found in '" + data.module + "' module")
else {
var m = modules[data.module][data.method];
m({});
}
});
core.log.info("app initializing...")
sandbox.broadcast.publish("app/ready", {});
return exports;
}
return init();
}
var config = appConfig[appConfig.state];
window.core = new Core(config);
window.sandbox = new Sandbox(core);
})(window) | mit |
IngSW-unipv/Progetto-A | Sette_e_Mezzo/src/partitaOnline/events/GiocatoreIniziaTurno.java | 754 | /*
* 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 partitaOnline.events;
/**
*
* @author root
*/
public class GiocatoreIniziaTurno {
private String giocatore;
/**
*
* @param giocatore giocatore che inizia il turno
*/
public GiocatoreIniziaTurno(String giocatore) {
this.giocatore = giocatore;
}
/**
*
* @return giocatore che inizia il turno
*/
public String getGiocatore() {
return giocatore;
}
@Override
public String toString() {
return "evento\tGiocatoreIniziaTurno\t" + giocatore;
}
}
| mit |
peteward44/WebNES | project/js/db/4FF9772497E604216463904B0572E3F1C6A87177.js | 1440 | this.NesDb = this.NesDb || {};
NesDb[ '4FF9772497E604216463904B0572E3F1C6A87177' ] = {
"$": {
"name": "Best Play Pro Yakyuu",
"altname": "ベストプレープロ野球",
"class": "Licensed",
"catalog": "HSP-11",
"publisher": "ASCII",
"developer": "ASCII",
"region": "Japan",
"players": "2",
"date": "1988-07-15"
},
"peripherals": [
{
"device": [
{
"$": {
"type": "turbofile",
"name": "TurboFile"
}
}
]
}
],
"cartridge": [
{
"$": {
"system": "Famicom",
"revision": "A",
"crc": "E19293A2",
"sha1": "4FF9772497E604216463904B0572E3F1C6A87177",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2006-12-24"
},
"board": [
{
"$": {
"type": "HVC-SJROM",
"pcb": "HVC-SJROM-03",
"mapper": "1"
},
"prg": [
{
"$": {
"name": "HSP-11-1 PRG",
"size": "128k",
"crc": "E792DE94",
"sha1": "8AE3712827E01A2BB264A0817AC24A49D73685E0"
}
}
],
"chr": [
{
"$": {
"name": "HSP-11-0 CHR",
"size": "32k",
"crc": "13DE672A",
"sha1": "E0168759766EE4DE4ED84475437F67E6FDDC964C"
}
}
],
"wram": [
{
"$": {
"size": "8k",
"battery": "1"
}
}
],
"chip": [
{
"$": {
"type": "MMC1A"
}
}
]
}
]
}
]
};
| mit |
TeamSPoon/logicmoo_workspace | packs_web/swish/web/node_modules/ace/build/src/snippets/coffee.js | 2664 | define("ace/snippets/coffee", ["require", "exports", "module"], function(require, exports, module) {
"use strict";
exports.snippetText = "# Closure loop\n\
snippet forindo\n\
for ${1:name} in ${2:array}\n\
do ($1) ->\n\
${3:// body}\n\
# Array comprehension\n\
snippet fora\n\
for ${1:name} in ${2:array}\n\
${3:// body...}\n\
# Object comprehension\n\
snippet foro\n\
for ${1:key}, ${2:value} of ${3:object}\n\
${4:// body...}\n\
# Range comprehension (inclusive)\n\
snippet forr\n\
for ${1:name} in [${2:start}..${3:finish}]\n\
${4:// body...}\n\
snippet forrb\n\
for ${1:name} in [${2:start}..${3:finish}] by ${4:step}\n\
${5:// body...}\n\
# Range comprehension (exclusive)\n\
snippet forrex\n\
for ${1:name} in [${2:start}...${3:finish}]\n\
${4:// body...}\n\
snippet forrexb\n\
for ${1:name} in [${2:start}...${3:finish}] by ${4:step}\n\
${5:// body...}\n\
# Function\n\
snippet fun\n\
(${1:args}) ->\n\
${2:// body...}\n\
# Function (bound)\n\
snippet bfun\n\
(${1:args}) =>\n\
${2:// body...}\n\
# Class\n\
snippet cla class ..\n\
class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\
${2}\n\
snippet cla class .. constructor: ..\n\
class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\
constructor: (${2:args}) ->\n\
${3}\n\
\n\
${4}\n\
snippet cla class .. extends ..\n\
class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} extends ${2:ParentClass}\n\
${3}\n\
snippet cla class .. extends .. constructor: ..\n\
class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} extends ${2:ParentClass}\n\
constructor: (${3:args}) ->\n\
${4}\n\
\n\
${5}\n\
# If\n\
snippet if\n\
if ${1:condition}\n\
${2:// body...}\n\
# If __ Else\n\
snippet ife\n\
if ${1:condition}\n\
${2:// body...}\n\
else\n\
${3:// body...}\n\
# Else if\n\
snippet elif\n\
else if ${1:condition}\n\
${2:// body...}\n\
# Ternary If\n\
snippet ifte\n\
if ${1:condition} then ${2:value} else ${3:other}\n\
# Unless\n\
snippet unl\n\
${1:action} unless ${2:condition}\n\
# Switch\n\
snippet swi\n\
switch ${1:object}\n\
when ${2:value}\n\
${3:// body...}\n\
\n\
# Log\n\
snippet log\n\
console.log ${1}\n\
# Try __ Catch\n\
snippet try\n\
try\n\
${1}\n\
catch ${2:error}\n\
${3}\n\
# Require\n\
snippet req\n\
${2:$1} = require '${1:sys}'${3}\n\
# Export\n\
snippet exp\n\
${1:root} = exports ? this\n\
";
exports.scope = "coffee";
});
(function() {
window.require(["ace/snippets/coffee"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})(); | mit |
shafiqabs/bdeducations | app/Resources/assets/module/pagination/js/jplist.views-control.min.js | 1959 | /*
jPList - jQuery Data Grid Controls - http://jplist.com
Copyright 2014 jPList Software. All rights reserved.
*/
(function(){jQuery.fn.jplist.ui.controls.ViewsDTO=function(d){this.view=d}})();(function(){var d=function(a,b){var c;c=null;c=a.params.defaultView;c=b?a.params.defaultView:a.params.currentView;c=new jQuery.fn.jplist.ui.controls.ViewsDTO(c);return c=new jQuery.fn.jplist.app.dto.StatusDTO(a.name,a.action,a.type,c,a.inStorage,a.inAnimation,a.isAnimateToTop,a.inDeepLinking)},f=function(a){a.params.$buttons.on("click",function(){var b=jQuery(this).attr("data-type");a.$root.removeClass(a.params.types.join(" ")).addClass(b);a.params.currentView=b;a.history.addStatus(d(a,!1));a.observer.trigger(a.observer.events.unknownStatusesChanged,
[!1])})},e=function(a){a.params={$buttons:a.$control.find("[data-type]"),defaultView:a.$control.attr("data-default")||"list-view",currentView:a.$control.attr("data-default")||"list-view",types:[]};0<a.params.$buttons.length&&(a.params.$buttons.each(function(){var b=jQuery(this).attr("data-type");b&&a.params.types.push(b)}),f(a));return jQuery.extend(this,a)};e.prototype.getStatus=function(a){return d(this,a)};e.prototype.getDeepLink=function(){var a="",b;this.inDeepLinking&&(b=d(this,!1),b.data&&
(a=this.name+this.options.delimiter0+"view="+b.data.view));return a};e.prototype.getStatusByDeepLink=function(a,b){var c=null;this.inDeepLinking&&(c=d(this,!0),c.data.view=b);return c};e.prototype.setStatus=function(a,b){a.data&&(this.$root.removeClass(this.params.types.join(" ")),!this.inStorage&&b?(this.$root.addClass(this.params.defaultView),a.data.view=this.params.defaultView,this.params.currentView=this.params.defaultView,this.observer.trigger(this.observer.events.statusChanged,[a])):(this.$root.addClass(a.data.view),
this.params.currentView=a.data.view))};jQuery.fn.jplist.ui.controls.Views=function(a){return new e(a)};jQuery.fn.jplist.controlTypes.views={className:"Views",options:{}}})();
| mit |
adecker89/MemeifyMe | MemeifyMe/src/main/java/com/adecker/memeifyme/CapturedPreviewFragment.java | 5035 | package com.adecker.memeifyme;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.*;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
/**
* Created by alex on 11/16/13.
*/
public class CapturedPreviewFragment extends Fragment {
private String[] text = {"Wow", "What r\nyou doing", "so scare", "Concern", "plz no", "nevr scratch again"};
private Rect faceRect;
private ArrayList<TextView> blurbs = new ArrayList<TextView>();
private Bitmap bm;
private TextDragLayout mTextOverlay;
private MemeOverlay mMemeOverlay;
private FrameLayout mOverlayFrame;
private ImageView mImageView;
public CapturedPreviewFragment(Bitmap bm, Rect faceRect) {
this.bm = bm;
this.faceRect = faceRect;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_capture, container, false);
mImageView = (ImageView) rootView.findViewById(R.id.image);
mImageView.setImageBitmap(bm);
mTextOverlay = new TextDragLayout(getActivity());
mMemeOverlay = new MemeOverlay(getActivity(), faceRect);
mOverlayFrame = (FrameLayout) rootView.findViewById(R.id.text_overlay);
mOverlayFrame.addView(mMemeOverlay);
mOverlayFrame.addView(mTextOverlay);
Button captureButton = (Button) rootView.findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
shareBitmap(bm);
}
}
);
Random rnd = new Random();
for (String str : text) {
TextView tv = new TextView(getActivity());
tv.setTextSize(32);
tv.setText(str);
tv.setTextColor(Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
blurbs.add(tv);
mTextOverlay.addView(tv);
}
return rootView;
}
public void shareBitmap(Bitmap bm) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/jpg");
Uri uri = storeImage(compositeBitmap(bm));
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(intent);
}
private Uri storeImage(Bitmap bm) {
File file = getOutputMediaFile(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE);
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Uri.parse("file://" + file.getAbsolutePath());
}
/**
* Create a File for saving an image or video
*/
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Doge");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Doge", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
} else if (type == MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
private Bitmap compositeBitmap(Bitmap bm) {
Bitmap mutable = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
Canvas canvas = new Canvas(mutable);
canvas.drawBitmap(bm, new Matrix(), null);
Matrix matrix = new Matrix();
matrix.postScale(canvas.getWidth() / (float) mImageView.getWidth(), canvas.getHeight() / (float) mImageView
.getHeight());
canvas.setMatrix(matrix);
mMemeOverlay.draw(canvas);
mTextOverlay.draw(canvas);
return mutable;
}
}
| mit |
devonhollowood/adventofcode | 2021/src/day05.rs | 4156 | use anyhow::{anyhow, Result};
use chumsky::prelude::{Parser, Simple};
use chumsky::Error;
use nalgebra::{vector, Vector2};
use std::collections::HashMap;
type Vec2 = Vector2<i64>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Line {
start: Vec2,
end: Vec2,
}
impl Line {
fn is_vertical(&self) -> bool {
self.start.x == self.end.x
}
fn is_horizontal(&self) -> bool {
self.start.y == self.end.y
}
fn vertical_points(&self) -> Vec<Vec2> {
assert!(self.is_vertical());
let (min, max) = if self.start.y <= self.end.y {
(self.start, self.end)
} else {
(self.end, self.start)
};
(min.y..=max.y).map(|y| vector![self.start.x, y]).collect()
}
fn horizontal_points(&self) -> Vec<Vec2> {
assert!(self.is_horizontal());
let (min, max) = if self.start.x <= self.end.x {
(self.start, self.end)
} else {
(self.end, self.start)
};
(min.x..=max.x).map(|x| vector![x, self.start.y]).collect()
}
fn diagonal_points(&self) -> Vec<Vec2> {
let (left, right) = if self.start.x <= self.end.x {
(self.start, self.end)
} else {
(self.end, self.start)
};
let mut result = Vec::new();
result.reserve((right.x - left.x + 1) as usize);
let sign = (right.y - left.y).signum();
let mut y = left.y;
for x in left.x..=right.x {
result.push(vector![x, y]);
y += sign;
}
result
}
}
fn parser() -> impl Parser<char, Vec<Line>, Error = Simple<char>> {
use chumsky::prelude::*;
use chumsky::text::*;
let point = int(10)
.map(|i: String| i.parse::<i64>().unwrap())
.then_ignore(just(","))
.then(int(10).map(|i: String| i.parse::<i64>().unwrap()))
.map(|(x, y)| vector![x, y]);
point
.then_ignore(just(" -> "))
.then(point)
.map(|(start, end)| Line { start, end })
.separated_by(just("\n"))
.allow_leading()
.allow_trailing()
.then_ignore(end())
}
pub fn parse(input: &str) -> Result<Vec<Line>> {
parser()
.parse(input)
.map_err(|errs| errs.into_iter().reduce(|acc, err| acc.merge(err)).unwrap())
.map_err(|err| anyhow!("error parsing day 5 input: {:?}", err))
}
pub fn part1(input: &[Line]) -> usize {
let mut counter: HashMap<Vec2, usize> = HashMap::new();
for point in input
.iter()
.filter_map(|l| {
if l.is_vertical() {
Some(l.vertical_points())
} else if l.is_horizontal() {
Some(l.horizontal_points())
} else {
None
}
})
.flatten()
{
*counter.entry(point).or_default() += 1;
}
counter.values().filter(|v| **v >= 2).count()
}
pub fn part2(input: &[Line]) -> usize {
let mut counter: HashMap<Vec2, usize> = HashMap::new();
for point in input
.iter()
.map(|l| {
if l.is_vertical() {
l.vertical_points()
} else if l.is_horizontal() {
l.horizontal_points()
} else {
l.diagonal_points()
}
})
.flatten()
{
*counter.entry(point).or_default() += 1;
}
counter.values().filter(|v| **v >= 2).count()
}
#[cfg(test)]
mod tests {
use super::*;
const INPUT: &str = r"
0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2";
#[test]
fn test_parse() {
let input = parse(INPUT).unwrap();
assert_eq!(input.len(), 10);
assert_eq!(
input[0],
Line {
start: vector![0, 9],
end: vector![5, 9]
}
);
}
#[test]
fn test_part1() {
let input = parse(INPUT).unwrap();
assert_eq!(part1(&input), 5);
}
#[test]
fn test_part2() {
let input = parse(INPUT).unwrap();
assert_eq!(part2(&input), 12);
}
}
| mit |
exclusivecoin/Exclusive | src/rpcwallet.cpp | 61946 | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "init.h"
#include "base58.h"
using namespace json_spirit;
using namespace std;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
static void accountingDeprecationCheck()
{
if (!GetBoolArg("-enableaccounts", false))
throw runtime_error(
"Accounting API is deprecated and will be removed in future.\n"
"It can easily result in negative or odd balances if misused or misunderstood, which has happened in the field.\n"
"If you still want to enable it, add to your config file enableaccounts=1\n");
if (GetBoolArg("-staking", true))
throw runtime_error("If you want to use accounting API, staking must be disabled, add to your config file staking=0\n");
}
std::string HelpRequiringPassphrase()
{
return pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet is unlocked for staking only.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase() || wtx.IsCoinStake())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj, diff;
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint())));
obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply)));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP()));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewpubkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewpubkey [account]\n"
"Returns new public key for coinbase generation.");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
vector<unsigned char> vchPubKey = newKey.Raw();
return HexStr(vchPubKey.begin(), vchPubKey.end());
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new ExclusiveCoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current ExclusiveCoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <ExclusiveCoinaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ExclusiveCoin address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <ExclusiveCoinaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ExclusiveCoin address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <ExclusiveCoinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ExclusiveCoin address");
// Amount
int64_t nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64_t> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <ExclusiveCoinaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <ExclusiveCoinaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
return false;
return (key.GetPubKey().GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <ExclusiveCoinaddress> [minconf=1]\n"
"Returns the total amount received by <ExclusiveCoinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ExclusiveCoin address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64_t nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
accountingDeprecationCheck();
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64_t nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64_t GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64_t nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal() || wtx.GetDepthInMainChain() < 0)
continue;
int64_t nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64_t GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number.
int64_t nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsTrusted())
continue;
int64_t allFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
accountingDeprecationCheck();
string strAccount = AccountFromValue(params[0]);
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
accountingDeprecationCheck();
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64_t nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <toExclusiveCoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ExclusiveCoin address");
int64_t nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64_t> > vecSend;
int64_t totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid ExclusiveCoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64_t nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64_t nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed");
}
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a ExclusiveCoin address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
// Construct using pay-to-script-hash:
CScript inner;
inner.SetMultisig(nRequired, pubkeys);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value addredeemscript(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
{
string msg = "addredeemscript <redeemScript> [account]\n"
"Add a P2SH address with a specified redeemScript to the wallet.\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Construct using pay-to-script-hash:
vector<unsigned char> innerData = ParseHexV(params[0], "redeemScript");
CScript inner(innerData.begin(), innerData.end());
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem
{
int64_t nAmount;
int nConf;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64_t nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64_t nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
accountingDeprecationCheck();
return ListReceived(params, true);
}
static void MaybePushAddress(Object & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64_t nFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Sent
if ((!wtx.IsCoinStake()) && (!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.first);
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
bool stop = false;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.first);
if (wtx.IsCoinBase() || wtx.IsCoinStake())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
if (!wtx.IsCoinStake())
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
else
{
entry.push_back(Pair("amount", ValueFromAmount(-nFee)));
stop = true; // only one coinstake output
}
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
if (stop)
break;
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
accountingDeprecationCheck();
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64_t> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64_t nFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (nDepth >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64_t)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (pwalletMain->mapWallet.count(hash))
{
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
TxToJSON(wtx, 0, entry);
int64_t nCredit = wtx.GetCredit();
int64_t nDebit = wtx.GetDebit();
int64_t nNet = nCredit - nDebit;
int64_t nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
entry.push_back(Pair("details", details));
}
else
{
CTransaction tx;
uint256 hashBlock = 0;
if (GetTransaction(hash, tx, hashBlock))
{
TxToJSON(tx, 0, entry);
if (hashBlock == 0)
entry.push_back(Pair("confirmations", 0));
else
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
else
entry.push_back(Pair("confirmations", 0));
}
}
}
else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
}
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill [new-size]\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
unsigned int nSize = max(GetArg("-keypool", 100), (int64_t)0);
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size");
nSize = (unsigned int) params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(nSize);
if (pwalletMain->GetKeyPoolSize() < nSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("ExclusiveCoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("ExclusiveCoin-lock-wa");
int64_t nMyWakeTime = GetTimeMillis() + *((int64_t*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64_t nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
MilliSleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64_t*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase <passphrase> <timeout> [stakingonly]\n"
"Stores the wallet decryption key in memory for <timeout> seconds.\n"
"if [stakingonly] is true sending functions are disabled.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
NewThread(ThreadTopUpKeyPool, NULL);
int64_t* pnSleepTime = new int64_t(params[1].get_int64());
NewThread(ThreadCleanWalletPassphrase, pnSleepTime);
// ppcoin: if user OS account compromised prevent trivial sendmoney commands
if (params.size() > 2)
fWalletUnlockStakingOnly = params[2].get_bool();
else
fWalletUnlockStakingOnly = false;
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; ExclusiveCoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw())));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <ExclusiveCoinaddress>\n"
"Return information about <ExclusiveCoinaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value validatepubkey(const Array& params, bool fHelp)
{
if (fHelp || !params.size() || params.size() > 2)
throw runtime_error(
"validatepubkey <ExclusiveCoinpubkey>\n"
"Return information about <ExclusiveCoinpubkey>.");
std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str());
CPubKey pubKey(vchPubKey);
bool isValid = pubKey.IsValid();
bool isCompressed = pubKey.IsCompressed();
CKeyID keyID = pubKey.GetID();
CBitcoinAddress address;
address.Set(keyID);
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
ret.push_back(Pair("iscompressed", isCompressed));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
// ppcoin: reserve balance from being staked for network protection
Value reservebalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"reservebalance [<reserve> [amount]]\n"
"<reserve> is true or false to turn balance reserve on or off.\n"
"<amount> is a real and rounded to cent.\n"
"Set reserve amount not participating in network protection.\n"
"If no parameters provided current setting is printed.\n");
if (params.size() > 0)
{
bool fReserve = params[0].get_bool();
if (fReserve)
{
if (params.size() == 1)
throw runtime_error("must provide amount to reserve balance.\n");
int64_t nAmount = AmountFromValue(params[1]);
nAmount = (nAmount / CENT) * CENT; // round to cent
if (nAmount < 0)
throw runtime_error("amount cannot be negative.\n");
nReserveBalance = nAmount;
}
else
{
if (params.size() > 1)
throw runtime_error("cannot specify amount to turn off reserve.\n");
nReserveBalance = 0;
}
}
Object result;
result.push_back(Pair("reserve", (nReserveBalance > 0)));
result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
return result;
}
// ppcoin: check wallet integrity
Value checkwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"checkwallet\n"
"Check wallet for integrity.\n");
int nMismatchSpent;
int64_t nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// ppcoin: repair wallet
Value repairwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"repairwallet\n"
"Repair wallet if checkwallet reports any problem.\n");
int nMismatchSpent;
int64_t nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// NovaCoin: resend unconfirmed wallet transactions
Value resendtx(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"resendtx\n"
"Re-send unconfirmed transactions.\n"
);
ResendWalletTransactions(true);
return Value::null;
}
// ppcoin: make a public-private key pair
Value makekeypair(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"makekeypair [prefix]\n"
"Make a public/private key pair.\n"
"[prefix] is optional preferred prefix for the public key.\n");
string strPrefix = "";
if (params.size() > 0)
strPrefix = params[0].get_str();
CKey key;
key.MakeNewKey(false);
CPrivKey vchPrivKey = key.GetPrivKey();
Object result;
result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end())));
result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw())));
return result;
}
| mit |
cuckata23/wurfl-data | data/thl_w100s_ver1.php | 329 | <?php
return array (
'id' => 'thl_w100s_ver1',
'fallback' => 'generic_android_ver4_2',
'capabilities' =>
array (
'model_name' => 'W100S',
'brand_name' => 'ThL',
'physical_screen_height' => '100',
'physical_screen_width' => '57',
'resolution_width' => '540',
'resolution_height' => '960',
),
);
| mit |
PatrickgHayes/nnClassify | src/Pickler_.py | 4978 | # This file has all the methods for pickling and unpickling data
import cv2
import random
import os
import math
import numpy as np
import shutil
import re
import pickle
from src import Constants
from src.Constants import BASE_DIR
from src.Constants import PRED_DIR
from src.Constants import TRAIN_DIR
from src.MyUtils_ import MyUtils
class Pickler:
@staticmethod
def pickle_wells(pred_set):
""" This method pickles all the wells in a prediction set
individually"""
categories = MyUtils.listdir_nohidden(os.path.join(pred_set,"Images"))
if not os.path.exists(os.path.join(pred_set, "Pickles")):
os.makedirs(os.path.join(pred_set, "Pickles"))
#The highest level directory will have a folder for each category
# (0_Eyes, 1_Eye, 2_Eyes, etc.)
for category in categories:
if not os.path.exists(os.path.join(pred_set, "Pickles", category)):
os.makedirs(os.path.join(pred_set, "Pickles", category))
wells = MyUtils.listdir_nohidden(os.path.join(pred_set, "Images"
,category))
# Inside each category will be a bunch of folders were each folder
# is a singel well
for well in wells:
print ("Pickling well" + well)
files = list(MyUtils.listdir_nohidden(
os.path.join(pred_set, "Images", category, well)))
images = []
for img in files:
images.append(img)
images_np = np.zeros((len(images), 100, 100, 3))
for i in range(0, len(images)):
images_np[i,:,:,:] = cv2.imread(os.path.join(
pred_set, 'Images', category, well, images[i]))
pickle.dump(images_np,
open(os.path.join(pred_set, 'Pickles'
, category, well),"wb"))
print ("Done with well " + well)
print (" ")
return
@staticmethod
def pickle_wells_no_category(pred_set):
""" This method pickles all the images for a prediction set.
A prediction set has no categories"""
if not os.path.exists(os.path.join(pred_set, "Pickles")):
os.makedirs(os.path.join(pred_set, "Pickles"))
wells = MyUtils.listdir_nohidden(os.path.join(pred_set, "Images"))
# Inside each category will be a bunch of folders were each folder
# is a singel well
for well in wells:
print ("Pickling well" + well)
files = list(MyUtils.listdir_nohidden(os.path.join(
pred_set, "Images", well)))
images = []
for img in files:
images.append(img)
images_np = np.zeros((len(images), 100, 100, 3))
for i in range(0, len(images)):
images_np[i,:,:,:] = cv2.imread(os.path.join(pred_set
,'Images'
, well, images[i]))
pickle.dump(images_np,
open(os.path.join(pred_set, 'Pickles'
,well),"wb"))
print ("Done with well " + well)
print (" ")
return
@staticmethod
def pickleIndividualSet(set_path):
"""This method pickles a set of individual images so
that we don't have to read
in all the images individaully each time"""
labels = []
all_images_np = np.empty((0,100,100,3))
categories = MyUtils.listdir_nohidden(os.path.join(set_path
,'Images'))
for category in categories:
images = []
files = list(MyUtils.listdir_nohidden(os.path.join(set_path
,"Images", category)))
for img in files:
images.append(img)
print (len(images))
images_np = np.zeros((len(images), 100, 100, 3))
for i in range(0, len(images)):
images_np[i,:,:,:] = cv2.imread(os.path.join(set_path
,'Images', category, images[i]))
if category == Constants.WEIRD :
labels.append([0,0,1])
elif category == Constants.NORMAL :
labels.append([0,1,0])
else:
labels.append([1,0,0])
all_images_np = np.concatenate((all_images_np, images_np),
axis = 0)
labels_np = np.array(labels)
pickle.dump( all_images_np,
open(os.path.join(set_path, 'images.p'),"wb"))
pickle.dump( labels_np,
open(os.path.join(set_path, 'labels.p'),"wb"))
return
| mit |
SplitTime/OpenSplitTime | spec/services/raw_time_pairer_spec.rb | 2678 | require "rails_helper"
RSpec.describe RawTimePairer do
subject { RawTimePairer.new(event_group: event_group, raw_times: raw_times) }
let(:event_group) { build_stubbed(:event_group) }
let(:raw_time_1) { build_stubbed(:raw_time, event_group_id: event_group.id, bib_number: "10", split_name: "cunningham", bitkey: 1, stopped_here: false) }
let(:raw_time_2) { build_stubbed(:raw_time, event_group_id: event_group.id, bib_number: "10", split_name: "cunningham", bitkey: 64, stopped_here: true) }
let(:raw_time_3) { build_stubbed(:raw_time, event_group_id: event_group.id, bib_number: "11", split_name: "cunningham", bitkey: 1, with_pacer: true) }
let(:raw_time_4) { build_stubbed(:raw_time, event_group_id: event_group.id, bib_number: "11", split_name: "cunningham", bitkey: 64, with_pacer: true) }
let(:raw_time_5) { build_stubbed(:raw_time, event_group_id: event_group.id, bib_number: "10", split_name: "maggie", bitkey: 1) }
let(:raw_time_6) { build_stubbed(:raw_time, event_group_id: event_group.id, bib_number: "10", split_name: "maggie", bitkey: 64) }
let(:raw_time_7) { build_stubbed(:raw_time, event_group_id: event_group.id, bib_number: "10", split_name: "cunningham", bitkey: 64) }
let(:raw_time_bad_split) { build_stubbed(:raw_time, event_group_id: event_group.id, bib_number: "10", split_name: "bad-split", bitkey: 1) }
let(:raw_time_wildcard_1) { build_stubbed(:raw_time, event_group_id: event_group.id, bib_number: "10*", split_name: "cunningham", bitkey: 1) }
let(:raw_time_wildcard_2) { build_stubbed(:raw_time, event_group_id: event_group.id, bib_number: "10*", split_name: "cunningham", bitkey: 64) }
describe "#pair" do
context "when all raw_times can be paired" do
let(:raw_times) { [raw_time_1, raw_time_2, raw_time_3, raw_time_4, raw_time_5, raw_time_6, raw_time_7] }
it "returns an array of paired raw_time arrays" do
expected = [[raw_time_1, raw_time_2], [nil, raw_time_7], [raw_time_3, raw_time_4], [raw_time_5, raw_time_6]]
expect(subject.pair).to eq(expected)
end
it "retains boolean attributes" do
expect(subject.pair.first.map(&:stopped_here)).to eq([false, true])
expect(subject.pair.third.map(&:with_pacer)).to eq([true, true])
end
end
context "when raw_times contain wildcard characters" do
let(:raw_times) { [raw_time_1, raw_time_2, raw_time_wildcard_1, raw_time_wildcard_2] }
it "pairs matching wildcard bib_numbers with each other but not with any other raw_time" do
expected = [[raw_time_1, raw_time_2], [raw_time_wildcard_1, raw_time_wildcard_2]]
expect(subject.pair).to eq(expected)
end
end
end
end
| mit |
richardfullmer/openriff | src/Openriff/Entity/Track.php | 208 | <?php
/**
* @author Richard Fullmer <richardfullmer@gmail.com>
*/
class Track
{
protected $id;
protected $queue;
protected $trackId;
protected $createdAt;
protected $updatedAt;
}
| mit |
wichtounet/dll | include/dll/transform/lcn_layer.hpp | 514 | //=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
// Include the dyn version (for dyn_dbn)
#include "dll/transform/dyn_lcn_layer.hpp"
#include "dll/transform/lcn_layer_impl.hpp"
#include "dll/transform/lcn_layer_desc.hpp"
| mit |
jeremykendall/12-tdds-of-christmas | tests/Tdd/FizzBuzzTest.php | 2352 | <?php
namespace Tdd\Test;
use Tdd\FizzBuzz;
/**
* Test class for FizzBuzz.
* Generated by PHPUnit on 2012-09-28 at 15:20:51.
*/
class FizzBuzzTest extends \PHPUnit_Framework_TestCase
{
/**
* @var FizzBuzz
*/
protected $fizzBuzz;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
parent::setUp();
$this->fizzBuzz = new FizzBuzz();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
$this->fizzBuzz = null;
parent::tearDown();
}
public function intDataProvider()
{
return array(
array(1),
array(2),
array(4),
array(7)
);
}
public function multipleThreeDataProvider()
{
return array(
array(3),
array(6),
array(9),
array(12)
);
}
public function multipleFiveDataProvider()
{
return array(
array(5),
array(10),
array(20),
array(25)
);
}
public function multipleThreeAndFiveDataProvider()
{
return array(
array(15),
array(30),
array(45),
array(60)
);
}
/**
* @dataProvider intDataProvider
*/
public function testOfReturnsIntWhenNotMultipleOfThreeAndOrFive($a)
{
$int = $this->fizzBuzz->of($a);
$this->assertEquals($a, $int);
$this->assertInternalType('int', $int);
}
/**
* @dataProvider multipleThreeDataProvider
*/
public function testMultipleOfThreeReturnsFizz($a)
{
$this->assertEquals('Fizz', $this->fizzBuzz->of($a));
}
/**
* @dataProvider multipleFiveDataProvider
*/
public function testMultipleOfFiveReturnsBuzz($a)
{
$this->assertEquals('Buzz', $this->fizzBuzz->of($a));
}
/**
* @dataProvider multipleThreeAndFiveDataProvider
*/
public function testMultipleOfThreeAndFiveReturnsFizzBuzz($a)
{
$this->assertEquals('FizzBuzz', $this->fizzBuzz->of($a));
}
}
| mit |
anirbanatweb/stelinpd | stelinpd/settings.py | 2666 | """
Django settings for stelinpd project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1y@xhc#ks&wqal)gd(96cn@m&_mad(&9+&qx4kzdjmxed94%=d'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'stelinpd.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'stelinpd.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
| mit |
d3cod3/HybridPlayGameSkeleton | android/android/src/com/hybridplay/shared/SharedFunctions.java | 11689 | package com.hybridplay.shared;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.ByteOrder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import org.apache.http.util.ByteArrayBuffer;
import com.hybridplay.game.android.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class SharedFunctions {
public static final int GAMES_MENU_INDEX = 0;
public static final int CONNECT_MENU_INDEX = 1;
public static final int INSTRUCTIONS_MENU_INDEX = 2;
public static final int CREDITS_MENU_INDEX = 3;
public static final String HP_PREF_WEBSITE = "hpg_website";
public static final String HP_PREF_USER = "hpg_user";
public static final String HP_PREF_PASS = "hpg_pass";
public static final String HP_PREF_SENSOR_POSITION = "hpg_sensor_position";
public static final String HP_PREF_SENSOR_X_CALIB = "hpg_sensor_x_calib";
public static final String HP_PREF_SENSOR_Y_CALIB = "hpg_sensor_y_calib";
public static final String HP_PREF_SENSOR_Z_CALIB = "hpg_sensor_z_calib";
public static final String HP_PREF_SENSOR_IR_CALIB = "hpg_sensor_ir_calib";
public static int BTorWIFI = 0; // 0 - BLUETOOTH, 1 - WIFI
public static final String HP_SENSOR_SSID = "HYBRIDPLAY";
public static final String HP_SENSOR_PASSWD = "HYBRIDPLAY";
public static final String HP_SENSOR_IP = "192.168.1.99";
public static final int HP_SENSOR_PORT = 9999;
public static final String HP_BT_SENSOR_SSID = "hybridPLAY";
public static final String HP_SENSOR_MODE = "hpg_sensor_mode"; // single player, multi player
public static final String HP_GAMES_FLAG = "HYBRIDPLAY GAME SKELETON";
public static final String BASE_APP_DIR = "/hybridplayGameSkeleton";
public static final String sensorPossiblePositions[] ={"HORIZONTAL BUT. LEFT","HORIZONTAL BUT. RIGHT","HORIZONTAL INVERTED BUT. LEFT","HORIZONTAL INVERTED BUT. RIGHT","VERTICAL BUT. DOWN","VERTICAL BUT. UP","VERTICAL INVERTED BUT. UP","VERTICAL INVERTED BUT. DOWN"};
public static String wifiIpAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
// Convert little-endian to big-endianif needed
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
}
byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
String ipAddressString;
try {
ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
} catch (UnknownHostException ex) {
Log.e("WIFIIP", "Unable to get host address.");
ipAddressString = null;
}
return ipAddressString;
}
public static void showToast(Context context,CharSequence toastMessage) {
Toast toast = Toast.makeText(context, toastMessage, Toast.LENGTH_LONG);
toast.getView().setBackgroundColor(context.getResources().getColor(R.color.hp_green));
toast.show();
}
public static Calendar getTime(int timezone){
// get the supported ids for the requested timezone
String[] ids = TimeZone.getAvailableIDs(timezone * 60 * 60 * 1000);
// if no ids were returned, something is wrong. get out.
if (ids.length == 0){
return null;
}
SimpleTimeZone pdt = new SimpleTimeZone(timezone * 60 * 60 * 1000, ids[0]);
// set up rules for daylight savings time
pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
// create a GregorianCalendar with the Pacific Daylight time zone
// and the current date and time
Calendar calendar = new GregorianCalendar(pdt);
Date trialTime = new Date();
calendar.setTime(trialTime);
return calendar;
}
@SuppressLint("SimpleDateFormat")
public static int timeZone(){
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("Z");
String localTime = date.format(currentLocalTime);
if(localTime.substring(0,1).equals("-")){
return Integer.parseInt(localTime.substring(2, 3))*-1;
}else{
return Integer.parseInt(localTime.substring(2, 3));
}
}
public static Bitmap getBitmapFromSDCard(Context context,String fileName) {
String _path = Environment.getExternalStorageDirectory()+fileName;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap myBitmap = BitmapFactory.decodeFile(_path, options);
if (options.outWidth != -1 && options.outHeight != -1) {
return myBitmap;
}else {
myBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.logo);
return myBitmap;
}
}
public static void getBitmapFromURL(String fileUrl,final ImageView imgView) {
AsyncTask<String, Object, String> task = new AsyncTask<String, Object, String>() {
@Override
protected String doInBackground(String... params) {
URL myFileUrl = null;
try {
myFileUrl = new URL(params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.setUseCaches(true);
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bmImg = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
imgView.setImageBitmap(bmImg);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return null;
}
};
task.execute(fileUrl);
}
public static void initHPStorage(){
new Thread(new Runnable(){
@Override
public void run() {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + BASE_APP_DIR);
if(!dir.exists()) {
dir.mkdirs();
Log.d("HPG STORAGE MKDIR","BASE DIR CREATED");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
public static void DownloadFromUrl(String DownloadUrl, String fileName) {
final String du = DownloadUrl;
final String fn = fileName;
new Thread(new Runnable(){
@Override
public void run() {
try {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File baseAppDir = new File (root.getAbsolutePath() + BASE_APP_DIR);
if(!baseAppDir.exists()) {
baseAppDir.mkdirs();
Log.d("TEST MKDIR","BASE DIR CREATED");
}
File dir = new File (root.getAbsolutePath());
if(!dir.exists()) {
dir.mkdirs();
Log.d("TEST MKDIR","GAMES IMG DIR CREATED");
}
// Create a URL for the desired page
URL url = new URL(du); //you can write here any link
File file = new File(dir, fn);
if(!file.exists()){
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fn);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
public static boolean isInternetOn(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public static void setWIFI(Context context, boolean state){
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(state);
}
public static boolean setBluetooth(boolean enable) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
boolean isEnabled = bluetoothAdapter.isEnabled();
if (enable && !isEnabled) {
return bluetoothAdapter.enable();
}
else if(!enable && isEnabled) {
return bluetoothAdapter.disable();
}
// No need to change bluetooth state
return true;
}
public static boolean initBTLE(Context activityContext){
// verify BLE device support
if (!activityContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
return false;
}
// Initializes a BLUETOOTH adapter. For API level 18 and above, get a
// reference to BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager) activityContext.getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter btAdapter = bluetoothManager.getAdapter();
// Checks if BLUETOOTH is supported on the device.
if (btAdapter == null) {
return false;
}
/*if (btAdapter.isEnabled()) {
btAdapter.disable();
}
btAdapter.enable();*/
return true;
}
public static boolean isTabletDevice(Context activityContext) {
// Verifies if the Generalized Size of the device is XLARGE to be
// considered a Tablet
boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_XLARGE);
// If XLarge, checks if the Generalized Density is at least MDPI
// (160dpi)
if (xlarge) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
// DENSITY_TV=213, DENSITY_XHIGH=320
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
// Yes, this is a tablet!
return true;
}
}
// No, this is not a tablet!
return false;
}
}
| mit |
syroegkin/mikora.eu | src/browser/home/HomePage.react.js | 1027 | import Component from 'react-pure-render/component';
import React from 'react';
import Helmet from 'react-helmet';
import Header from '../ui/Header.react';
import Menu from '../ui/menu/Menu.react';
import { defineMessages, FormattedMessage } from 'react-intl';
const _messages = defineMessages({
headerTitle: {
defaultMessage: 'Control Panel',
id: 'control.home.header.title'
},
title: {
defaultMessage: 'Dashboard',
id: 'control.home.title'
},
control: {
defaultMessage: 'Control',
id: 'control.home.tmp.title'
}
});
export default class HomePage extends Component {
render() {
return (
<div className="home-page">
<FormattedMessage {..._messages.headerTitle} >
{headerTitle => <Helmet title={headerTitle} />}
</FormattedMessage>
<FormattedMessage {..._messages.title} >
{title => <Header title={title} />}
</FormattedMessage>
<Menu />
<FormattedMessage {..._messages.control} />
</div>
);
}
}
| mit |
oleg-kiviljov/shopster | config/deploy.rb | 985 | # config valid only for Capistrano 3.1
lock '3.2.1'
# Define the name of the application
set :application, 'shopster'
# Define where can Capistrano access the source repository
set :repo_url, 'git@bitbucket.org:firenze/shopster.git'
# Define where to put your application code
set :deploy_to, "/home/deployer/apps/shopster"
set :deploy_via, :remote_cache
# Stages
set :stages, ["production"]
# Options
set :pty, true
set :format, :pretty
set :use_sudo, false
namespace :deploy do
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
# Your restart mechanism here, for example:
execute :touch, release_path.join('tmp/restart.txt')
end
end
after :publishing, :restart
after :restart, :clear_cache do
on roles(:web), in: :groups, limit: 3, wait: 10 do
# Here we can do anything such as:
# within release_path do
# execute :rake, 'cache:clear'
# end
end
end
end
| mit |
Quilt4/Quilt4Net | Quilt4Net.Sample.Console/Commands/Session/SessionCommands.cs | 525 | using Quilt4Net.Interfaces;
using Tharga.Toolkit.Console.Commands.Base;
namespace Quilt4Net.Sample.Console.Commands.Session
{
internal class SessionCommands : ContainerCommandBase
{
public SessionCommands(ISessionHandler sessionHandler)
: base("Session")
{
RegisterCommand(new ListSessionsCommand(sessionHandler));
RegisterCommand(new RegisterSessionCommand(sessionHandler));
RegisterCommand(new EndSessionCommand(sessionHandler));
}
}
} | mit |
ztepsic/myrdngs | application/config/user_agents.php | 5836 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| USER AGENT TYPES
| -------------------------------------------------------------------
| This file contains four arrays of user agent data. It is used by the
| User Agent Class to help identify browser, platform, robot, and
| mobile device data. The array keys are used to identify the device
| and the array values are used to set the actual name of the item.
|
*/
$platforms = array (
'windows nt 6.0' => 'Windows Longhorn',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.0' => 'Windows 2000',
'windows nt 5.1' => 'Windows XP',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows' => 'Unknown Windows OS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS'
);
// The order of this array should NOT be changed. Many browsers return
// multiple browser types so we want to identify the sub-type first.
$browsers = array(
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Chrome' => 'Chrome',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse',
'Windows-Media-Player' => 'Windows Media Player',
'NSPlayer' => 'Windows Media Player NSPlayer',
'QuickTime' => 'QuickTime'
);
$mobiles = array(
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => "Motorola",
'nokia' => "Nokia",
'palm' => "Palm",
'iphone' => "Apple iPhone",
'ipod' => "Apple iPod Touch",
'sony' => "Sony Ericsson",
'ericsson' => "Sony Ericsson",
'blackberry' => "BlackBerry",
'cocoon' => "O2 Cocoon",
'blazer' => "Treo",
'lg' => "LG",
'amoi' => "Amoi",
'xda' => "XDA",
'mda' => "MDA",
'vario' => "Vario",
'htc' => "HTC",
'samsung' => "Samsung",
'sharp' => "Sharp",
'sie-' => "Siemens",
'alcatel' => "Alcatel",
'benq' => "BenQ",
'ipaq' => "HP iPaq",
'mot-' => "Motorola",
'playstation portable' => "PlayStation Portable",
'hiptop' => "Danger Hiptop",
'nec-' => "NEC",
'panasonic' => "Panasonic",
'philips' => "Philips",
'sagem' => "Sagem",
'sanyo' => "Sanyo",
'spv' => "SPV",
'zte' => "ZTE",
'sendo' => "Sendo",
// Operating Systems
'symbian' => "Symbian",
'SymbianOS' => "SymbianOS",
'elaine' => "Palm",
'palm' => "Palm",
'series60' => "Symbian S60",
'windows ce' => "Windows CE",
// Browsers
'obigo' => "Obigo",
'netfront' => "Netfront Browser",
'openwave' => "Openwave Browser",
'mobilexplorer' => "Mobile Explorer",
'operamini' => "Opera Mini",
'opera mini' => "Opera Mini",
// Other
'digital paths' => "Digital Paths",
'avantgo' => "AvantGo",
'xiino' => "Xiino",
'novarra' => "Novarra Transcoder",
'vodafone' => "Vodafone",
'docomo' => "NTT DoCoMo",
'o2' => "O2",
// Fallback
'mobile' => "Generic Mobile",
'wireless' => "Generic Mobile",
'j2me' => "Generic Mobile",
'midp' => "Generic Mobile",
'cldc' => "Generic Mobile",
'up.link' => "Generic Mobile",
'up.browser' => "Generic Mobile",
'smartphone' => "Generic Mobile",
'cellphone' => "Generic Mobile"
);
// There are hundreds of bots but these are the most common.
$robots = array(
'googlebot' => 'Googlebot',
'msnbot' => 'MSNBot',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'askjeeves' => 'AskJeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos',
'mediapartners-google' => 'Mediapartners-Google',
'twiceler' => 'Twiceler-0.9',
'pogodak' => 'Pogodak.hr'
);
/* End of file user_agents.php */
/* Location: ./system/application/config/user_agents.php */ | mit |
rsanchezsaez/gltut-glfw | gltut/gltut 04b/Scene.cpp | 5131 | //
// Scene.cpp
// gltut-glfw
//
// Copyright (C) 2010-2012 by Jason L. McKesson
// Xcode and glfw adaptation: Ricardo Sánchez-Sáez.
//
// This file is licensed under the MIT License.
//
#include "Scene.h"
#include <string>
#include <vector>
#include "debug.h"
#include "glhelpers.h"
#include "GLFW/glfw3.h"
#include <math.h>
const float vertexData[] = {
0.25f, 0.25f, -1.25f, 1.0f,
0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, 0.25f, -1.25f, 1.0f,
0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, 0.25f, -1.25f, 1.0f,
0.25f, 0.25f, -2.75f, 1.0f,
-0.25f, 0.25f, -2.75f, 1.0f,
0.25f, -0.25f, -2.75f, 1.0f,
0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, 0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, 0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, 0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, 0.25f, -2.75f, 1.0f,
0.25f, 0.25f, -1.25f, 1.0f,
0.25f, -0.25f, -2.75f, 1.0f,
0.25f, -0.25f, -1.25f, 1.0f,
0.25f, 0.25f, -1.25f, 1.0f,
0.25f, 0.25f, -2.75f, 1.0f,
0.25f, -0.25f, -2.75f, 1.0f,
0.25f, 0.25f, -2.75f, 1.0f,
0.25f, 0.25f, -1.25f, 1.0f,
-0.25f, 0.25f, -1.25f, 1.0f,
0.25f, 0.25f, -2.75f, 1.0f,
-0.25f, 0.25f, -1.25f, 1.0f,
-0.25f, 0.25f, -2.75f, 1.0f,
0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
0.25f, -0.25f, -1.25f, 1.0f,
0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
};
GLuint offsetUniform;
GLuint frustumScaleUniform;
GLuint zNearUniform, zFarUniform;
Scene::Scene()
{
}
void Scene::init()
{
_shaderProgram = createShaderProgramWithFilenames("ManualPerspective.vert", "StandardColors.frag");
glUseProgram(_shaderProgram);
printOpenGLError();
// Initialize Vertex Buffer
glGenBuffers(1, &_vertexBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
printOpenGLError();
// Vertex array object
glGenVertexArrays(1, &_vertexArrayObject);
glBindVertexArray(_vertexArrayObject);
printOpenGLError();
// Enable cull facing
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CW);
// Uniforms
offsetUniform = glGetUniformLocation(_shaderProgram, "offset");
frustumScaleUniform = glGetUniformLocation(_shaderProgram, "frustumScale");
zNearUniform = glGetUniformLocation(_shaderProgram, "zNear");
zFarUniform = glGetUniformLocation(_shaderProgram, "zFar");
glUniform1f(frustumScaleUniform, 1.0f);
glUniform1f(zNearUniform, 1.0f);
glUniform1f(zFarUniform, 3.0f);
}
Scene::~Scene()
{
glDeleteProgram(_shaderProgram);
glDeleteBuffers(1, &_vertexBufferObject);
printOpenGLError();
}
const float aspectRatio = 1.0f;
void Scene::reshape(int width, int height)
{
int finalWidth = width;
int finalHeight = height;
int derivedHeight = width * (1/aspectRatio);
int derivedWidth = height * aspectRatio;
if (derivedHeight <= height)
{
finalHeight = derivedHeight;
}
else if (derivedWidth <= width)
{
finalWidth = derivedWidth;
}
glViewport( (width-finalWidth) / 2,
(height-finalHeight) / 2,
finalWidth,
finalHeight);
this->draw();
}
void Scene::draw()
{
glClearColor(0.2f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUniform2f(offsetUniform, 0.5f, 0.5f);
size_t colorData = sizeof(vertexData) / 2;
glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, (void*)colorData);
printOpenGLError();
glDrawArrays(GL_TRIANGLES, 0, 36);
printOpenGLError();
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
printOpenGLError();
}
void Scene::keyStateChanged(int key, int action)
{
} | mit |
korylprince/go-ad-auth | passwd_test.go | 4560 | package auth
import (
"fmt"
"math/rand"
"strings"
"testing"
"time"
)
func TestConnModifyDNPassword(t *testing.T) {
if testConfig.Server == "" {
t.Skip("ADTEST_SERVER not set")
return
}
if testConfig.BindUPN == "" || testConfig.BindPass == "" {
t.Skip("ADTEST_BIND_UPN or ADTEST_BIND_PASS not set")
return
}
if testConfig.BaseDN == "" {
t.Skip("ADTEST_BASEDN not set")
return
}
config := &Config{Server: testConfig.Server, Port: testConfig.Port, Security: testConfig.BindSecurity, BaseDN: testConfig.BaseDN}
conn, err := config.Connect()
if err != nil {
t.Fatal("Error connecting to server:", err)
}
defer conn.Conn.Close()
status, err := conn.Bind(testConfig.BindUPN, testConfig.BindPass)
if err != nil {
t.Fatal("Error binding to server:", err)
}
if !status {
t.Fatal("Error binding to server: invalid credentials")
}
if err = conn.ModifyDNPassword("CN=Invalid User,"+testConfig.BaseDN, "TestPassword123!"); !strings.Contains(err.Error(), "Password error") {
t.Error("Invalid DN: Expected password error but got:", err)
}
if testConfig.PasswordUPN == "" {
t.Skip("ADTEST_PASSWORD_UPN not set")
return
}
dn, err := conn.GetDN("userPrincipalName", testConfig.PasswordUPN)
if err != nil {
t.Fatal("Error finding test user:", err)
}
var long = "A123!aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
if err = conn.ModifyDNPassword(dn, long); !strings.Contains(err.Error(), "Password error") {
t.Fatal("Long password: Expected password error but got:", err)
}
//set password 1
if err = conn.ModifyDNPassword(dn, "Random123!"); err != nil {
t.Fatal("ModifyDNPassword 1: Expected err to be nil but got:", err)
}
//authenticate 1
status, err = Authenticate(config, testConfig.PasswordUPN, "Random123!")
if err != nil {
t.Fatal("Authenticate 1: Expected err to be nil but got:", err)
}
if !status {
t.Fatal("Authenticate 1: Expected status to be true")
}
//set password 2
if err = conn.ModifyDNPassword(dn, "Random321!"); err != nil {
t.Fatal("ModifyDNPassword 2: Expected err to be nil but got:", err)
}
//authenticate 2
status, err = Authenticate(config, testConfig.PasswordUPN, "Random321!")
if err != nil {
t.Fatal("Authenticate 2: Expected err to be nil but got:", err)
}
if !status {
t.Fatal("Authenticate 2: Expected status to be true")
}
}
func TestUpdatePassword(t *testing.T) {
if testConfig.Server == "" {
t.Skip("ADTEST_SERVER not set")
return
}
if testConfig.BindUPN == "" || testConfig.BindPass == "" {
t.Skip("ADTEST_BIND_UPN or ADTEST_BIND_PASS not set")
return
}
if testConfig.BaseDN == "" {
t.Skip("ADTEST_BASEDN not set")
return
}
if testConfig.PasswordUPN == "" {
t.Skip("ADTEST_PASSWORD_UPN not set")
return
}
config := &Config{Server: testConfig.Server, Port: testConfig.Port, Security: testConfig.BindSecurity, BaseDN: testConfig.BaseDN}
conn, err := config.Connect()
if err != nil {
t.Fatal("Error connecting to server:", err)
}
defer conn.Conn.Close()
status, err := conn.Bind(testConfig.BindUPN, testConfig.BindPass)
if err != nil {
t.Fatal("Error binding to server:", err)
}
if !status {
t.Fatal("Error binding to server: invalid credentials")
}
dn, err := conn.GetDN("userPrincipalName", testConfig.PasswordUPN)
if err != nil {
t.Fatal("Error finding test user:", err)
}
if err = conn.ModifyDNPassword(dn, "Random456!"); err != nil {
t.Fatal("ModifyDNPassword: Expected err to be nil but got:", err)
}
if err = UpdatePassword(config, testConfig.PasswordUPN, "invalid password", "Random654!"); !strings.Contains(err.Error(), "Password error") {
t.Fatal("Invalid password: Expected password error but got:", err)
}
//choose random password to get around AD password history
rand.Seed(time.Now().Unix())
randPass := fmt.Sprintf("Random%d!", rand.Int31())
if err = UpdatePassword(config, testConfig.PasswordUPN, "Random456!", randPass); err != nil {
t.Fatal("Valid password: Expected err to be nil but got:", err)
}
status, err = Authenticate(config, testConfig.PasswordUPN, randPass)
if err != nil {
t.Fatal("Authenticate: Expected err to be nil but got:", err)
}
if !status {
t.Fatal("Authenticate: Expected status to be true")
}
}
| mit |
OdaShinsuke/sample | swagger_modelname/src/main/java/sample/swagger_modelname/linkerror/LinkErrorBean.java | 256 | package sample.swagger_modelname.linkerror;
import com.wordnik.swagger.annotations.ApiModel;
@ApiModel(description="LinkErrorBean:定義が残るが、プロパティのリンクで問題が出る")
public class LinkErrorBean {
public String field1;
}
| mit |
Lambda-3/Stargraph | stargraph-core/src/main/java/net/stargraph/core/query/Rules.java | 8155 | package net.stargraph.core.query;
/*-
* ==========================License-Start=============================
* stargraph-core
* --------------------------------------------------------------------
* Copyright (C) 2017 Lambda^3
* --------------------------------------------------------------------
* 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.
* ==========================License-End===============================
*/
import com.typesafe.config.Config;
import com.typesafe.config.ConfigObject;
import com.typesafe.config.ConfigValue;
import net.stargraph.query.Language;
import net.stargraph.UnsupportedLanguageException;
import net.stargraph.core.query.nli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public final class Rules {
private Logger logger = LoggerFactory.getLogger(getClass());
private Marker marker = MarkerFactory.getMarker("query");
private Map<Language, List<DataModelTypePattern>> dataModelTypePatterns;
private Map<Language, List<QueryPlanPatterns>> queryPlanPatterns;
private Map<Language, List<Pattern>> stopPatterns;
private Map<Language, List<QueryTypePatterns>> queryTypePatterns;
public Rules(Config config) {
logger.info(marker, "Loading Rules.");
this.dataModelTypePatterns = loadDataModelTypePatterns(Objects.requireNonNull(config));
this.queryPlanPatterns = loadQueryPlanPatterns(Objects.requireNonNull(config));
this.stopPatterns = loadStopPatterns(config);
this.queryTypePatterns = loadQueryTypePatterns(config);
}
public List<DataModelTypePattern> getDataModelTypeRules(Language language) {
if (dataModelTypePatterns.containsKey(language)) {
return dataModelTypePatterns.get(language);
}
throw new UnsupportedLanguageException(language);
}
public List<QueryPlanPatterns> getQueryPlanRules(Language language) {
if (queryPlanPatterns.containsKey(language)) {
return queryPlanPatterns.get(language);
}
throw new UnsupportedLanguageException(language);
}
public List<Pattern> getStopRules(Language language) {
if (stopPatterns.containsKey(language)) {
return stopPatterns.get(language);
}
throw new UnsupportedLanguageException(language);
}
public List<QueryTypePatterns> getQueryTypeRules(Language language) {
if (queryTypePatterns.containsKey(language)) {
return queryTypePatterns.get(language);
}
throw new UnsupportedLanguageException(language);
}
private Map<Language, List<DataModelTypePattern>> loadDataModelTypePatterns(Config config) {
Map<Language, List<DataModelTypePattern>> rulesByLang = new HashMap<>();
ConfigObject configObject = config.getObject("rules.syntatic-pattern");
configObject.keySet().forEach(strLang -> {
Language language = Language.valueOf(strLang.toUpperCase());
rulesByLang.compute(language, (l, r) -> {
List<DataModelTypePattern> rules = new ArrayList<>();
List<? extends Config> patternCfg = configObject.toConfig().getConfigList(strLang);
for (Config cfg : patternCfg) {
Map.Entry<String, ConfigValue> entry = cfg.entrySet().stream().findFirst().orElse(null);
String modelStr = entry.getKey();
@SuppressWarnings("unchecked")
List<String> patternList = (List<String>) entry.getValue().unwrapped();
rules.addAll(patternList.stream()
.map(p -> new DataModelTypePattern(p, DataModelType.valueOf(modelStr)))
.collect(Collectors.toList()));
}
logger.info(marker, "Loaded {} Data Model Type patterns for '{}'", rules.size(), l);
return rules;
});
});
return rulesByLang;
}
@SuppressWarnings("unchecked")
private Map<Language, List<QueryPlanPatterns>> loadQueryPlanPatterns(Config config) {
Map<Language, List<QueryPlanPatterns>> rulesByLang = new LinkedHashMap<>();
ConfigObject configObject = config.getObject("rules.planner-pattern");
configObject.keySet().forEach(strLang -> {
Language language = Language.valueOf(strLang.toUpperCase());
List<QueryPlanPatterns> plans = new ArrayList<>();
List<? extends ConfigObject> innerCfg = configObject.toConfig().getObjectList(strLang);
innerCfg.forEach(e -> {
Map<String, Object> plan = e.unwrapped();
String planId = plan.keySet().toArray(new String[1])[0];
List<String> triplePatterns = (List<String>)plan.values().toArray()[0];
plans.add(new QueryPlanPatterns(planId,
triplePatterns.stream().map(TriplePattern::new).collect(Collectors.toList())));
});
rulesByLang.put(language, plans);
});
return rulesByLang;
}
private Map<Language, List<Pattern>> loadStopPatterns(Config config) {
Map<Language, List<Pattern>> rulesByLang = new LinkedHashMap<>();
ConfigObject configObject = config.getObject("rules.stop-pattern");
configObject.keySet().forEach(strLang -> {
Language language = Language.valueOf(strLang.toUpperCase());
List<String> patternStr = configObject.toConfig().getStringList(strLang);
rulesByLang.compute(language,
(lang, pattern) -> patternStr.stream().map(Pattern::compile).collect(Collectors.toList()));
logger.info(marker, "Loaded {} Stop patterns for '{}'", rulesByLang.get(language).size(), language);
});
return rulesByLang;
}
private Map<Language, List<QueryTypePatterns>> loadQueryTypePatterns(Config config) {
Map<Language, List<QueryTypePatterns>> rulesByLang = new HashMap<>();
ConfigObject configObject = config.getObject("rules.query-pattern");
configObject.keySet().forEach(strLang -> {
Language language = Language.valueOf(strLang.toUpperCase());
ConfigObject innerCfg = configObject.toConfig().getObject(strLang);
List<QueryTypePatterns> patterns = new ArrayList<>();
rulesByLang.compute(language, (l, q) -> {
innerCfg.keySet().forEach(key -> {
QueryType queryType = QueryType.valueOf(key);
List<String> patternStr = innerCfg.toConfig().getStringList(key);
patterns.add(new QueryTypePatterns(queryType,
patternStr.stream().map(Pattern::compile).collect(Collectors.toList())));
});
logger.info(marker, "Loaded {} Query Type patterns for '{}'", patterns.size(), language);
return patterns;
});
});
return rulesByLang;
}
}
| mit |
kaguillera/newspipeline | node_modules/inky/test/inky.js | 2258 | var Inky = require('../lib/inky');
var parse = require('..');
var cheerio = require('cheerio');
var assert = require('assert');
var fs = require('fs');
var rimraf = require('rimraf');
var vfs = require('vinyl-fs');
var exec = require('child_process').exec;
var compare = require('./lib/compare');
describe('Inky', () => {
it('can take in settings in the constructor', () => {
var config = {
components: { column: 'col' },
columnCount: 16
}
var inky = new Inky(config);
assert.equal(inky.components.column, 'col', 'Sets custom component tags');
assert.equal(inky.columnCount, 16, 'Sets a custom column count');
});
it('should have an array of component tags', () => {
var inky = new Inky();
assert(Array.isArray(inky.componentTags), 'Inky.zftags is an array');
});
it(`doesn't choke on inline elements`, () => {
var input = '<container>This is a link to <a href="#">ZURB.com</a>.</container>';
var expected = `
<table class="container">
<tbody>
<tr>
<td>This is a link to <a href="#">ZURB.com</a>.</td>
</tr>
</tbody>
</table>
`;
compare(input, expected);
});
it(`doesn't choke on special characters`, () => {
var input = '<container>This is a link tö <a href="#">ZURB.com</a>.</container>';
var expected = `
<table class="container">
<tbody>
<tr>
<td>This is a link tö <a href="#">ZURB.com</a>.</td>
</tr>
</tbody>
</table>
`;
compare(input, expected);
});
});
describe('Inky wrappers', () => {
const INPUT = 'test/fixtures/test.html';
const OUTPUT = 'test/fixtures/_build';
const OUTFILE = 'test/fixtures/_build/test.html';
afterEach(done => {
rimraf(OUTPUT, done);
});
it('can process a glob of files', done => {
parse({
src: INPUT,
dest: OUTPUT
}, () => {
assert(fs.existsSync(OUTFILE), 'Output file exists');
done();
});
});
it('can process a Gulp stream of files', done => {
vfs.src(INPUT)
.pipe(parse())
.pipe(vfs.dest(OUTPUT))
.on('finish', () => {
assert(fs.existsSync(OUTFILE), 'Output file exists');
done();
});
});
});
| mit |
rodionovd/cuckoo-osx-analyzer | tests/test_probesgenerator.py | 7437 | #!/usr/bin/env python
# Copyright (C) 2015 Dmitry Rodionov
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
import filecmp
import unittest
from os import remove, path
from common import TESTS_DIR
from difflib import unified_diff
from subprocess import check_call
from analyzer.darwin.lib.dtrace.autoprobes import generate_probes
from analyzer.darwin.lib.dtrace.autoprobes import dereference_type
from analyzer.darwin.lib.dtrace.autoprobes import serialize_atomic_type
from analyzer.darwin.lib.dtrace.autoprobes import serialize_struct_type
from analyzer.darwin.lib.dtrace.autoprobes import serialize_type_with_template
SIGNATURES_FILE = path.join(TESTS_DIR, "..", "config", "signatures.yml")
class ProbesGeneratorTestCase(unittest.TestCase):
def result_file(self):
return path.join(TESTS_DIR, "assets", "probes", self._testMethodName + ".d")
def reference_file(self):
return path.join(TESTS_DIR, "assets", "probes", self._testMethodName + ".d.reference")
def tearDown(self):
if path.isfile(self.result_file()):
remove(self.result_file())
def assertEmptyDiff(self, diff):
if len(diff) > 0:
self.fail("Diff is not empty:\n" + diff)
def assertDtraceCompiles(self, script_file):
# Define the required stuff (see apicalls.d)
decl = """self int64_t arguments_stack[unsigned long, string];self deeplevel;dtrace:::BEGIN{self->deeplevel = 0;self->arg0 = (int64_t)0;self->arg1 = (int64_t)0;self->arg2 = (int64_t)0;self->arg3 = (int64_t)0;self->arg4 = (int64_t)0;self->arg5 = (int64_t)0;self->arg6 = (int64_t)0;self->arg7 = (int64_t)0;self->arg8 = (int64_t)0;self->arg9 = (int64_t)0;self->arg10 = (int64_t)0;self->arg11 = (int64_t)0;}"""
with open(script_file, "r+") as outfile:
contents = outfile.read()
outfile.seek(0, 0)
outfile.write(decl + "\n" + contents)
check_call(["sudo", "dtrace", "-e", "-C", "-s", script_file, "-c", "date"])
# UNIT TESTS
def test_probes_dereference_value_type(self):
# given
type = "scalar_t"
# when
output = dereference_type(type)
# then
self.assertEqual("scalar_t", output)
def test_probes_dereference_reference_type(self):
# given
type = "foo *"
# when
output = dereference_type(type)
# then
self.assertEqual("foo", output)
def test_probes_dereference_reference_type_with_random_spaces(self):
# given
type = "foo * "
# when
output = dereference_type(type)
# then
self.assertEqual("foo", output)
def test_probes_dereference_types_that_must_not_be_dereferenced(self):
# given
type_string = "char *"
type_pointer = "void *"
# when
output_string = dereference_type(type_string)
output_pointer = dereference_type(type_pointer)
# then
self.assertEqual("char *", output_string)
self.assertEqual("void *", output_pointer)
def test_probes_atomic_type_serialization(self):
# given
type = "float"
accessor = "self->arg0"
# when
output = serialize_atomic_type(type, type, accessor)
# then
self.assertEqual("(float)(self->arg0)", output)
def test_probes_atomic_pointer_type_serialization(self):
# given
type = "int *"
accessor = "self->arg0"
# when
output = serialize_atomic_type(type, "int", accessor)
# then
self.assertEqual(
"!!(self->arg0) ? (int)0 : *(int *)copyin((uint64_t)self->arg0, sizeof(int))",
output
)
def test_probes_struct_type_serialization(self):
# given
type = "foo_t"
accessor = "self->arg0"
types = {
"float": {
"printf_specifier": "%f",
"native": True
},
"char *": {
"printf_specifier": '"%S"',
"native": True,
"template":
'!!(${ARG}) ? copyinstr((uint64_t)${ARG}) : "<NULL>"'
},
"foo_t": {
"native": False,
"struct": {
"value_f": "float",
"value_str": "char *"
}
}
}
# when
output = serialize_struct_type(type, accessor, types)
# then
self.assertEqual(
'(float)(((foo_t)(self->arg0)).value_f), !!(((foo_t)(self->arg0)).value_str) ? copyinstr((uint64_t)((foo_t)(self->arg0)).value_str) : "<NULL>"',
output
)
def test_probes_struct_pointer_type_serialization(self):
# given
type = "foo_t *"
accessor = "self->arg0"
types = {
"float": {
"printf_specifier": "%f",
"native": True
},
"int": {
"printf_specifier": "%f",
"native": True
},
"foo_t": {
"native": False,
"struct": {
"value_f": "float",
"value_int": "int *"
}
}
}
# when
output = serialize_struct_type(type, accessor, types)
# then
self.assertEqual(
"!!(((foo_t *)(self->arg0))->value_int) ? (int)0 : *(int *)copyin((uint64_t)((foo_t *)(self->arg0))->value_int, sizeof(int)), (float)(((foo_t *)(self->arg0))->value_f)",
output
)
def test_probes_template_type_serialization(self):
# given
type = "string"
accessor = "self->arg0"
types = {
"string": {
"printf_specifier": '"%S"',
"native": False,
"template": '!!(${ARG}) ? copyinstr((uint64_t)${ARG}) : "<NULL>"'
}
}
# when
output = serialize_type_with_template(type, accessor, types)
# then
self.assertEqual(
'!!(self->arg0) ? copyinstr((uint64_t)self->arg0) : "<NULL>"',
output
)
def test_probes_integration(self):
# given
source = [{
"api": "system",
"is_success_condition": "retval == 0",
"args": [
{"name": "command", "type": "char *"}
],
"retval_type": "int",
"category": "foobar"
},
{
"api": "socket",
"is_success_condition": "retval > 0",
"args": [
{"name": "domain", "type": "int"},
{"name": "type", "type": "double"},
{"name": "protocol", "type": "test_t *"}
],
"retval_type": "size_t",
"category": "network"
}]
destination = self.result_file()
# when
generate_probes(source, destination)
# then
self.assertEmptyDiff(file_diff(self.reference_file(), destination))
self.assertDtraceCompiles(destination)
def file_diff(a, b):
with open(a, 'r') as astream, open(b, 'r') as bstream:
return "".join(unified_diff(
astream.readlines(),
bstream.readlines(),
path.basename(a), path.basename(b),
n=0
))
| mit |
GCModeller-Cloud/php-dotnet | test/Console/httpSocket.php | 288 | <?php
include __DIR__ . "../../../package.php";
dotnet::AutoLoad();
Imports("php.http");
class services {
public function hello($request) {
$echo = $request["echo"];
return "message: hello {$echo}!";
}
}
$http = new httpSocket("127.0.0.1", 85);
$http->Run(new services()); | mit |
worksap-ate/vity | html/js/core/utils.js | 793 |
define([], function() {
'use strict';
var uuid4 = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};
var perror = function(err) {
console.error(err);
};
var readOnlyProperty = function() {
var that = this;
return function() {
console.error(that, 'is read only');
throw 'attemp to set a read-only property : ' + that;
if (console.trace) {
console.trace();
}
}
};
var getTimeStamp = function() {
return (new Date()).getTime();
};
return {
uuid4: uuid4,
readOnlyProperty: readOnlyProperty,
getTimeStamp: getTimeStamp,
perror: perror
};
// end of define
});
| mit |
kpboyle1/devtreks | src/DevTreks.Data/AppHelpers/BudgetsModelHelper.cs | 109371 | using DevTreks.Data.DataAccess;
using DevTreks.Data.EditHelpers;
using DevTreks.Models;
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace DevTreks.Data.AppHelpers
{
/// <summary>
///Purpose: Entity Framework BudgetsModelHelper support class
///Author: www.devtreks.org
///Date: 2016, March
///References: www.devtreks.org/helptreks/linkedviews/help/linkedview/HelpFile/148
/// </summary>
public class BudgetsModelHelper
{
public BudgetsModelHelper(DevTreksContext dataContext, DevTreks.Data.ContentURI dtoURI)
{
this._dataContext = dataContext;
_dtoContentURI = dtoURI;
}
private DevTreksContext _dataContext { get; set; }
private DevTreks.Data.ContentURI _dtoContentURI { get; set; }
private string _parentName { get; set; }
private int _parentId { get; set; }
public async Task<bool> SetURIBudgets(ContentURI uri, bool saveInFileSystemContent)
{
bool bHasSet = false;
int iStartRow = uri.URIDataManager.StartRow;
int iPageSize = uri.URIDataManager.PageSize;
if (uri.URINodeName == Agreement.AGREEMENT_BASE_TYPES.servicebase.ToString())
{
var s = await _dataContext.Service.SingleOrDefaultAsync(x => x.PKId == uri.URIId);
if (s != null)
{
// count the budget packs without loading them
var qry = _dataContext
.BudgetSystem
.Include(t => t.LinkedViewToBudgetSystem)
.Where(a => a.ServiceId == uri.URIId)
.OrderBy(m => m.Name)
.Skip(iStartRow)
.Take(iPageSize);
if (qry != null)
{
s.BudgetSystem = await qry.ToAsyncEnumerable().ToList();
if (s.BudgetSystem != null)
{
uri.URIDataManager.RowCount =
_dataContext
.BudgetSystem
.Where(a => a.ServiceId == uri.URIId)
.Count();
}
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL1");
}
uri.URIModels.Service = s;
//need the budgettype collection set too
bHasSet = await SetURIBudgetSystemType(s, uri);
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL");
}
}
else if (uri.URINodeName == Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var rc = await _dataContext.BudgetSystem.SingleOrDefaultAsync(x => x.PKId == uri.URIId);
if (rc != null)
{
var qry = _dataContext
.BudgetSystemToEnterprise
.Include(t => t.LinkedViewToBudgetSystemToEnterprise)
.Where(a => a.BudgetSystem.PKId == uri.URIId)
.OrderBy(m => m.Name)
.Skip(iStartRow)
.Take(iPageSize);
if (qry != null)
{
rc.BudgetSystemToEnterprise = await qry.ToAsyncEnumerable().ToList();
if (rc.BudgetSystemToEnterprise != null)
{
uri.URIDataManager.RowCount =
_dataContext
.BudgetSystemToEnterprise
.Where(a => a.BudgetSystem.PKId == uri.URIId)
.Count();
}
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL1");
}
uri.URIModels.BudgetSystem = rc;
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL");
}
}
else if (uri.URINodeName
== Economics1.BUDGET_TYPES.budget.ToString())
{
var rp = await _dataContext.BudgetSystemToEnterprise.SingleOrDefaultAsync(x => x.PKId == uri.URIId);
if (rp != null)
{
var qry = _dataContext
.BudgetSystemToTime
.Include(t => t.LinkedViewToBudgetSystemToTime)
.Where(a => a.BudgetSystemToEnterprise.PKId == uri.URIId)
.OrderBy(m => m.Date)
.Skip(iStartRow)
.Take(iPageSize);
if (qry != null)
{
rp.BudgetSystemToTime = await qry.ToAsyncEnumerable().ToList();
if (rp.BudgetSystemToTime != null)
{
uri.URIDataManager.RowCount =
_dataContext
.BudgetSystemToTime
.Where(a => a.BudgetSystemToEnterprise.PKId == uri.URIId)
.Count();
}
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL1");
}
uri.URIModels.BudgetSystemToEnterprise = rp;
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL");
}
}
else if (uri.URINodeName
== Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var rp = await _dataContext.BudgetSystemToTime.SingleOrDefaultAsync(x => x.PKId == uri.URIId);
if (rp != null)
{
// count the outcomes first
var qry = _dataContext
.BudgetSystemToOutcome
.Include(t => t.Outcome)
.ThenInclude(t => t.LinkedViewToOutcome)
.Where(a => a.BudgetSystemToTime.PKId == uri.URIId)
.OrderBy(m => m.Date)
.Skip(iStartRow)
.Take(iPageSize);
if (qry != null)
{
rp.BudgetSystemToOutcome = await qry.ToAsyncEnumerable().ToList();
if (rp.BudgetSystemToOutcome != null)
{
uri.URIDataManager.RowCount =
_dataContext
.BudgetSystemToOutcome
.Where(a => a.BudgetSystemToTime.PKId == uri.URIId)
.Count();
}
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL1");
}
// add the operations to the total
var qry2 = _dataContext
.BudgetSystemToOperation
.Include(t => t.Operation)
.ThenInclude(t => t.LinkedViewToOperation)
.Where(a => a.BudgetSystemToTime.PKId == uri.URIId)
.OrderBy(m => m.Date)
.Skip(iStartRow)
.Take(iPageSize);
if (qry2 != null)
{
rp.BudgetSystemToOperation = await qry2.ToAsyncEnumerable().ToList();
if (rp.BudgetSystemToOperation != null)
{
uri.URIDataManager.RowCount +=
_dataContext
.BudgetSystemToOperation
.Where(a => a.BudgetSystemToTime.PKId == uri.URIId)
.Count();
}
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL1");
}
//set the parent object
uri.URIModels.BudgetSystemToTime = rp;
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL");
}
}
else if (uri.URINodeName
== Economics1.BUDGET_TYPES.budgetoperation.ToString())
{
var rp = await _dataContext.BudgetSystemToOperation.SingleOrDefaultAsync(x => x.PKId == uri.URIId);
if (rp != null)
{
var qry = _dataContext
.BudgetSystemToInput
.Include(t => t.InputSeries)
.ThenInclude(t => t.LinkedViewToInputSeries)
.Where(a => a.BudgetSystemToOperation.PKId == uri.URIId)
.OrderBy(m => m.InputDate)
.Skip(iStartRow)
.Take(iPageSize);
if (qry != null)
{
rp.BudgetSystemToInput = await qry.ToAsyncEnumerable().ToList();
if (rp.BudgetSystemToInput != null)
{
uri.URIDataManager.RowCount =
_dataContext
.BudgetSystemToInput
.Where(a => a.BudgetSystemToOperation.PKId == uri.URIId)
.Count();
}
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL1");
}
//set the parent object
uri.URIModels.BudgetSystemToOperation = rp;
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL");
}
}
else if (uri.URINodeName
== Economics1.BUDGET_TYPES.budgetinput.ToString())
{
var qry = _dataContext
.BudgetSystemToInput
.Include(t => t.InputSeries)
.Include(t => t.InputSeries.LinkedViewToInputSeries)
.Where(r => r.PKId == uri.URIId);
if (qry != null)
{
uri.URIModels.BudgetSystemToInput = await qry.FirstOrDefaultAsync();
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL1");
}
}
else if (uri.URINodeName
== Economics1.BUDGET_TYPES.budgetoutcome.ToString())
{
var rp = await _dataContext.BudgetSystemToOutcome.SingleOrDefaultAsync(x => x.PKId == uri.URIId);
if (rp != null)
{
var qry = _dataContext
.BudgetSystemToOutput
.Include(t => t.OutputSeries)
.ThenInclude(t => t.LinkedViewToOutputSeries)
.Where(a => a.BudgetSystemToOutcome.PKId == uri.URIId)
.OrderBy(m => m.OutputDate)
.Skip(iStartRow)
.Take(iPageSize);
if (qry != null)
{
rp.BudgetSystemToOutput = await qry.ToAsyncEnumerable().ToList();
if (rp.BudgetSystemToOutput != null)
{
uri.URIDataManager.RowCount =
_dataContext
.BudgetSystemToOutput
.Where(a => a.BudgetSystemToOutcome.PKId == uri.URIId)
.Count();
}
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL1");
}
//set the parent object
uri.URIModels.BudgetSystemToOutcome = rp;
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL");
}
}
else if (uri.URINodeName
== Economics1.BUDGET_TYPES.budgetoutput.ToString())
{
var qry = _dataContext
.BudgetSystemToOutput
.Include(t => t.OutputSeries)
.Include(t => t.OutputSeries.LinkedViewToOutputSeries)
.Where(r => r.PKId == uri.URIId);
if (qry != null)
{
uri.URIModels.BudgetSystemToOutput = await qry.FirstOrDefaultAsync();
}
else
{
uri.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_CANTMAKEMODEL1");
}
}
if (string.IsNullOrEmpty(uri.ErrorMessage))
{
bHasSet = true;
}
return bHasSet;
}
private async Task<bool> SetURIBudgetSystemType(Service s, ContentURI uri)
{
bool bHasSet = true;
if (uri.URINodeName == Agreement.AGREEMENT_BASE_TYPES.servicebase.ToString())
{
uri.URIModels.BudgetSystemType = new List<BudgetSystemType>();
//filter the budget types by this service's network
if (s != null)
{
var qry = _dataContext
.BudgetSystemType
.Where(rt => rt.NetworkId == s.NetworkId)
.OrderBy(rt => rt.Name);
if (qry != null)
{
uri.URIModels.BudgetSystemType = await qry.ToListAsync();
}
}
if (uri.URIModels.BudgetSystemType.Count == 0)
{
//first record is an allcategories and ok for default
BudgetSystemType rt = await _dataContext.BudgetSystemType.SingleOrDefaultAsync(x => x.PKId == 0);
if (rt != null)
{
uri.URIModels.BudgetSystemType.Add(rt);
}
}
}
return bHasSet;
}
public void GetURIBudgets()
{
if (_dtoContentURI.URINodeName
== Agreement.AGREEMENT_BASE_TYPES.servicebase.ToString())
{
var qry = _dataContext
.Service
.Where(s => s.PKId == _dtoContentURI.URIId);
}
else if (_dtoContentURI.URINodeName
== Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var qryRC = _dataContext
.BudgetSystem
.Where(rc => rc.PKId == _dtoContentURI.URIId);
}
else if (_dtoContentURI.URINodeName
== Economics1.BUDGET_TYPES.budget.ToString())
{
var qryRP
= _dataContext
.BudgetSystemToEnterprise
.Where(rp => rp.PKId == _dtoContentURI.URIId);
}
else if (_dtoContentURI.URINodeName
== Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var qryR = _dataContext
.BudgetSystemToTime
.Where(r => r.PKId == _dtoContentURI.URIId);
}
else if (_dtoContentURI.URINodeName
== Economics1.BUDGET_TYPES.budgetoutcome.ToString())
{
var qryR = _dataContext
.BudgetSystemToOutcome
.Where(r => r.PKId == _dtoContentURI.URIId);
}
else if (_dtoContentURI.URINodeName
== Economics1.BUDGET_TYPES.budgetoutput.ToString())
{
var qryR = _dataContext
.BudgetSystemToOutput
.Where(r => r.PKId == _dtoContentURI.URIId);
}
else if (_dtoContentURI.URINodeName
== Economics1.BUDGET_TYPES.budgetoperation.ToString())
{
var qryR = _dataContext
.BudgetSystemToOperation
.Where(r => r.PKId == _dtoContentURI.URIId);
}
else if (_dtoContentURI.URINodeName
== Economics1.BUDGET_TYPES.budgetinput.ToString())
{
var qryR = _dataContext
.BudgetSystemToInput
.Where(r => r.PKId == _dtoContentURI.URIId);
}
_dtoContentURI.URIDataManager.RowCount = 1;
}
public async Task<bool> AddBudgets(EditHelper.ArgumentsEdits argumentsEdits)
{
bool bIsAdded = false;
bool bHasSet = false;
bool bHasAdded = await AddBudgets(argumentsEdits.SelectionsToAdd);
if (bHasAdded)
{
try
{
int iNotUsed = await _dataContext.SaveChangesAsync();
bIsAdded = true;
//only the edit panel needs an updated collection of budgets
if (_dtoContentURI.URIDataManager.ServerActionType
== Helpers.GeneralHelpers.SERVER_ACTION_TYPES.edit)
{
bHasSet = await SetURIBudgets(_dtoContentURI, false);
}
}
catch (Exception e)
{
_dtoContentURI.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
e.ToString(), "ERROR_INTRO");
}
if (_dtoContentURI.ErrorMessage.Length > 0)
{
bHasSet = await SetURIBudgets(_dtoContentURI, false);
}
}
return bIsAdded;
}
private async Task<bool> AddBudgets(List<ContentURI> addedURIs)
{
string sParentNodeName = string.Empty;
int iParentId = 0;
EditModelHelper editHelper = new EditModelHelper();
bool bIsAdded = false;
foreach (ContentURI addedURI in addedURIs)
{
Helpers.GeneralHelpers.GetParentIdAndNodeName(addedURI, out iParentId, out sParentNodeName);
if (!string.IsNullOrEmpty(addedURI.ErrorMessage))
{
_dtoContentURI.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "INSERT_NOPARENT");
return false;
}
if (addedURI.URINodeName == Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var newBudgetSystem = new BudgetSystem
{
Num = Helpers.GeneralHelpers.NONE,
Name = addedURI.URIName,
Description = Helpers.GeneralHelpers.NONE,
Date = Helpers.GeneralHelpers.GetDateShortNow(),
LastChangedDate = Helpers.GeneralHelpers.GetDateShortNow(),
DocStatus = (short)Helpers.GeneralHelpers.DOCS_STATUS.notreviewed,
BudgetSystemToEnterprise = null,
LinkedViewToBudgetSystem = null,
TypeId = 0,
BudgetSystemType = null,
ServiceId = iParentId,
Service = null
};
_dataContext.BudgetSystem.Add(newBudgetSystem);
_dataContext.Entry(newBudgetSystem).State = EntityState.Added;
bIsAdded = true;
}
else if (addedURI.URINodeName == Economics1.BUDGET_TYPES.budget.ToString())
{
AccountToLocal local = await Locals.GetDefaultLocal(_dtoContentURI, _dataContext);
var newBudgetSystemToEnterprise = new BudgetSystemToEnterprise
{
Num = Helpers.GeneralHelpers.NONE,
Num2 = Helpers.GeneralHelpers.NONE,
Name = addedURI.URIName,
Description = Helpers.GeneralHelpers.NONE,
InitialValue = 0,
SalvageValue = 0,
LastChangedDate = Helpers.GeneralHelpers.GetDateShortNow(),
RatingClassId = (local != null) ? local.RatingGroupId : 0,
RealRateId = (local != null) ? local.RealRateId : 0,
NominalRateId = (local != null) ? local.NominalRateId : 0,
DataSourceId = (local != null) ? local.DataSourcePriceId : 0,
GeoCodeId = (local != null) ? local.GeoCodePriceId : 0,
CurrencyClassId = (local != null) ? local.CurrencyGroupId : 0,
UnitClassId = (local != null) ? local.UnitGroupId : 0,
BudgetSystemId = iParentId,
BudgetSystem = null,
BudgetSystemToTime = null,
LinkedViewToBudgetSystemToEnterprise = null
};
_dataContext.BudgetSystemToEnterprise.Add(newBudgetSystemToEnterprise);
_dataContext.Entry(newBudgetSystemToEnterprise).State = EntityState.Added;
bIsAdded = true;
}
else if (addedURI.URINodeName == Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var budget = await _dataContext.BudgetSystemToEnterprise.SingleOrDefaultAsync(x => x.PKId == iParentId);
if (budget != null)
{
var newBudgetSystemToTime = new BudgetSystemToTime
{
Num = Helpers.GeneralHelpers.NONE,
Name = addedURI.URIName,
Description = Helpers.GeneralHelpers.NONE,
//to front of list
Date = Helpers.GeneralHelpers.GetDateSortOld(),
DiscountYorN = true,
GrowthPeriods = 0,
GrowthTypeId = 0,
CommonRefYorN = true,
EnterpriseName = Helpers.GeneralHelpers.NONE,
EnterpriseUnit = Helpers.GeneralHelpers.NONE,
EnterpriseAmount = 1,
AOHFactor = 0,
IncentiveAmount = 0,
IncentiveRate = 0,
LastChangedDate = Helpers.GeneralHelpers.GetDateShortNow(),
BudgetSystemToEnterpriseId = iParentId,
BudgetSystemToEnterprise = null,
BudgetSystemToOperation = null,
BudgetSystemToOutcome = null,
LinkedViewToBudgetSystemToTime = null
};
_dataContext.BudgetSystemToTime.Add(newBudgetSystemToTime);
_dataContext.Entry(newBudgetSystemToTime).State = EntityState.Added;
bIsAdded = true;
}
}
else if (addedURI.URINodeName == Prices.OUTCOME_PRICE_TYPES.outcome.ToString())
{
//when the inputs are included in the qry can add them too
var outcome = await _dataContext
.Outcome
.Include(t => t.OutcomeToOutput)
.Where(r => r.PKId == addedURI.URIId)
.FirstOrDefaultAsync();
//var outcome = _dataContext.Outcome.SingleOrDefaultAsync(x => x.PKId == addedURI.URIId);
if (outcome != null)
{
var newBudgetSystemToOutcome = new BudgetSystemToOutcome
{
Num = outcome.Num,
Name = outcome.Name,
Description = outcome.Description,
ResourceWeight = 0,
Amount = outcome.Amount,
Unit = outcome.Unit,
EffectiveLife = outcome.EffectiveLife,
SalvageValue = outcome.SalvageValue,
IncentiveAmount = outcome.IncentiveAmount,
IncentiveRate = outcome.IncentiveRate,
Date = outcome.Date,
BudgetSystemToTimeId = iParentId,
BudgetSystemToTime = null,
OutcomeId = outcome.PKId,
Outcome = null,
BudgetSystemToOutput = null
};
_dataContext.BudgetSystemToOutcome.Add(newBudgetSystemToOutcome);
_dataContext.Entry(newBudgetSystemToOutcome).State = EntityState.Added;
bIsAdded = true;
if (outcome.OutcomeToOutput != null)
{
//save the outcome so the outcome foreign key can be found
int iNotUsed = await _dataContext.SaveChangesAsync();
foreach (var outputseries in outcome.OutcomeToOutput)
{
var newBudgetSystemToOutput = new BudgetSystemToOutput
{
Num = outputseries.Num,
Name = outputseries.Name,
Description = outputseries.Description,
IncentiveRate = outputseries.IncentiveRate,
IncentiveAmount = outputseries.IncentiveAmount,
OutputAmount1 = outputseries.OutputAmount1,
OutputTimes = outputseries.OutputTimes,
OutputCompositionAmount = outputseries.OutputCompositionAmount,
OutputCompositionUnit = outputseries.OutputCompositionUnit,
OutputDate = outputseries.OutputDate,
RatingClassId = outputseries.RatingClassId,
RealRateId = outputseries.RealRateId,
GeoCodeId = outputseries.GeoCodeId,
NominalRateId = outputseries.NominalRateId,
BudgetSystemToOutcomeId = newBudgetSystemToOutcome.PKId,
BudgetSystemToOutcome = null,
OutputId = outputseries.OutputId,
OutputSeries = null,
};
_dataContext.BudgetSystemToOutput.Add(newBudgetSystemToOutput);
_dataContext.Entry(newBudgetSystemToOutput).State = EntityState.Added;
bIsAdded = true;
}
}
}
}
else if (addedURI.URINodeName == Prices.OUTPUT_PRICE_TYPES.outputseries.ToString())
{
var outputseries = await _dataContext.OutputSeries.SingleOrDefaultAsync(x => x.PKId == addedURI.URIId);
if (outputseries != null)
{
var newBudgetSystemToOutput = new BudgetSystemToOutput
{
Num = outputseries.Num,
Name = outputseries.Name,
Description = outputseries.Description,
IncentiveRate = 0,
IncentiveAmount = 0,
OutputCompositionAmount = 1,
OutputCompositionUnit = Helpers.GeneralHelpers.NONE,
OutputAmount1 = outputseries.OutputAmount1,
OutputTimes = 1,
OutputDate = outputseries.OutputDate,
RatingClassId = outputseries.RatingClassId,
RealRateId = outputseries.RealRateId,
NominalRateId = outputseries.NominalRateId,
GeoCodeId = outputseries.GeoCodeId,
BudgetSystemToOutcomeId = iParentId,
BudgetSystemToOutcome = null,
OutputId = outputseries.PKId,
OutputSeries = null
};
_dataContext.BudgetSystemToOutput.Add(newBudgetSystemToOutput);
_dataContext.Entry(newBudgetSystemToOutput).State = EntityState.Added;
bIsAdded = true;
}
}
else if (addedURI.URINodeName == Prices.OPERATION_PRICE_TYPES.operation.ToString())
{
//when the inputs are included in the qry can add them too
var operation = await _dataContext
.Operation
.Include(t => t.OperationToInput)
.Where(r => r.PKId == addedURI.URIId)
.FirstOrDefaultAsync();
//var operation = _dataContext.Operation.SingleOrDefaultAsync(x => x.PKId == addedURI.URIId);
if (operation != null)
{
var newBudgetSystemToOperation = new BudgetSystemToOperation
{
Num = operation.Num,
Name = operation.Name,
Description = operation.Description,
ResourceWeight = 0,
Amount = operation.Amount,
Unit = operation.Unit,
EffectiveLife = operation.EffectiveLife,
SalvageValue = operation.SalvageValue,
IncentiveAmount = operation.IncentiveAmount,
IncentiveRate = operation.IncentiveRate,
Date = operation.Date,
BudgetSystemToTimeId = iParentId,
BudgetSystemToTime = null,
OperationId = operation.PKId,
Operation = null,
BudgetSystemToInput = null
};
_dataContext.BudgetSystemToOperation.Add(newBudgetSystemToOperation);
_dataContext.Entry(newBudgetSystemToOperation).State = EntityState.Added;
bIsAdded = true;
if (operation.OperationToInput != null)
{
//save the operation so the operation foreign key can be found
int iNotUsed = await _dataContext.SaveChangesAsync();
foreach (var inputseries in operation.OperationToInput)
{
var newBudgetSystemToInput = new BudgetSystemToInput
{
Num = inputseries.Num,
Name = inputseries.Name,
Description = inputseries.Description,
IncentiveRate = inputseries.IncentiveRate,
IncentiveAmount = inputseries.IncentiveAmount,
InputPrice1Amount = inputseries.InputPrice1Amount,
InputPrice2Amount = inputseries.InputPrice2Amount,
InputPrice3Amount = inputseries.InputPrice3Amount,
InputTimes = inputseries.InputTimes,
InputDate = inputseries.InputDate,
InputUseAOHOnly = false,
RatingClassId = inputseries.RatingClassId,
RealRateId = inputseries.RealRateId,
GeoCodeId = inputseries.GeoCodeId,
NominalRateId = inputseries.NominalRateId,
BudgetSystemToOperationId = newBudgetSystemToOperation.PKId,
BudgetSystemToOperation = null,
InputId = inputseries.InputId,
InputSeries = null,
};
_dataContext.BudgetSystemToInput.Add(newBudgetSystemToInput);
_dataContext.Entry(newBudgetSystemToInput).State = EntityState.Added;
bIsAdded = true;
}
}
}
}
else if (addedURI.URINodeName == Prices.INPUT_PRICE_TYPES.inputseries.ToString())
{
var inputseries = await _dataContext.InputSeries.SingleOrDefaultAsync(x => x.PKId == addedURI.URIId);
if (inputseries != null)
{
var newBudgetSystemToInput = new BudgetSystemToInput
{
Num = inputseries.Num,
Name = inputseries.Name,
Description = inputseries.Description,
IncentiveRate = 0,
IncentiveAmount = 0,
InputPrice1Amount = inputseries.InputPrice1Amount,
InputPrice2Amount = 0,
InputPrice3Amount = 0,
InputTimes = 1,
InputDate = inputseries.InputDate,
InputUseAOHOnly = false,
RatingClassId = inputseries.RatingClassId,
RealRateId = inputseries.RealRateId,
GeoCodeId = inputseries.GeoCodeId,
NominalRateId = inputseries.NominalRateId,
BudgetSystemToOperationId = iParentId,
BudgetSystemToOperation = null,
InputId = inputseries.PKId,
InputSeries = null,
};
_dataContext.BudgetSystemToInput.Add(newBudgetSystemToInput);
_dataContext.Entry(newBudgetSystemToInput).State = EntityState.Added;
bIsAdded = true;
}
}
else if (addedURI.URINodeName == LinkedViews.LINKEDVIEWS_TYPES.linkedview.ToString())
{
bIsAdded = await AddBudgetsLinkedView(addedURI, _dtoContentURI.URINodeName);
}
}
return bIsAdded;
}
private async Task<bool> AddBudgetsLinkedView(ContentURI addedURI,
string inputNodeName)
{
bool bIsAdded = false;
if (_dtoContentURI.URIDataManager.ServerSubActionType
== Helpers.GeneralHelpers.SERVER_SUBACTION_TYPES.adddefaults)
{
int iAddInId = 0;
string sAddInName = string.Empty;
Dictionary<int, string> addins = await LinkedViews.GetDefaultAddInOrLocalId(
_dtoContentURI, _dataContext);
if (addins.Count > 0)
{
iAddInId = addins.FirstOrDefault().Key;
sAddInName = addins.FirstOrDefault().Value;
}
if (iAddInId != 0)
{
if (inputNodeName == Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var newLinkedView = new LinkedViewToBudgetSystem
{
LinkedViewName = sAddInName,
IsDefaultLinkedView = false,
LinkingXmlDoc = string.Empty,
LinkingNodeId = _dtoContentURI.URIId,
BudgetSystem = null,
LinkedViewId = iAddInId,
LinkedView = null
};
_dataContext.LinkedViewToBudgetSystem.Add(newLinkedView);
_dataContext.Entry(newLinkedView).State = EntityState.Added;
bIsAdded = true;
}
else if (inputNodeName == Economics1.BUDGET_TYPES.budget.ToString())
{
var newLinkedView = new LinkedViewToBudgetSystemToEnterprise
{
LinkedViewName = sAddInName,
IsDefaultLinkedView = false,
LinkingXmlDoc = string.Empty,
LinkingNodeId = _dtoContentURI.URIId,
BudgetSystemToEnterprise = null,
LinkedViewId = iAddInId,
LinkedView = null
};
_dataContext.LinkedViewToBudgetSystemToEnterprise.Add(newLinkedView);
_dataContext.Entry(newLinkedView).State = EntityState.Added;
bIsAdded = true;
}
else if (inputNodeName == Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var newLinkedView = new LinkedViewToBudgetSystemToTime
{
LinkedViewName = sAddInName,
IsDefaultLinkedView = false,
LinkingXmlDoc = string.Empty,
LinkingNodeId = _dtoContentURI.URIId,
BudgetSystemToTime = null,
LinkedViewId = iAddInId,
LinkedView = null
};
_dataContext.LinkedViewToBudgetSystemToTime.Add(newLinkedView);
_dataContext.Entry(newLinkedView).State = EntityState.Added;
bIsAdded = true;
}
}
}
else
{
if (inputNodeName == Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var newLinkedView = new LinkedViewToBudgetSystem
{
LinkedViewName = addedURI.URIName,
IsDefaultLinkedView = false,
LinkingXmlDoc = string.Empty,
LinkingNodeId = _dtoContentURI.URIId,
BudgetSystem = null,
LinkedViewId = addedURI.URIId,
LinkedView = null
};
_dataContext.LinkedViewToBudgetSystem.Add(newLinkedView);
_dataContext.Entry(newLinkedView).State = EntityState.Added;
bIsAdded = true;
}
else if (inputNodeName == Economics1.BUDGET_TYPES.budget.ToString())
{
var newLinkedView = new LinkedViewToBudgetSystemToEnterprise
{
LinkedViewName = addedURI.URIName,
IsDefaultLinkedView = false,
LinkingXmlDoc = string.Empty,
LinkingNodeId = _dtoContentURI.URIId,
BudgetSystemToEnterprise = null,
LinkedViewId = addedURI.URIId,
LinkedView = null
};
_dataContext.LinkedViewToBudgetSystemToEnterprise.Add(newLinkedView);
_dataContext.Entry(newLinkedView).State = EntityState.Added;
bIsAdded = true;
}
else if (inputNodeName == Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var newLinkedView = new LinkedViewToBudgetSystemToTime
{
LinkedViewName = addedURI.URIName,
IsDefaultLinkedView = false,
LinkingXmlDoc = string.Empty,
LinkingNodeId = _dtoContentURI.URIId,
BudgetSystemToTime = null,
LinkedViewId = addedURI.URIId,
LinkedView = null
};
_dataContext.LinkedViewToBudgetSystemToTime.Add(newLinkedView);
_dataContext.Entry(newLinkedView).State = EntityState.Added;
bIsAdded = true;
}
}
return bIsAdded;
}
public async Task<bool> DeleteBudgets(EditHelper.ArgumentsEdits argumentsEdits)
{
bool bIsDeleted = false;
bool bHasSet = true;
//store updated budgets ids in node name and id dictionary
Dictionary<string, int> deletedIds = new Dictionary<string, int>();
bHasSet = await DeleteBudgets(argumentsEdits.SelectionsToAdd, deletedIds);
if (deletedIds.Count > 0)
{
try
{
int iNotUsed = await _dataContext.SaveChangesAsync();
bIsDeleted = true;
//this gets the edited objects
bHasSet = await SetURIBudgets(_dtoContentURI, false);
}
catch (Exception e)
{
_dtoContentURI.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
e.ToString(), "ERROR_INTRO");
}
if (_dtoContentURI.ErrorMessage.Length > 0)
{
bHasSet = await SetURIBudgets(_dtoContentURI, false);
}
}
return bIsDeleted;
}
private async Task<bool> DeleteBudgets(List<ContentURI> deletionURIs,
Dictionary<string, int> deletedIds)
{
bool bHasSet = true;
string sKeyName = string.Empty;
foreach (ContentURI deletionURI in deletionURIs)
{
if (deletionURI.URINodeName == Economics1.BUDGET_TYPES.budgettype.ToString())
{
var budgetType = await _dataContext.BudgetSystemType.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (budgetType != null)
{
_dataContext.Entry(budgetType).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
else if (deletionURI.URINodeName == Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var budgetClass = await _dataContext.BudgetSystem.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (budgetClass != null)
{
_dataContext.Entry(budgetClass).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
else if (deletionURI.URINodeName == Economics1.BUDGET_TYPES.budget.ToString())
{
var budget = await _dataContext.BudgetSystemToEnterprise.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (budget != null)
{
_dataContext.Entry(budget).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
else if (deletionURI.URINodeName == Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var budgettotime = await _dataContext.BudgetSystemToTime.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (budgettotime != null)
{
_dataContext.Entry(budgettotime).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
else if (deletionURI.URINodeName == Economics1.BUDGET_TYPES.budgetoutcome.ToString())
{
var budgetoutcome = await _dataContext.BudgetSystemToOutcome.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (budgetoutcome != null)
{
_dataContext.Entry(budgetoutcome).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
else if (deletionURI.URINodeName == Economics1.BUDGET_TYPES.budgetoutput.ToString())
{
var budgettooutput = await _dataContext.BudgetSystemToOutput.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (budgettooutput != null)
{
_dataContext.Entry(budgettooutput).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
else if (deletionURI.URINodeName == Economics1.BUDGET_TYPES.budgetoperation.ToString())
{
var budgettooperation = await _dataContext.BudgetSystemToOperation.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (budgettooperation != null)
{
_dataContext.Entry(budgettooperation).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
else if (deletionURI.URINodeName == Economics1.BUDGET_TYPES.budgetinput.ToString())
{
var budgettoinput = await _dataContext.BudgetSystemToInput.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (budgettoinput != null)
{
_dataContext.Entry(budgettoinput).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
else if (deletionURI.URINodeName == LinkedViews.LINKEDVIEWS_TYPES.linkedview.ToString())
{
if (_dtoContentURI.URINodeName == Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var linkedview = await _dataContext.LinkedViewToBudgetSystem.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (linkedview != null)
{
_dataContext.Entry(linkedview).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
else if (_dtoContentURI.URINodeName == Economics1.BUDGET_TYPES.budget.ToString())
{
var linkedview = await _dataContext.LinkedViewToBudgetSystemToEnterprise.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (linkedview != null)
{
_dataContext.Entry(linkedview).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
else if (_dtoContentURI.URINodeName == Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var linkedview = await _dataContext.LinkedViewToBudgetSystemToTime.SingleOrDefaultAsync(x => x.PKId == deletionURI.URIId);
if (linkedview != null)
{
_dataContext.Entry(linkedview).State = EntityState.Deleted;
sKeyName = string.Concat(deletionURI.URINodeName, deletionURI.URIId);
if (deletedIds.ContainsKey(sKeyName) == false)
{
deletedIds.Add(sKeyName, deletionURI.URIId);
}
}
}
}
}
return bHasSet;
}
public async Task<bool> UpdateBudgets(List<EditHelper.ArgumentsEdits> edits)
{
bool bIsUpdated = false;
bool bHasSet = true;
//store updated budgets ids in node name and id dictionary
Dictionary<string, int> updatedIds = new Dictionary<string, int>();
bool bNeedsNewCollections = await UpdateBudgets(edits, updatedIds);
if (updatedIds.Count > 0)
{
try
{
int iNotUsed = await _dataContext.SaveChangesAsync();
bIsUpdated = true;
if (bNeedsNewCollections)
{
bHasSet = await SetURIBudgets(_dtoContentURI, false);
}
}
catch (Exception e)
{
_dtoContentURI.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
e.ToString(), "ERROR_INTRO");
}
if (_dtoContentURI.ErrorMessage.Length > 0)
{
bHasSet = await SetURIBudgets(_dtoContentURI, false);
}
}
return bIsUpdated;
}
private async Task<bool> UpdateBudgets(List<EditHelper.ArgumentsEdits> edits,
Dictionary<string, int> updatedIds)
{
bool bNeedsNewCollections = true;
bool bHasSet = true;
string sKeyName = string.Empty;
foreach (EditHelper.ArgumentsEdits edit in edits)
{
if (edit.EditAttName == LinkedViews.LINKINGXMLDOC)
{
//uritoadd has parent node name
bHasSet = await UpdateBudgetsLinkedView(edit, updatedIds, edit.URIToAdd.URINodeName);
bNeedsNewCollections = false;
}
else
{
if (edit.URIToAdd.URINodeName == Economics1.BUDGET_TYPES.budgettype.ToString())
{
var budgetType = await _dataContext.BudgetSystemType.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (budgetType != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
//update the property to the new value
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(budgetType), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(budgetType).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
else if (edit.URIToAdd.URINodeName == Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var budgetClass = await _dataContext.BudgetSystem.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (budgetClass != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
//update the property to the new value
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(budgetClass), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(budgetClass).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
else if (edit.URIToAdd.URINodeName == Economics1.BUDGET_TYPES.budget.ToString())
{
var budget = await _dataContext.BudgetSystemToEnterprise.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (budget != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(budget), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(budget).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
else if (edit.URIToAdd.URINodeName == Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var budgettimeperiod = await _dataContext.BudgetSystemToTime.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (budgettimeperiod != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
//update the property to the new value
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(budgettimeperiod), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(budgettimeperiod).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
else if (edit.URIToAdd.URINodeName == Economics1.BUDGET_TYPES.budgetoutcome.ToString())
{
var budgetoutcome = await _dataContext.BudgetSystemToOutcome.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (budgetoutcome != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
//update the property to the new value
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(budgetoutcome), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(budgetoutcome).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
else if (edit.URIToAdd.URINodeName == Economics1.BUDGET_TYPES.budgetoutput.ToString())
{
var budgetoutput = await _dataContext.BudgetSystemToOutput.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (budgetoutput != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
//update the property to the new value
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(budgetoutput), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(budgetoutput).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
else if (edit.URIToAdd.URINodeName == Economics1.BUDGET_TYPES.budgetoperation.ToString())
{
var budgetoperation = await _dataContext.BudgetSystemToOperation.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (budgetoperation != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
//update the property to the new value
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(budgetoperation), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(budgetoperation).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
else if (edit.URIToAdd.URINodeName == Economics1.BUDGET_TYPES.budgetinput.ToString())
{
var budgetinput = await _dataContext.BudgetSystemToInput.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (budgetinput != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
//update the property to the new value
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(budgetinput), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(budgetinput).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
else if (edit.URIToAdd.URINodeName == LinkedViews.LINKEDVIEWS_TYPES.linkedview.ToString())
{
bHasSet = await UpdateBudgetsLinkedView(edit, updatedIds, _dtoContentURI.URINodeName);
}
}
}
return bNeedsNewCollections;
}
private async Task<bool> UpdateBudgetsLinkedView(EditHelper.ArgumentsEdits edit,
Dictionary<string, int> updatedIds, string inputNodeName)
{
string sKeyName = string.Empty;
bool bHasSet = true;
if (inputNodeName == Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var linkedview = await _dataContext.LinkedViewToBudgetSystem.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (linkedview != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
//update the property to the new value
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(linkedview), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(linkedview).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
else if (inputNodeName == Economics1.BUDGET_TYPES.budget.ToString())
{
var linkedview = await _dataContext.LinkedViewToBudgetSystemToEnterprise.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (linkedview != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
//update the property to the new value
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(linkedview), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(linkedview).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
else if (inputNodeName == Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var linkedview = await _dataContext.LinkedViewToBudgetSystemToTime.SingleOrDefaultAsync(x => x.PKId == edit.URIToAdd.URIId);
if (linkedview != null)
{
RuleHelpers.GeneralRules.ValidateXSDInput(edit);
//update the property to the new value
string sErroMsg = string.Empty;
EditModelHelper.UpdateDbEntityProperty(_dataContext.Entry(linkedview), edit.EditAttName,
edit.EditAttValue, edit.EditDataType, ref sErroMsg);
_dtoContentURI.ErrorMessage = sErroMsg;
_dataContext.Entry(linkedview).State = EntityState.Modified;
sKeyName = string.Concat(edit.URIToAdd.URINodeName, edit.URIToAdd.URIId);
if (updatedIds.ContainsKey(sKeyName) == false)
{
updatedIds.Add(sKeyName, edit.URIToAdd.URIId);
}
}
}
return bHasSet;
}
public async Task<bool> SaveURIFirstDocAsync()
{
bool bHasSavedDoc = false;
if (string.IsNullOrEmpty(_dtoContentURI.URIClub.ClubDocFullPath))
{
//when the file path is not set, too much data is prevented
return true;
}
//make sure to return a regular collection
bool bSaveInFileSystemContent = false;
bool bHasSet = await SetURIBudgets(_dtoContentURI, bSaveInFileSystemContent);
XElement root = XmlLinq.GetRootXmlDoc();
bool bHasGoodDoc = false;
_parentName = string.Empty;
//add any missing ancestor up to servicebase root.firstchild
bool bHasGoodAncestors = await AddAncestors(_dtoContentURI.URIId, _dtoContentURI.URINodeName,
root);
if (bHasGoodAncestors
&& !string.IsNullOrEmpty(_parentName))
{
//add all descendants below _dtoContentURI (but use a new ContentURI
ContentURI tempURI = new ContentURI();
bHasGoodDoc = await AddDescendants(tempURI, _parentId, _parentName, _dtoContentURI.URIId,
_dtoContentURI.URINodeName, root);
}
if (bHasGoodDoc)
{
bHasSavedDoc = await EditModelHelper.SaveStandardContentXmlDocAsync(_dtoContentURI, root);
}
else
{
//add an error message
_dtoContentURI.ErrorMessage = DevTreks.Exceptions.DevTreksErrors.MakeStandardErrorMsg(
string.Empty, "MODELHELPERS_BADXMLCONTENT");
}
return bHasSavedDoc;
}
private async Task<bool> AddAncestors(int id, string nodeName, XElement root)
{
bool bHasGoodAncestors = false;
if (root.HasElements)
{
if (_dtoContentURI.URINodeName == nodeName)
{
//don't insert self
_parentName = nodeName;
_parentId = id;
return true;
}
}
//deserialize objects
if (nodeName == Agreement.AGREEMENT_BASE_TYPES.servicebase.ToString())
{
var currentObject = await _dataContext.Service.SingleOrDefaultAsync(x => x.PKId == id);
if (currentObject != null)
{
_parentName = nodeName;
_parentId = id;
if (_dtoContentURI.URINodeName != Agreement.AGREEMENT_BASE_TYPES.servicebase.ToString())
{
XElement el = MakeServiceBaseXml(currentObject);
if (el != null)
{
root.AddFirst(el);
bHasGoodAncestors = true;
}
}
else
{
bHasGoodAncestors = true;
}
}
}
else if (nodeName == Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var currentObject = await GetBudgetSystem(id);
if (currentObject != null)
{
id = currentObject.ServiceId;
nodeName = Agreement.AGREEMENT_BASE_TYPES.servicebase.ToString();
bHasGoodAncestors = await AddAncestors(id,
nodeName, root);
if (bHasGoodAncestors)
{
_parentName = nodeName;
_parentId = id;
if (_dtoContentURI.URINodeName != Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
XElement el = MakeBudgetSystemXml(currentObject);
bHasGoodAncestors = Economics1.AddBudgetElementToParent(root, el,
string.Empty, id.ToString(), nodeName, currentObject);
}
}
}
}
else if (nodeName == Economics1.BUDGET_TYPES.budget.ToString())
{
var currentObject = await GetBudget(id);
if (currentObject != null)
{
id = currentObject.BudgetSystemId;
nodeName = Economics1.BUDGET_TYPES.budgetgroup.ToString();
bHasGoodAncestors = await AddAncestors(id,
nodeName, root);
if (bHasGoodAncestors)
{
_parentName = nodeName;
_parentId = id;
if (_dtoContentURI.URINodeName != Economics1.BUDGET_TYPES.budget.ToString())
{
XElement el = MakeBudgetXml(currentObject);
bHasGoodAncestors = Economics1.AddBudgetElementToParent(root, el,
string.Empty, id.ToString(), nodeName, null);
}
}
}
}
else if (nodeName == Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var currentObject = await GetBudgetTime(id);
if (currentObject != null)
{
id = currentObject.BudgetSystemToEnterpriseId;
nodeName = Economics1.BUDGET_TYPES.budget.ToString();
bHasGoodAncestors = await AddAncestors(id,
nodeName, root);
if (bHasGoodAncestors)
{
_parentName = nodeName;
_parentId = id;
if (_dtoContentURI.URINodeName != Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
XElement el = MakeBudgetSystemToTimeXml(currentObject);
bHasGoodAncestors = Economics1.AddBudgetElementToParent(root, el,
string.Empty, id.ToString(), nodeName, null);
//add the grouping nodes
XElement groupOutcome = XElement.Parse(Economics1.BUDGET_OUTCOMES_NODE);
bHasGoodAncestors = Economics1.AddBudgetElementToParent(root, groupOutcome,
string.Empty, currentObject.PKId.ToString(), Economics1.BUDGET_TYPES.budgettimeperiod.ToString(), null);
//add a grouping node
XElement groupOperation = XElement.Parse(Economics1.BUDGET_OPERATIONS_NODE);
bHasGoodAncestors = Economics1.AddBudgetElementToParent(root, groupOperation,
string.Empty, currentObject.PKId.ToString(), Economics1.BUDGET_TYPES.budgettimeperiod.ToString(), null);
}
}
}
}
else if (nodeName == Economics1.BUDGET_TYPES.budgetoutcome.ToString())
{
var currentObject = await GetBudgetOutcome(id);
if (currentObject != null)
{
id = currentObject.BudgetSystemToTimeId;
nodeName = Economics1.BUDGET_TYPES.budgettimeperiod.ToString();
bHasGoodAncestors = await AddAncestors(id,
nodeName, root);
if (bHasGoodAncestors)
{
_parentName = nodeName;
_parentId = id;
if (_dtoContentURI.URINodeName != Economics1.BUDGET_TYPES.budgetoutcome.ToString())
{
XElement el = MakeBudgetSystemToOutcomeXml(currentObject);
bHasGoodAncestors = Economics1.AddBudgetElementToParent(root, el,
Economics1.BUDGET_TYPES.budgetoutcomes.ToString(), id.ToString(), nodeName, null);
}
}
}
}
else if (nodeName == Economics1.BUDGET_TYPES.budgetoutput.ToString())
{
var currentObject = await GetBudgetOutput(id);
if (currentObject != null)
{
id = currentObject.BudgetSystemToOutcomeId;
nodeName = Economics1.BUDGET_TYPES.budgetoutcome.ToString();
bHasGoodAncestors = await AddAncestors(id,
nodeName, root);
if (bHasGoodAncestors)
{
_parentName = nodeName;
_parentId = id;
//return bhasgoodancestors
}
}
}
else if (nodeName == Economics1.BUDGET_TYPES.budgetoperation.ToString())
{
var currentObject = await GetBudgetOperation(id);
if (currentObject != null)
{
id = currentObject.BudgetSystemToTimeId;
nodeName = Economics1.BUDGET_TYPES.budgettimeperiod.ToString();
bHasGoodAncestors = await AddAncestors(id,
nodeName, root);
if (bHasGoodAncestors)
{
_parentName = nodeName;
_parentId = id;
if (_dtoContentURI.URINodeName != Economics1.BUDGET_TYPES.budgetoperation.ToString())
{
XElement el = MakeBudgetSystemToOperationXml(currentObject);
bHasGoodAncestors = Economics1.AddBudgetElementToParent(root, el,
Economics1.BUDGET_TYPES.budgetoperations.ToString(), id.ToString(), nodeName, null);
}
}
}
}
else if (nodeName == Economics1.BUDGET_TYPES.budgetinput.ToString())
{
var currentObject = await GetBudgetInput(id);
if (currentObject != null)
{
id = currentObject.BudgetSystemToOperationId;
nodeName = Economics1.BUDGET_TYPES.budgetoperation.ToString();
bHasGoodAncestors = await AddAncestors(id,
nodeName, root);
if (bHasGoodAncestors)
{
_parentName = nodeName;
_parentId = id;
//return bhasgoodancestors
}
}
}
return bHasGoodAncestors;
}
private async Task<bool> AddDescendants(ContentURI tempURI, int parentId, string parentNodeName,
int childId, string childNodeName, XElement root)
{
bool bHasGoodDescendants = false;
bool bHasBeenAdded = false;
//deserialize objects
if (childNodeName == Agreement.AGREEMENT_BASE_TYPES.servicebase.ToString())
{
var obj1 = await _dataContext.Service.SingleOrDefaultAsync(x => x.PKId == childId);
if (obj1 != null)
{
XElement el = MakeServiceBaseXml(obj1);
if (el != null)
{
root.AddFirst(el);
}
bool bHasSet = await SetTempURIBudgets(tempURI, childNodeName, childId);
if (tempURI.URIModels.Service.BudgetSystem != null)
{
if (tempURI.URIModels.Service.BudgetSystem.Count == 0)
{
bHasGoodDescendants = true;
}
foreach (var child in tempURI.URIModels.Service.BudgetSystem)
{
bHasGoodDescendants = await AddDescendants(tempURI, childId, childNodeName,
child.PKId, Economics1.BUDGET_TYPES.budgetgroup.ToString(),
root);
}
}
else
{
bHasGoodDescendants = true;
}
}
}
else if (childNodeName == Economics1.BUDGET_TYPES.budgetgroup.ToString())
{
var obj2 = await GetBudgetSystem(childId);
if (obj2 != null)
{
XElement el = MakeBudgetSystemXml(obj2);
bHasBeenAdded = Economics1.AddBudgetElementToParent(root, el,
string.Empty, parentId.ToString(), parentNodeName, obj2);
if (bHasBeenAdded)
{
//don't allow servicebase docs to go deeper or docs will get too large to handle
if (_dtoContentURI.URINodeName != Agreement.AGREEMENT_BASE_TYPES.servicebase.ToString())
{
bool bHasSet = await SetTempURIBudgets(tempURI, childNodeName, childId);
if (tempURI.URIModels.BudgetSystem.BudgetSystemToEnterprise != null)
{
if (tempURI.URIModels.BudgetSystem.BudgetSystemToEnterprise.Count == 0)
{
bHasGoodDescendants = true;
}
foreach (var child in tempURI.URIModels.BudgetSystem.BudgetSystemToEnterprise)
{
bHasGoodDescendants = await AddDescendants(tempURI, childId, childNodeName,
child.PKId, Economics1.BUDGET_TYPES.budget.ToString(),
root);
}
}
else
{
bHasGoodDescendants = true;
}
}
else
{
bHasGoodDescendants = true;
}
}
}
}
else if (childNodeName == Economics1.BUDGET_TYPES.budget.ToString())
{
var obj3 = await GetBudget(childId);
if (obj3 != null)
{
XElement el = MakeBudgetXml(obj3);
bHasBeenAdded = Economics1.AddBudgetElementToParent(root, el,
string.Empty, parentId.ToString(), parentNodeName, null);
if (bHasBeenAdded)
{
bool bHasSet = await SetTempURIBudgets(tempURI, childNodeName, childId);
if (tempURI.URIModels.BudgetSystemToEnterprise.BudgetSystemToTime != null)
{
if (tempURI.URIModels.BudgetSystemToEnterprise.BudgetSystemToTime.Count == 0)
{
bHasGoodDescendants = true;
}
foreach (var child in tempURI.URIModels.BudgetSystemToEnterprise.BudgetSystemToTime)
{
bHasGoodDescendants = await AddDescendants(tempURI, childId, childNodeName,
child.PKId, Economics1.BUDGET_TYPES.budgettimeperiod.ToString(),
root);
}
}
else
{
bHasGoodDescendants = true;
}
}
}
}
else if (childNodeName == Economics1.BUDGET_TYPES.budgettimeperiod.ToString())
{
var obj4 = await GetBudgetTime(childId);
if (obj4 != null)
{
XElement el = MakeBudgetSystemToTimeXml(obj4);
bHasBeenAdded = Economics1.AddBudgetElementToParent(root, el,
string.Empty, parentId.ToString(), parentNodeName, null);
if (bHasBeenAdded)
{
bool bHasSet = await SetTempURIBudgets(tempURI, childNodeName, childId);
//add the grouping nodes
XElement groupOutcome = XElement.Parse(Economics1.BUDGET_OUTCOMES_NODE);
bHasBeenAdded = EditHelpers.XmlLinq.AddElementToParent(root, groupOutcome,
string.Empty, childId.ToString(), childNodeName);
//add a grouping node
XElement groupOperation = XElement.Parse(Economics1.BUDGET_OPERATIONS_NODE);
bHasBeenAdded = EditHelpers.XmlLinq.AddElementToParent(root, groupOperation,
string.Empty, childId.ToString(), childNodeName);
if (bHasBeenAdded)
{
//first do the outcomes
if (tempURI.URIModels.BudgetSystemToTime.BudgetSystemToOutcome != null)
{
if (tempURI.URIModels.BudgetSystemToTime.BudgetSystemToOutcome.Count == 0)
{
bHasGoodDescendants = true;
}
foreach (var child in tempURI.URIModels.BudgetSystemToTime.BudgetSystemToOutcome)
{
bHasGoodDescendants = await AddDescendants(tempURI, childId, childNodeName,
child.PKId, Economics1.BUDGET_TYPES.budgetoutcome.ToString(),
root);
}
}
else
{
bHasGoodDescendants = true;
}
//then the operations
if (tempURI.URIModels.BudgetSystemToTime.BudgetSystemToOperation != null)
{
if (tempURI.URIModels.BudgetSystemToTime.BudgetSystemToOperation.Count == 0)
{
bHasGoodDescendants = true;
}
foreach (var child in tempURI.URIModels.BudgetSystemToTime.BudgetSystemToOperation)
{
bHasGoodDescendants = await AddDescendants(tempURI, childId, childNodeName,
child.PKId, Economics1.BUDGET_TYPES.budgetoperation.ToString(),
root);
}
}
else
{
bHasGoodDescendants = true;
}
}
}
}
}
else if (childNodeName == Economics1.BUDGET_TYPES.budgetoutcome.ToString())
{
var obj4 = await GetBudgetOutcome(childId);
if (obj4 != null)
{
XElement el = MakeBudgetSystemToOutcomeXml(obj4);
bHasBeenAdded = Economics1.AddBudgetElementToParent(root, el,
Economics1.BUDGET_TYPES.budgetoutcomes.ToString(), parentId.ToString(),
parentNodeName, null);
if (bHasBeenAdded)
{
bool bHasSet = await SetTempURIBudgets(tempURI, childNodeName, childId);
if (tempURI.URIModels.BudgetSystemToOutcome.BudgetSystemToOutput != null)
{
if (tempURI.URIModels.BudgetSystemToOutcome.BudgetSystemToOutput.Count == 0)
{
bHasGoodDescendants = true;
}
foreach (var child in tempURI.URIModels.BudgetSystemToOutcome.BudgetSystemToOutput)
{
bHasGoodDescendants = await AddDescendants(tempURI, childId, childNodeName,
child.PKId, Economics1.BUDGET_TYPES.budgetoutput.ToString(),
root);
}
}
else
{
bHasGoodDescendants = true;
}
}
}
}
else if (childNodeName == Economics1.BUDGET_TYPES.budgetoutput.ToString())
{
var obj4 = await GetBudgetOutput(childId);
if (obj4 != null)
{
XElement el = MakeBudgetSystemToOutputXml(obj4);
bHasBeenAdded = Economics1.AddBudgetElementToParent(root, el,
string.Empty, parentId.ToString(), parentNodeName, null);
if (bHasBeenAdded)
{
bHasGoodDescendants = true;
}
}
}
else if (childNodeName == Economics1.BUDGET_TYPES.budgetoperation.ToString())
{
var obj4 = await GetBudgetOperation(childId);
if (obj4 != null)
{
XElement el = MakeBudgetSystemToOperationXml(obj4);
bHasBeenAdded = Economics1.AddBudgetElementToParent(root, el,
Economics1.BUDGET_TYPES.budgetoperations.ToString(), parentId.ToString(),
parentNodeName, null);
if (bHasBeenAdded)
{
bool bHasSet = await SetTempURIBudgets(tempURI, childNodeName, childId);
if (tempURI.URIModels.BudgetSystemToOperation.BudgetSystemToInput != null)
{
if (tempURI.URIModels.BudgetSystemToOperation.BudgetSystemToInput.Count == 0)
{
bHasGoodDescendants = true;
}
foreach (var child in tempURI.URIModels.BudgetSystemToOperation.BudgetSystemToInput)
{
bHasGoodDescendants = await AddDescendants(tempURI, childId, childNodeName,
child.PKId, Economics1.BUDGET_TYPES.budgetinput.ToString(),
root);
}
}
else
{
bHasGoodDescendants = true;
}
}
}
}
else if (childNodeName == Economics1.BUDGET_TYPES.budgetinput.ToString())
{
var obj4 = await GetBudgetInput(childId);
if (obj4 != null)
{
XElement el = MakeBudgetSystemToInputXml(obj4);
bHasBeenAdded = Economics1.AddBudgetElementToParent(root, el,
string.Empty, parentId.ToString(), parentNodeName, null);
if (bHasBeenAdded)
{
bHasGoodDescendants = true;
}
}
}
return bHasGoodDescendants;
}
private async Task<bool> SetTempURIBudgets(ContentURI tempURI, string nodeName, int id)
{
tempURI.URINodeName = nodeName;
tempURI.URIId = id;
Helpers.AppSettings.CopyURIAppSettings(_dtoContentURI, tempURI);
bool bHasSet = await SetURIBudgets(tempURI, true);
return bHasSet;
}
public XElement MakeServiceBaseXml(Service sb)
{
XElement currentNode = null;
if (sb != null)
{
currentNode = new XElement(Agreement.AGREEMENT_BASE_TYPES.servicebase.ToString());
var currentObjContext = _dataContext.Entry(sb);
Dictionary<string, string> propValues = new Dictionary<string, string>();
foreach (var property in currentObjContext.Metadata.GetProperties())
{
if (currentObjContext.Property(property.Name).CurrentValue == null)
{
propValues.Add(property.Name, string.Empty);
}
else
{
var currentValue = currentObjContext
.Property(property.Name).CurrentValue.ToString();
propValues.Add(property.Name, currentValue);
}
}
EditModelHelper.SetAttributes(propValues, currentNode);
}
return currentNode;
}
private async Task<BudgetSystem> GetBudgetSystem(int id)
{
BudgetSystem bs = await _dataContext
.BudgetSystem
.Include(t => t.BudgetSystemType)
.Include(t => t.LinkedViewToBudgetSystem)
.Where(b => b.PKId == id)
.FirstOrDefaultAsync();
return bs;
}
private XElement MakeBudgetSystemXml(BudgetSystem obj)
{
XElement currentNode = new XElement(Economics1.BUDGET_TYPES.budgetgroup.ToString());
var currentObjContext = _dataContext.Entry(obj);
Dictionary<string, string> propValues = new Dictionary<string, string>();
foreach (var property in currentObjContext.Metadata.GetProperties())
{
if (currentObjContext.Property(property.Name).CurrentValue == null)
{
propValues.Add(property.Name, string.Empty);
}
else
{
var currentValue = currentObjContext
.Property(property.Name).CurrentValue.ToString();
propValues.Add(property.Name, currentValue);
}
}
EditModelHelper.SetAttributes(propValues, currentNode);
//add any linked view child elements
if (obj.LinkedViewToBudgetSystem != null)
{
foreach (var lv in obj.LinkedViewToBudgetSystem)
{
EditModelHelper.AddXmlAttributeToDoc(lv.LinkingXmlDoc, currentNode);
}
}
return currentNode;
}
private async Task<BudgetSystemToEnterprise> GetBudget(int id)
{
BudgetSystemToEnterprise bs = await _dataContext
.BudgetSystemToEnterprise
.Include(t => t.LinkedViewToBudgetSystemToEnterprise)
.Where(b => b.PKId == id)
.FirstOrDefaultAsync();
return bs;
}
private XElement MakeBudgetXml(BudgetSystemToEnterprise obj)
{
XElement currentNode = new XElement(Economics1.BUDGET_TYPES.budget.ToString());
var currentObjContext = _dataContext.Entry(obj);
Dictionary<string, string> propValues = new Dictionary<string, string>();
foreach (var property in currentObjContext.Metadata.GetProperties())
{
if (currentObjContext.Property(property.Name).CurrentValue == null)
{
propValues.Add(property.Name, string.Empty);
}
else
{
var currentValue = currentObjContext
.Property(property.Name).CurrentValue.ToString();
propValues.Add(property.Name, currentValue);
}
}
EditModelHelper.SetAttributes(propValues, currentNode);
//add any linked view child elements
if (obj.LinkedViewToBudgetSystemToEnterprise != null)
{
foreach (var lv in obj.LinkedViewToBudgetSystemToEnterprise)
{
EditModelHelper.AddXmlAttributeToDoc(lv.LinkingXmlDoc, currentNode);
}
}
return currentNode;
}
private async Task<BudgetSystemToTime> GetBudgetTime(int id)
{
BudgetSystemToTime bs = await _dataContext
.BudgetSystemToTime
.Include(t => t.LinkedViewToBudgetSystemToTime)
.Where(b => b.PKId == id)
.FirstOrDefaultAsync();
return bs;
}
private XElement MakeBudgetSystemToTimeXml(BudgetSystemToTime obj)
{
XElement currentNode = new XElement(Economics1.BUDGET_TYPES.budgettimeperiod.ToString());
var currentObjContext = _dataContext.Entry(obj);
Dictionary<string, string> propValues = new Dictionary<string, string>();
foreach (var property in currentObjContext.Metadata.GetProperties())
{
if (currentObjContext.Property(property.Name).CurrentValue == null)
{
propValues.Add(property.Name, string.Empty);
}
else
{
var currentValue = currentObjContext
.Property(property.Name).CurrentValue.ToString();
propValues.Add(property.Name, currentValue);
}
}
EditModelHelper.SetAttributes(propValues, currentNode);
//add any linked view child elements
if (obj.LinkedViewToBudgetSystemToTime != null)
{
foreach (var lv in obj.LinkedViewToBudgetSystemToTime)
{
EditModelHelper.AddXmlAttributeToDoc(lv.LinkingXmlDoc, currentNode);
}
}
return currentNode;
}
private async Task<BudgetSystemToOutcome> GetBudgetOutcome(int id)
{
BudgetSystemToOutcome bs = await _dataContext
.BudgetSystemToOutcome
.Include(t => t.Outcome)
.Include(t => t.Outcome.OutcomeClass)
.Include(t => t.Outcome.OutcomeClass.OutcomeType)
.Include(t => t.Outcome.LinkedViewToOutcome)
.Where(b => b.PKId == id)
.FirstOrDefaultAsync();
return bs;
}
private XElement MakeBudgetSystemToOutcomeXml(BudgetSystemToOutcome obj)
{
XElement currentNode = new XElement(Economics1.BUDGET_TYPES.budgetoutcome.ToString());
var currentObjContext = _dataContext.Entry(obj);
Dictionary<string, string> propValues = new Dictionary<string, string>();
foreach (var property in currentObjContext.Metadata.GetProperties())
{
if (currentObjContext.Property(property.Name).CurrentValue == null)
{
propValues.Add(property.Name, string.Empty);
}
else
{
var currentValue = currentObjContext
.Property(property.Name).CurrentValue.ToString();
propValues.Add(property.Name, currentValue);
}
}
EditModelHelper.SetAttributes(propValues, currentNode);
//add any linked view child elements
if (obj.Outcome != null)
{
Economics1.AddBaseOutcomeToXml(currentNode, obj);
if (obj.Outcome.LinkedViewToOutcome != null)
{
foreach (var lv in obj.Outcome.LinkedViewToOutcome)
{
EditModelHelper.AddXmlAttributeToDoc(lv.LinkingXmlDoc, currentNode);
}
}
}
return currentNode;
}
private async Task<BudgetSystemToOutput> GetBudgetOutput(int id)
{
BudgetSystemToOutput bs = await _dataContext
.BudgetSystemToOutput
.Include(t => t.OutputSeries)
.Include(t => t.OutputSeries.Output.OutputClass)
.Include(t => t.OutputSeries.Output.OutputClass.OutputType)
.Include(t => t.OutputSeries.LinkedViewToOutputSeries)
.Where(b => b.PKId == id)
.FirstOrDefaultAsync();
return bs;
}
private XElement MakeBudgetSystemToOutputXml(BudgetSystemToOutput obj)
{
XElement currentNode = new XElement(Economics1.BUDGET_TYPES.budgetoutput.ToString());
var currentObjContext = _dataContext.Entry(obj);
Dictionary<string, string> propValues = new Dictionary<string, string>();
foreach (var property in currentObjContext.Metadata.GetProperties())
{
if (currentObjContext.Property(property.Name).CurrentValue == null)
{
propValues.Add(property.Name, string.Empty);
}
else
{
var currentValue = currentObjContext
.Property(property.Name).CurrentValue.ToString();
propValues.Add(property.Name, currentValue);
}
}
EditModelHelper.SetAttributes(propValues, currentNode);
//add any linked view child elements
if (obj.OutputSeries != null)
{
Economics1.AddBaseOutputSeriesToXml(currentNode, obj);
if (obj.OutputSeries.LinkedViewToOutputSeries != null)
{
foreach (var lv in obj.OutputSeries.LinkedViewToOutputSeries)
{
EditModelHelper.AddXmlAttributeToDoc(lv.LinkingXmlDoc, currentNode);
}
}
}
return currentNode;
}
private async Task<BudgetSystemToOperation> GetBudgetOperation(int id)
{
BudgetSystemToOperation bs = await _dataContext
.BudgetSystemToOperation
.Include(t => t.Operation)
.Include(t => t.Operation.OperationClass)
.Include(t => t.Operation.OperationClass.OperationType)
.Include(t => t.Operation.LinkedViewToOperation)
.Where(b => b.PKId == id)
.FirstOrDefaultAsync();
return bs;
}
private XElement MakeBudgetSystemToOperationXml(BudgetSystemToOperation obj)
{
XElement currentNode = new XElement(Economics1.BUDGET_TYPES.budgetoperation.ToString());
var currentObjContext = _dataContext.Entry(obj);
Dictionary<string, string> propValues = new Dictionary<string, string>();
foreach (var property in currentObjContext.Metadata.GetProperties())
{
if (currentObjContext.Property(property.Name).CurrentValue == null)
{
propValues.Add(property.Name, string.Empty);
}
else
{
var currentValue = currentObjContext
.Property(property.Name).CurrentValue.ToString();
propValues.Add(property.Name, currentValue);
}
}
EditModelHelper.SetAttributes(propValues, currentNode);
//add any linked view child elements
if (obj.Operation != null)
{
Economics1.AddBaseOperationToXml(currentNode, obj);
if (obj.Operation.LinkedViewToOperation != null)
{
foreach (var lv in obj.Operation.LinkedViewToOperation)
{
EditModelHelper.AddXmlAttributeToDoc(lv.LinkingXmlDoc, currentNode);
}
}
}
return currentNode;
}
private async Task<BudgetSystemToInput> GetBudgetInput(int id)
{
BudgetSystemToInput bs = await _dataContext
.BudgetSystemToInput
.Include(t => t.InputSeries)
.Include(t => t.InputSeries.Input.InputClass)
.Include(t => t.InputSeries.Input.InputClass.InputType)
.Include(t => t.InputSeries.LinkedViewToInputSeries)
.Where(b => b.PKId == id)
.FirstOrDefaultAsync();
return bs;
}
private XElement MakeBudgetSystemToInputXml(BudgetSystemToInput obj)
{
XElement currentNode = new XElement(Economics1.BUDGET_TYPES.budgetinput.ToString());
var currentObjContext = _dataContext.Entry(obj);
Dictionary<string, string> propValues = new Dictionary<string, string>();
foreach (var property in currentObjContext.Metadata.GetProperties())
{
if (currentObjContext.Property(property.Name).CurrentValue == null)
{
propValues.Add(property.Name, string.Empty);
}
else
{
var currentValue = currentObjContext
.Property(property.Name).CurrentValue.ToString();
propValues.Add(property.Name, currentValue);
}
}
EditModelHelper.SetAttributes(propValues, currentNode);
//add any linked view child elements
if (obj.InputSeries != null)
{
Economics1.AddBaseInputSeriesToXml(currentNode, obj);
if (obj.InputSeries.LinkedViewToInputSeries != null)
{
foreach (var lv in obj.InputSeries.LinkedViewToInputSeries)
{
EditModelHelper.AddXmlAttributeToDoc(lv.LinkingXmlDoc, currentNode);
}
}
}
return currentNode;
}
}
}
| mit |
le0pard/go-falcon | utils/auth.go | 102 | package utils
const (
AUTH_PLAIN = "plain"
AUTH_APOP = "apop"
AUTH_CRAM_MD5 = "cram-md5"
)
| mit |
DustinCampbell/omnisharp-roslyn | tests/OmniSharp.Roslyn.CSharp.Tests/FindReferencesFacts.cs | 7927 | using System.Linq;
using System.Threading.Tasks;
using OmniSharp.Models;
using OmniSharp.Models.FindUsages;
using OmniSharp.Roslyn.CSharp.Services.Navigation;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class FindReferencesFacts : AbstractSingleRequestHandlerTestFixture<FindUsagesService>
{
public FindReferencesFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
}
protected override string EndpointName => OmniSharpEndpoints.FindUsages;
[Fact]
public async Task CanFindReferencesOfLocalVariable()
{
const string code = @"
public class Foo
{
public Foo(string s)
{
var pr$$op = s + 'abc';
prop += 'woo';
}
}";
var usages = await FindUsagesAsync(code);
Assert.Equal(2, usages.QuickFixes.Count());
}
[Fact]
public async Task CanFindReferencesOfMethodParameter()
{
const string code = @"
public class Foo
{
public Foo(string $$s)
{
var prop = s + 'abc';
}
}";
var usages = await FindUsagesAsync(code);
Assert.Equal(2, usages.QuickFixes.Count());
}
[Fact]
public async Task CanFindReferencesOfField()
{
const string code = @"
public class Foo
{
public string p$$rop;
}
public class FooConsumer
{
public FooConsumer()
{
var foo = new Foo();
var prop = foo.prop;
}
}";
var usages = await FindUsagesAsync(code);
Assert.Equal(2, usages.QuickFixes.Count());
}
[Fact]
public async Task CanFindReferencesOfConstructor()
{
const string code = @"
public class Foo
{
public F$$oo() {}
}
public class FooConsumer
{
public FooConsumer()
{
var temp = new Foo();
}
}";
var usages = await FindUsagesAsync(code);
Assert.Equal(2, usages.QuickFixes.Count());
}
[Fact]
public async Task CanFindReferencesOfMethod()
{
const string code = @"
public class Foo
{
public void b$$ar() { }
}
public class FooConsumer
{
public FooConsumer()
{
new Foo().bar();
}
}";
var usages = await FindUsagesAsync(code);
Assert.Equal(2, usages.QuickFixes.Count());
}
[Fact]
public async Task ExcludesMethodDefinition()
{
const string code = @"
public class Foo
{
public void b$$ar() { }
}
public class FooConsumer
{
public FooConsumer()
{
new Foo().bar();
}
}";
var usages = await FindUsagesAsync(code, excludeDefinition: true);
Assert.Single(usages.QuickFixes);
}
[Fact]
public async Task CanFindReferencesOfPublicAutoProperty()
{
const string code = @"
public class Foo
{
public string p$$rop {get;set;}
}
public class FooConsumer
{
public FooConsumer()
{
var foo = new Foo();
var prop = foo.prop;
}
}";
var usages = await FindUsagesAsync(code);
Assert.Equal(2, usages.QuickFixes.Count());
}
[Fact]
public async Task CanFindReferencesOfClass()
{
const string code = @"
public class F$$oo
{
public string prop {get;set;}
}
public class FooConsumer
{
public FooConsumer()
{
var temp = new Foo();
var prop = foo.prop;
}
}";
var usages = await FindUsagesAsync(code);
Assert.Equal(2, usages.QuickFixes.Count());
}
[Fact]
public async Task LimitReferenceSearchToThisFile()
{
var testFiles = new[]
{
new TestFile("a.cs", @"
public class F$$oo {
public Foo Clone() {
return null;
}
}"),
new TestFile("b.cs",
@"public class Bar : Foo { }")
};
var usages = await FindUsagesAsync(testFiles, onlyThisFile: false);
Assert.Equal(3, usages.QuickFixes.Count());
Assert.Equal("a.cs", usages.QuickFixes.ElementAt(0).FileName);
Assert.Equal("a.cs", usages.QuickFixes.ElementAt(1).FileName);
Assert.Equal("b.cs", usages.QuickFixes.ElementAt(2).FileName);
usages = await FindUsagesAsync(testFiles, onlyThisFile: true);
Assert.Equal(2, usages.QuickFixes.Count());
Assert.Equal("a.cs", usages.QuickFixes.ElementAt(0).FileName);
Assert.Equal("a.cs", usages.QuickFixes.ElementAt(1).FileName);
}
[Fact]
public async Task DontFindDefinitionInAnotherFile()
{
var testFiles = new[]
{
new TestFile("a.cs",
@"public class Bar : F$$oo {}"),
new TestFile("b.cs", @"
public class Foo {
public Foo Clone() {
return null;
}
}")
};
var usages = await FindUsagesAsync(testFiles, onlyThisFile: true);
Assert.Single(usages.QuickFixes);
Assert.Equal("a.cs", usages.QuickFixes.ElementAt(0).FileName);
}
private Task<QuickFixResponse> FindUsagesAsync(string code, bool excludeDefinition = false)
{
return FindUsagesAsync(new[] { new TestFile("dummy.cs", code) }, false, excludeDefinition);
}
private async Task<QuickFixResponse> FindUsagesAsync(TestFile[] testFiles, bool onlyThisFile, bool excludeDefinition = false)
{
SharedOmniSharpTestHost.AddFilesToWorkspace(testFiles);
var file = testFiles.Single(tf => tf.Content.HasPosition);
var point = file.Content.GetPointFromPosition();
var requestHandler = GetRequestHandler(SharedOmniSharpTestHost);
var request = new FindUsagesRequest
{
Line = point.Line,
Column = point.Offset,
FileName = file.FileName,
Buffer = file.Content.Code,
OnlyThisFile = onlyThisFile,
ExcludeDefinition = excludeDefinition
};
return await requestHandler.Handle(request);
}
}
}
| mit |
anden3/SpaceInvadersVGC | Space Invaders/Bullet.hpp | 295 | #pragma once
#include <VirtualGameConsole/VGCVector.h>
struct Bullet {
Bullet(VGCVector position, VGCVector direction, int damage, int speed) :
position(position), direction(direction), damage(damage), speed(speed) {}
int speed;
int damage;
VGCVector position;
VGCVector direction;
};
| mit |
repne/happyface | HappyFace/Data/InMemoryStore.cs | 952 | using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace HappyFace.Data
{
public class InMemoryStore<TKey, TValue> : IKeyValueStore<TKey, TValue>
{
private readonly ConcurrentDictionary<TKey, TValue> _inner;
public InMemoryStore()
{
_inner = new ConcurrentDictionary<TKey,TValue>();
}
public TValue Get(TKey key)
{
return _inner[key];
}
public void Set(TKey key, TValue value)
{
_inner.AddOrUpdate(key, value, (k, v) => v);
}
public void Delete(TKey key)
{
TValue value;
_inner.TryRemove(key, out value);
}
public bool Exists(TKey key)
{
return _inner.ContainsKey(key);
}
public IEnumerable<TValue> GetAll()
{
return _inner.Select(x => x.Value);
}
}
} | mit |
tmccombs/travis-build | spec/build/addons/mariadb_spec.rb | 1510 | require 'spec_helper'
describe Travis::Build::Addons::Mariadb, :sexp do
let(:script) { stub('script') }
let(:config) { '10.0' }
let(:data) { payload_for(:push, :ruby, config: { addons: { mariadb: config } }) }
let(:sh) { Travis::Shell::Builder.new }
let(:addon) { described_class.new(script, sh, Travis::Build::Data.new(data), config) }
subject { sh.to_sexp }
before { addon.after_prepare }
it { store_example }
it_behaves_like 'compiled script' do
let(:cmds) { ["service mysql stop", "service mysql start"] }
end
it 'sets TRAVIS_MARIADB_VERSION' do
should include_sexp [:export, ['TRAVIS_MARIADB_VERSION', '10.0']]
end
it { should include_sexp [:cmd, "service mysql stop", sudo: true] }
it { should include_sexp [:cmd, "apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 #{Travis::Build::Addons::Mariadb::MARIADB_GPG_KEY}", sudo: true] }
it { should include_sexp [:cmd, 'add-apt-repository "deb http://%p/mariadb/repo/%p/ubuntu $(lsb_release -cs) main"' % [Travis::Build::Addons::Mariadb::MARIADB_MIRROR, config], sudo: true] }
it { should include_sexp [:cmd, "apt-get update -qq", sudo: true] }
it { should include_sexp [:cmd, "apt-get install -o Dpkg::Options::='--force-confnew' mariadb-server libmariadbclient-dev", sudo: true, echo: true, timing: true] }
it { should include_sexp [:cmd, "service mysql start", sudo: true, echo: true, timing: true] }
it { should include_sexp [:cmd, "mysql --version", echo: true] }
end
| mit |
sunlazor/pattern-recognition | genetic-algorithm/Test1Color/Neural/Neuron.cs | 605 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Neural
{
class Neuron
{
double[] x; // входные сигналы
double[] w; // весовые коэффициенты
double w0; // доп вес
double sum; // сумма
double y; // выход аксон
double h;
public Neuron(int neuronCount)
{
x = new double[neuronCount];
w = new double[neuronCount];
}
}
}
| mit |
Pachenko/kaliBackOffice | src/Gbl/BackOfficeBundle/GblBackOfficeBundle.php | 195 | <?php
namespace Gbl\BackOfficeBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class GblBackOfficeBundle extends Bundle
{
public function getParent()
{
return 'FOSUserBundle';
}
}
| mit |
steveafrost/daily-documentary | db/migrate/20170112021122_documentaries.rb | 261 | class Documentaries < ActiveRecord::Migration[5.0]
def change
create_table :documentaries do |t|
t.string :title
t.string :image
t.string :url
t.integer :views
t.boolean :timeline
t.boolean :watchlist
end
end
end
| mit |
eessex/force | src/lib/setup.js | 9432 | //
// Sets up initial project settings, middleware, mounted apps, and
// global configuration such as overriding Backbone.sync and
// populating sharify data
//
import config from "../config"
import _ from "underscore"
import addRequestId from "express-request-id"
import artsyPassport from "@artsy/passport"
import artsyXapp from "@artsy/xapp"
import Backbone from "backbone"
import bodyParser from "body-parser"
import cookieParser from "cookie-parser"
import express from "express"
import favicon from "serve-favicon"
import glob from "glob"
import helmet from "helmet"
import logger from "artsy-morgan"
import path from "path"
import session from "cookie-session"
import sharify from "sharify"
import siteAssociation from "artsy-eigen-web-association"
import superSync from "backbone-super-sync"
import { IpFilter as ipfilter } from "express-ipfilter"
import timeout from "connect-timeout"
import "./setup_sharify"
import cache from "./cache"
import downcase from "./middleware/downcase"
import ensureSSL from "./middleware/ensure_ssl"
import escapedFragmentMiddleware from "./middleware/escaped_fragment"
import hardcodedRedirects from "./middleware/hardcoded_redirects"
import hstsMiddleware from "./middleware/hsts"
import localsMiddleware from "./middleware/locals"
import proxyGravity from "./middleware/proxy_to_gravity"
import proxyReflection from "./middleware/proxy_to_reflection"
import sameOriginMiddleware from "./middleware/same_origin"
import errorHandlingMiddleware from "./middleware/error_handler"
import backboneErrorHelper from "./middleware/backbone_error_helper"
import CurrentUser from "./current_user"
import splitTestMiddleware from "../desktop/components/split_test/middleware"
import marketingModals from "./middleware/marketing_modals"
import { addIntercomUserHash } from "./middleware/intercom"
import compression from "compression"
import { assetMiddleware } from "./middleware/assetMiddleware"
import { unsupportedBrowserCheck } from "lib/middleware/unsupportedBrowser"
import { pageCacheMiddleware } from "lib/middleware/pageCacheMiddleware"
// FIXME: When deploying new Sentry SDK to prod we quickly start to see errors
// like "`CURRENT_USER` is undefined". We need more investigation because this
// only appears in prod, under load, and seems fine on staging.
// import * as Sentry from "@sentry/node"
// Old Sentry SDK
import RavenServer from "raven"
const {
API_REQUEST_TIMEOUT,
API_URL,
APP_TIMEOUT,
CLIENT_ID,
CLIENT_SECRET,
COOKIE_DOMAIN,
DEFAULT_CACHE_TIME,
IP_DENYLIST,
NODE_ENV,
SENTRY_PRIVATE_DSN,
SEGMENT_WRITE_KEY_SERVER,
SESSION_COOKIE_KEY,
SESSION_COOKIE_MAX_AGE,
SESSION_SECRET,
} = config
export default function (app) {
app.set("trust proxy", true)
// Denied IPs
if (IP_DENYLIST && IP_DENYLIST.length > 0) {
app.use(
ipfilter(IP_DENYLIST.split(","), {
allowedHeaders: ["x-forwarded-for"],
log: false,
mode: "deny",
})
)
}
// Timeout middleware
if (process.env.NODE_ENV === "production") {
app.use(timeout(APP_TIMEOUT || "29s"))
}
// Inject sharify data and asset middleware before any app code so that when
// crashing errors occur we'll at least get a 500 error page.
app.use(sharify)
app.use(assetMiddleware())
// Error reporting
if (SENTRY_PRIVATE_DSN) {
RavenServer.config(SENTRY_PRIVATE_DSN).install()
app.use(RavenServer.requestHandler())
}
app.use(compression())
// Blank page used by Eigen for caching web views.
// See: https://github.com/artsy/microgravity-private/pull/1138
app.use(require("../desktop/apps/blank"))
// Make sure we're using SSL and prevent clickjacking
app.use(ensureSSL)
app.use(hstsMiddleware)
if (!NODE_ENV === "test") {
app.use(helmet.frameguard())
}
// Inject UUID for each request into the X-Request-Id header
app.use(addRequestId())
// Override Backbone to use server-side sync, inject the XAPP token,
// add redis caching, and timeout for slow responses.
superSync.timeout = API_REQUEST_TIMEOUT
superSync.cacheClient = cache.client
superSync.defaultCacheTime = DEFAULT_CACHE_TIME
Backbone.sync = function (method, model, options) {
if (options.headers == null) {
options.headers = {}
}
options.headers["X-XAPP-TOKEN"] = artsyXapp.token || ""
return superSync(method, model, options)
}
// Cookie and session middleware
app.use(cookieParser())
app.use(
session({
secret: SESSION_SECRET,
domain: process.env.NODE_ENV === "development" ? "" : COOKIE_DOMAIN,
name: SESSION_COOKIE_KEY,
maxAge: SESSION_COOKIE_MAX_AGE,
secure: process.env.NODE_ENV === "production" || NODE_ENV === "staging",
httpOnly: false,
})
)
// Body parser has to be after proxy middleware for
// node-http-proxy to work with POST/PUT/DELETE
app.use("/api", proxyGravity.api)
app.use(proxyReflection)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
// Passport middleware for authentication.
app.use(
artsyPassport(
_.extend({}, config, {
CurrentUser: CurrentUser,
ARTSY_URL: API_URL,
ARTSY_ID: CLIENT_ID,
ARTSY_SECRET: CLIENT_SECRET,
SEGMENT_WRITE_KEY: SEGMENT_WRITE_KEY_SERVER,
userKeys: [
"collector_level",
"default_profile_id",
"email",
"has_partner_access",
"id",
"lab_features",
"name",
"paddle_number",
"phone",
"roles",
"type",
],
})
)
)
// Add CSRF to the cookie and remove it from the page. This will allows the
// caching on the html.
app.use((req, res, next) => {
res.cookie("CSRF_TOKEN", res.locals.sd.CSRF_TOKEN)
// Clear the embedded CSRF_TOKEN, an alternative method would be to update
// @artsy/passport to make the CSRF_TOKEN optional.
delete res.locals.sd.CSRF_TOKEN
next()
})
// Development servers
if (process.env.NODE_ENV === "development") {
app.use(require("./webpack-dev-server").app)
app.use(
require("stylus").middleware({
src: path.resolve(__dirname, "../desktop"),
dest: path.resolve(__dirname, "../desktop/public"),
})
)
app.use(
require("stylus").middleware({
src: path.resolve(__dirname, "../mobile"),
dest: path.resolve(__dirname, "../mobile/public"),
})
)
}
// Static assets
// Mount static assets from root public folder
app.use(express.static("public"))
// Mount static assets from sub-app /app `public` folders
glob
.sync(`${__dirname}/../{public,{desktop,mobile}/**/public}`)
.forEach(folder => {
app.use(express.static(folder))
})
app.use(
favicon(path.resolve(__dirname, "../mobile/public/images/favicon.ico"))
)
app.use("/(.well-known/)?apple-app-site-association", siteAssociation)
// Redirect requests before they even have to deal with Force routing
app.use(downcase)
app.use(hardcodedRedirects)
app.use(localsMiddleware)
app.use(backboneErrorHelper)
app.use(sameOriginMiddleware)
app.use(escapedFragmentMiddleware)
app.use(logger)
app.use(unsupportedBrowserCheck)
app.use(addIntercomUserHash)
app.use(pageCacheMiddleware)
// Routes for pinging system time and up
app.get("/system/time", (req, res) =>
res.status(200).send({ time: Date.now() })
)
app.get("/system/up", (req, res) => {
res.status(200).send({ nodejs: true })
})
// Sets up mobile marketing signup modal
app.use(marketingModals)
if (NODE_ENV !== "test") {
app.use(splitTestMiddleware)
}
// Setup hot-swap loader. See https://github.com/artsy/express-reloadable
if (process.env.NODE_ENV === "development") {
const { createReloadable } = require("@artsy/express-reloadable")
const mountAndReload = createReloadable(app, require)
app.use((req, res, next) => {
if (res.locals.sd.IS_MOBILE) {
// Mount reloadable mobile app
const mobileApp = mountAndReload(path.resolve("src/mobile"))
mobileApp(req, res, next)
} else {
next()
}
})
// Mount reloadable desktop
mountAndReload(path.resolve("src/desktop"), {
watchModules: [
path.resolve(process.cwd(), "src/v2"),
"@artsy/reaction",
"@artsy/stitch",
"@artsy/palette",
"@artsy/fresnel",
],
})
// In staging or prod, mount routes normally
} else {
app.use((req, res, next) => {
if (res.locals.sd.IS_MOBILE) {
// Mount mobile app
require("../mobile")(req, res, next)
} else {
next()
}
})
// Mount desktop app
app.use(require("../desktop"))
}
// Ensure CurrentUser is set for Artsy Passport
// TODO: Investigate race condition b/t reaction's use of AP
artsyPassport.options.CurrentUser = CurrentUser
// 404 handler
app.get("*", (req, res, next) => {
const err = new Error()
err.status = 404
err.message = "Not Found"
next(err)
})
// Error handling
// FIXME: Investigate issue with new Sentry middleware. See note near import.
// Sentry error handling appear above other middleware
// if (SENTRY_PUBLIC_DSN) {
// app.use(Sentry.Handlers.errorHandler())
// }
// Old Sentry SDK.
if (SENTRY_PRIVATE_DSN) {
app.use(RavenServer.errorHandler())
}
app.use(errorHandlingMiddleware)
}
| mit |
vipinkhushu/Xunbao | checkAnswer.php | 1864 | <?php
session_start();
include('login/credentials.php');
$conn=new mysqli ($DB_SERVER , $DB_USERNAME ,$DB_PASSWORD , $DB_DATABASE);
if($conn->connect_error)
{
die("connection failed: ".$conn->connect_error);
}
$secureans=mysqli_real_escape_string($conn,stripslashes($_POST['answer']));
$ans=strtolower($secureans);
$sql="SELECT `level` FROM `users` WHERE `email`='$_SESSION[user_check]'";
$result= $conn->query($sql);
if($result->num_rows > 0)
{
while($row= $result->fetch_assoc())
{
$level=$row['level'];
break;
}
}
$sql="INSERT INTO `submissions` (`level` , `user` ,`answer`,`time_stamp`) VALUES ('$level' ,'$_SESSION[user_check]', '$ans',now())";
$conn->query($sql);
$a=0;
$level++;
$sql="SELECT `answer` FROM `question` WHERE `level`='$level'";
$result= $conn->query($sql);
if($result->num_rows > 0)
{
while($row= $result->fetch_assoc())
{
if($ans==$row['answer'])
{
$a=1;
}
break;
}
}
if($a==1)
{
$sql = "UPDATE `users` SET `level`='$level',`lastSubmission`=now() WHERE email='$_SESSION[user_check]'";
if ($conn->query($sql) === TRUE) {
//echo "Record updated successfully";
header('location: home.php');
} else {
//echo "Error updating record: " . $conn->error;
header('location: index.php');
}
$conn->close();
}
else if($level==6){
if($ans==$_SESSION["user_check"]){
$sql = "UPDATE `users` SET `level`='$level',`lastSubmission`=now() WHERE email='$_SESSION[user_check]'";
if ($conn->query($sql) === TRUE) {
//echo "Record updated successfully";
header('location: home.php');
} else {
//echo "Error updating record: " . $conn->error;
header('location: index.php');
}
$conn->close();
}else{
header('location: home.php?answer=0');
}
}
else
{
header('location: home.php?answer=0');
//echo $level;
}
?> | mit |
rajasekaran247/school-administrative-services | public/modules/scholarships/scholarships.client.module.js | 135 | 'use strict';
// Use applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('scholarships'); | mit |
jchildren/custom-ghosthack | src/dataStruct.cpp | 602 | //dataStruct.cpp
#include "dataStruct.h"
void inputData::inputData(){
dataSet irisData;
m_filePath[20] = "../data/";
m_fileNames[3] =
{"iris_training.dat",
"iris_test.dat",
"iris_validation.dat"};
//issues here
for (unsigned f=1; f <= 3; ++f){
myFile.open (filePath + fileNames[f].c_str());
for (unsigned i=1; myFile.good(); ++i){
for (unsigned j=1; j <= 4; ++j){
myFile >> irisData.trainingSet.inputs(j, i)
}
for (unsigned j=1; j <= 3; ++j){
myFile >> irisData.trainingSet.inputs(j, i)
}
}
myFile.close();
}
}
| mit |
AoiKuiyuyou/AoikFileTypeAsso | src/aoikfiletypeasso/config_const.py | 682 | # coding: utf-8
from __future__ import absolute_import
#/
CFG_K_VAR_D = 'var_d'
CFG_K_VAR_D_K__EXT_CLS_PREFIX = '_EXT_CLS_PREFIX'
CFG_K_VAR_D_K__EXT_CLS_PREFIX_V_DFT = 'aoikfiletypeasso.'
CFG_K_VAR_D_K__SHELLNEW_REMOVE_UNSPECIFIED = '_SHELLNEW_REMOVE_UNSPECIFIED'
#/
CFG_K_EXT_INFO_D = 'ext_d'
CFG_K_EXT_INFO_K_CLS = 'cls'
CFG_K_EXT_INFO_K_CLS_FRIENDLY_TYPE_NAME = 'clsftn'
CFG_K_EXT_INFO_K_EXT_CONTENT_TYPE = 'extct'
CFG_K_EXT_INFO_K_EXT_PERCEIVED_TYPE = 'extpt'
CFG_K_EXT_INFO_K_CMD_INFO_S = 'cmd_s'
CFG_K_EXT_INFO_K_CMD_OPEN = 'open'
CFG_K_EXT_INFO_K_CMD_EDIT = 'edit'
CFG_K_EXT_INFO_K_CMD_DFT = 'cmd_dft'
CFG_K_EXT_INFO_K_SHELLNEW_INFO = 'new'
CFG_K_EXT_INFO_K_ICON = 'icon'
| mit |
Onikah/binary-codes | config.js | 3966 | // # Ghost Configuration
// Setup your Ghost install for various [environments](http://support.ghost.org/config/#about-environments).
// Ghost runs in `development` mode by default. Full documentation can be found at http://support.ghost.org/config/
var path = require('path'),
config;
config = {
// ### Production
// When running Ghost in the wild, use the production environment.
// Configure your URL and mail settings here
production: {
url: 'http://miningcode.herokuapp.com/',
mail: {},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
server: {
host: '0.0.0.0',
port: process.env.PORT
}
},
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
// Change this to your Ghost blog's published URL.
url: 'http://miningcode.herokuapp.com/',
// Example mail config
// Visit http://support.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
// #### Database
// Ghost supports sqlite3 (default), MySQL & PostgreSQL
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
// #### Server
// Can be host & port (default), or socket
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
},
// #### Paths
// Specify where your content directory lives
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing MySQL
// Used by Travis - Automated testing run through GitHub
'testing-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing pg
// Used by Travis - Automated testing run through GitHub
'testing-pg': {
url: 'http://127.0.0.1:2369',
database: {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
}
};
module.exports = config;
| mit |
Archeia/Kread-Ex-Scripts | Fomar0153/fomar0153_-_equipment_skills.rb | 9317 | =begin
Equipment Skills System Script
by Fomar0153
Version 1.0
----------------------
Notes
----------------------
Requires an AP System if you want characters to
learn skills pernamently.
If using my Custom Equipment Slots script then
make sure this script is above the Equipment Slots Script
and make sure you have the compatability patch.
Allows learning of skills by equipment with the
option to learn skills pernamently.
----------------------
Instructions
----------------------
Set Learn_Skills to false if you want the skills to
only be temporary.
If you can learn skills then you need to set up AP for
each skill you put on an item.
In the notes section put:
AP:n
where n is the ap required to learn pernamently.
Then follow the instructions below about how to add skills
to weapons and armor.
----------------------
Known bugs
----------------------
None
=end
module Equipment_Skills
# If set to false then characters will not
# learn the skills pernamently and you will
# not need an ap system
Learn_Skills = true
Weapons = []
# Add weapon skills in this format
# Weapons[weapon_id] = [skillid1, skillid2]
Weapons[1] = [7,8]
Armors = []
# Add weapon skills in this format
# Armors[armor_id] = [skillid1, skillid2]
Armors[3] = [5]
def self.get_ap_cost(skill_id)
t = $data_skills[skill_id].note
if t.include?("AP:")
ap = /AP:(\d+)/.match(t)
ap = ap[0].split(":")
return ap[1].to_i
end
return 999
end
end
class Game_Actor < Game_Battler
attr_reader :ap
#--------------------------------------------------------------------------
# ● Aliases setup
#--------------------------------------------------------------------------
alias eqskills_setup setup
def setup(actor_id)
eqskills_setup(actor_id)
if Equipment_Skills::Learn_Skills
@ap = []
end
end
#--------------------------------------------------------------------------
# ● Rewrites change_equip
#--------------------------------------------------------------------------
def change_equip(slot_id, item)
return unless trade_item_with_party(item, equips[slot_id])
if equips[slot_id].is_a?(RPG::Weapon)
unless Equipment_Skills::Weapons[equips[slot_id].id] == nil
for skill in Equipment_Skills::Weapons[equips[slot_id].id]
if Equipment_Skills::Learn_Skills
if @ap[skill] == nil
@ap[skill] = 0
end
unless @ap[skill] >= Equipment_Skills.get_ap_cost(skill)
forget_skill(skill)
end
else
forget_skill(skill)
end
end
end
end
if equips[slot_id].is_a?(RPG::Armor)
unless Equipment_Skills::Armors[equips[slot_id].id] == nil
for skill in Equipment_Skills::Armors[equips[slot_id].id]
if Equipment_Skills::Learn_Skills
if @ap[skill] == nil
@ap[skill] = 0
end
unless @ap[skill] >= Equipment_Skills.get_ap_cost(skill)
forget_skill(skill)
end
else
forget_skill(skill)
end
end
end
end
return if item && equip_slots[slot_id] != item.etype_id
@equips[slot_id].object = item
refresh
end
#--------------------------------------------------------------------------
# ● New Method or Rewrites gain_ap
#--------------------------------------------------------------------------
def gain_ap(ap)
if Equipment_Skills::Learn_Skills
for item in self.equips
if item.is_a?(RPG::Weapon)
unless Equipment_Skills::Weapons[item.id] == nil
for skill in Equipment_Skills::Weapons[item.id]
if @ap[skill] == nil
@ap[skill] = 0
end
last_ap = @ap[skill]
@ap[skill] += ap
if last_ap < Equipment_Skills.get_ap_cost(skill) and Equipment_Skills.get_ap_cost(skill) <= @ap[skill]
SceneManager.scene.add_message(actor.name + " learns " + $data_skills[skill].name + ".")
end
end
end
end
if item.is_a?(RPG::Armor)
unless Equipment_Skills::Armors[item.id] == nil
for skill in Equipment_Skills::Armors[item.id]
if @ap[skill] == nil
@ap[skill] = 0
end
@ap[skill] += ap
end
end
end
end
end
end
#--------------------------------------------------------------------------
# ● Aliases refresh
#--------------------------------------------------------------------------
alias eqskills_refresh refresh
def refresh
eqskills_refresh
for item in self.equips
if item.is_a?(RPG::Weapon)
unless Equipment_Skills::Weapons[item.id] == nil
for skill in Equipment_Skills::Weapons[item.id]
learn_skill(skill)
end
end
end
if item.is_a?(RPG::Armor)
unless Equipment_Skills::Armors[item.id] == nil
for skill in Equipment_Skills::Armors[item.id]
learn_skill(skill)
end
end
end
end
# relearn any class skills you may have forgotten
self.class.learnings.each do |learning|
learn_skill(learning.skill_id) if learning.level <= @level
end
end
end
class Window_EquipItem < Window_ItemList
#--------------------------------------------------------------------------
# ● Rewrites col_max
#--------------------------------------------------------------------------
def col_max
return 1
end
#--------------------------------------------------------------------------
# ● Aliases update_help
#--------------------------------------------------------------------------
alias eqskills_update_help update_help
def update_help
eqskills_update_help
if @actor && @status_window
@status_window.refresh(item)
end
end
end
class Scene_Equip < Scene_MenuBase
#--------------------------------------------------------------------------
# ● Rewrites create_item_window
#--------------------------------------------------------------------------
alias eqskills_create_item_window create_item_window
def create_item_window
wx = @status_window.width # Edited line if you need to merge
wy = @slot_window.y + @slot_window.height
ww = @slot_window.width # Edited line if you need to merge
wh = Graphics.height - wy
@item_window = Window_EquipItem.new(wx, wy, ww, wh)
@item_window.viewport = @viewport
@item_window.help_window = @help_window
@item_window.status_window = @status_window
@item_window.actor = @actor
@item_window.set_handler(:ok, method(:on_item_ok))
@item_window.set_handler(:cancel, method(:on_item_cancel))
@slot_window.item_window = @item_window
end
end
class Window_EquipStatus < Window_Base
#--------------------------------------------------------------------------
# ● Rewrites window_height
#--------------------------------------------------------------------------
def window_height
Graphics.height - (2 * line_height + standard_padding * 2)#fitting_height(visible_line_number)
end
#--------------------------------------------------------------------------
# ● Aliases refresh
#--------------------------------------------------------------------------
alias eqskills_refresh refresh
def refresh(item = nil)
eqskills_refresh
contents.clear
draw_actor_name(@actor, 4, 0) if @actor
6.times {|i| draw_item(0, line_height * (1 + i), 2 + i) }
unless item == nil
if item.is_a?(RPG::Weapon)
unless Equipment_Skills::Weapons[item.id] == nil
skills = Equipment_Skills::Weapons[item.id]
end
end
if item.is_a?(RPG::Armor)
unless Equipment_Skills::Armors[item.id] == nil
skills = Equipment_Skills::Armors[item.id]
end
end
unless skills == nil
change_color(normal_color)
draw_text(4, 168, width, line_height, "Equipment Skills")
change_color(system_color)
i = 1
for skill in skills
draw_text(4, 168 + 24 * i, width, line_height, $data_skills[skill].name)
if @actor.ap[skill] == nil
@actor.ap[skill] = 0
end
i = i + 1
if Equipment_Skills::Learn_Skills
draw_current_and_max_values(4, 168 + 24 * i, width - 50, [@actor.ap[skill],Equipment_Skills.get_ap_cost(skill)].min, Equipment_Skills.get_ap_cost(skill), system_color, system_color)
i = i + 1
end
end
end
end
end
end
class Window_EquipSlot < Window_Selectable
#--------------------------------------------------------------------------
# ● Aliases update
#--------------------------------------------------------------------------
alias eqskills_update update
def update
eqskills_update
@status_window.refresh(self.item) if self.active == true
end
end
class Scene_Battle < Scene_Base
#--------------------------------------------------------------------------
# ● New method add_text
#--------------------------------------------------------------------------
def add_message(text)
$game_message.add('\.' + text)
end
end | mit |
algorithmwatch/datenspende | src/scripts/overlay/injection.js | 3785 | import { handleLater, handleRun, handleOverlaySetting } from './index';
// for crawler countdown
var countDownIntervalTime = 10;
var countDownInterval = null;
export function initOverlay() {
createOverlay();
addCloseListener();
addRunButtonListener();
addLaterButtonListener();
addOverlaySettingListener();
}
export function showOverlay() {
var overlayNode = document.querySelector('#crawler__overlay');
overlayNode.style.display = 'block';
// start coutdown for run crawler
startCountDown();
}
export function hideOverlay() {
var overlayNode = document.querySelector('#crawler__overlay');
overlayNode.style.display = 'none';
}
function createOverlay() {
var overlayNode = document.createElement('div');
overlayNode.id = 'crawler__overlay';
overlayNode.style.display = 'none';
var overlayContent = `
<div class='overlay__wrapper'>
<div class='overlay__header'>
<a class='overlay__logo-wrapper' href='//algorithmwatch.org/de/datenspende/' target='_blank'>
<img class='overlay__logo' src=${chrome.runtime.getURL('icons/ds-icon-64.png')} alt='Datenspende Logo'>
<div class='logo__claim'>Datenspende</div>
</a>
<div class='overlay__close-button'>x</div>
</div>
<div class='overlay__content'>
<div class='overlay__countdown'>Die nächste Suchanfrage startet in ${countDownIntervalTime} Sekunden.</div>
<div class='input__wrapper'>
<button id='overlay__run-btn' class='overlay__button'>Sofort starten</button>
<button id='overlay__later-btn' class='overlay__button'>Jetzt nicht</button>
<div></div>
</div>
<div class='input__wrapper'>
<label class="overlay__setting" for='overlay__setting'><input type='checkbox' name='overlay__setting' id='overlay__setting'>Nicht wieder anzeigen.</label>
</div>
</div>
</div>
`
overlayNode.insertAdjacentHTML( 'beforeend', overlayContent );
document.body.appendChild(overlayNode);
}
function addCloseListener() {
var closeBtnEl = document.querySelector('.overlay__close-button');
closeBtnEl.onclick = () => {
handleRun();
setTimeout(closeOverlay, 200);
}
}
function addRunButtonListener() {
var runButton = document.querySelector('#overlay__run-btn');
runButton.onclick = (e) => {
handleRun();
setTimeout(closeOverlay, 200);
}
}
function addLaterButtonListener() {
var laterButton = document.querySelector('#overlay__later-btn');
laterButton.onclick = (e) => {
handleLater();
setTimeout(closeOverlay, 200);
}
}
function addOverlaySettingListener(){
var overlaySetting = document.querySelector('#overlay__setting');
overlaySetting.onclick = (e) => {
handleOverlaySetting(!overlaySetting.checked);
setTimeout(closeOverlay, 200);
overlaySetting.checked = false;
}
}
function closeOverlay() {
var overlayNode = document.querySelector('#crawler__overlay');
hideOverlay();
clearTimer();
}
function startCountDown() {
var countDownNode = document.querySelector('.overlay__countdown');
startTimer(countDownIntervalTime, countDownNode);
}
function startTimer(duration, display) {
var timer = duration;
var seconds = null;
countDownInterval = setInterval(() => {
seconds = timer;
display.textContent = `Die nächste Suchanfrage startet in ${seconds} Sekunden.`;
if (--timer < 0) {
clearTimer();
closeOverlay();
return handleRun();
}
}, 1000);
}
function clearTimer() {
// set to initial value
var countDownNode = document.querySelector('.overlay__countdown');
countDownNode.textContent = `Die nächste Suchanfrage startet in ${countDownIntervalTime} Sekunden.`;
clearInterval(countDownInterval);
}
| mit |
qyxxjd/AndroidBasicProject | classic/src/main/java/com/classic/core/utils/AppInfoUtil.java | 4234 | package com.classic.core.utils;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import java.util.ArrayList;
import java.util.List;
/**
* 应用程序相关信息工具类
*
* @author 续写经典
* @version 1.0 2015/11/4
*/
public final class AppInfoUtil {
private AppInfoUtil() { }
/**
* 获取应用程序信息
*/
public static PackageInfo getPackageInfo(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), 0);
return info;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取应用程序名称
*/
public static String getAppName(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
return context.getResources().getString(labelRes);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取应用程序版本名称
*/
public static String getVersionName(Context context) {
return null == getPackageInfo(context) ? null : getPackageInfo(context).versionName;
}
/**
* 获取应用程序版本号
*/
public static int getVersionCode(Context context) {
return null == getPackageInfo(context) ? null : getPackageInfo(context).versionCode;
}
/**
* 获取应用程序包名
*/
public static String getPackageName(Context context) {
return null == getPackageInfo(context) ? null : getPackageInfo(context).packageName;
}
/**
* 判断当前应用程序是否处于后台
* <pre>需要权限:<uses-permission android:name="android.permission.GET_TASKS" /> </pre>
*/
public static boolean isApplicationToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
/**
* 获取当前运行的进程名
*/
public static String getProcessName(Context context) {
int pid = android.os.Process.myPid();
ActivityManager activityManager = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
/**
* 获取当前运行的所有进程名
*/
public static List<String> getProcessName(Context context, String packageName) {
List<String> list = new ArrayList<String>();
ActivityManager activityManager = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
if (appProcess.processName.startsWith(packageName)) {
list.add(appProcess.processName);
}
}
return list;
}
/**
* 获取当前运行界面的包名
*/
public static String getTopPackageName(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
ComponentName cn = activityManager.getRunningTasks(1).get(0).topActivity;
return cn.getPackageName();
}
}
| mit |
plotly/plotly.py | packages/python/plotly/plotly/validators/histogram/marker/colorbar/_thicknessmode.py | 544 | import _plotly_utils.basevalidators
class ThicknessmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self,
plotly_name="thicknessmode",
parent_name="histogram.marker.colorbar",
**kwargs
):
super(ThicknessmodeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
values=kwargs.pop("values", ["fraction", "pixels"]),
**kwargs
)
| mit |
cgarciae/umvc | Zenject/Main/Scripts/Providers/MonoBehaviourSingletonProvider.cs | 1657 | #if !ZEN_NOT_UNITY3D
using System;
using System.Collections.Generic;
using System.Linq;
using ModestTree;
using UnityEngine;
namespace Zenject
{
public class MonoBehaviourSingletonProvider : ProviderBase
{
Component _instance;
DiContainer _container;
Type _componentType;
GameObject _gameObject;
public MonoBehaviourSingletonProvider(
Type componentType, DiContainer container, GameObject gameObject)
{
Assert.That(componentType.DerivesFrom<Component>());
_gameObject = gameObject;
_componentType = componentType;
_container = container;
}
public override Type GetInstanceType()
{
return _componentType;
}
public override object GetInstance(InjectContext context)
{
Assert.That(_componentType.DerivesFromOrEqual(context.MemberType));
if (_instance == null)
{
Assert.That(!_container.AllowNullBindings,
"Tried to instantiate a MonoBehaviour with type '{0}' during validation. Object graph: {1}", _componentType, context.GetObjectGraphString());
_instance = _gameObject.AddComponent(_componentType);
Assert.That(_instance != null);
_container.Inject(_instance);
}
return _instance;
}
public override IEnumerable<ZenjectResolveException> ValidateBinding(InjectContext context)
{
return BindingValidator.ValidateObjectGraph(_container, _componentType, context, null);
}
}
}
#endif
| mit |
CruxFerryman/eastmoney_postspider | eastmoney_postspider/spiders/eastmoney_spider.py | 3600 | import scrapy
from eastmoney_postspider.items import EastmoneyPostspiderItem
import xlrd
import requests
year_check = 2016
month_now = 10
month_max = 9
month_min = 1
class EastmoneySpider(scrapy.Spider):
# Get Constituent Codes in a workbook
xlsname = "000300cons.xls"
bk = xlrd.open_workbook(xlsname)
shxrange = range(bk.nsheets)
try:
sh = bk.sheet_by_name("20160613")
except:
print("No sheet in %s named 20160613") % xlsname
nrows = sh.nrows
ncols = sh.ncols
codes = []
for i in range(1, nrows):
code = sh.row_values(i, start_colx=0, end_colx=1)
codes.append(code)
# Configure a scrapy spider
name = "eastmoney_test"
allowed_domains = ["guba.eastmoney.com"]
url_prefix = "http://guba.eastmoney.com/list,"
url_suffix = ",f_1.html"
start_urls = []
for code in codes:
start_url = url_prefix + str(code)[3:-2] + url_suffix
start_urls.append(start_url)
# Scrap websites and save useful values to items
def parse(self, response):
item = EastmoneyPostspiderItem()
pagenum = response.url.split('f_')[1][:-5]
res = response.status
pagenum = int(pagenum) + 1
baseurl = 'http://guba.eastmoney.com'
newurl = response.url.split('f_')[0] + 'f_' + str(pagenum) + '.html'
for sel in response.xpath('//div[@id="articlelistnew"]'):
code_tmp = response.xpath('//span[@id="stockif"]/span/@data-popstock').extract()
title_tmp = sel.xpath('div[starts-with(@class,"articleh")]/span[@class="l3"]/a[1]/text()').extract()
writer_tmp = sel.xpath('div[starts-with(@class,"articleh")]/span[@class="l4"]/a[1]/text()').extract()
read_tmp = sel.xpath('div[starts-with(@class,"articleh")]/span[@class="l1"]/text()').extract()
comment_tmp = sel.xpath('div[starts-with(@class,"articleh")]/span[@class="l2"]/text()').extract()
date_tmp = sel.xpath('div[starts-with(@class,"articleh")]/span[@class="l6"]/text()').extract()
href_tmp = sel.xpath('div[starts-with(@class,"articleh")]/span[@class="l3"]/a[1]/@href').extract()
postpages_url = []
for href in href_tmp:
if href[:1] == '/':
postpage_url = baseurl + href
else:
postpage_url = baseurl + '/' + href
postpages_url.append(postpage_url)
# Get post dates in their detail pages
years = []
key1 = '<div class="zwfbtime">'
key2 = '<div id="zwconttbtns">'
for url in postpages_url:
# index = postpages_url.index(url)
r = requests.get(url)
cont = r.content
fa = cont.find(key1)
fb = cont.find(key2)
year = cont[fa:fb].split('-')[0][-4:]
month = cont[fa:fb].split('-')[1]
years.append(year)
item['year'] = years
item['code'] = code_tmp
item['title'] = title_tmp
item['writer'] = writer_tmp
item['read'] = read_tmp
item['comment'] = comment_tmp
item['date'] = date_tmp
item['url'] = postpages_url
# Check the most recent post date in a page, double check when insert into sql table
if int(years[1]) == year_check:
if (int(month) <= month_max) and (int(month) >= month_min):
yield item
yield scrapy.Request(newurl, self.parse, dont_filter=True)
| mit |
nodule/express | nodes/patch/node.js | 34 | output = [$.app, 'patch', $.path]
| mit |
reevoo/gem-miner | lib/gem-miner/miner.rb | 2758 | require 'base64'
require 'octokit'
require 'gem-miner/github_client'
require 'gem-miner/logger'
module GemMiner
class Miner
include Logger
GEMFILE_REGEX = /gem[\s]+([^\n\;]+)/
GEMSPEC_REGEX = /dependency[\s]+([^\n\;]+)/
def self.gems_for(github_search_query, github_token)
new(github_search_query, GithubClient.new(github_token)).gems
end
def initialize(github_search_query, github_client = GithubClient.new)
@github_search_query = github_search_query
@github_client = github_client
end
# A hash of gems and the repositories they are used in:
#
# {
# "pry '~> 1'" => ['reevoo/flakes', 'reevoo/gem-miner'],
# ...
# }
def gems
@gems ||= collect_gems!
end
private
# Collects gem specifications from Gemfiles and Gemspecs.
# Returns a hash of gems and the repositories they are used in:
#
# {
# "pry '~> 1'" => ['reevoo/flakes', 'reevoo/gem-miner'],
# ...
# }
def collect_gems!
gemfiles = parse_sources('Gemfile', GEMFILE_REGEX)
gemspecs = parse_sources('gemspec', GEMSPEC_REGEX)
gems = merge_hashes(gemfiles, gemspecs)
# Invert the PROJECT => [GEMS] hash to a GEM => [PROJECTS] hash
gems = invert_hash_of_arrays(gems)
# Sort it
gems = gems.sort.to_h
end
# Collects all of the gemfiles for all Reevoo repositories.
# Returns a dictionary with the gem as the key and an array of repositories
# as values.
def parse_sources(filename, regex)
results = search("filename:#{filename} #{@github_search_query}")
log "Parsing #{results.count} #{filename}s"
files = results.reduce({}) do |memo, result|
# We might have more than one dep file in a repository...
memo[result[:name]] ||= []
memo[result[:name]] += extract_deps(result[:content], regex)
log '.'
memo
end
log "done!\n"
files
end
def extract_deps(file, regex)
file.gsub(/\"/, '\'').scan(regex).flatten
end
def search(query)
@github_client.files(query)
end
# Merge two hashes of lists
#
# h1 = { a: [1, 2, 3], b: [2, 4] }
# h2 = { b: [1, 3], c: [1, 2, 3] }
# merge_hashes(h1, h2) # => { a: [1, 2, 3], b: [1, 2, 3, 4], c: [1, 2, 3] }
#
# From http://stackoverflow.com/questions/11171834
def merge_hashes(hash1, hash2)
hash1.merge(hash2) { |key, oldval, newval| (oldval | newval) }
end
# Converts a hash of the form A => [Bs] to B => [As]
def invert_hash_of_arrays(hash)
hash.reduce({}) do |memo, (key, values)|
values.each do |v|
memo[v] ||= []
memo[v] << key
end
memo
end
end
end
end
| mit |
MATize/smokee | smokee-parent/smokee-core/src/main/java/at/mse/walchhofer/smokee/interception/SmokEETransactionInterceptorBinding.java | 576 | package at.mse.walchhofer.smokee.interception;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;
@Inherited
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ METHOD, FIELD, TYPE })
public @interface SmokEETransactionInterceptorBinding {
}
| mit |
clair-design/clair | packages/react/src/components/Icon/lib/Book/index.tsx | 264 | import { IconContainer, IconProps } from "@components/Icon/lib/Container";
import { Book } from "@clair/icons";
import { getStyleMergedComponent } from "@src/utils";
export const IconBook = getStyleMergedComponent<IconProps>({
template: Book
})(IconContainer);
| mit |
MrSlide/project-unum | gulp/lint.js | 444 | 'use strict'
const gulp = require('gulp')
const standard = require('gulp-standard')
/**
* Lint the JavaScript files using Standard
*/
gulp.task('lintJs', function (cb) {
return gulp.src([
'./src/**/*.js',
'./app/**/*.js',
'./gulp/**/*.js',
'./gulpfile.js',
'!./app/static/**/*'
])
.pipe(standard())
.pipe(standard.reporter('default', {
breakOnError: true,
breakOnWarning: true,
quiet: false
}))
})
| mit |
quyse/inanity | deps/freetype/configure.js | 1396 | /* configure for building freetype
*/
exports.configureCompiler = function(objectFile, compiler) {
// object files: <conf>/module.object
var a = /^([^\/]+)\/([^\/\.]+)\.([^\/\.]+)$/.exec(objectFile);
compiler.configuration = a[1];
compiler.setSourceFile('repo/src/' + a[2] + '/' + a[3] + '.c');
compiler.cppMode = false;
compiler.addIncludeDir('repo/include');
compiler.addIncludeDir('../zlib');
compiler.addMacro('FT2_BUILD_LIBRARY');
compiler.addMacro('FT_CONFIG_OPTION_SYSTEM_ZLIB');
compiler.strict = false;
};
var modules = {
autofit: "autofit",
base: "ftbase ftdebug ftinit ftmm ftsystem ftbitmap ftglyph",
bdf: "bdf",
bzip2: "ftbzip2",
cache: "ftcache",
cff: "cff",
cid: "type1cid",
gxvalid: "gxvalid",
gzip: "ftgzip",
lzw: "ftlzw",
otvalid: "otvalid",
pcf: "pcf",
pfr: "pfr",
psaux: "psaux",
pshinter: "pshinter",
psnames: "psnames",
raster: "raster",
sfnt: "sfnt",
smooth: "smooth",
truetype: "truetype",
type1: "type1",
type42: "type42",
winfonts: "winfnt"
};
exports.configureComposer = function(libraryFile, composer) {
// library files: <conf>/library
var a = /^(([^\/]+)\/)([^\/]+)$/.exec(libraryFile);
var confDir = a[1];
composer.configuration = a[2];
for (var module in modules) {
var objects = modules[module].split(' ');
for(var i = 0; i < objects.length; ++i)
composer.addObjectFile(confDir + module + '.' + objects[i]);
}
};
| mit |
huazh/node-opcua | lib/client/client_publish_engine.js | 9015 | "use strict";
require("requirish")._(module);
var _ = require("underscore");
var subscription_service = require("lib/services/subscription_service");
var assert = require("better-assert");
var debugLog = require("lib/misc/utils").make_debugLog(__filename);
//xx var debugLog = console.log;
/**
* A client side implementation to deal with publish service.
*
* @class ClientSidePublishEngine
*
* @param session {ClientSession} - the client session
* @param options {object} - the client session
* @constructor
*
* The ClientSidePublishEngine encapsulates the mechanism to
* deal with a OPCUA Server and constantly sending PublishRequest
* The ClientSidePublishEngine also performs notification acknowledgements.
* Finally, ClientSidePublishEngine dispatch PublishResponse to the correct
* Subscription id callback
*/
function ClientSidePublishEngine(session) {
assert(session instanceof Object);
this.session = session;
this.subscriptionAcknowledgements = [];
this.subscriptionIdFuncMap = {};
this.timeoutHint = 10000; // 10 s by default
}
/**
* @method acknowledge_notification
* @param subscriptionId {Number} the subscription id
* @param sequenceNumber {Number} the sequence number
*/
ClientSidePublishEngine.prototype.acknowledge_notification = function (subscriptionId, sequenceNumber) {
this.subscriptionAcknowledgements.push({
subscriptionId: subscriptionId,
sequenceNumber: sequenceNumber
});
};
ClientSidePublishEngine.prototype.cleanup_acknowledgment_for_subscription = function (subscriptionId) {
this.subscriptionAcknowledgements = this.subscriptionAcknowledgements.filter(function (a) {
return a.subscriptionId !== subscriptionId;
});
};
/**
* @method send_publish_request
*/
ClientSidePublishEngine.prototype.send_publish_request = function () {
var self = this;
setImmediate(function () {
if (!self.session) {
// session has been terminated
return;
}
self._send_publish_request();
});
};
ClientSidePublishEngine.prototype._send_publish_request = function () {
debugLog("sending publish request".yellow);
var self = this;
assert(self.session, "ClientSidePublishEngine terminated ?");
var subscriptionAcknowledgements = self.subscriptionAcknowledgements;
self.subscriptionAcknowledgements = [];
// as started in the spec (Spec 1.02 part 4 page 81 5.13.2.2 Function DequeuePublishReq())
// the server will dequeue the PublishRequest in first-in first-out order
// and will validate if the publish request is still valid by checking the timeoutHint in the RequestHeader.
// If the request timed out, the server will send a Bad_Timeout service result for the request and de-queue
// another publish request.
//
// in Part 4. page 144 Request Header the timeoutHint is described this way.
// timeoutHint UInt32 This timeout in milliseconds is used in the Client side Communication Stack to
// set the timeout on a per-call base.
// For a Server this timeout is only a hint and can be used to cancel long running
// operations to free resources. If the Server detects a timeout, he can cancel the
// operation by sending the Service result Bad_Timeout. The Server should wait
// at minimum the timeout after he received the request before cancelling the operation.
// The value of 0 indicates no timeout.
// In issue#40 (MonitoredItem on changed not fired), we have found that some server might wrongly interpret
// the timeoutHint of the request header ( and will bang a Bad_Timeout regardless if client send timeoutHint=0)
// as a work around here , we force the timeoutHint to be set to a suitable value.
//
// see https://github.com/node-opcua/node-opcua/issues/141
// This suitable value shall be at least the time between two keep alive signal that the server will send.
// (i.e revisedLifetimeCount * revisedPublishingInterval)
var publish_request = new subscription_service.PublishRequest({
requestHeader: {timeoutHint: self.timeoutHint}, // see note
subscriptionAcknowledgements: subscriptionAcknowledgements
});
self.session.publish(publish_request, function (err, response) {
if (err) {
debugLog("xxxxxxxxxxxxxxxxxxx ClientSidePublishEngine.prototype._send_publish_request ".red, err.message.yellow);
} else {
debugLog("xxxxxxxxxxxxxxxxxxx ClientSidePublishEngine.prototype._send_publish_request ".cyan);
self._receive_publish_response(response);
}
});
};
ClientSidePublishEngine.prototype.terminate = function () {
this.session = null;
};
/**
* the number of active subscriptions managed by this publish engine.
* @property subscriptionCount
* @type {Number}
*/
ClientSidePublishEngine.prototype.__defineGetter__("subscriptionCount", function () {
var self = this;
return Object.keys(self.subscriptionIdFuncMap).length;
});
ClientSidePublishEngine.publishRequestCountInPipeline = 5;
/**
* @method registerSubscriptionCallback
*
* @param subscriptionId
* @param timeoutHint
* @param {Function} callback
*/
ClientSidePublishEngine.prototype.registerSubscriptionCallback = function (subscriptionId, timeoutHint, callback) {
var self = this;
assert(!self.subscriptionIdFuncMap.hasOwnProperty(subscriptionId)); // already registered ?
assert(_.isFinite(timeoutHint));
self.subscriptionIdFuncMap[subscriptionId] = callback;
self.timeoutHint = Math.max(self.timeoutHint,timeoutHint);
// Spec 1.02 part 4 5.13.5 Publish
// [..] in high latency networks, the Client may wish to pipeline Publish requests
// to ensure cyclic reporting from the Server. Pipelining involves sending more than one Publish
// request for each Subscription before receiving a response. For example, if the network introduces a
// delay between the Client and the Server of 5 seconds and the publishing interval for a Subscription
// is one second, then the Client will have to issue Publish requests every second instead of waiting for
// a response to be received before sending the next request.
self.send_publish_request();
// send more than one publish request to server to cope with latency
for (var i = 0; i < ClientSidePublishEngine.publishRequestCountInPipeline - 1; i++) {
self.send_publish_request();
}
};
/**
* @method unregisterSubscriptionCallback
*
* @param subscriptionId
*/
ClientSidePublishEngine.prototype.unregisterSubscriptionCallback = function (subscriptionId) {
var self = this;
if (subscriptionId === "pending") {
console.log("special subscriptionId here");
}
assert(self.subscriptionIdFuncMap.hasOwnProperty(subscriptionId));
delete self.subscriptionIdFuncMap[subscriptionId];
};
ClientSidePublishEngine.prototype._receive_publish_response = function (response) {
debugLog("receive publish response".yellow.bold);
var self = this;
// the id of the subscription sending the notification message
var subscriptionId = response.subscriptionId;
// the sequence numbers available in this subscription
// for retransmission and not acknowledged by the client
// -- var available_seq = response.availableSequenceNumbers;
// has the server more notification for us ?
// -- var moreNotifications = response.moreNotifications;
var notificationMessage = response.notificationMessage;
// notificationMessage.sequenceNumber
// notificationMessage.publishTime
// notificationMessage.notificationData[]
notificationMessage.notificationData = notificationMessage.notificationData || [];
if (notificationMessage.notificationData.length !== 0) {
self.acknowledge_notification(subscriptionId, notificationMessage.sequenceNumber);
}
//else {
// this is a keep-alive notification
// in this case , we shall not acknowledge notificationMessage.sequenceNumber
// which is only an information of what will be the future sequenceNumber.
//}
var callback_for_subscription = self.subscriptionIdFuncMap[subscriptionId];
if (callback_for_subscription && self.session !== null) {
// feed the server with a new publish Request to the server
self.send_publish_request();
// delegate notificationData to the subscription callback
callback_for_subscription(notificationMessage.notificationData, notificationMessage.publishTime);
} else {
debugLog(" ignoring notificationMessage", notificationMessage, " for subscription", subscriptionId);
debugLog(" because there is no callback for the subscription.");
debugLog(" or because there is no session for the subscription (session terminated ?).");
}
};
exports.ClientSidePublishEngine = ClientSidePublishEngine;
| mit |
renzon/scripts3tarde | backend/test/soma_tests.py | 332 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from unittest import TestCase
def soma(param, param1):
return param+param1
class SomaTests(TestCase):
def testes_soma(self):
resultado = soma(1, 2)
self.assertEqual(3, resultado)
self.assertEqual(3.5, soma(0.5, 3))
| mit |
leixdd/CATIA | app/Http/Controllers/post_admin.php | 3669 | <?php
namespace CATIA\Http\Controllers;
use Illuminate\Http\Request;
use CATIA\Http\Requests;
use CATIA\post;
use CATIA\Commands\PostCommand;
use CATIA\Http\Requests\PostRequest;
use CATIA\Commands\PostUpdate;
use CATIA\Commands\Deleterpost;
class post_admin extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$post_list = post::orderBy('is_main', 'desc')->get();
return view('post/post_list', compact('post_list'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('post/post_add');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(PostRequest $request)
{
$applicant_image = $request->file('thumb');
if ($applicant_image) {
$applicant_image_filename = '/images/CMS/thumbnails/' . $applicant_image->getClientOriginalName();
$applicant_image->move(public_path('images/CMS/thumbnails/'), $applicant_image_filename);
} else {
$applicant_image_filename = null;
}
//list commands
$post = new PostCommand(0, $request->input('title'),$request->input('cnt'),$request->input('user'),$applicant_image_filename, $request->input('announcement'));
$this->dispatch($post);
return \Redirect::route('adminpanel.index')
->with('message', 'Posted');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$post_list = post::find($id);
return $post_list;
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$post_single = post::find($id);
return view('post/post_edit', compact('post_single'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(PostRequest $request, $id)
{
$applicant_image = $request->file('thumb');
$current_applicant_image = post::find($id)->post_thumb;
if ($applicant_image) {
$applicant_image_filename = '/images/CMS/thumbnails/' . $applicant_image->getClientOriginalName();
$applicant_image->move(public_path('/images/CMS/thumbnails/'), $applicant_image_filename);
} else {
$applicant_image_filename = $current_applicant_image;
}
$updatePost = new PostUpdate($id, $request->input('title'),$request->input('cnt'),$request->input('user'),$applicant_image_filename,$request->input('announcement'));
$this->dispatch($updatePost);
return \Redirect::route('adminpanel.index')
->with('message', 'The Post was edited');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$delete_command = new Deleterpost($id);
$this->dispatch($delete_command);
return \Redirect::route('adminpanel.index')
->with('message', 'Post #' . $id . ' already deleted to the list');
}
}
| mit |
SentimensRG/ctx | ctx_test.go | 2846 | package ctx
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestBindFunc(t *testing.T) {
f := BindFunc(func(d Doner) { panic("called") })
assert.Panics(t, func() { f.Bind(nil) }, "called")
}
func TestC(t *testing.T) {
ch := make(chan struct{})
close(ch)
select {
case <-C(ch).Done():
default:
t.Error("doner did not reflect closed state of channel")
}
}
func TestDefer(t *testing.T) {
ch := make(chan struct{})
close(ch)
chT := make(chan struct{})
Defer(C(ch), func() { close(chT) })
select {
case <-chT:
case <-time.After(time.Millisecond):
t.Error("deferred function was not called")
}
}
func TestLink(t *testing.T) {
ch := make(chan struct{})
close(ch)
select {
case <-Link(C(ch), C(nil)):
case <-time.After(time.Millisecond):
t.Error("link did not fire despite a Doner having fired")
}
}
func TestJoin(t *testing.T) {
ch := make(chan struct{})
close(ch)
c, cancel := context.WithCancel(context.Background())
d := Join(C(ch), c)
select {
case <-d.Done():
t.Error("premature firing of join-Doner")
default:
}
cancel()
select {
case <-d.Done():
case <-time.After(time.Millisecond):
t.Error("join-Doner did not fire despite all constituent Doners having fired")
}
}
func TestCtx(t *testing.T) {
ch := make(chan struct{})
c := AsContext(C(ch)) // should not panic
t.Run("Deadline", func(t *testing.T) {
d, ok := c.Deadline()
assert.Zero(t, d)
assert.False(t, ok)
})
t.Run("Value", func(t *testing.T) {
// should always be nil
assert.Nil(t, c.Value(struct{}{}))
})
t.Run("Err", func(t *testing.T) {
assert.NoError(t, c.Err())
close(ch)
assert.EqualError(t, c.Err(), context.Canceled.Error())
})
}
func TestWithCancel(t *testing.T) {
d, cancel := WithCancel(C(make(chan struct{})))
t.Run("NotCancelled", func(t *testing.T) {
select {
case <-d.Done():
t.Error("Doner expired by default")
default:
}
})
t.Run("Cancelled", func(t *testing.T) {
cancel()
select {
case <-d.Done():
default:
t.Error("not cancelled")
}
})
t.Run("IdempotentCancel", func(t *testing.T) {
cancel() // subsequent calls to cancel should not panic
})
t.Run("CloseUnderlyingDoner", func(t *testing.T) {
ch := make(chan struct{})
d, cancel := WithCancel(C(ch))
defer cancel() // should not panic
close(ch)
select {
case <-d.Done():
case <-time.After(time.Millisecond):
t.Error("not cancelled")
}
})
}
func TestTick(t *testing.T) {
ch := make(chan struct{})
tc := Tick(C(ch))
t.Run("RecvWhileOpen", func(t *testing.T) {
for i := 0; i < 10; i++ {
select {
case <-tc:
case <-time.After(time.Millisecond):
t.Error("no tick")
}
}
})
t.Run("BlockWhenClose", func(t *testing.T) {
close(ch)
select {
case <-tc:
t.Error("failed to stop ticking")
default:
}
})
}
| mit |
haifani/asiik | application/controllers/Penyulang.php | 4978 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Penyulang extends CI_Controller {
function __construct() {
parent::__construct();
if ($this->session->userdata('is_logged_in') != TRUE && $this->uri->segment(1) != 'Auth' && $this->session->userdata('id_level_user') == '5' ){
$this -> session -> set_flashdata('info_login', 'Anda tidak mempunyai otentifikasi ke halaman ini. Silahkan login ulang untuk mengakses sesuai dengan hak otentifikasi anda!');
redirect('Auth');
}
date_default_timezone_set("Asia/Jakarta");
$this->load->model('M_penyulang', 'penyulang', true);
}
public function index()
{
//page info
$data['dashboardtitle']= 'Penyulang';
$data['pe_active']= 'active';
$data['pe_open']= 'open';
$data['pe_sub']= 'active';
$data['page']= '';
$data['sub_page']= 'Penyulang';
$data['activated_bread']= 'active';
$this->load->view('Penyulang/data',$data);
}
public function fetch_data()
{
$list = $this->penyulang->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $penyulang) {
$no++;
$row = array();
$row[] = $penyulang->nama_rayon;
$row[] = $penyulang->nama_penyulang;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_penyulang('."'".$penyulang->kode_penyulang."'".')"><i class="glyphicon glyphicon-pencil"></i></a>
<a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_penyulang('."'".$penyulang->kode_penyulang."'".')"><i class="glyphicon glyphicon-trash"></i></a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->penyulang->count_all(),
"recordsFiltered" => $this->penyulang->count_filtered(),
"data" => $data,
);
//output to json format
//echo json_encode($output);
$this->output ->set_content_type('application/json')->set_output(json_encode($output));
}
public function ajax_edit($id)
{
$data = $this->penyulang->get_by_id($id);
$this->output ->set_content_type('application/json')->set_output(json_encode($data));
}
public function ajax_add()
{
$this->_validate();
$data = array(
'nama_penyulang' => $this->input->post('nama_penyulang'),
'kode_rayon' => $this->input->post('kode_rayon')
);
$insert = $this->penyulang->save($data);
$this->output ->set_content_type('application/json')->set_output(json_encode(array("status" => TRUE)));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'nama_penyulang' => $this->input->post('nama_penyulang'),
'kode_rayon' => $this->input->post('kode_rayon')
);
$this->penyulang->update(array('kode_penyulang' => $this->input->post('id_penyulang')), $data);
$this->output ->set_content_type('application/json')->set_output(json_encode(array("status" => TRUE)));
}
public function ajax_delete($id)
{
$this->penyulang->delete_by_id($id);
$this->output ->set_content_type('application/json')->set_output(json_encode(array("status" => TRUE)));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('kode_rayon') == '')
{
$data['inputerror'][] = 'kode_rayon';
$data['error_string'][] = 'Rayon Harus di isi';
$data['status'] = FALSE;
}
if($this->input->post('nama_penyulang') == '')
{
$data['inputerror'][] = 'nama_penyulang';
$data['error_string'][] = 'Nama Penyulang Harus di isi';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo json_encode($data);
exit();
}
}
public function buildPenyulang(){
//run the query for the cities we specified earlier
$districtData['nama']=$this->penyulang->fetch_penyulang();
$output = null;
$output .= "<option value='' selected >--Pilih Penyulang--</option>";
foreach ($districtData['nama'] as $row)
{
//here we build a dropdown item line for each query result
$output .= "<option value='".$row->kode_penyulang."'> ".$row->nama_penyulang."</option>";
}
$this->output->set_output($output);
}
}
| mit |
aspose-tasks/Aspose.Tasks-for-.NET | Demos/src/Aspose.Tasks.Live.Demos.UI/Controllers/AsposeTasksMetadataController.cs | 6917 | using Aspose.Tasks;
using Aspose.Tasks.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Aspose.Tasks.Live.Demos.UI.Models;
using System.Reflection;
namespace Aspose.Tasks.Live.Demos.UI.Controllers
{
/// <summary>
/// AsposeTasksMetadataController class
/// </summary>
public class AsposeTasksMetadataController : TasksBase
{
///<Summary>
/// Properties method to get metadata
///</Summary>
///
[HttpPost]
public HttpResponseMessage Properties(string folderName, string fileName)
{
try
{
Project project = new Project(Path.Combine(Config.Configuration.WorkingDirectory, folderName, fileName));
return Request.CreateResponse(HttpStatusCode.OK, new PropertiesResponse(project));
}
catch (Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
}
}
///<Summary>
/// Properties method. Should include 'FileName', 'id', 'properties' as params
///</Summary>
[HttpPost]
[AcceptVerbs("GET", "POST")]
public Response Download()
{
Aspose.Tasks.Live.Demos.UI.Models.License.SetAsposeTasksLicense();
Opts.AppName = "MetadataApp";
Opts.MethodName = "Download";
try
{
var request = Request.Content.ReadAsAsync<JObject>().Result;
Opts.FileName = Convert.ToString(request["FileName"]);
Opts.ResultFileName = Opts.FileName;
Opts.FolderName = Convert.ToString(request["id"]);
Project project = new Project(Opts.WorkingFileName);
var pars = request["properties"]["BuiltIn"].ToObject<List<DocProperty>>();
SetBuiltInProperties(project, pars);
pars = request["properties"]["Custom"].ToObject<List<DocProperty>>();
SetCustomProperties(project, pars);
return Process((inFilePath, outPath, zipOutFolder) => { project.Save(outPath, Aspose.Tasks.Saving.SaveFileFormat.MPP); });
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new Response
{
Status = "500 " + ex.Message,
StatusCode = 500
};
}
}
//<Summary>
// Properties method.Should include 'FileName', 'id' as params
//</Summary>
[HttpPost]
[AcceptVerbs("GET", "POST")]
public Response Clear()
{
Opts.AppName = "MetadataApp";
Opts.MethodName = "Clear";
try
{
var request = Request.Content.ReadAsAsync<JObject>().Result;
Opts.FileName = Convert.ToString(request["FileName"]);
Opts.ResultFileName = Opts.FileName;
Opts.FolderName = Convert.ToString(request["id"]);
Project project = new Project(Opts.WorkingFileName);
project.CustomProps.Clear();
return Process((inFilePath, outPath, zipOutFolder) => { project.Save(outPath, Aspose.Tasks.Saving.SaveFileFormat.MPP); });
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new Response
{
Status = "500 " + ex.Message,
StatusCode = 500
};
}
}
/// <summary>
/// SetBuiltInProperties
/// </summary>
/// <param name="workbook"></param>
/// <param name="pars"></param>
private void SetBuiltInProperties(Project project, List<DocProperty> pars)
{
var builtin = project.BuiltInProps;
var t = builtin.GetType();
foreach (var par in pars)
{
var prop = t.GetProperty(par.Name);
if (prop != null)
switch (par.Type)
{
case PropertyType.String:
prop.SetValue(builtin, Convert.ToString(par.Value));
break;
case PropertyType.Boolean:
prop.SetValue(builtin, Convert.ToBoolean(par.Value));
break;
case PropertyType.Number:
prop.SetValue(builtin, Convert.ToInt32(par.Value));
break;
case PropertyType.DateTime:
prop.SetValue(builtin, Convert.ToDateTime(par.Value));
break;
case PropertyType.Double:
prop.SetValue(builtin, Convert.ToDouble(par.Value));
break;
}
}
}
/// <summary>
/// SetCustomProperties
/// </summary>
/// <param name="workbook"></param>
/// <param name="pars"></param>
private void SetCustomProperties(Project project, List<DocProperty> pars)
{
var custom = project.CustomProps;
custom.Clear();
foreach (var par in pars)
switch (par.Type)
{
case PropertyType.String:
custom.Add(par.Name, Convert.ToString(par.Value));
break;
case PropertyType.Boolean:
custom.Add(par.Name, Convert.ToBoolean(par.Value));
break;
case PropertyType.Number:
custom.Add(par.Name, Convert.ToInt32(par.Value));
break;
case PropertyType.DateTime:
custom.Add(par.Name, Convert.ToDateTime(par.Value));
break;
case PropertyType.Double:
custom.Add(par.Name, Convert.ToDouble(par.Value));
break;
}
}
/// <summary>
/// PropertiesResponse
/// </summary>
private class PropertiesResponse
{
//public BuiltInProjectPropertyCollection BuiltIn { get; set; }
//public CustomProjectPropertyCollection Custom { get; set; }
public List<DocProperty> BuiltIn { get; set; }
public List<DocProperty> Custom { get; set; }
public PropertiesResponse(Project project)
{
BuiltIn = new List<DocProperty>();
Custom = new List<DocProperty>();
foreach (var obj in project.BuiltInProps)
{
DocProperty metadataObject = new DocProperty
{
Name = obj.Name,
Value = obj.Value,
Type = PropertyType.String
};
BuiltIn.Add(metadataObject);
}
foreach (var obj in project.CustomProps)
{
string value = obj.Type.ToString();
PropertyType propertyType = PropertyType.None;
switch (value.ToLower())
{
case "string":
propertyType = PropertyType.String;
break;
case "datetime":
propertyType = PropertyType.DateTime;
break;
case "number":
propertyType = PropertyType.Number;
break;
case "boolean":
propertyType = PropertyType.Boolean;
break;
}
DocProperty metadataObject = new DocProperty
{
Name = obj.Name,
Value = obj.Value,
Type = propertyType
};
Custom.Add(metadataObject);
}
}
}
/// <summary>
/// The same fields as in DocumentProperty
/// </summary>
private class DocProperty
{
public string Name { get; set; }
public object Value { get; set; }
public PropertyType Type { get; set; }
}
public enum PropertyType
{
/// <summary>The property is a None value.</summary>
None,
/// <summary>The property is a String value.</summary>
String,
/// <summary>The property is a Date Time Value.</summary>
DateTime,
/// <summary>The property is an integer number.</summary>
Number,
/// <summary>The property is a Boolean.</summary>
Boolean,
/// <summary>The property is a Double.</summary>
Double,
}
}
}
| mit |
AFC-Gladiators/gladiators-site | wp-content/themes/engrave-lite/admin/main/options/00.variables.php | 9485 | <?php
/**
* Theme setup functions.
*
* @package ThinkUpThemes
*/
//----------------------------------------------------------------------------------
// ADD CUSTOM VARIABLES
//----------------------------------------------------------------------------------
// Add global variables used in Redux framework
function thinkup_reduxvariables() {
// Fetch options stored in $data.
global $thinkup_redux_variables;
// 1.1. General settings.
$GLOBALS['thinkup_general_logoswitch'] = thinkup_var ( 'thinkup_general_logoswitch' );
$GLOBALS['thinkup_general_logolink'] = thinkup_var ( 'thinkup_general_logolink', 'url' );
$GLOBALS['thinkup_general_logolinkretina'] = thinkup_var ( 'thinkup_general_logolinkretina', 'url' );
$GLOBALS['thinkup_general_sitetitle'] = thinkup_var ( 'thinkup_general_sitetitle' );
$GLOBALS['thinkup_general_sitedescription'] = thinkup_var ( 'thinkup_general_sitedescription' );
$GLOBALS['thinkup_general_faviconlink'] = thinkup_var ( 'thinkup_general_faviconlink', 'url' );
$GLOBALS['thinkup_general_layout'] = thinkup_var ( 'thinkup_general_layout' );
$GLOBALS['thinkup_general_sidebars'] = thinkup_var ( 'thinkup_general_sidebars' );
$GLOBALS['thinkup_general_fixedlayoutswitch'] = thinkup_var ( 'thinkup_general_fixedlayoutswitch' );
$GLOBALS['thinkup_general_breadcrumbswitch'] = thinkup_var ( 'thinkup_general_breadcrumbswitch' );
$GLOBALS['thinkup_general_breadcrumbdelimeter'] = thinkup_var ( 'thinkup_general_breadcrumbdelimeter' );
$GLOBALS['thinkup_general_customcss'] = thinkup_var ( 'thinkup_general_customcss' );
$GLOBALS['thinkup_general_customjavafront'] = thinkup_var ( 'thinkup_general_customjavafront' );
// 1.2. Homepage.
$GLOBALS['thinkup_homepage_layout'] = thinkup_var ( 'thinkup_homepage_layout' );
$GLOBALS['thinkup_homepage_sidebars'] = thinkup_var ( 'thinkup_homepage_sidebars' );
$GLOBALS['thinkup_homepage_sliderswitch'] = thinkup_var ( 'thinkup_homepage_sliderswitch' );
$GLOBALS['thinkup_homepage_slidername'] = thinkup_var ( 'thinkup_homepage_slidername' );
$GLOBALS['thinkup_homepage_sliderpreset'] = thinkup_var ( 'thinkup_homepage_sliderpreset' );
$GLOBALS['thinkup_homepage_sliderpresetwidth'] = thinkup_var ( 'thinkup_homepage_sliderpresetwidth' );
$GLOBALS['thinkup_homepage_sliderpresetheight'] = thinkup_var ( 'thinkup_homepage_sliderpresetheight' );
$GLOBALS['thinkup_homepage_sectionswitch'] = thinkup_var ( 'thinkup_homepage_sectionswitch' );
$GLOBALS['thinkup_homepage_section1_icon'] = thinkup_var ( 'thinkup_homepage_section1_icon' );
$GLOBALS['thinkup_homepage_section1_title'] = thinkup_var ( 'thinkup_homepage_section1_title' );
$GLOBALS['thinkup_homepage_section1_desc'] = thinkup_var ( 'thinkup_homepage_section1_desc' );
$GLOBALS['thinkup_homepage_section1_link'] = thinkup_var ( 'thinkup_homepage_section1_link' );
$GLOBALS['thinkup_homepage_section2_icon'] = thinkup_var ( 'thinkup_homepage_section2_icon' );
$GLOBALS['thinkup_homepage_section2_title'] = thinkup_var ( 'thinkup_homepage_section2_title' );
$GLOBALS['thinkup_homepage_section2_desc'] = thinkup_var ( 'thinkup_homepage_section2_desc' );
$GLOBALS['thinkup_homepage_section2_link'] = thinkup_var ( 'thinkup_homepage_section2_link' );
$GLOBALS['thinkup_homepage_section3_icon'] = thinkup_var ( 'thinkup_homepage_section3_icon' );
$GLOBALS['thinkup_homepage_section3_title'] = thinkup_var ( 'thinkup_homepage_section3_title' );
$GLOBALS['thinkup_homepage_section3_desc'] = thinkup_var ( 'thinkup_homepage_section3_desc' );
$GLOBALS['thinkup_homepage_section3_link'] = thinkup_var ( 'thinkup_homepage_section3_link' );
$GLOBALS['thinkup_homepage_introswitch'] = thinkup_var ( 'thinkup_homepage_introswitch' );
$GLOBALS['thinkup_homepage_introaction'] = thinkup_var ( 'thinkup_homepage_introaction' );
$GLOBALS['thinkup_homepage_introactionteaser'] = thinkup_var ( 'thinkup_homepage_introactionteaser' );
$GLOBALS['thinkup_homepage_introactionbutton'] = thinkup_var ( 'thinkup_homepage_introactionbutton' );
$GLOBALS['thinkup_homepage_introactionlink'] = thinkup_var ( 'thinkup_homepage_introactionlink' );
$GLOBALS['thinkup_homepage_introactionpage'] = thinkup_var ( 'thinkup_homepage_introactionpage' );
$GLOBALS['thinkup_homepage_introactioncustom'] = thinkup_var ( 'thinkup_homepage_introactioncustom' );
// 1.3. Header
$GLOBALS['thinkup_header_searchswitch'] = thinkup_var ( 'thinkup_header_searchswitch' );
$GLOBALS['thinkup_header_socialswitch'] = thinkup_var ( 'thinkup_header_socialswitch' );
$GLOBALS['thinkup_header_socialmessage'] = thinkup_var ( 'thinkup_header_socialmessage' );
$GLOBALS['thinkup_header_facebookswitch'] = thinkup_var ( 'thinkup_header_facebookswitch' );
$GLOBALS['thinkup_header_facebooklink'] = thinkup_var ( 'thinkup_header_facebooklink' );
$GLOBALS['thinkup_header_facebookiconswitch'] = thinkup_var ( 'thinkup_header_facebookiconswitch' );
$GLOBALS['thinkup_header_facebookcustomicon'] = thinkup_var ( 'thinkup_header_facebookcustomicon', 'url' );
$GLOBALS['thinkup_header_twitterswitch'] = thinkup_var ( 'thinkup_header_twitterswitch' );
$GLOBALS['thinkup_header_twitterlink'] = thinkup_var ( 'thinkup_header_twitterlink' );
$GLOBALS['thinkup_header_twittericonswitch'] = thinkup_var ( 'thinkup_header_twittericonswitch' );
$GLOBALS['thinkup_header_twittercustomicon'] = thinkup_var ( 'thinkup_header_twittercustomicon', 'url' );
$GLOBALS['thinkup_header_googleswitch'] = thinkup_var ( 'thinkup_header_googleswitch' );
$GLOBALS['thinkup_header_googlelink'] = thinkup_var ( 'thinkup_header_googlelink' );
$GLOBALS['thinkup_header_googleiconswitch'] = thinkup_var ( 'thinkup_header_googleiconswitch' );
$GLOBALS['thinkup_header_googlecustomicon'] = thinkup_var ( 'thinkup_header_googlecustomicon', 'url' );
$GLOBALS['thinkup_header_linkedinswitch'] = thinkup_var ( 'thinkup_header_linkedinswitch' );
$GLOBALS['thinkup_header_linkedinlink'] = thinkup_var ( 'thinkup_header_linkedinlink' );
$GLOBALS['thinkup_header_linkediniconswitch'] = thinkup_var ( 'thinkup_header_linkediniconswitch' );
$GLOBALS['thinkup_header_linkedincustomicon'] = thinkup_var ( 'thinkup_header_linkedincustomicon', 'url' );
$GLOBALS['thinkup_header_flickrswitch'] = thinkup_var ( 'thinkup_header_flickrswitch' );
$GLOBALS['thinkup_header_flickrlink'] = thinkup_var ( 'thinkup_header_flickrlink' );
$GLOBALS['thinkup_header_flickriconswitch'] = thinkup_var ( 'thinkup_header_flickriconswitch' );
$GLOBALS['thinkup_header_flickrcustomicon'] = thinkup_var ( 'thinkup_header_flickrcustomicon', 'url' );
$GLOBALS['thinkup_header_lastfmswitch'] = thinkup_var ( 'thinkup_header_lastfmswitch' );
$GLOBALS['thinkup_header_lastfmlink'] = thinkup_var ( 'thinkup_header_lastfmlink' );
$GLOBALS['thinkup_header_lastfmiconswitch'] = thinkup_var ( 'thinkup_header_lastfmiconswitch' );
$GLOBALS['thinkup_header_lastfmcustomicon'] = thinkup_var ( 'thinkup_header_lastfmcustomicon', 'url' );
$GLOBALS['thinkup_header_rssswitch'] = thinkup_var ( 'thinkup_header_rssswitch' );
$GLOBALS['thinkup_header_rsslink'] = thinkup_var ( 'thinkup_header_rsslink' );
$GLOBALS['thinkup_header_rssiconswitch'] = thinkup_var ( 'thinkup_header_rssiconswitch' );
$GLOBALS['thinkup_header_rsscustomicon'] = thinkup_var ( 'thinkup_header_rsscustomicon', 'url' );
// 1.4. Footer.
$GLOBALS['thinkup_footer_layout'] = thinkup_var ( 'thinkup_footer_layout' );
$GLOBALS['thinkup_footer_widgetswitch'] = thinkup_var ( 'thinkup_footer_widgetswitch' );
// 1.5.1. Blog - Main page.
$GLOBALS['thinkup_blog_layout'] = thinkup_var ( 'thinkup_blog_layout' );
$GLOBALS['thinkup_blog_sidebars'] = thinkup_var ( 'thinkup_blog_sidebars' );
$GLOBALS['thinkup_blog_postswitch'] = thinkup_var ( 'thinkup_blog_postswitch' );
// 1.5.2. Blog - Single post.
$GLOBALS['thinkup_post_layout'] = thinkup_var ( 'thinkup_post_layout' );
$GLOBALS['thinkup_post_sidebars'] = thinkup_var ( 'thinkup_post_sidebars' );
// 1.6. Portfolio. - PREMIUM FEATURE
// 1.7. Contact Page. - PREMIUM FEATURE
// 1.8. Special pages. - PREMIUM FEATURE
// 1.9. Notification bar. - PREMIUM FEATURE
// 1.10. Search engine optimization. - PREMIUM FEATURE
// 1.11. Typography. - PREMIUM FEATURE
// 1.12. Custom styling. - PREMIUM FEATURE
// 1.13. Support.
}
add_action( 'thinkup_hook_header', 'thinkup_reduxvariables' );
?> | mit |
natholas/raspiDash | api/cpu_temp.php | 124 | <?php
$data = ["cpu_temp"=>shell_exec("cat /sys/class/thermal/thermal_zone0/temp")];
echo json_encode($data);
?>
| mit |
sebj54/postcss-sprite | test/test.js | 372 | var postcss = require('postcss');
var expect = require('chai').expect;
var plugin = require('../');
var test = function (input, output, opts) {
expect(postcss(plugin(opts)).process(input).css).to.eql(output);
};
describe('postcss-sprites', function () {
/* Write tests here
it('does something', function () {
test('a{ }', 'a{ }');
});*/
});
| mit |
tlsalmin/sukat | tests/test_sukat_sock.cpp | 53154 | #ifndef _GNU_SOURCE
#define _GNU_SOURCE
#include <unistd.h>
#endif
#include <iostream>
#include <fstream>
#include <random>
#include <string>
#include "gtest/gtest.h"
#include "test_common.h"
extern "C"{
#include "sukat_log_internal.c"
#include "sukat_sock.c"
#include "sukat_event.h"
#include <stdlib.h>
#include <sys/un.h>
}
void get_random_socket(char *where, size_t length)
{
int fd;
snprintf(where, length,
"/tmp/sukat_sock_sun_test_XXXXXX");
fd = mkstemp(where);
ASSERT_NE(-1, fd);
close(fd);
unlink(where);
}
class sukat_sock_test_tipc : public ::testing::Test
{
protected:
// You can remove any or all of the following functions if its body is empty.
sukat_sock_test_tipc() {
// You can do set-up work for each test here.
}
virtual ~sukat_sock_test_tipc() {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up and
// cleaning up each test, you can define the following methods:
virtual void SetUp() {
memset(&default_cbs, 0, sizeof(default_cbs));
memset(&default_endpoint_params, 0, sizeof(default_endpoint_params));
default_cbs.log_cb = test_log_cb;
memset(&default_params, 0, sizeof(default_params));
// Code here will be called immediately after the constructor (right
// before each test).
}
virtual void TearDown() {
// Code here will be called immediately after each test (right
// before the destructor).
}
void get_random_port(struct sukat_sock_endpoint_params *params)
{
static bool random_seeded;
if (!random_seeded)
{
FILE *urandom = fopen("/dev/urandom", "r");
unsigned int seed;
size_t n_read;
EXPECT_NE(nullptr, urandom);
n_read = fread(&seed, sizeof(seed), 1, urandom);
EXPECT_EQ(1, n_read);
fclose(urandom);
srand(seed);
random_seeded = true;
}
params->ptipc.port_type = 63 + ((uint32_t)rand() % UINT32_MAX);
params->ptipc.port_instance = ((uint32_t)rand() % UINT32_MAX);
params->ptipc.scope = TIPC_NODE_SCOPE;
}
bool check_tipc()
{
std::ifstream procfile("/proc/modules");
char buf[128];
if (procfile.is_open())
{
std::string line;
while (getline(procfile, line))
{
if (line.find("tipc") != std::string::npos)
{
procfile.close();
return true;
}
}
procfile.close();
}
snprintf(buf, sizeof(buf), "Failed to check for TIPC: %s",
strerror(errno));
default_cbs.log_cb(SUKAT_LOG_ERROR, buf);
return false;
}
bool wait_for_tipc_server(sukat_sock_t *ctx, uint32_t name_type,
uint32_t name_instance, int wait)
{
struct sockaddr_tipc topsrv = { };
struct tipc_subscr subscr= { };
struct tipc_event event = { };
int sd = socket(AF_TIPC, SOCK_SEQPACKET, 0);
memset(&topsrv, 0, sizeof(topsrv));
topsrv.family = AF_TIPC;
topsrv.addrtype = TIPC_ADDR_NAME;
topsrv.addr.name.name.type = TIPC_TOP_SRV;
topsrv.addr.name.name.instance = TIPC_TOP_SRV;
/* Connect to topology server */
if (0 > connect(sd, (struct sockaddr *)&topsrv, sizeof(topsrv))) {
ERR(ctx, "Client: failed to connect to topology server: %S",
strerror(errno));
return false;
}
subscr.seq.type = htonl(name_type);
subscr.seq.lower = htonl(name_instance);
subscr.seq.upper = htonl(name_instance);
subscr.timeout = htonl(wait);
subscr.filter = htonl(TIPC_SUB_SERVICE);
if (send(sd, &subscr, sizeof(subscr), 0) != sizeof(subscr)) {
ERR(ctx, "Client: failed to send subscription: %s",strerror(errno));
return false;
}
/* Now wait for the subscription to fire */
if (recv(sd, &event, sizeof(event), 0) != sizeof(event)) {
ERR(ctx, "Client: failed to receive event: %s", strerror(errno));
return false;
}
if (event.event != htonl(TIPC_PUBLISHED)) {
ERR(ctx, "Client: server {%u,%u} not published within %u [s]\n: %s",
name_type, name_instance, wait/1000, strerror(errno));
return false;
}
LOG(ctx, "Server published TIPC!");
close(sd);
return true;
}
// Objects declared here can be used by all tests
struct sukat_sock_cbs default_cbs;
struct sukat_sock_params default_params;
struct sukat_sock_endpoint_params default_endpoint_params;
};
struct test_ctx
{
int yeah;
};
TEST_F(sukat_sock_test_tipc, sukat_sock_test_tipc)
{
sukat_sock_t *ctx, *client_ctx;
sukat_sock_endpoint_t *server_endpoint, *client_endpoint;
struct test_ctx tctx = { };
bool bret;
int err;
default_params.caller_ctx = &tctx;
default_endpoint_params.server = true;
default_endpoint_params.domain = AF_TIPC;
default_endpoint_params.type = SOCK_SEQPACKET;
get_random_port(&default_endpoint_params);
if (check_tipc() == false)
{
default_cbs.log_cb(SUKAT_LOG,
"Skipping TIPC socket. modprobe tipc to enable");
return;
}
ctx = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, ctx);
server_endpoint = sukat_sock_endpoint_add(ctx, &default_endpoint_params);
EXPECT_NE(nullptr, server_endpoint);
default_endpoint_params.server = false;
bret = wait_for_tipc_server(ctx, default_endpoint_params.ptipc.port_type,
default_endpoint_params.ptipc.port_instance, 1000);
EXPECT_EQ(true, bret);
client_ctx = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, client_ctx);
client_endpoint =
sukat_sock_endpoint_add(client_ctx, &default_endpoint_params);
EXPECT_NE(nullptr, client_endpoint);
err = sukat_sock_read(ctx, 0);
EXPECT_NE(-1, err);
sukat_sock_disconnect(client_ctx, client_endpoint);
sukat_sock_destroy(client_ctx);
err = sukat_sock_read(ctx, 0);
EXPECT_NE(-1, err);
sukat_sock_disconnect(ctx, server_endpoint);
sukat_sock_destroy(ctx);
}
class sukat_sock_test_sun : public ::testing::Test
{
protected:
// You can remove any or all of the following functions if its body is empty.
sukat_sock_test_sun() {
// You can do set-up work for each test here.
}
virtual ~sukat_sock_test_sun() {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up and
// cleaning up each test, you can define the following methods:
virtual void SetUp() {
memset(&default_cbs, 0, sizeof(default_cbs));
memset(&default_params, 0, sizeof(default_params));
memset(&default_endpoint_params, 0, sizeof(default_endpoint_params));
default_cbs.log_cb = test_log_cb;
get_random_socket(sun_template, sizeof(sun_template));
default_endpoint_params.punix.name = sun_template;
default_endpoint_params.domain = AF_UNIX;
default_endpoint_params.punix.is_abstract = true;
default_endpoint_params.type = SOCK_STREAM;
}
virtual void TearDown() {
default_endpoint_params.punix.name = NULL;
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests
struct sukat_sock_cbs default_cbs;
struct sukat_sock_params default_params;
struct sukat_sock_endpoint_params default_endpoint_params;
char sun_template[sizeof(((struct sockaddr_un *)0)->sun_path) - 2];
};
struct sun_test_ctx
{
bool connected_should;
bool connected_visited;
bool connected_should_disconnect;
sukat_sock_endpoint_t *newest_client;
void *new_ctx;
size_t n_connects;
size_t n_disconnects;
};
struct test_client
{
int id;
};
void *new_conn_cb(void *ctx, sukat_sock_endpoint_t *client,
sukat_sock_event_t event)
{
struct sun_test_ctx *tctx = (struct sun_test_ctx *)ctx;
EXPECT_EQ(true, tctx->connected_should);
if (event == SUKAT_SOCK_CONN_EVENT_DISCONNECT)
{
EXPECT_EQ(true, tctx->connected_should_disconnect);
tctx->n_disconnects++;
}
else
{
tctx->n_connects++;
}
tctx->newest_client = client;
tctx->connected_visited = true;
return tctx->new_ctx;
}
TEST_F(sukat_sock_test_sun, sukat_sock_test_faulty_param)
{
sukat_sock_t *server;
sukat_sock_endpoint_t *endpoint;
// Test with no params
server = sukat_sock_create(NULL, &default_cbs);
EXPECT_EQ(nullptr, server);
// Test peer without main
endpoint = sukat_sock_endpoint_add(NULL, &default_endpoint_params);
EXPECT_EQ(nullptr, endpoint);
server = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, server);
endpoint = sukat_sock_endpoint_add(server, NULL);
EXPECT_EQ(nullptr, endpoint);
sukat_sock_destroy(server);
}
TEST_F(sukat_sock_test_sun, sukat_sock_test_external_epoll)
{
int master_epoll;
sukat_sock_t *server;
// Test with another epoll.
master_epoll = epoll_create1(EPOLL_CLOEXEC);
EXPECT_NE(-1, master_epoll);
// First with a faulty master_epoll.
default_params.master_epoll_fd_set = true;
default_params.master_epoll_fd = -1;
server = sukat_sock_create(&default_params, &default_cbs);
EXPECT_EQ(nullptr, server);
get_random_socket(sun_template, sizeof(sun_template));
default_params.master_epoll_fd = master_epoll;
server = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, server);
sukat_sock_destroy(server);
close(master_epoll);
}
TEST_F(sukat_sock_test_sun, sukat_sock_test_sun_stream_connect)
{
sukat_sock_t *server, *client;
sukat_sock_endpoint_t *server_endpoint, *client_endpoint;
struct sun_test_ctx tctx = { };
int err;
default_params.caller_ctx = &tctx;
default_cbs.conn_cb = new_conn_cb;
server = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, server);
default_endpoint_params.server = true;
server_endpoint = sukat_sock_endpoint_add(server, &default_endpoint_params);
EXPECT_NE(nullptr, server_endpoint);
default_cbs.conn_cb = NULL;
client = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, server);
default_endpoint_params.server = false;
client_endpoint = sukat_sock_endpoint_add(client, &default_endpoint_params);
EXPECT_NE(nullptr, client_endpoint);
tctx.connected_should = true;
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.connected_visited);
EXPECT_EQ(2, server->n_connections);
tctx.connected_should = tctx.connected_visited = false;
sukat_sock_disconnect(client, client_endpoint);
tctx.connected_should = tctx.connected_should_disconnect = true;
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.connected_visited);
tctx.connected_should = tctx.connected_visited =
tctx.connected_should_disconnect = false;
sukat_sock_destroy(client);
sukat_sock_disconnect(server, server_endpoint);
sukat_sock_destroy(server);
}
TEST_F(sukat_sock_test_sun, sukat_sock_test_sun_stream_connect_many)
{
struct sun_test_ctx tctx = { };
sukat_sock_t *server;
sukat_sock_endpoint_t *server_endpoint;
size_t i;
const size_t n_clients = SOMAXCONN;
sukat_sock_t *clients[n_clients];
sukat_sock_endpoint_t *client_endpoints[n_clients];
int err;
default_params.caller_ctx = &tctx;
default_cbs.conn_cb = new_conn_cb;
server = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, server);
default_endpoint_params.server = true;
server_endpoint = sukat_sock_endpoint_add(server, &default_endpoint_params);
EXPECT_NE(nullptr, server_endpoint);
default_cbs.conn_cb = NULL;
default_endpoint_params.server = false;
for (i = 0; i < n_clients; i++)
{
clients[i] = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, clients[i]);
client_endpoints[i] =
sukat_sock_endpoint_add(clients[i], &default_endpoint_params);
EXPECT_NE(nullptr, client_endpoints[i]);
}
tctx.connected_should = true;
err = sukat_sock_read(server, 0);
EXPECT_NE(-1, err);
EXPECT_EQ(true, tctx.connected_visited);
EXPECT_EQ(n_clients + 1, server->n_connections);
EXPECT_EQ(n_clients, tctx.n_connects);
tctx.connected_should = tctx.connected_visited = false;
for (i = 0; i < n_clients; i++)
{
sukat_sock_disconnect(clients[i], client_endpoints[i]);
sukat_sock_destroy(clients[i]);
}
tctx.connected_should = tctx.connected_should_disconnect = true;
err = sukat_sock_read(server, 0);
EXPECT_NE(-1, err);
EXPECT_EQ(true, tctx.connected_visited);
EXPECT_EQ(n_clients, tctx.n_disconnects);
sukat_sock_disconnect(server, server_endpoint);
sukat_sock_destroy(server);
}
struct read_ctx
{
sukat_sock_endpoint_t *newest_client;
struct {
uint16_t len_cb_should_visit:1;
uint16_t len_cb_visited:1;
uint16_t return_corrupt:1;
uint16_t should_disconnect:1;
uint16_t connect_visited:1;
uint16_t msg_cb_should_visit:1;
uint16_t msg_cb_visited:1;
uint16_t compare_payload:1;
uint16_t compared_payload:1;
uint16_t copy_client:1;
uint16_t unused:6;
};
uint8_t *buf;
size_t offset;
size_t n_messages;
};
#pragma pack (1)
struct test_msg
{
uint64_t type;
uint64_t len;
uint8_t data[];
};
#pragma pack (0)
static int len_cb(void *ctx, __attribute__((unused))uint8_t *buf,
size_t buf_len)
{
struct read_ctx *tctx = (struct read_ctx*)ctx;
struct test_msg *msg = (struct test_msg *)buf;
EXPECT_NE(nullptr, buf);
EXPECT_NE(nullptr, tctx);
tctx->len_cb_visited = true;
if (tctx->return_corrupt == true)
{
return -1;
}
if (buf_len < sizeof(*msg))
{
return 0;
}
return msg->len;
}
static void msg_cb(void *ctx, sukat_sock_endpoint_t *client, uint8_t *buf,
size_t buf_len)
{
struct read_ctx *tctx = (struct read_ctx*)ctx;
EXPECT_EQ(true, tctx->msg_cb_should_visit);
tctx->msg_cb_visited = true;
tctx->newest_client = client;
if (tctx->compare_payload)
{
int compareval;
compareval = memcmp(buf, tctx->buf + tctx->offset, buf_len);
EXPECT_EQ(0, compareval);
tctx->offset += buf_len;
tctx->compared_payload = true;
}
if (tctx->copy_client)
{
tctx->newest_client = (sukat_sock_endpoint_t *)malloc(sizeof(*client));
EXPECT_NE(nullptr, tctx->newest_client);
memcpy(tctx->newest_client, client, sizeof(*client));
}
tctx->n_messages++;
}
void *new_conn_cb_for_read(void *ctx, sukat_sock_endpoint_t *client,
sukat_sock_event_t event)
{
struct read_ctx *tctx = (struct read_ctx *)ctx;
tctx->newest_client = client;
if (tctx->should_disconnect)
{
EXPECT_EQ(SUKAT_SOCK_CONN_EVENT_DISCONNECT, event);
}
tctx->connect_visited = true;
return NULL;
}
TEST_F(sukat_sock_test_sun, sukat_sock_test_sun_stream_read)
{
sukat_sock_t *server, *client_ctx;
sukat_sock_endpoint_t *server_endpoint;
sukat_sock_endpoint_t *client_from_server;
sukat_sock_endpoint_t *client_endpoint;
uint8_t buf[BUFSIZ];
struct test_msg *msg = (struct test_msg *)buf;
struct read_ctx tctx = { };
int err;
enum sukat_sock_send_return send_ret;
size_t msg_len = 5000, i, total_sent, total_read;
default_cbs.msg_len_cb = len_cb;
default_cbs.conn_cb = new_conn_cb_for_read;
default_cbs.msg_cb = msg_cb;
default_endpoint_params.server = true;
default_params.caller_ctx = (void *)&tctx;
tctx.buf = buf;
tctx.compare_payload = true;
server = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, server);
server_endpoint = sukat_sock_endpoint_add(server, &default_endpoint_params);
EXPECT_NE(nullptr, server_endpoint);
default_endpoint_params.server = false;
client_ctx = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, client_ctx);
client_endpoint =
sukat_sock_endpoint_add(client_ctx,&default_endpoint_params);
EXPECT_NE(nullptr, client_endpoint);
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(2, server->n_connections);
client_from_server = tctx.newest_client;
/* Simple single message */
msg->type = 0;
msg->len = sizeof(*msg);
send_ret = sukat_send_msg(client_ctx, client_endpoint, buf, msg->len, NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
tctx.len_cb_should_visit = tctx.msg_cb_should_visit = true;
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.len_cb_visited);
EXPECT_EQ(true, tctx.msg_cb_visited);
EXPECT_EQ(true, tctx.compared_payload);
tctx.offset = 0;
tctx.compared_payload = tctx.msg_cb_visited = false;
/* Reply */
err = sukat_send_msg(server, client_from_server, buf, msg->len, NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
tctx.len_cb_visited = tctx.msg_cb_visited = false;
err = sukat_sock_read(client_ctx, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.len_cb_visited);
EXPECT_EQ(true, tctx.msg_cb_visited);
tctx.offset = 0;
/* Message that needs caching */
tctx.len_cb_should_visit = true;
tctx.msg_cb_should_visit = false;
tctx.len_cb_visited = tctx.msg_cb_visited = false;
send_ret =
sukat_send_msg(server, client_from_server, buf, sizeof(*msg) / 2, NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
err = sukat_sock_read(client_ctx, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.len_cb_visited);
EXPECT_EQ(false, tctx.msg_cb_visited);
tctx.offset = 0;
/* Continue */
send_ret = sukat_send_msg(server, client_from_server,
buf + (sizeof(*msg) / 2), sizeof(*msg) / 2, NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
tctx.msg_cb_should_visit = true;
err = sukat_sock_read(client_ctx, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.len_cb_visited);
EXPECT_EQ(true, tctx.msg_cb_visited);
tctx.len_cb_visited = tctx.msg_cb_visited = false;
tctx.offset = 0;
/* Longer message */
memset(buf, 'c', msg_len);
msg->len = msg_len;
msg->type = 0;
/* Send first half */
send_ret = sukat_send_msg(server, client_from_server, buf, msg_len / 2, NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
tctx.msg_cb_should_visit = false;
err = sukat_sock_read(client_ctx, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.len_cb_visited);
EXPECT_EQ(false, tctx.msg_cb_visited);
tctx.len_cb_visited = tctx.msg_cb_visited = false;
tctx.offset = 0;
/* Send second half */
send_ret =
sukat_send_msg(server, client_from_server, buf + (msg_len / 2),
msg_len / 2, NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
tctx.msg_cb_should_visit = true;
err = sukat_sock_read(client_ctx, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.len_cb_visited);
EXPECT_EQ(true, tctx.msg_cb_visited);
tctx.len_cb_visited = tctx.msg_cb_visited = false;
tctx.offset = 0;
tctx.msg_cb_should_visit = tctx.len_cb_should_visit = false;
/* Send lots of small messages */
msg_len = 40;
for (i = 0; i < 100; i++)
{
memset(buf + i * msg_len, i, msg_len);
msg = (struct test_msg *)(buf + i * msg_len);
msg->type = 0;
msg->len = msg_len;
send_ret = sukat_send_msg(server, client_from_server,
(uint8_t *)msg, msg->len, NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
}
tctx.n_messages = 0;
tctx.msg_cb_should_visit = tctx.len_cb_should_visit = true;
err = sukat_sock_read(client_ctx, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.len_cb_visited);
EXPECT_EQ(true, tctx.msg_cb_visited);
EXPECT_EQ(100, tctx.n_messages);
/* Send messages until EAGAIN. */
memset(buf, 0, sizeof(buf));
msg = (struct test_msg *)(buf);
msg->type = 0;
msg->len = sizeof(buf);
total_sent = 0;
while ((send_ret =
sukat_send_msg(server, client_from_server, (uint8_t *)msg,
msg->len, NULL)) == SUKAT_SEND_OK)
{
total_sent += msg_len;
}
EXPECT_EQ(SUKAT_SEND_EAGAIN, send_ret);
EXPECT_GT(total_sent, 0);
total_read = 0;
while ((err = read(client_endpoint->info.fd, buf, sizeof(buf))) > 0)
{
total_read += err;
}
EXPECT_EQ(-1, err);
EXPECT_GT(total_read, 0);
EXPECT_TRUE(errno == EAGAIN || errno == EWOULDBLOCK);
/* So somehow I can't get the send side to ever send a partial message
* I'll just do the send caching test in AF_INET */
sukat_sock_disconnect(server, client_from_server);
sukat_sock_disconnect(server, server_endpoint);
sukat_sock_disconnect(client_ctx, client_endpoint);
sukat_sock_destroy(client_ctx);
sukat_sock_destroy(server);
}
TEST_F(sukat_sock_test_sun, sukat_sock_test_sun_seqpacket)
{
sukat_sock_t *server, *client;
sukat_sock_endpoint_t *server_endpoint, *server_from_client,
*client_from_server;
struct read_ctx tctx = { };
int err;
char buf[BUFSIZ];
enum sukat_sock_send_return send_ret;
default_endpoint_params.type = SOCK_SEQPACKET;
default_cbs.msg_len_cb = len_cb;
default_cbs.conn_cb = new_conn_cb_for_read;
default_cbs.msg_cb = msg_cb;
default_endpoint_params.server = true;
default_params.caller_ctx = (void *)&tctx;
server = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, server);
server_endpoint = sukat_sock_endpoint_add(server, &default_endpoint_params);
EXPECT_NE(nullptr, server_endpoint);
default_endpoint_params.server = false;
client = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, client);
server_from_client = sukat_sock_endpoint_add(client,
&default_endpoint_params);
EXPECT_NE(nullptr, client);
// Accept client
err = sukat_sock_read(server, 100);
EXPECT_EQ(0, err);
EXPECT_NE(nullptr, tctx.newest_client);
client_from_server = tctx.newest_client;
snprintf(buf, sizeof(buf), "Hello there new seqpacket client");
send_ret = sukat_send_msg(server, client_from_server,
(uint8_t *)buf, strlen(buf), NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
tctx.buf = (uint8_t *)buf;
tctx.compare_payload = tctx.msg_cb_should_visit = true;
err = sukat_sock_read(client, 100);
EXPECT_EQ(true, tctx.msg_cb_visited);
EXPECT_EQ(0, err);
tctx.msg_cb_visited = false;
tctx.offset = 0;
snprintf(buf, sizeof(buf), "Hello there seqpacket server");
send_ret = sukat_send_msg(client, server_from_client, (uint8_t *)buf,
strlen(buf), NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
err = sukat_sock_read(server, 100);
EXPECT_EQ(true, tctx.msg_cb_visited);
EXPECT_EQ(0, err);
sukat_sock_disconnect(client, client_from_server);
sukat_sock_disconnect(client, server_from_client);
sukat_sock_disconnect(server, server_endpoint);
sukat_sock_destroy(client);
sukat_sock_destroy(server);
}
class sukat_sock_test_sun_dgram : public ::testing::Test
{
protected:
sukat_sock_test_sun_dgram() {
}
virtual ~sukat_sock_test_sun_dgram() {
}
virtual void SetUp() {
memset(&default_cbs, 0, sizeof(default_cbs));
memset(&default_params, 0, sizeof(default_params));
memset(&default_endpoint_params, 0, sizeof(default_endpoint_params));
memset(&tctx, 0, sizeof(tctx));
get_random_socket(sun_template, sizeof(sun_template));
default_cbs.log_cb = test_log_cb;
default_cbs.msg_cb = msg_cb;
default_params.caller_ctx = &tctx;
default_endpoint_params.punix.name = sun_template;
default_endpoint_params.domain = AF_UNIX;
default_endpoint_params.punix.is_abstract = true;
default_endpoint_params.type = SOCK_DGRAM;
default_endpoint_params.server = true;
server = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, server);
server_endpoint =
sukat_sock_endpoint_add(server,&default_endpoint_params);
EXPECT_NE(nullptr, server_endpoint);
}
virtual void TearDown() {
default_endpoint_params.punix.name = NULL;
sukat_sock_disconnect(server, server_endpoint);
sukat_sock_destroy(server);
}
struct sukat_sock_cbs default_cbs;
struct sukat_sock_params default_params;
struct sukat_sock_endpoint_params default_endpoint_params;
char sun_template[sizeof(((struct sockaddr_un *)0)->sun_path) - 2];
sukat_sock_t *server;
sukat_sock_endpoint_t *server_endpoint;
struct read_ctx tctx;
};
TEST_F(sukat_sock_test_sun_dgram, sukat_sock_test_sun_dgram_recv)
{
int fd;
ssize_t ret;
size_t i;
const size_t n_messages = 9, message_size = 16;
char buf[BUFSIZ];
sukat_sock_endpoint_t client_endpoint;
default_endpoint_params.server = false;
fd = socket_create(NULL, &default_endpoint_params, &client_endpoint);
EXPECT_GT(fd, -1);
snprintf((char *)buf, sizeof(buf) - 1, "Hello there connectionless");
ret = write(fd, buf, strlen(buf));
EXPECT_EQ(strlen(buf), ret);
tctx.buf = (uint8_t *)buf;
tctx.compare_payload = true;
tctx.msg_cb_should_visit = true;
ret = sukat_sock_read(server, 0);
EXPECT_EQ(0, ret);
EXPECT_EQ(true, tctx.msg_cb_visited);
EXPECT_EQ(true, tctx.compared_payload);
EXPECT_EQ(1, tctx.n_messages);
tctx.msg_cb_visited = tctx.compared_payload = false;
tctx.offset = 0;
tctx.n_messages = 0;
// Now test with many messages
for (i = 0; i < n_messages; i++)
{
void *target = buf + i * message_size;
memset(target, i, message_size);
ret = write(fd, target, message_size);
EXPECT_EQ(message_size, ret);
}
ret = sukat_sock_read(server, 0);
EXPECT_EQ(0, ret);
EXPECT_EQ(true, tctx.msg_cb_visited);
EXPECT_EQ(n_messages, tctx.n_messages);
EXPECT_EQ(true, tctx.compared_payload);
close(fd);
}
TEST_F(sukat_sock_test_sun_dgram, sukat_sock_test_sun_dgram_send)
{
char buf[BUFSIZ];
sukat_sock_t *server2;
sukat_sock_endpoint_t *server2_endpoint, *server1_from_server2,
*server2_from_server1;
enum sukat_sock_send_return sock_ret;
int ret;
tctx.buf = (uint8_t *)buf;
tctx.compare_payload = true;
server2 = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, server2);
default_endpoint_params.server = false;
server1_from_server2 =
sukat_sock_endpoint_add(server2, &default_endpoint_params);
ASSERT_NE(nullptr, server1_from_server2);
get_random_socket(sun_template, sizeof(sun_template));
default_endpoint_params.server = true;
server2_endpoint = sukat_sock_endpoint_add(server2, &default_endpoint_params);
ASSERT_NE(nullptr, server2_endpoint);
snprintf(buf, sizeof(buf), "Hello there server 1");
sock_ret = sukat_send_msg(server2, server1_from_server2,
(uint8_t *)buf, strlen(buf),
server2_endpoint);
EXPECT_EQ(SUKAT_SEND_OK, sock_ret);
tctx.copy_client = true;
tctx.msg_cb_should_visit = true;
ret = sukat_sock_read(server, 100);
EXPECT_EQ(0, ret);
ASSERT_EQ(true, tctx.msg_cb_visited);
server2_from_server1 = tctx.newest_client;
tctx.msg_cb_visited = tctx.copy_client = false;
tctx.offset = 0;
snprintf(buf, sizeof(buf), "Hey back from server1");
sock_ret = sukat_send_msg(server, server2_from_server1, (uint8_t *)buf,
strlen(buf), server_endpoint);
EXPECT_EQ(SUKAT_SEND_OK, sock_ret);
ret = sukat_sock_read(server2, 100);
EXPECT_EQ(0, ret);
EXPECT_EQ(true, tctx.msg_cb_visited);
tctx.offset = 0;
tctx.msg_cb_visited = false;
// Send one without a source.
snprintf(buf, sizeof(buf), "Hey from secret admirer");
sock_ret = sukat_send_msg(server, server2_from_server1, (uint8_t *)buf,
strlen(buf), NULL);
EXPECT_EQ(SUKAT_SEND_OK, sock_ret);
ret = sukat_sock_read(server2, 100);
EXPECT_EQ(0, ret);
EXPECT_EQ(true, tctx.msg_cb_visited);
sukat_sock_disconnect(server2, server2_endpoint);
sukat_sock_disconnect(server2, server1_from_server2);
sukat_sock_destroy(server2);
free(server2_from_server1);
}
struct cb_disco_ctx
{
sukat_sock_t *ctx;
sukat_sock_endpoint_t *destroy_this_too;
sukat_sock_endpoint_t *client;
bool disco_in_len;
bool disco_in_conn;
bool disco_in_msg;
bool destroy_in_len;
bool destroy_in_conn;
bool destroy_in_msg;
int ret;
};
int len_cb_disconnects(void *ctx,
__attribute__((unused)) uint8_t *buf,
__attribute__((unused)) size_t buf_len)
{
struct cb_disco_ctx *tctx = (struct cb_disco_ctx *)ctx;
EXPECT_NE(nullptr, tctx);
if (tctx->disco_in_len)
{
EXPECT_NE(nullptr, tctx->client);
sukat_sock_disconnect(tctx->ctx, tctx->client);
tctx->client = NULL;
}
if (tctx->destroy_in_len)
{
if (tctx->destroy_this_too)
{
sukat_sock_disconnect(tctx->ctx, tctx->destroy_this_too);
}
tctx->destroy_this_too = NULL;
sukat_sock_destroy(tctx->ctx);
}
return tctx->ret;
}
void *disco_conn_cb(void *ctx, sukat_sock_endpoint_t *client,
__attribute__((unused)) sukat_sock_event_t event)
{
struct cb_disco_ctx *tctx = (struct cb_disco_ctx *)ctx;
EXPECT_NE(nullptr, tctx);
tctx->client = client;
if (tctx->disco_in_conn)
{
EXPECT_NE(nullptr, tctx->client);
sukat_sock_disconnect(tctx->ctx, client);
tctx->client = NULL;
}
if (tctx->destroy_in_conn)
{
if (tctx->destroy_this_too)
{
sukat_sock_disconnect(tctx->ctx, tctx->destroy_this_too);
}
tctx->destroy_this_too = NULL;
sukat_sock_destroy(tctx->ctx);
}
tctx->client = client;
return NULL;
}
void disco_msg_cb(void *ctx, sukat_sock_endpoint_t *client,
__attribute__((unused)) uint8_t *buf,
__attribute__((unused)) size_t buf_len)
{
struct cb_disco_ctx *tctx = (struct cb_disco_ctx *)ctx;
EXPECT_NE(nullptr, tctx);
if (tctx->disco_in_msg)
{
EXPECT_NE(nullptr, tctx->client);
sukat_sock_disconnect(tctx->ctx, client);
tctx->client = NULL;
}
if (tctx->destroy_in_msg)
{
if (tctx->destroy_this_too)
{
sukat_sock_disconnect(tctx->ctx, tctx->destroy_this_too);
}
tctx->destroy_this_too = NULL;
sukat_sock_destroy(tctx->ctx);
}
}
TEST_F(sukat_sock_test_sun, sukat_sock_test_sun_removal_in_cb)
{
sukat_sock_t *server, *client;
sukat_sock_endpoint_t *server_endpoint, *client_endpoint;
struct cb_disco_ctx tctx= { };
int err;
uint8_t msg[512];
memset(msg, 0, sizeof(msg));
default_cbs.conn_cb = disco_conn_cb;
default_cbs.msg_cb = disco_msg_cb;
default_cbs.msg_len_cb = len_cb_disconnects;
default_endpoint_params.server = true;
default_params.caller_ctx = &tctx;
server = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, server);
server_endpoint = sukat_sock_endpoint_add(server, &default_endpoint_params);
EXPECT_NE(nullptr, server_endpoint);
tctx.ctx = server;
default_endpoint_params.server = false;
client = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, client);
client_endpoint = sukat_sock_endpoint_add(client, &default_endpoint_params);
EXPECT_NE(nullptr, client_endpoint);
// First disco in conn
tctx.disco_in_conn = true;
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(1, server->n_connections);
sukat_sock_disconnect(client, client_endpoint);
// Disco in len_cb
tctx.disco_in_conn = false;
tctx.disco_in_len = true;
client_endpoint = sukat_sock_endpoint_add(client, &default_endpoint_params);
EXPECT_NE(nullptr, client_endpoint);
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(2, server->n_connections);
err = sukat_send_msg(client, client_endpoint, msg, sizeof(msg), NULL);
EXPECT_EQ(SUKAT_SEND_OK, err);
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(1, server->n_connections);
err = sukat_sock_read(client, 0);
EXPECT_EQ(0, err);
// Disco in msg_cb
tctx.disco_in_len = false;
tctx.disco_in_msg = true;
client_endpoint = sukat_sock_endpoint_add(client, &default_endpoint_params);
EXPECT_NE(nullptr, client_endpoint);
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(2, server->n_connections);
err = sukat_send_msg(client, client_endpoint, msg, sizeof(msg), NULL);
EXPECT_EQ(SUKAT_SEND_OK, err);
tctx.ret = sizeof(msg);
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(1, server->n_connections);
err = sukat_sock_read(client, 0);
EXPECT_EQ(0, err);
tctx.disco_in_msg = false;
// same for destroys.
tctx.ctx = server;
client_endpoint = sukat_sock_endpoint_add(client, &default_endpoint_params);
EXPECT_NE(nullptr, client_endpoint);
tctx.destroy_in_conn = tctx.disco_in_conn = true;
tctx.destroy_this_too = server_endpoint;
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
sukat_sock_disconnect(client, client_endpoint);
// Destroy in conn_cb
get_random_socket(sun_template, sizeof(sun_template));
tctx.destroy_in_conn = tctx.disco_in_conn = false;
default_endpoint_params.server = true;
server = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, server);
server_endpoint = sukat_sock_endpoint_add(server, &default_endpoint_params);
EXPECT_NE(nullptr, server_endpoint);
tctx.ctx = server;
tctx.destroy_this_too = server_endpoint;
default_endpoint_params.server = false;
client_endpoint = sukat_sock_endpoint_add(client, &default_endpoint_params);
EXPECT_NE(nullptr, client_endpoint);
// Destroy in len_cb
tctx.disco_in_len = tctx.destroy_in_len = true;
err = sukat_send_msg(client, client_endpoint, msg, sizeof(msg), NULL);
EXPECT_EQ(SUKAT_SEND_OK, err);
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
sukat_sock_disconnect(client, client_endpoint);
tctx.disco_in_len = tctx.destroy_in_len = false;
get_random_socket(sun_template, sizeof(sun_template));
default_endpoint_params.server = true;
server = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, server);
server_endpoint = sukat_sock_endpoint_add(server, &default_endpoint_params);
EXPECT_NE(nullptr, server_endpoint);
// Destroy in msg_cb.
tctx.ctx = server;
tctx.destroy_this_too = server_endpoint;
default_endpoint_params.server = false;
client_endpoint = sukat_sock_endpoint_add(client, &default_endpoint_params);
EXPECT_NE(nullptr, client_endpoint);
tctx.disco_in_msg = tctx.destroy_in_msg = true;
err = sukat_send_msg(client, client_endpoint, msg, sizeof(msg), NULL);
EXPECT_EQ(SUKAT_SEND_OK, err);
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
sukat_sock_disconnect(client, client_endpoint);
sukat_sock_destroy(client);
tctx.disco_in_msg = tctx.destroy_in_msg = false;
}
TEST_F(sukat_sock_test_sun, sukat_sock_test_sun_peering)
{
sukat_sock_t *peer1, *peer2;
sukat_sock_endpoint_t *endpoint1, *endpoint2;
sukat_sock_endpoint_t *peer1_to_peer2, *peer2_to_peer1;
sukat_sock_endpoint_t *peer1_from_peer2, *peer2_from_peer1;
char *peer1_name, *peer2_name;
struct read_ctx tctx = { };
int err;
uint8_t buf[BUFSIZ];
struct test_msg *msg = (struct test_msg *)buf;
enum sukat_sock_send_return send_ret;
memset(buf, 0, sizeof(buf));
default_cbs.msg_len_cb = len_cb;
default_cbs.msg_cb = msg_cb;
default_cbs.conn_cb = new_conn_cb_for_read;
default_params.caller_ctx = (void *)&tctx;
peer1 = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, peer1);
peer2 = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, peer2);
default_endpoint_params.server = true;
endpoint1 = sukat_sock_endpoint_add(peer1, &default_endpoint_params);
EXPECT_NE(nullptr, endpoint1);
peer1_name = strdup(default_endpoint_params.punix.name);
EXPECT_NE(nullptr, peer1_name);
get_random_socket(sun_template, sizeof(sun_template));
endpoint2 = sukat_sock_endpoint_add(peer2, &default_endpoint_params);
EXPECT_NE(nullptr, endpoint2);
peer2_name = strdup(default_endpoint_params.punix.name);
EXPECT_NE(nullptr, peer2_name);
default_endpoint_params.server = false;
peer1_to_peer2 = sukat_sock_endpoint_add(peer1, &default_endpoint_params);
EXPECT_NE(nullptr, peer1_to_peer2);
default_endpoint_params.punix.name = peer1_name;
peer2_to_peer1 = sukat_sock_endpoint_add(peer2, &default_endpoint_params);
EXPECT_NE(nullptr, peer2_to_peer1);
err = sukat_sock_read(peer1, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.connect_visited);
peer2_from_peer1 = tctx.newest_client;
tctx.connect_visited = false;
err = sukat_sock_read(peer2, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.connect_visited);
peer1_from_peer2 = tctx.newest_client;
tctx.connect_visited = false;
msg->len = 500;
send_ret = sukat_send_msg(peer1, peer1_to_peer2, buf, msg->len, NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
send_ret = sukat_send_msg(peer2, peer2_to_peer1, buf, msg->len, NULL);
EXPECT_EQ(SUKAT_SEND_OK, send_ret);
tctx.msg_cb_should_visit = tctx.len_cb_should_visit = true;
err = sukat_sock_read(peer1, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.len_cb_visited);
EXPECT_EQ(true, tctx.msg_cb_visited);
tctx.msg_cb_visited = tctx.len_cb_visited = false;
err = sukat_sock_read(peer2, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.len_cb_visited);
EXPECT_EQ(true, tctx.msg_cb_visited);
tctx.msg_cb_visited = tctx.len_cb_visited = false;
sukat_sock_disconnect(peer1, peer2_from_peer1);
sukat_sock_disconnect(peer2, peer1_from_peer2);
sukat_sock_disconnect(peer1, peer1_to_peer2);
sukat_sock_disconnect(peer2, peer2_to_peer1);
sukat_sock_disconnect(peer1, endpoint1);
sukat_sock_disconnect(peer2, endpoint2);
sukat_sock_destroy(peer1);
sukat_sock_destroy(peer2);
free(peer1_name);
free(peer2_name);
}
class sukat_sock_test_inet : public ::testing::Test
{
protected:
// You can remove any or all of the following functions if its body is empty.
sukat_sock_test_inet() {
// You can do set-up work for each test here.
}
virtual ~sukat_sock_test_inet() {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up and
// cleaning up each test, you can define the following methods:
virtual void SetUp() {
memset(&default_cbs, 0, sizeof(default_cbs));
memset(&default_params, 0, sizeof(default_params));
memset(&default_endpoint_params, 0, sizeof(default_endpoint_params));
default_cbs.log_cb = test_log_cb;
default_endpoint_params.pinet.ip = local_ipv4;
default_endpoint_params.domain = AF_UNSPEC;
default_endpoint_params.type = SOCK_STREAM;
}
virtual void TearDown() {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests
struct sukat_sock_cbs default_cbs;
struct sukat_sock_params default_params;
struct sukat_sock_endpoint_params default_endpoint_params;
const char *local_ipv4 = "127.0.0.1", *local_ipv6 = "::1";
};
void *inet_conn_cb(void *ctx, sukat_sock_endpoint_t *client,
sukat_sock_event_t event)
{
struct read_ctx *tctx = (struct read_ctx *)ctx;
tctx->connect_visited = true;
tctx->newest_client = client;
if (tctx->should_disconnect)
{
EXPECT_EQ(SUKAT_SOCK_CONN_EVENT_DISCONNECT, event);
}
return NULL;
}
TEST_F(sukat_sock_test_inet, sukat_sock_test_basic_client_server)
{
sukat_sock_t *ctx, *client_ctx;;
sukat_sock_endpoint_t *server_endpoint, *client_endpoint;
char portbuf[strlen("65535") + 1];
int err;
struct read_ctx tctx = { };
sukat_sock_endpoint_t *client = NULL;
uint8_t buf[BUFSIZ];
struct test_msg *msg = (struct test_msg*)buf;
enum sukat_sock_send_return ret;
size_t messages_sent = 0;
tctx.buf = buf;
memset(buf, 0, sizeof(buf));
default_endpoint_params.server = true;
default_params.caller_ctx = &tctx;
default_cbs.conn_cb = inet_conn_cb;
default_cbs.msg_cb = msg_cb;
default_cbs.msg_len_cb = len_cb;
ctx = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, ctx);
server_endpoint = sukat_sock_endpoint_add(ctx, &default_endpoint_params);
EXPECT_NE(nullptr, server_endpoint);
EXPECT_EQ(AF_INET, get_domain(server_endpoint));
EXPECT_EQ(SOCK_STREAM, server_endpoint->info.type);
EXPECT_NE(0, sukat_sock_get_port(server_endpoint));
snprintf(portbuf, sizeof(portbuf), "%hu",
sukat_sock_get_port(server_endpoint));
default_endpoint_params.server = false;
default_endpoint_params.pinet.port = portbuf;
client_ctx = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, client_ctx);
client_endpoint =
sukat_sock_endpoint_add(client_ctx, &default_endpoint_params);
EXPECT_NE(nullptr, client_endpoint);
EXPECT_EQ(AF_INET, get_domain(client_endpoint));
EXPECT_EQ(SOCK_STREAM, client_endpoint->info.type);
err = sukat_sock_read(ctx, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(true, tctx.connect_visited);
client = tctx.newest_client;
tctx.connect_visited = false;
err = sukat_sock_read(client_ctx, 100);
EXPECT_EQ(0, err);
EXPECT_NE(true, client_endpoint->connect_in_progress);
EXPECT_NE(true, client_endpoint->epollout);
EXPECT_EQ(true, tctx.connect_visited);
tctx.connect_visited = false;
tctx.msg_cb_should_visit = true;
/* Lets try to get partial writes/reads */
msg->type = 0;
msg->len = 5555;
while ((ret = sukat_send_msg(ctx, client, buf, msg->len, NULL)) ==
SUKAT_SEND_OK)
{
messages_sent++;
}
EXPECT_NE(0, client->write_cache.len);
EXPECT_EQ(true, client->epollout);
err = sukat_sock_read(client_ctx, 0);
EXPECT_EQ(0, err);
EXPECT_EQ(tctx.n_messages, messages_sent - 1);
err = sukat_sock_read(ctx, 0);
EXPECT_EQ(0, err);
tctx.compare_payload = true;
err = sukat_sock_read(client_ctx, 100);
EXPECT_EQ(0, err);
EXPECT_EQ(tctx.n_messages, messages_sent);
tctx.should_disconnect = true;
sukat_sock_disconnect(ctx, client);
err = sukat_sock_read(client_ctx, 100);
EXPECT_EQ(0, err);
sukat_sock_destroy(client_ctx);
sukat_sock_disconnect(ctx, server_endpoint);
sukat_sock_destroy(ctx);
}
TEST_F(sukat_sock_test_inet, sukat_sock_test_ipv6)
{
sukat_sock_t *server, *client;
sukat_sock_endpoint_t *server_endpoint, *client_endpoint;
char portbuf[strlen("65535") + 1];
int err;
default_endpoint_params.server = true;
default_endpoint_params.pinet.ip = local_ipv6;
default_endpoint_params.type = SOCK_DGRAM;
server = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, server);
server_endpoint = sukat_sock_endpoint_add(server, &default_endpoint_params);
EXPECT_EQ(AF_INET6, get_domain(server_endpoint));
EXPECT_EQ(SOCK_DGRAM, server_endpoint->info.type);
EXPECT_NE(0, server_endpoint->info.sin.sin_port);
snprintf(portbuf, sizeof(portbuf), "%hu",
ntohs(server_endpoint->info.sin6.sin6_port));
default_endpoint_params.server = false;
default_endpoint_params.pinet.port = portbuf;
client = sukat_sock_create(&default_params, &default_cbs);
ASSERT_NE(nullptr, client);
client_endpoint = sukat_sock_endpoint_add(client, &default_endpoint_params);
EXPECT_EQ(AF_INET6, get_domain(client_endpoint));
EXPECT_EQ(SOCK_DGRAM, client_endpoint->info.type);
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
sukat_sock_disconnect(client, client_endpoint);
sukat_sock_destroy(client);
err = sukat_sock_read(server, 0);
EXPECT_EQ(0, err);
sukat_sock_disconnect(server, server_endpoint);
sukat_sock_destroy(server);
}
class sukat_sock_test_inet_stream_server : public ::testing::Test
{
protected:
sukat_sock_test_inet_stream_server() {
}
virtual ~sukat_sock_test_inet_stream_server() {
}
virtual void SetUp() {
memset(&default_cbs, 0, sizeof(default_cbs));
memset(&default_params, 0, sizeof(default_params));
memset(&default_endpoint_params, 0, sizeof(default_endpoint_params));
default_cbs.log_cb = test_log_cb;
default_endpoint_params.domain = AF_UNSPEC;
default_endpoint_params.type = SOCK_STREAM;
default_endpoint_params.server = true;
default_endpoint_params.pinet.port = portbuf;
snprintf(portbuf, sizeof(portbuf), "%hu", (unsigned short)0);
server = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, server);
endpoint = sukat_sock_endpoint_add(server, &default_endpoint_params);
EXPECT_NE(nullptr, endpoint);
EXPECT_NE(0, sukat_sock_get_port(endpoint));
snprintf(portbuf, sizeof(portbuf), "%hu",
sukat_sock_get_port(endpoint));
default_endpoint_params.server = false;
}
virtual void TearDown() {
sukat_sock_disconnect(server, endpoint);
sukat_sock_destroy(server);
}
struct sukat_sock_cbs default_cbs;
struct sukat_sock_params default_params;
struct sukat_sock_endpoint_params default_endpoint_params;
sukat_sock_t *server;
sukat_sock_endpoint_t *endpoint;
char portbuf[strlen("65535") + 1];
};
struct failed_conn_ctx
{
sukat_sock_endpoint_t *endpoint;
unsigned int should_visit:1;
unsigned int visited:1;
unsigned int unused:6;
};
void *failed_conn_cb(void *caller_ctx, sukat_sock_endpoint_t *endpoint,
enum sukat_sock_new_conn_event event)
{
EXPECT_NE(nullptr, caller_ctx);
if (caller_ctx)
{
struct failed_conn_ctx *conn_ctx = (struct failed_conn_ctx *)caller_ctx;
EXPECT_EQ(true, conn_ctx->should_visit);
EXPECT_EQ(SUKAT_SOCK_CONN_EVENT_DISCONNECT, event);
EXPECT_EQ(conn_ctx->endpoint, endpoint);
conn_ctx->endpoint = NULL;
conn_ctx->visited = true;
}
return NULL;
}
TEST_F(sukat_sock_test_inet_stream_server, sukat_sock_test_failed_conn)
{
sukat_sock_t *client;
struct failed_conn_ctx conn_ctx = { };
int err;
default_params.caller_ctx = &conn_ctx;
default_cbs.conn_cb = failed_conn_cb;
client = sukat_sock_create(&default_params, &default_cbs);
EXPECT_NE(nullptr, client);
conn_ctx.endpoint = sukat_sock_endpoint_add(client, &default_endpoint_params);
EXPECT_NE(nullptr, conn_ctx.endpoint);
sukat_sock_disconnect(server, endpoint);
endpoint = NULL;
conn_ctx.should_visit = true;
err = sukat_sock_read(client, 100);
EXPECT_EQ(0, err);
EXPECT_EQ(true, conn_ctx.visited);
EXPECT_EQ(nullptr, conn_ctx.endpoint);
sukat_sock_destroy(client);
}
class sukat_sock_test_unix_splice : public ::testing::Test
{
protected:
struct splice_ctx
{
int intermediary_fds[2];
int server_pair[2];
int client_pair[2];
sukat_sock_endpoint_t *client_from_server;
};
sukat_sock_test_unix_splice() {
}
virtual ~sukat_sock_test_unix_splice() {
}
static void *splice_conn_cb(void *ctx, sukat_sock_endpoint_t *endpoint,
sukat_sock_event_t event)
{
struct splice_ctx *test_ctx = (struct splice_ctx *)ctx;
EXPECT_NE(nullptr, test_ctx);
if (event == SUKAT_SOCK_CONN_EVENT_ACCEPTED)
{
test_ctx->client_from_server = endpoint;
}
else if (event == SUKAT_SOCK_CONN_EVENT_DISCONNECT)
{
if (endpoint == test_ctx->client_from_server)
{
test_ctx->client_from_server = NULL;
}
}
return NULL;
}
static void
splice_splice_cb(void *ctx, sukat_sock_endpoint_t *endpoint,
int *fd, int **intermediary)
{
struct splice_ctx *test_ctx = (struct splice_ctx *)ctx;
EXPECT_NE(nullptr, test_ctx);
if (endpoint == test_ctx->client_from_server)
{
*fd = test_ctx->server_pair[1];
}
else
{
*fd = test_ctx->client_pair[1];
}
/* Use same fds for server and client intermediary. Yeah that'll probably
* never misfire.. */
if (test_ctx->intermediary_fds[0] != -1 &&
test_ctx->intermediary_fds[1] != -1)
{
*intermediary = test_ctx->intermediary_fds;
}
}
virtual void SetUp() {
struct sukat_sock_params params = { };
struct sukat_sock_cbs cbs = { };
struct sukat_sock_endpoint_params eparams = { };
unsigned int i;
char abstract_socket[256];
int err, *intptr;
for (intptr = (int *)&test_ctx, i = 0; i < n_fds; i++, intptr++)
{
*intptr = -1;
}
params.caller_ctx = &test_ctx;
cbs.log_cb = test_log_cb;
cbs.conn_cb = splice_conn_cb;
cbs.splice_cb = splice_splice_cb;
server = sukat_sock_create(¶ms, &cbs);
EXPECT_NE(nullptr, server);
client = sukat_sock_create(¶ms, &cbs);
EXPECT_NE(nullptr, client);
get_random_socket(abstract_socket, sizeof(abstract_socket));
eparams.type = SOCK_STREAM;
eparams.domain = AF_UNIX;
eparams.punix.is_abstract = true;
eparams.punix.name = abstract_socket;
eparams.server = true;
server_endpoint = sukat_sock_endpoint_add(server, &eparams);
EXPECT_NE(nullptr, server_endpoint);
eparams.server = false;
client_endpoint = sukat_sock_endpoint_add(client, &eparams);
EXPECT_NE(nullptr, client_endpoint);
err = sukat_sock_read(server, 100);
EXPECT_EQ(0, err);
EXPECT_NE(nullptr, test_ctx.client_from_server);
err = socketpair(AF_UNIX, SOCK_STREAM | O_NONBLOCK | O_CLOEXEC,
0, test_ctx.client_pair);
EXPECT_EQ(0, err);
err = socketpair(AF_UNIX, SOCK_STREAM | O_NONBLOCK | O_CLOEXEC,
0, test_ctx.server_pair);
EXPECT_EQ(0, err);
}
virtual void TearDown()
{
unsigned int i;
int *fdptr = (int *)&test_ctx;
for (i = 0; i < n_fds; i++, fdptr++)
{
if (*fdptr != -1)
{
close(*fdptr);
}
}
sukat_sock_disconnect(client, test_ctx.client_from_server);
sukat_sock_disconnect(client, client_endpoint);
sukat_sock_disconnect(server, server_endpoint);
sukat_sock_destroy(client);
sukat_sock_destroy(server);
}
struct splice_ctx test_ctx;
sukat_sock_t *server, *client;
sukat_sock_endpoint_t *server_endpoint, *client_endpoint;
const size_t n_fds = 6;
};
TEST_F(sukat_sock_test_unix_splice, sukat_sock_test_splice_basic)
{
int err;
ssize_t ret;
char buf[BUFSIZ], cmpbuf[BUFSIZ];
err = pipe2(test_ctx.intermediary_fds, O_CLOEXEC | O_NONBLOCK);
EXPECT_EQ(0, err);
snprintf(buf, sizeof(buf), "Hello from client");
ret = write(test_ctx.client_pair[0], buf, strlen(buf));
EXPECT_LT(0, ret);
ret = sukat_sock_splice_to(client, client_endpoint, test_ctx.client_pair[1],
test_ctx.intermediary_fds);
EXPECT_EQ(strlen(buf), ret);
err = sukat_sock_read(server, 100);
EXPECT_EQ(0, err);
ret = read(test_ctx.server_pair[0], cmpbuf, sizeof(cmpbuf));
EXPECT_EQ(strlen(buf), ret);
err = strncmp(buf, cmpbuf, strlen(buf));
EXPECT_EQ(0, err);
}
TEST_F(sukat_sock_test_unix_splice, sukat_sock_test_splice_bufsiz)
{
int err;
ssize_t ret;
size_t total = 0, total_recv = 0;
char buf[BUFSIZ], cmpbuf[BUFSIZ];
err = pipe2(test_ctx.intermediary_fds, O_CLOEXEC | O_NONBLOCK);
EXPECT_EQ(0, err);
memset(buf, 'c', sizeof(buf));
memset(cmpbuf, 0, sizeof(cmpbuf));
while (total < sizeof(buf))
{
ret = write(test_ctx.server_pair[0], buf + total, sizeof(buf) - total);
EXPECT_LT(0, ret);
total += (size_t)ret;
ret = sukat_sock_splice_to(server, test_ctx.client_from_server,
test_ctx.server_pair[1],
test_ctx.intermediary_fds);
EXPECT_LT(0, ret);
err = sukat_sock_read(client, 100);
EXPECT_EQ(0, err);
ret = read(test_ctx.client_pair[0], cmpbuf + total_recv,
sizeof(cmpbuf) - total_recv);
EXPECT_LT(0, ret);
}
err = memcmp(buf, cmpbuf, sizeof(buf));
EXPECT_EQ(0, err);
}
TEST_F(sukat_sock_test_unix_splice, sukat_sock_test_splice_pipes)
{
int *fdptr;
unsigned int i;
int err;
ssize_t ret;
char buf[BUFSIZ], cmpbuf[BUFSIZ];
for (i = 0, fdptr = (int *)&test_ctx.server_pair; i < 4; i++, fdptr++)
{
close(*fdptr);
*fdptr = -1;
}
err = pipe2(test_ctx.server_pair, O_CLOEXEC | O_NONBLOCK);
EXPECT_EQ(0, err);
err = pipe2(test_ctx.client_pair, O_CLOEXEC | O_NONBLOCK);
EXPECT_EQ(0, err);
snprintf(buf, sizeof(buf), "Client tries to do this without intermediary");
ret = write(test_ctx.client_pair[1], buf, strlen(buf));
EXPECT_EQ(strlen(buf), ret);
ret = sukat_sock_splice_to(client, client_endpoint, test_ctx.client_pair[0],
NULL);
EXPECT_LE(0, ret);
err = sukat_sock_read(server, 100);
EXPECT_EQ(0, err);
ret = read(test_ctx.server_pair[0], cmpbuf, sizeof(buf));
EXPECT_EQ(strlen(buf), ret);
err = memcmp(buf, cmpbuf, strlen(buf));
EXPECT_EQ(0, err);
}
| mit |
LandRegistry/service-tests-alpha | features/support/env.rb | 1504 |
$app_systemofrecord = (ENV['SYSTEM_OF_RECORD_API_URL'] || 'http://0.0.0.0:8000')
$app_mint = (ENV['MINT_API_URL'] || 'http://0.0.0.0:8001')
$app_property_frontend = (ENV['PROPERTY_FRONTEND_URL'] || 'http://0.0.0.0:8002')
$app_search_api = (ENV['SEARCH_API_URL'] || 'http://0.0.0.0:8003')
$app_casework_frontend = (ENV['CASEWORK_FRONTEND_URL'] || 'http://0.0.0.0:8004')
$app_public_titles_api = (ENV['PUBLIC_TITLES_API_URL'] || 'http://0.0.0.0:8005')
# the-feeder (not a webapp) http://0.0.0.0:8006
$app_service_frontend = (ENV['SERVICE_FRONTEND_URL'] || 'http://0.0.0.0:8007')
$app_decision = (ENV['DECISION_URL'] || 'http://0.0.0.0:8009')
$app_ownership = (ENV['OWNERSHIP_URL'] || 'http://0.0.0.0:8010')
$app_matching = (ENV['MATCHING_URL'] || 'http://0.0.0.0:8011')
# fixtures (internal use only) http://0.0.0.0:8012
$app_introductions = (ENV['INTRODUCTIONS_URL'] || 'http://0.0.0.0:8013')
$app_cases = (ENV['CASES_URL'] || 'http://0.0.0.0:8014')
$app_historian = (ENV['HISTORIAN_URL'] || 'http://0.0.0.0:8015')
#$app_XXX = (ENV['XX_URL'] || 'http://0.0.0.0:80XX')
| mit |
butla/experiments | curtsies_cli_ui/main.py | 1251 | import asyncio
import random
from curtsies import FullscreenWindow, Input, FSArray
from curtsies.fmtfuncs import red, bold, green, yellow
print(yellow('this prints normally, not to the alternate screen'))
async def bla(window, array_):
mark = '|'
while True:
color = random.choice([red, green, yellow])
row = random.choice(range(window.height))
column = random.choice(range(window.width-len(mark)))
a[row, column:column+len(mark)] = [color(mark)]
window.render_to_terminal(array_)
await asyncio.sleep(random.random())
async def bla_2(window, array_):
mark = '-'
while True:
color = random.choice([red, green, yellow])
row = random.choice(range(window.height))
column = random.choice(range(window.width-len(mark)))
a[row, column:column+len(mark)] = [color(mark)]
window.render_to_terminal(array_)
await asyncio.sleep(random.random()/2)
l = asyncio.get_event_loop()
with FullscreenWindow() as window:
with Input() as input_generator:
a = FSArray(window.height, window.width)
window.render_to_terminal(a)
l.create_task(bla(window, a))
l.create_task(bla_2(window, a))
l.run_forever()
| mit |
netzke/netzke-communitypack | test/communitypack_test_app/spec/components/book_grid_with_live_search_spec.rb | 1040 | require 'spec_helper'
describe BookGridWithLiveSearch, :type => :request, :js => true do
before :each do
FactoryGirl.create(:book, :title => "One Hundred Years of Solitude")
FactoryGirl.create(:book, :title => "Moby Dick")
end
it "search for 'Moby' should list 1 book" do
visit '/components/BookGridWithLiveSearch'
grid_count.should == 2
fill_in 'live_search_field', :with => 'Moby'
sleep(0.6) # wait until search gets triggered
grid_count.should == 1
end
it "search for 'Moby' should list 'Moby Dick'" do
visit '/components/BookGridWithLiveSearch'
grid_count.should == 2
fill_in 'live_search_field', :with => 'Moby'
sleep(0.6) # wait until search gets triggered
grid_cell_value(0,:title).should == "Moby Dick"
end
it "search for 'not a book title' shouldn't list anything" do
visit '/components/BookGridWithLiveSearch'
fill_in 'live_search_field', :with => 'not a book title'
sleep(0.6) # wait until search gets triggered
grid_count.should == 0
end
end
| mit |
NinjaDero/Directly | setup.py | 728 | #!/usr/bin/env python
from distutils.core import setup
setup(name='Directly',
version='1.0',
description='ExtDirect python implementation for Django-powered apps.',
author='Alex Mannhold',
author_email='EvilDwarf@gmx.net',
url='https://github.com/NinjaDero/Directly',
download_url='https://github.com/NinjaDero/Directly/archive/master.zip',
packages=['Directly'],
package_dir={'Directly':'Directly'},
package_data={'Directly':['LICENCE']},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Programming Language :: Python',
],
)
| mit |
fstudio/Phoenix | include/Flavorless/FlavorlessConvert.hpp | 742 | /*********************************************************************************************************
* FlavorlessConvert.hpp
* Note: Phoenix Flavorless Library
* Date: @2015.04
* E-mail:<forcemz@outlook.com>
* Copyright (C) 2015 The ForceStudio All Rights Reserved.
**********************************************************************************************************/
#ifndef FLAVORLESS_CONVERT_HPP
#define FLAVORLESS_CONVERT_HPP
#include "FlavorlessInternal.h"
template <class Character,class T> inline std::basic_string<Character> to_string(T value)
{
std::basic_stringstream ss;
ss<<val;
return ss.str();
}
template <class Character,class T>
class FlavorlessConvert{
public:
FlavorlessConvert();
};
#endif
| mit |
karapetyan-ashot/pms | EasySoftware.PMS.Core/Models/Task.cs | 1960 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EasySoftware.PMS.Core.Models
{
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
[DataContract]
public partial class Task : ModelBase
{
[DataMember]
public int Id { get; set; }
[DataMember]
public int ProjectId { get; set; }
[DataMember]
public int CategoryId { get; set; }
[DataMember]
public Nullable<int> ApplicationId { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string Notes { get; set; }
[DataMember]
public int StateId { get; set; }
[DataMember]
public Nullable<int> ReleaseId { get; set; }
[DataMember]
public Nullable<int> SprintId { get; set; }
[DataMember]
public System.DateTime Created { get; set; }
[DataMember]
public int CreatedBy { get; set; }
[DataMember]
public System.DateTime Modified { get; set; }
[DataMember]
public int ModifiedBy { get; set; }
[DataMember]
public string CategoryIdPath { get; set; }
[DataMember]
public string CategoryNamePath { get; set; }
[DataMember]
public string CreatedByName { get; set; }
[DataMember]
public string ModifiedByName { get; set; }
[DataMember]
public int Sort { get; set; }
[DataMember]
public Nullable<int> ResponsibleId { get; set; }
[DataMember]
public Nullable<int> ParentId { get; set; }
// public virtual Project Project { get; set; }
}
}
| mit |
md5555/devicecast | lib/native/MenuFactory.js | 4091 | const {dialog, MenuItem} = require('electron')
var packageJson = require('../../package.json');
var logger = require('../common/logger');
var SOUND_ICON = String.fromCharCode('0xD83D', '0xDD0A');
var setSpeaker = function (menuItem) {
logger.debug('Setting menu label to [%s]', menuItem.label);
};
var removeSpeaker = function (menuItem) {
menuItem.icon = null;
logger.debug('Removing menu label to [%s]', menuItem.label);
};
var about = function () {
logger.debug('Adding About Menu Item');
return new MenuItem({
id: 'about',
label: 'About',
click: function () {
dialog.showMessageBox({
title: 'About',
message: packageJson.name + ' - v' + packageJson.version + '. ' + 'Created by ' + packageJson.author,
detail: packageJson.description + ' \nProject: ' + packageJson.repository.url,
buttons: ["OK"]
});
}
});
};
var aboutStreamFeature = function () {
logger.debug('Adding About Stream Feature Item');
return new MenuItem({
id: 'about-stream',
label: 'About This Feature',
click: function () {
dialog.showMessageBox({
title: 'Stream Selection',
message: 'You can cast OSX Audio Output (default) or you\'re Internal Microphone.',
detail: 'Casting the Internal Microphone turns the speaker into a mega-phone!',
buttons: ["OK"]
});
}
});
};
var quit = function (cb) {
logger.debug('Adding Quit Menu Item');
return new MenuItem({
id: 'quit',
label: 'Quit',
click: cb
});
};
var separator = function () {
return new MenuItem({type: 'separator'});
};
var sonosDeviceItem = function (device, onClickHandler) {
var label = device.name;
logger.debug('Adding Sonos Menu Item [%s]', label);
return new MenuItem({
id: device.name,
label: label,
click: onClickHandler
});
};
var raumfeldDeviceItem = function (fqn, device, onClickHandler) {
var label = device.name;
logger.debug('Adding Raumfeld Menu Item [%s]', label);
return new MenuItem({
id: fqn,
label: label,
click: onClickHandler
});
};
var jongoDeviceItem = function (device, onClickHandler) {
var label = device.name;
logger.debug('Adding Jongo Menu Item [%s]', label);
return new MenuItem({
id: device.name,
label: label,
click: onClickHandler
});
};
var chromeCastItem = function (fqn, device, onClickHandler) {
var label = device.name;
logger.debug('Adding Chromecast Menu Item [%s]', label);
return new MenuItem({
id: fqn,
label: label,
click: onClickHandler
});
};
var chromeCastAudioItem = function (device, onClickHandler) {
var label = device.name;
logger.debug('Adding Chromecast Audio Menu Item [%s]', label);
return new MenuItem({
id: device.name,
label: label,
click: onClickHandler
});
};
var castToDeviceMenu = function (menu) {
logger.debug('Adding cast to device menu');
return new MenuItem({
label: 'Select Device...',
submenu: menu
})
};
var steamMenu = function (menu) {
logger.debug('Adding stream menu');
return new MenuItem({
label: 'Stream',
submenu: menu
});
};
var scanningForDevices = function () {
logger.debug('Adding Scanning for Devices...');
return new MenuItem({
label: 'Scanning for Devices...'
});
};
module.exports = {
setSpeaker: setSpeaker,
removeSpeaker: removeSpeaker,
about: about,
aboutStreamFeature: aboutStreamFeature,
quit: quit,
scanningForDevices: scanningForDevices,
separator: separator,
sonosDeviceItem: sonosDeviceItem,
castToDeviceMenu: castToDeviceMenu,
steamMenu: steamMenu,
jongoDeviceItem: jongoDeviceItem,
chromeCastItem: chromeCastItem,
chromeCastAudioItem: chromeCastAudioItem,
raumfeldDeviceItem: raumfeldDeviceItem
};
| mit |
gatsbyjs/gatsby | examples/using-javascript-transforms/src/articles/2017-05-30-choropleth-on-d3v4-alternate/index.js | 5544 | import React from "react"
import { graphql } from "gatsby"
import BlogPostChrome from "../../components/BlogPostChrome"
const d3 = require(`d3`)
// this is an additional method to export data and make it usable elsewhere
export const frontmatter = {
title: `Alternate Choropleth on d3v4`,
written: `2017-05-30`,
layoutType: `post`,
path: `/choropleth-on-d3v4-alternate/`,
category: `data science`,
description: `Even more things about the choropleth. No, seriously.`,
}
class choroplethAltBase extends React.Component {
componentDidMount() {
this.d3Node = d3.select(`div#states`)
let measurements = {
width: this.d3Node._groups[0][0].clientWidth,
height: this.d3Node._groups[0][0].clientHeight,
}
let space = graph.setup(this.d3Node, measurements)
/*
we begin drawing here, grab the data and use it to draw
*/
d3.queue()
.defer(d3.json, stateDataURL)
.defer(d3.csv, statisticsDataURL)
.awaitAll(function (error, results) {
let states = results[0].states
let stats = results[1]
let mergedData = mergeData(states, `abbrev`, stats, `Abbreviation`)
graph.draw(space, mergedData, measurements)
})
}
componentWillUnmount() {
d3.select(`svg`).remove()
}
render() {
let data = this.props.data.markdownRemark
let html = data.html
return (
<BlogPostChrome
{...{
frontmatter: this.props.data.javascriptFrontmatter.frontmatter,
site: this.props.data.site,
}}
>
<div className="section">
<div className="container">
<div id="states" />
<div id="tooltip" />
</div>
</div>
<div className="section">
<div className="container">
<div dangerouslySetInnerHTML={{ __html: html }} />
</div>
</div>
</BlogPostChrome>
)
}
}
export default choroplethAltBase
let graph = {} // we namespace our d3 graph into setup and draw
const stateDataURL = `https://gist.githubusercontent.com/jbolda/52cd5926e9241d26489ec82fa2bddf37/raw/f409b82e51072ea23746325eff7aa85b7ef4ebbd/states.json`
const statisticsDataURL = `https://gist.githubusercontent.com/jbolda/52cd5926e9241d26489ec82fa2bddf37/raw/f409b82e51072ea23746325eff7aa85b7ef4ebbd/stats.csv`
graph.setup = (selection, measurements) => {
// the path string is drawn expecting:
// a width of 950px
// a height of 600px
// which gives an aspect ratio of 1.6
let svg = selection
.append(`svg`)
.attr(`width`, measurements.width)
.attr(`height`, measurements.width / 1.6)
return svg
}
graph.draw = (svg, data, measurements) => {
/*
our data expects an array of objects
each object is expected to have:
name: tooltip - the full name of the state
abbrev: mergeData - used as the key to merge the json and csv
low: tooltip, color domain
high: tooltip, color domain
average: tooltip, path fill
*/
let color = d3
.scaleQuantize()
.range([
`rgb(237,248,233)`,
`rgb(186,228,179)`,
`rgb(116,196,118)`,
`rgb(49,163,84)`,
`rgb(0,109,44)`,
])
color.domain([
d3.min(data, function (d) {
return d.low
}),
d3.max(data, function (d) {
return d.high
}),
])
let scaleFactor = measurements.width / 950
let states = svg.selectAll(`path.states`).data(data)
states
.enter()
.append(`path`)
.attr(`class`, `state`)
.attr(`id`, d => d.abbrev)
.attr(`stroke`, `gray`)
.attr(`d`, d => d.path)
.attr(`transform`, `scale(` + scaleFactor + `)`)
.style(`fill`, d => color(d.average))
.on(`mouseover`, mouseOver)
.on(`mouseout`, mouseOut)
}
let tooltipHtml = d =>
`<h4>` +
d.name +
`</h4><table>` +
`<tr><td>Low</td><td>` +
d.low +
`</td></tr>` +
`<tr><td>High</td><td>` +
d.high +
`</td></tr>` +
`<tr><td>Avg</td><td>` +
d.average +
`</td></tr>` +
`</table>`
let mouseOver = d => {
let tooltip = d3
.select(`#tooltip`)
.html(tooltipHtml(d))
.style(`opacity`, 0.9)
.style(`left`, d3.event.pageX + `px`)
.style(`top`, d3.event.pageY - 28 + `px`)
tooltip.transition().duration(200)
}
let mouseOut = () => {
d3.select(`#tooltip`).transition().duration(500).style(`opacity`, 0)
}
// eslint-disable-next-line no-unused-vars
function scale(scaleFactor, width, height) {
return d3.geoTransform({
point: function (x, y) {
this.stream.point(
(x - width / 2) * scaleFactor + width / 2,
(y - height / 2) * scaleFactor + height / 2
)
},
})
}
let mergeData = (d1, d1key, d2, d2key) => {
let data = []
d1.forEach(s1 => {
d2.forEach(s2 => {
if (s1[d1key] === s2[d2key]) {
data.push(Object.assign({}, s1, s2))
}
})
})
return data
}
// We want to keep this component mostly about the code
// so we write our explanation with markdown and manually pull it in here.
// Within the config, we loop all of the markdown and createPages. However,
// it will ignore any files appended with an _underscore. We can still manually
// query for it here, and get the transformed html though because remark transforms
// any markdown based node.
export const pageQuery = graphql`
query choroplethOnD3v4Alt {
markdownRemark(
fields: {
slug: { eq: "/2017-05-30-choropleth-on-d3v4-alternate/_choropleth/" }
}
) {
html
}
javascriptFrontmatter {
...JSBlogPost_frontmatter
}
site {
...site_sitemetadata
}
}
`
| mit |
Malkovski/Telerik | C#/C# Part 1/Exercises/MissCat3/Properties/AssemblyInfo.cs | 1392 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MissCat3")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MissCat3")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("14699b6c-93e1-42ef-8a2f-f0f0deb2d95a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
deplug/deplug | src/lib/script.ts | 1419 | import fs from 'fs'
import genet from '@genet/api'
import path from 'path'
import { promisify } from 'util'
import vm from 'vm'
const promiseReadFile = promisify(fs.readFile)
export default class Script {
static async execute(file: string) {
const code = await promiseReadFile(file, 'utf8')
const wrapper =
`(function(module, require, __filename, __dirname){ ${code} })`
const options = {
filename: file,
displayErrors: true,
}
const dir = path.dirname(file)
const func = vm.runInThisContext(wrapper, options)
const root = global as any
function isAvailable(name) {
try {
root.require.resolve(name)
return true
} catch (err) {
return false
}
}
function req(name) {
if (name === 'genet') {
return genet
} else if (name.startsWith('./')) {
const resolved = path.resolve(dir, name)
if (isAvailable(resolved)) {
return root.require(resolved)
}
} else {
const resolved = path.resolve(dir, 'node_modules', name)
if (isAvailable(resolved)) {
return root.require(resolved)
}
}
return root.require(name)
}
const module: any = {}
func(module, req, file, dir)
if (typeof module.exports !== 'function') {
throw new TypeError('module.exports must be a function')
}
return module.exports
}
}
| mit |
Vulnerator/Vulnerator | Model/BusinessLogic/WasspReader.cs | 10681 | using log4net;
using System;
using System.Collections.ObjectModel;
using System.Data.SQLite;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using Vulnerator.Model.DataAccess;
using Vulnerator.Helper;
using Vulnerator.Model.Object;
using File = System.IO.File;
namespace Vulnerator.Model.BusinessLogic
{
class WasspReader
{
private DatabaseInterface databaseInterface = new DatabaseInterface();
private string wasspFile;
string _groupName = null;
public string ReadWassp(Object.File file, string groupName)
{
try
{
if (file.FilePath.IsFileInUse())
{
LogWriter.LogError($"'{file.FileName}' is in use; please close any open instances and try again.");
return "Failed; File In Use";
}
HTMLtoXML htmlReader = new HTMLtoXML();
wasspFile = htmlReader.Convert(file.FilePath);
if (wasspFile.Equals("Failed; See Log"))
{ return wasspFile; }
ParseWasspWithXmlReader(wasspFile, file);
return "Processed";
}
catch (Exception exception)
{
string error = $"Unable to process WASSP file '{file.FileName}'.";
LogWriter.LogErrorWithDebug(error, exception);
return "Failed; See Log";
}
finally
{
if (File.Exists(wasspFile))
{ File.Delete(wasspFile); }
}
}
private void ParseWasspWithXmlReader(string wasspFile, Object.File file)
{
try
{
XmlReaderSettings xmlReaderSettings = GenerateXmlReaderSettings();
if (DatabaseBuilder.sqliteConnection.State.ToString().Equals("Closed"))
{ DatabaseBuilder.sqliteConnection.Open(); }
using (SQLiteTransaction sqliteTransaction = DatabaseBuilder.sqliteConnection.BeginTransaction())
{
using (SQLiteCommand sqliteCommand = DatabaseBuilder.sqliteConnection.CreateCommand())
{
databaseInterface.InsertParameterPlaceholders(sqliteCommand);
sqliteCommand.Parameters["FindingType"].Value = "WASSP";
sqliteCommand.Parameters["GroupName"].Value = string.IsNullOrWhiteSpace(_groupName) ? "All" : _groupName;
sqliteCommand.Parameters["SourceName"].Value = "Windows Automated Security Scanning Program (WASSP)";
sqliteCommand.Parameters["SourceVersion"].Value = string.Empty;
sqliteCommand.Parameters["SourceRelease"].Value = string.Empty;
databaseInterface.InsertParsedFileSource(sqliteCommand, file);
using (XmlReader xmlReader = XmlReader.Create(wasspFile, xmlReaderSettings))
{
while (xmlReader.Read())
{
if (xmlReader.IsStartElement() && xmlReader.Name.Equals("table"))
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
switch (xmlReader.Name)
{
case "MachineInfo":
{
sqliteCommand.Parameters["DiscoveredHostName"].Value = ObtainItemValue(xmlReader).Trim();
sqliteCommand.Parameters["DisplayedHostName"].Value = sqliteCommand.Parameters["DiscoveredHostName"].Value;
break;
}
case "TestInfo":
{
sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value = ObtainItemValue(xmlReader);
break;
}
case "DateInfo":
{
string dateTime = ObtainItemValue(xmlReader).Replace("\n", string.Empty);
sqliteCommand.Parameters["FirstDiscovered"].Value = DateTime.ParseExact(
dateTime, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture).ToShortDateString();
sqliteCommand.Parameters["LastObserved"].Value = sqliteCommand.Parameters["FirstDiscovered"].Value;
break;
}
case "ValueInfo":
{
sqliteCommand.Parameters["VulnerabilityTitle"].Value = ObtainItemValue(xmlReader);
break;
}
case "DescriptionInfo":
{
sqliteCommand.Parameters["VulnerabilityDescription"].Value = ObtainItemValue(xmlReader);
break;
}
case "TestRes":
{
sqliteCommand.Parameters["Status"].Value = ObtainItemValue(xmlReader).ToVulneratorStatus();
break;
}
case "VulnInfo":
{
sqliteCommand.Parameters["PrimaryRawRiskIndicator"].Value = ObtainItemValue(xmlReader).ToRawRisk();
break;
}
case "RecInfo":
{
sqliteCommand.Parameters["FixText"].Value = ObtainItemValue(xmlReader);
break;
}
}
}
else if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.Name.Equals("table"))
{
sqliteCommand.Parameters["DeltaAnalysisIsRequired"].Value = "False";
if (sqliteCommand.Parameters["VulnerabilityVersion"].Value == DBNull.Value)
{ sqliteCommand.Parameters["VulnerabilityVersion"].Value = string.Empty; }
if (sqliteCommand.Parameters["VulnerabilityRelease"].Value == DBNull.Value)
{ sqliteCommand.Parameters["VulnerabilityRelease"].Value = string.Empty; }
databaseInterface.InsertVulnerabilitySource(sqliteCommand);
databaseInterface.InsertHardware(sqliteCommand);
databaseInterface.InsertVulnerability(sqliteCommand);
databaseInterface.MapVulnerabilityToSource(sqliteCommand);
databaseInterface.UpdateUniqueFinding(sqliteCommand);
databaseInterface.InsertUniqueFinding(sqliteCommand);
break;
}
}
}
}
}
}
sqliteTransaction.Commit();
}
}
catch (Exception exception)
{
LogWriter.LogError("Unable to parse WASSP file with XML reader.");
throw exception;
}
finally
{ DatabaseBuilder.sqliteConnection.Close(); }
}
private string ObtainItemValue(XmlReader xmlReader)
{
try
{
while (xmlReader.Read())
{
if (xmlReader.IsStartElement())
{ break; }
}
xmlReader.Read();
return xmlReader.Value;
}
catch (Exception exception)
{
LogWriter.LogError("Unable to obtain current node value.");
throw exception;
}
}
private XmlReaderSettings GenerateXmlReaderSettings()
{
try
{
XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.IgnoreWhitespace = true;
xmlReaderSettings.IgnoreComments = true;
xmlReaderSettings.ValidationType = ValidationType.Schema;
xmlReaderSettings.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.ProcessInlineSchema;
xmlReaderSettings.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.ProcessSchemaLocation;
return xmlReaderSettings;
}
catch (Exception exception)
{
LogWriter.LogError("Unable to generate XmlReaderSettings.");
throw exception;
}
}
}
}
| mit |
JohnJosuaPaderon/Citicon | Citicon/Forms/DriverTripReportForm.cs | 7002 | using Citicon.Data;
using Citicon.DataManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Citicon.Forms
{
public partial class DriverTripReportForm : Form
{
public DriverTripReportForm()
{
InitializeComponent();
TripReportManager = new TripReportManager();
}
public IEnumerable<Delivery> Deliveries { get; private set; }
private TripReportManager TripReportManager { get; }
private async Task GetDriverListAsync()
{
DriverDataGridView.Rows.Clear();
var range = new DateTimeRange(RangeStartDateTimePicker.Value, RangeEndDateTimePicker.Value);
try
{
var drivers = await EmployeeManager.GetTripReportDriverListAsync(range);
if (drivers != null && drivers.Any())
{
foreach (var driver in drivers)
{
AddToUI(driver);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
range = null;
}
}
private async Task GetDeliveryListAsync()
{
DeliveryDataGridView.Rows.Clear();
if (DriverDataGridView.SelectedRows.Count == 1)
{
var driver = DriverDataGridView.SelectedRows[0].Cells[DriverColumn.Name].Value as Employee;
var range = new DateTimeRange(RangeStartDateTimePicker.Value, RangeEndDateTimePicker.Value);
try
{
Deliveries = await DeliveryManager.GetTripReportDeliveryListByDriverAsync(range, driver);
if (Deliveries != null && Deliveries.Any())
{
foreach (var delivery in Deliveries)
{
AddToUI(delivery);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
range = null;
}
}
}
private void AddToUI(Delivery delivery)
{
if (delivery != null)
{
var row = new DataGridViewRow()
{
Height = 30
};
row.Cells.Add(new DataGridViewTextBoxCell { Value = delivery });
row.Cells.Add(new DataGridViewTextBoxCell { Value = delivery.ProjectDesign });
row.Cells.Add(new DataGridViewTextBoxCell { Value = delivery.DeliveryDate });
row.Cells.Add(new DataGridViewTextBoxCell { Value = delivery.Project });
row.Cells.Add(new DataGridViewTextBoxCell { Value = delivery.DeliveryReceiptNumberDisplay });
row.Cells.Add(new DataGridViewTextBoxCell { Value = delivery.TransitMixer });
row.Cells.Add(new DataGridViewTextBoxCell { Value = delivery.Project?.Location });
row.Cells.Add(new DataGridViewTextBoxCell { Value = delivery.Route });
row.Cells.Add(new DataGridViewTextBoxCell { Value = delivery.Route?.Rate });
row.Cells.Add(new DataGridViewTextBoxCell { Value = delivery.TransitMixer.Additionals });
DeliveryDataGridView.Rows.Add(row);
}
}
private async Task ExportTripReportAsync(TripReportMode mode)
{
if (Deliveries != null && Deliveries.Any())
{
Employee driver = null;
switch (mode)
{
case TripReportMode.All:
if (DriverDataGridView.Rows.Count <= 0)
{
MessageBox.Show("No drivers.");
return;
}
break;
case TripReportMode.Driver:
if (DriverDataGridView.SelectedRows[0].Cells[DriverColumn.Name].Value is Employee tempDriver && Deliveries.Any(d => d.Driver == tempDriver))
{
driver = tempDriver;
}
else
{
MessageBox.Show("No driver.");
return;
}
break;
}
TripReport tripReport = null;
var deliveryDateRange = new DateTimeRange(RangeStartDateTimePicker.Value, RangeEndDateTimePicker.Value);
switch (mode)
{
case TripReportMode.NotSet:
MessageBox.Show("Exporting information is not set.");
break;
case TripReportMode.All:
tripReport = TripReport.Extract(deliveryDateRange, await DeliveryManager.GetListByDeliveryDateRangeAsync(deliveryDateRange));
await TripReportManager.ExportAllDriverTripReportAsync(tripReport);
MessageBox.Show("Done");
break;
case TripReportMode.Driver:
tripReport = TripReport.ExtractDriver(deliveryDateRange, driver, Deliveries);
await TripReportManager.ExportDriverTripReportAsync(tripReport);
MessageBox.Show("Done");
break;
}
}
else
{
MessageBox.Show("No deliveries.");
}
}
private void AddToUI(Employee driver)
{
if (driver != null)
{
var row = new DataGridViewRow()
{
Height = 30
};
row.Cells.Add(new DataGridViewTextBoxCell { Value = driver });
DriverDataGridView.Rows.Add(row);
}
}
private void DriverTripReportForm_Load(object sender, EventArgs e)
{
}
private async void LoadButton_Click(object sender, EventArgs e)
{
await GetDriverListAsync();
}
private async void DriverDataGridView_SelectionChanged(object sender, EventArgs e)
{
await GetDeliveryListAsync();
}
private async void ExportDriverButton_Click(object sender, EventArgs e)
{
await ExportTripReportAsync(TripReportMode.Driver);
}
private async void ExportAllButton_Click(object sender, EventArgs e)
{
await ExportTripReportAsync(TripReportMode.All);
}
}
}
| mit |
vogdb/cm | library/CM/Url/BaseUrl.php | 983 | <?php
namespace CM\Url;
use CM_Exception_Invalid;
use League\Uri\Components\HierarchicalPath;
class BaseUrl extends AbstractUrl {
public function getUriRelativeComponents() {
$path = HierarchicalPath::createFromSegments([], HierarchicalPath::IS_ABSOLUTE);
if ($prefix = $this->getPrefix()) {
$path = $path->append($prefix);
}
return $path->getUriComponent();
}
/**
* @param string $url
* @return BaseUrl
* @throws CM_Exception_Invalid
*/
public static function create($url) {
/** @var BaseUrl $baseUrl */
$baseUrl = parent::_create($url);
if (!$baseUrl->isAbsolute()) {
throw new CM_Exception_Invalid('BaseUrl::create argument must be an absolute Url', null, [
'url' => $url,
]);
}
$path = $baseUrl->getPath();
return $baseUrl
->withPrefix($path)
->withoutRelativeComponents();
}
}
| mit |
yurikoma/PhysicsForGamesAIE_StudentWork | example2D/Application2D.cpp | 2837 | #include "Application2D.h"
#include "Texture.h"
#include "Font.h"
#include "Input.h"
Application2D::Application2D() {
}
Application2D::~Application2D() {
}
bool Application2D::startup() {
m_2dRenderer = new aie::Renderer2D();
m_font = new aie::Font("./font/consolas.ttf", 32);
// load some images to draw with
m_texture = new aie::Texture("./textures/numbered_grid.tga");
m_shipTexture = new aie::Texture("./textures/ship.png");
// load a small sound
m_audio = new aie::Audio("./audio/powerup.wav");
// set the ship properties
m_shipX = getWindowWidth() * 0.5f;
m_shipY = 100.0f;
m_shipSpeed = 250.0f;
m_timer = 0;
return true;
}
void Application2D::shutdown() {
delete m_audio;
delete m_font;
delete m_texture;
delete m_shipTexture;
delete m_2dRenderer;
}
void Application2D::update(float deltaTime) {
m_timer += deltaTime;
// input example
aie::Input* input = aie::Input::getInstance();
// use arrow keys to move camera
if (input->isKeyDown(aie::INPUT_KEY_UP))
m_shipY += m_shipSpeed * deltaTime;
if (input->isKeyDown(aie::INPUT_KEY_DOWN))
m_shipY -= m_shipSpeed * deltaTime;
if (input->isKeyDown(aie::INPUT_KEY_LEFT))
m_shipX -= m_shipSpeed * deltaTime;
if (input->isKeyDown(aie::INPUT_KEY_RIGHT))
m_shipX += m_shipSpeed * deltaTime;
// example of audio
if (input->wasKeyPressed(aie::INPUT_KEY_SPACE))
m_audio->play();
// exit the application
if (input->isKeyDown(aie::INPUT_KEY_ESCAPE))
quit();
}
void Application2D::draw() {
// wipe the screen to the background colour
clearScreen();
// begin drawing sprites
m_2dRenderer->begin();
// demonstrate moving sprite
m_2dRenderer->drawSprite(m_shipTexture, m_shipX, m_shipY);
// demonstrate animation
m_2dRenderer->setUVRect(int(m_timer) % 8 / 8.0f, 0, 1.f / 8, 1.f / 8);
m_2dRenderer->drawSprite(m_texture, 200, 200, 100, 100);
// reset the texture coordinates
m_2dRenderer->setUVRect(0, 0, 1, 1);
// draw a thin line
m_2dRenderer->drawLine(300, 300, 600, 400, 2, 1);
// draw a moving purple circle
m_2dRenderer->setRenderColour(1, 0, 1);
m_2dRenderer->drawCircle(sin(m_timer) * 100 + 600, 150, 50);
// draw a rotating red box
m_2dRenderer->setRenderColour(1, 0, 0);
m_2dRenderer->drawBox(600, 500, 60, 20, m_timer);
// draw a slightly rotated sprite with no texture, coloured yellow
m_2dRenderer->setRenderColour(1, 1, 0);
m_2dRenderer->drawSprite(nullptr, 400, 400, 50, 50, 3.14159f * 0.25f, 1);
// output some text, uses the last used colour
char fps[32];
sprintf_s(fps, 32, "FPS: %i", getFPS());
m_2dRenderer->drawText(m_font, fps, 0, 720 - 32);
m_2dRenderer->drawText(m_font, "Press Space for sound!", 0, 0);
// done drawing sprites
m_2dRenderer->end();
} | mit |
radinformatics/som-tools | som/api/google/models.py | 2536 | '''
models.py: base models
Copyright (c) 2017 Vanessa Sochat
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.
'''
class BatchManager:
'''a batch manager is bucket to hold multiple objects to filter, query, etc.
It a way to compile a set, and then run through a transaction. It is intended
to be a Base class for the DataStoreBatch and BigQueryBatch
'''
def __init__(self,client=None):
self.client = client
self.tasks = []
self.queries = []
def get(self):
raise NotImplementedError
def add(self):
raise NotImplementedError
def delete(self):
raise NotImplementedError
def runInsert(self):
raise NotImplementedError
def runQueries(self):
raise NotImplementedError
def query(self):
raise NotImplementedError
class ModelBase:
''' A ModelBase is an empty shell to guide functions / actions that should
be available for a model base subclass (eg, BigQuery or DataStore)
'''
def update_fields(self):
return NotImplementedError
def get_or_create(self):
return NotImplementedError
def setup(self):
return NotImplementedError
def save(self):
return NotImplementedError
def create(self):
return NotImplementedError
def delete(self):
return NotImplementedError
def update_or_create(self):
return NotImplementedError
def update(self):
return NotImplementedError
def get(self):
return NotImplementedError
| mit |
yoshiori/ruboty-sql | lib/ruboty/sql/version.rb | 59 | module Ruboty
module Sql
VERSION = "0.0.1"
end
end
| mit |
Minetweak/Minetweak | src/main/java/io/minetweak/event/bus/Subscribe.java | 323 | package io.minetweak.event.bus;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Logan Gorence
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Subscribe {
} | mit |
bodrovis/lessons_indexer | spec/addons/git_manager_spec.rb | 581 | RSpec.describe LessonsIndexer::Addons::GitManager::Pusher do
subject {described_class.new('test message')}
specify "#message" do
expect(subject.message).to eq('test message')
end
specify { expect(subject).to respond_to(:push!) }
end
RSpec.describe LessonsIndexer::Addons::GitManager::Brancher do
subject {described_class.new(false)}
specify "#ignore_master" do
expect(subject.ignore_master).to eq(false)
end
specify { expect(subject).to respond_to(:within_branch) }
specify "#get_branches" do
expect(subject.get_branches).to be_a Array
end
end | mit |
Jiiks/BetterDiscordApp | Plugins/dblClickEdit.plugin.js | 1691 | //META{"name":"dblClickEdit"}*//
var dblClickEdit = function () {};
dblClickEdit.prototype.handler = function(e) {
const message = e.target.closest('[class^=messageCozy]') || e.target.closest('[class^=messageCompact]');
if (!message) return;
const btn = message.querySelector('[class^=buttonContainer] [class^=button-]');
if (!btn) return;
btn.click();
const popup = document.querySelector('[class^=container][role=menu]');
if (!popup) return;
const rii = popup[Object.keys(popup).find(k => k.startsWith('__reactInternal'))];
if (!rii || !rii.memoizedProps || !rii.memoizedProps.children || !rii.memoizedProps.children[1] || !rii.memoizedProps.children[1].props || !rii.memoizedProps.children[1].props.onClick) return;
rii.memoizedProps.children[1].props.onClick();
};
dblClickEdit.prototype.onMessage = function () {
};
dblClickEdit.prototype.onSwitch = function () {
};
dblClickEdit.prototype.start = function () {
document.addEventListener('dblclick', this.handler);
};
dblClickEdit.prototype.load = function () {};
dblClickEdit.prototype.unload = function () {
document.removeEventListener('dblclick', this.handler);
};
dblClickEdit.prototype.stop = function () {
document.removeEventListener('dblclick', this.handler);
};
dblClickEdit.prototype.getSettingsPanel = function () {
return "";
};
dblClickEdit.prototype.getName = function () {
return "Double click edit";
};
dblClickEdit.prototype.getDescription = function () {
return "Double click messages to edit them";
};
dblClickEdit.prototype.getVersion = function () {
return "0.2.1";
};
dblClickEdit.prototype.getAuthor = function () {
return "Jiiks";
};
| mit |
deepcerulean/wings | lib/wings/version.rb | 37 | module Wings
VERSION = "0.0.1"
end
| mit |
elizabrock/adventofcode | day1.py | 775 | class Day1:
def __init__(self, input):
self._input = input
def destination(self):
return self._input.count("(") - self._input.count(")")
def enters_basement_at(self):
floor = 0
for i, char in enumerate(self._input):
if char == "(":
floor += 1
else:
floor -= 1
if floor < 0:
return i + 1
return -1
if __name__ == "__main__":
advent_code = open('input/day1_input.txt', 'r').read()
santa_floor = Day1(advent_code).destination()
print("Santa ends up on floor {0}.".format(santa_floor))
basement_floor = Day1(advent_code).enters_basement_at()
print("Santa first entered the basement on floor {0}.".format(basement_floor)) | mit |
kurraz-soft/prj-jack | modules/game/models/game_data/occupations/BeggarOccupation.php | 1139 | <?php
/**
* Created by PhpStorm.
* User: Kurraz
*/
namespace app\modules\game\models\game_data\occupations;
use app\modules\game\helpers\ArrayHelper;
use app\modules\game\models\game_data\base\IOccupation;
class BeggarOccupation implements IOccupation
{
public function getId()
{
return 'beggar';
}
public function getName()
{
return 'нищенка';
}
public function getDescriptions()
{
return [
'К тому времени, когда я подросла, единственным способом прокормиться, не воруя и не продавая своё тело, было просить милостыню. Подавали мне не охотно, так что жила всегда впроголодь. К тому же, стражи порядка и местные бандиты требовали свою долю. Не знаю, сколько бы я еще протянула.',
];
}
public function affectJsonData($data)
{
return ArrayHelper::sumArrays($data,[
]);
}
} | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.