code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
require 'ox'
module UPS
module Builders
# The {InternationalProductInvoiceBuilder} class builds UPS XML International invoice Produt Objects.
#
# @author Calvin Hughes
# @since 0.9.3
# @attr [String] name The Containing XML Element Name
# @attr [Hash] opts The international invoice product parts
class InternationalInvoiceProductBuilder < BuilderBase
include Ox
attr_accessor :name, :opts
def initialize(name, opts = {})
self.name = name
self.opts = opts
end
def description
element_with_value('Description', opts[:description])
end
def number
element_with_value('Number', opts[:number])
end
def value
element_with_value('Value', opts[:value])
end
def dimensions_unit
unit_of_measurement(opts[:dimensions_unit])
end
def part_number
element_with_value('PartNumber', opts[:part_number][0..9])
end
def commodity_code
element_with_value('CommodityCode', opts[:commodity_code])
end
def origin_country_code
element_with_value('OriginCountryCode', opts[:origin_country_code][0..2])
end
def product_unit
Element.new('Unit').tap do |unit|
unit << number
unit << value
unit << dimensions_unit
end
end
# Returns an XML representation of the current object
#
# @return [Ox::Element] XML representation of the current object
def to_xml
Element.new(name).tap do |product|
product << description
product << commodity_code if opts[:commodity_code]
product << part_number if opts[:part_number]
product << origin_country_code
product << product_unit
end
end
end
end
end
| veeqo/ups-ruby | lib/ups/builders/international_invoice_product_builder.rb | Ruby | mit | 1,835 |
require "octaccord/version"
require "octaccord/errors"
require "octaccord/command"
require "octaccord/formatter"
require "octaccord/iteration"
require "extensions"
module Octaccord
# Your code goes here...
end
| nomlab/octaccord | lib/octaccord.rb | Ruby | mit | 213 |
# Rushy Panchal
"""
See https://bittrex.com/Home/Api
"""
import urllib
import time
import requests
import hmac
import hashlib
BUY_ORDERBOOK = 'buy'
SELL_ORDERBOOK = 'sell'
BOTH_ORDERBOOK = 'both'
PUBLIC_SET = ['getmarkets', 'getcurrencies', 'getticker', 'getmarketsummaries', 'getorderbook',
'getmarkethistory']
MARKET_SET = ['getopenorders', 'cancel', 'sellmarket', 'selllimit', 'buymarket', 'buylimit']
ACCOUNT_SET = ['getbalances', 'getbalance', 'getdepositaddress', 'withdraw', 'getorder', 'getorderhistory', 'getwithdrawalhistory', 'getdeposithistory']
class Bittrex(object):
"""
Used for requesting Bittrex with API key and API secret
"""
def __init__(self, api_key, api_secret):
self.api_key = str(api_key) if api_key is not None else ''
self.api_secret = str(api_secret) if api_secret is not None else ''
self.public_set = set(PUBLIC_SET)
self.market_set = set(MARKET_SET)
self.account_set = set(ACCOUNT_SET)
def api_query(self, method, options=None):
"""
Queries Bittrex with given method and options
:param method: Query method for getting info
:type method: str
:param options: Extra options for query
:type options: dict
:return: JSON response from Bittrex
:rtype : dict
"""
if not options:
options = {}
nonce = str(int(time.time() * 1000))
base_url = 'https://bittrex.com/api/v1.1/%s/'
request_url = ''
if method in self.public_set:
request_url = (base_url % 'public') + method + '?'
elif method in self.market_set:
request_url = (base_url % 'market') + method + '?apikey=' + self.api_key + "&nonce=" + nonce + '&'
elif method in self.account_set:
request_url = (base_url % 'account') + method + '?apikey=' + self.api_key + "&nonce=" + nonce + '&'
request_url += urllib.urlencode(options)
signature = hmac.new(self.api_secret, request_url, hashlib.sha512).hexdigest()
headers = {"apisign": signature}
ret = requests.get(request_url, headers=headers)
return ret.json()
def get_markets(self):
"""
Used to get the open and available trading markets
at Bittrex along with other meta data.
:return: Available market info in JSON
:rtype : dict
"""
return self.api_query('getmarkets')
def get_currencies(self):
"""
Used to get all supported currencies at Bittrex
along with other meta data.
:return: Supported currencies info in JSON
:rtype : dict
"""
return self.api_query('getcurrencies')
def get_ticker(self, market):
"""
Used to get the current tick values for a market.
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:return: Current values for given market in JSON
:rtype : dict
"""
return self.api_query('getticker', {'market': market})
def get_market_summaries(self):
"""
Used to get the last 24 hour summary of all active exchanges
:return: Summaries of active exchanges in JSON
:rtype : dict
"""
return self.api_query('getmarketsummaries')
def get_orderbook(self, market, depth_type, depth=20):
"""
Used to get retrieve the orderbook for a given market
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param depth_type: buy, sell or both to identify the type of orderbook to return.
Use constants BUY_ORDERBOOK, SELL_ORDERBOOK, BOTH_ORDERBOOK
:type depth_type: str
:param depth: how deep of an order book to retrieve. Max is 100, default is 20
:type depth: int
:return: Orderbook of market in JSON
:rtype : dict
"""
return self.api_query('getorderbook', {'market': market, 'type': depth_type, 'depth': depth})
def get_market_history(self, market, count):
"""
Used to retrieve the latest trades that have occured for a
specific market.
/market/getmarkethistory
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param count: Number between 1-100 for the number of entries to return (default = 20)
:type count: int
:return: Market history in JSON
:rtype : dict
"""
return self.api_query('getmarkethistory', {'market': market, 'count': count})
def buy_market(self, market, quantity, rate):
"""
Used to place a buy order in a specific market. Use buymarket to
place market orders. Make sure you have the proper permissions
set on your API keys for this call to work
/market/buymarket
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param quantity: The amount to purchase
:type quantity: float
:param rate: The rate at which to place the order.
This is not needed for market orders
:type rate: float
:return:
:rtype : dict
"""
return self.api_query('buymarket', {'market': market, 'quantity': quantity, 'rate': rate})
def buy_limit(self, market, quantity, rate):
"""
Used to place a buy order in a specific market. Use buylimit to place
limit orders Make sure you have the proper permissions set on your
API keys for this call to work
/market/buylimit
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param quantity: The amount to purchase
:type quantity: float
:param rate: The rate at which to place the order.
This is not needed for market orders
:type rate: float
:return:
:rtype : dict
"""
return self.api_query('buylimit', {'market': market, 'quantity': quantity, 'rate': rate})
def sell_market(self, market, quantity, rate):
"""
Used to place a sell order in a specific market. Use sellmarket to place
market orders. Make sure you have the proper permissions set on your
API keys for this call to work
/market/sellmarket
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param quantity: The amount to purchase
:type quantity: float
:param rate: The rate at which to place the order.
This is not needed for market orders
:type rate: float
:return:
:rtype : dict
"""
return self.api_query('sellmarket', {'market': market, 'quantity': quantity, 'rate': rate})
def sell_limit(self, market, quantity, rate):
"""
Used to place a sell order in a specific market. Use selllimit to place
limit orders Make sure you have the proper permissions set on your
API keys for this call to work
/market/selllimit
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param quantity: The amount to purchase
:type quantity: float
:param rate: The rate at which to place the order.
This is not needed for market orders
:type rate: float
:return:
:rtype : dict
"""
return self.api_query('selllimit', {'market': market, 'quantity': quantity, 'rate': rate})
def cancel(self, uuid):
"""
Used to cancel a buy or sell order
/market/cancel
:param uuid: uuid of buy or sell order
:type uuid: str
:return:
:rtype : dict
"""
return self.api_query('cancel', {'uuid': uuid})
def get_open_orders(self, market):
"""
Get all orders that you currently have opened. A specific market can be requested
/market/getopenorders
:param market: String literal for the market (ie. BTC-LTC)
:type market: str
:return: Open orders info in JSON
:rtype : dict
"""
return self.api_query('getopenorders', {'market': market})
def get_balances(self):
"""
Used to retrieve all balances from your account
/account/getbalances
:return: Balances info in JSON
:rtype : dict
"""
return self.api_query('getbalances', {})
def get_balance(self, currency):
"""
Used to retrieve the balance from your account for a specific currency
/account/getbalance
:param currency: String literal for the currency (ex: LTC)
:type currency: str
:return: Balance info in JSON
:rtype : dict
"""
return self.api_query('getbalance', {'currency': currency})
def get_deposit_address(self, currency):
"""
Used to generate or retrieve an address for a specific currency
/account/getdepositaddress
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: Address info in JSON
:rtype : dict
"""
return self.api_query('getdepositaddress', {'currency': currency})
def withdraw(self, currency, quantity, address):
"""
Used to withdraw funds from your account
/account/withdraw
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:param quantity: The quantity of coins to withdraw
:type quantity: float
:param address: The address where to send the funds.
:type address: str
:return:
:rtype : dict
"""
return self.api_query('withdraw', {'currency': currency, 'quantity': quantity, 'address': address})
def get_order(self, uuid):
"""
Used to get an order from your account
/account/getorder
:param uuid: The order UUID to look for
:type uuid: str
:return:
:rtype : dict
"""
return self.api_query('getorder', {'uuid': uuid})
def get_order_history(self, market = ""):
"""
Used to retrieve your order history
/account/getorderhistory
:param market: Bittrex market identifier (i.e BTC-DOGE)
:type market: str
:return:
:rtype : dict
"""
return self.api_query('getorderhistory', {"market": market})
def get_withdrawal_history(self, currency = ""):
"""
Used to retrieve your withdrawal history
/account/getwithdrawalhistory
:param currency: String literal for the currency (ie. BTC) (defaults to all)
:type currency: str
:return:
:rtype : dict
"""
return self.api_query('getwithdrawalhistory', {"currency": currency})
def get_deposit_history(self, currency = ""):
"""
Used to retrieve your deposit history
/account/getdeposithistory
:param currency: String literal for the currency (ie. BTC) (defaults to all)
:type currency: str
:return:
:rtype : dict
"""
return self.api_query('getdeposithistory', {"currency": currency})
| panchr/python-bittrex | bittrex/bittrex.py | Python | mit | 9,819 |
package co.edu.eafit.solver.lib.systemsolver.iterative;
public enum ENorm {
One, Infinite, Euclidean
}
| halzate93/solver | lib/src/co/edu/eafit/solver/lib/systemsolver/iterative/ENorm.java | Java | mit | 105 |
/**
* CacheStorage
* ============
*/
var fs = require('fs');
var dropRequireCache = require('../fs/drop-require-cache');
/**
* CacheStorage — хранилище для кэша.
* @name CacheStorage
* @param {String} filename Имя файла, в котором хранится кэш (в формате JSON).
* @constructor
*/
function CacheStorage(filename) {
this._filename = filename;
this._data = {};
this._mtime = 0;
}
CacheStorage.prototype = {
/**
* Загружает кэш из файла.
*/
load: function () {
if (fs.existsSync(this._filename)) {
dropRequireCache(require, this._filename);
try {
this._data = require(this._filename);
} catch (e) {
this._data = {};
}
this._mtime = fs.statSync(this._filename).mtime.getTime();
} else {
this._data = {};
}
},
/**
* Сохраняет кэш в файл.
*/
save: function () {
fs.writeFileSync(this._filename, 'module.exports = ' + JSON.stringify(this._data) + ';', 'utf8');
this._mtime = fs.statSync(this._filename).mtime.getTime();
},
/**
* Возвращает значение по префику и ключу.
* @param {String} prefix
* @param {String} key
* @returns {Object}
*/
get: function (prefix, key) {
return this._data[prefix] && this._data[prefix][key];
},
/**
* Устанавливает значение по префиксу и ключу.
* @param {String} prefix
* @param {String} key
* @param {Object} value
*/
set: function (prefix, key, value) {
(this._data[prefix] || (this._data[prefix] = {}))[key] = value;
},
/**
* Удаляет значение по префиксу и ключу.
* @param {String} prefix
* @param {String} key
*/
invalidate: function (prefix, key) {
var prefixObj = this._data[prefix];
if (prefixObj) {
delete prefixObj[key];
}
},
/**
* Удаляет все значения по префиксу.
* @param {String} prefix
*/
dropPrefix: function (prefix) {
delete this._data[prefix];
},
/**
* Очищает кэш.
*/
drop: function () {
this._data = {};
}
};
module.exports = CacheStorage;
| 1999/enb | lib/cache/cache-storage.js | JavaScript | mit | 2,450 |
#include "stdafx.h"
#include "FrustumCone.h"
using namespace glm;
FrustumCone::FrustumCone()
{
}
FrustumCone::~FrustumCone()
{
}
void FrustumCone::update(mat4 rotprojmatrix)
{
leftBottom = getDir(vec2(-1, -1), rotprojmatrix);
rightBottom = getDir(vec2(1, -1), rotprojmatrix);
leftTop = getDir(vec2(-1, 1), rotprojmatrix);
rightTop = getDir(vec2(1, 1), rotprojmatrix);
}
vec3 FrustumCone::getDir(vec2 uv, mat4 inv)
{
vec4 clip = inv * vec4(uv.x, uv.y, 0.1, 1.0);
return normalize(vec3(clip.x, clip.y, clip.z) / clip.w);
} | achlubek/vengineandroidndk | app/src/main/cpp/FrustumCone.cpp | C++ | mit | 549 |
import hexchat
import re
__module_name__ = 'BanSearch'
__module_author__ = 'TingPing'
__module_version__ = '2'
__module_description__ = 'Search for bans/quiets matching a user'
banhook = 0
quiethook = 0
endbanhook = 0
endquiethook = 0
banlist = []
quietlist = []
regexescapes = {'[':r'\[', ']':r'\]', '.':r'\.'}
ircreplace = {'{':'[', '}':']', '|':'\\'} # IRC nick substitutions
wildcards = {'?':r'.', '*': r'.*'} # translate wildcards to regex
def print_result(mask, matchlist, _type):
if matchlist:
print('\00318{}\017 had \00320{}\017 {} matches:'.format(mask, len(matchlist), _type))
for match in matchlist:
print('\t\t\t{}'.format(match))
else:
print('No {} matches for \00318{}\017 were found.'.format(_type, mask))
def match_mask(mask, searchmask):
if searchmask is None:
searchmask = ''
# A mask of $a:* can match a user with no account
if searchmask == '' and mask != '*':
return False
# A mask of $a will not match a user with no account
elif mask == '' and searchmask != '':
return True
# These have to be replaced in a very specific order
for match, repl in ircreplace.items():
mask = mask.replace(match, repl)
searchmask = searchmask.replace(match, repl)
for match, repl in regexescapes.items():
mask = mask.replace(match, repl)
for match, repl in wildcards.items():
mask = mask.replace(match, repl)
if '$' in mask and mask[0] != '$': # $#channel is used to forward users, ignore it
mask = mask.split('$')[0]
return bool(re.match(mask, searchmask, re.IGNORECASE))
def match_extban(mask, host, account, realname, usermask):
try:
extban, banmask = mask.split(':')
except ValueError:
extban = mask
banmask = ''
if '~' in extban:
invert = True
else:
invert = False
# Extbans from http://freenode.net/using_the_network.shtml
if ':' in usermask: # Searching for extban
userextban, usermask = usermask.split(':')
if extban == userextban:
ret = match_mask(banmask, usermask)
else:
return False
elif 'a' in extban:
ret = match_mask (banmask, account)
elif 'r' in extban:
ret = match_mask (banmask, realname)
elif 'x' in extban:
ret = match_mask (banmask, '{}#{}'.format(host, realname))
else:
return False
if invert:
return not ret
else:
return ret
def get_user_info(nick):
invalid_chars = ['*', '?', '$', '@', '!']
if any(char in nick for char in invalid_chars):
return (None, None, None) # It's a mask not a nick.
for user in hexchat.get_list('users'):
if user.nick == nick:
host = user.nick + '!' + user.host
account = user.account
realname = user.realname
return (host, account, realname)
return (nick + '!*@*', None, None)
def search_list(list, usermask):
matchlist = []
host, account, realname = get_user_info (usermask)
for mask in list:
# If extban we require userinfo or we are searching for extban
if mask[0] == '$' and (host or usermask[0] == '$'):
if match_extban (mask, host, account, realname, usermask):
matchlist.append(mask)
elif mask[0] != '$':
if host: # Was given a user
if match_mask (mask, host):
matchlist.append(mask)
else: # Was given a mask or no userinfo found
if match_mask (mask, usermask):
matchlist.append(mask)
return matchlist
def banlist_cb(word, word_eol, userdata):
global banlist
banlist.append(word[4])
return hexchat.EAT_HEXCHAT
def endbanlist_cb(word, word_eol, usermask):
global banhook
global endbanhook
global banlist
matchlist = []
hexchat.unhook(banhook)
banhook = 0
hexchat.unhook(endbanhook)
endbanhook = 0
if banlist:
matchlist = search_list(banlist, usermask)
banlist = []
print_result (usermask, matchlist, 'Ban')
return hexchat.EAT_HEXCHAT
def quietlist_cb(word, word_eol, userdata):
global quietlist
quietlist.append(word[5])
return hexchat.EAT_HEXCHAT
def endquietlist_cb(word, word_eol, usermask):
global quiethook
global endquiethook
global quietlist
matchlist = []
hexchat.unhook(quiethook)
quiethook = 0
hexchat.unhook(endquiethook)
endquiethook = 0
if quietlist:
matchlist = search_list(quietlist, usermask)
quietlist = []
print_result (usermask, matchlist, 'Quiet')
return hexchat.EAT_HEXCHAT
def search_cb(word, word_eol, userdata):
global banhook
global quiethook
global endbanhook
global endquiethook
if len(word) == 2:
hooks = (quiethook, banhook, endquiethook, endbanhook)
if not any(hooks):
banhook = hexchat.hook_server ('367', banlist_cb)
quiethook = hexchat.hook_server ('728', quietlist_cb)
endbanhook = hexchat.hook_server ('368', endbanlist_cb, word[1])
endquiethook = hexchat.hook_server ('729', endquietlist_cb, word[1])
hexchat.command('ban')
hexchat.command('quiet')
else:
print('A ban search is already in progress.')
else:
hexchat.command('help bansearch')
return hexchat.EAT_ALL
def unload_cb(userdata):
print(__module_name__ + ' version ' + __module_version__ + ' unloaded.')
hexchat.hook_unload(unload_cb)
hexchat.hook_command('bansearch', search_cb, help='BANSEARCH <mask|nick>')
hexchat.prnt(__module_name__ + ' version ' + __module_version__ + ' loaded.')
| TingPing/plugins | HexChat/bansearch.py | Python | mit | 5,101 |
package pathtree
// Items ...
type Items map[string]Items
// Add recursively adds a slice of strings to an Items map and makes parent
// keys as needed.
func (i Items) Add(path []string) {
if len(path) > 0 {
if v, ok := i[path[0]]; ok {
v.Add(path[1:])
} else {
result := make(Items)
result.Add(path[1:])
i[path[0]] = result
}
}
}
| marcusolsson/passtray | pathtree/tree.go | GO | mit | 353 |
<?php
namespace DiabloDB\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
abstract class Controller extends BaseController
{
use DispatchesCommands, ValidatesRequests;
}
| taskforcedev/DiabloDB | app/Http/Controllers/Controller.php | PHP | mit | 305 |
/**
* Module dependencies
*/
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
/**
* @constructor
*/
var MongooseStore = function (Session) {
this.Session = Session;
};
/**
* Load data
*/
// for koa-generic-session
MongooseStore.prototype.get = function *(sid, parse) {
try {
var data = yield this.Session.findOne({ sid: sid });
if (data && data.sid) {
if (parse === false) return data.blob;
return JSON.parse(data.blob);
} else {
return null;
}
} catch (err) {
console.error(err.stack);
return null;
}
};
// for koa-session-store
MongooseStore.prototype.load = function *(sid) {
return yield this.get(sid, false);
};
/**
* Save data
*/
MongooseStore.prototype.set = MongooseStore.prototype.save = function *(sid, blob) {
try {
if (typeof blob === 'object') blob = JSON.stringify(blob);
var data = {
sid: sid,
blob: blob,
updatedAt: new Date()
};
yield this.Session.findOneAndUpdate({ sid: sid }, data, { upsert: true, safe: true });
} catch (err) {
console.error(err.stack);
}
};
/**
* Remove data
*/
MongooseStore.prototype.destroy = MongooseStore.prototype.remove = function *(sid) {
try {
yield this.Session.remove({ sid: sid });
} catch (err) {
console.error(err.stack);
}
};
/**
* Create a Mongoose store
*/
exports.create = function (options) {
options = options || {};
options.collection = options.collection || 'sessions';
options.connection = options.connection || mongoose;
options.expires = options.expires || 60 * 60 * 24 * 14; // 2 weeks
options.model = options.model || 'SessionStore';
var SessionSchema = new Schema({
sid: {
type: String,
index: true
},
blob: String,
updatedAt: {
type: Date,
default: new Date(),
expires: options.expires
}
});
var Session = options.connection.model(options.model, SessionSchema, options.collection);
return new MongooseStore(Session);
};
| rfink/koa-session-mongoose | index.js | JavaScript | mit | 2,003 |
module DynamicModel
module Type
class Date < DynamicModel::Type::Base
end
end
end | rmoliva/dynamic_model | lib/dynamic_model/type/date.rb | Ruby | mit | 93 |
export function mapToCssModules (className, cssModule) {
if (!cssModule) return className
return className.split(' ').map(c => cssModule[c] || c).join(' ')
}
| suranartnc/graphql-blogs-app | .core/app/utils/coreui.js | JavaScript | mit | 162 |
package entity;
import javax.persistence.*;
@Entity
@Table(name = "tag", schema = "streambot", catalog = "")
public class TagEntity {
@Id
@Column(name = "ID", nullable = false)
private long id;
@ManyToOne
@JoinColumn(name = "ServerID", nullable = false)
private GuildEntity guild;
@Basic
@Column(name = "Name", nullable = true, length = -1)
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public GuildEntity getGuild() {
return guild;
}
public void setGuild(GuildEntity guild) {
this.guild = guild;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TagEntity tagEntity = (TagEntity) o;
if (id != tagEntity.id) return false;
if (guild != null ? !guild.equals(tagEntity.guild) : tagEntity.guild != null) return false;
return name != null ? name.equals(tagEntity.name) : tagEntity.name == null;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (guild != null ? guild.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
| Gyoo/Discord-Streambot | src/main/java/entity/TagEntity.java | Java | mit | 1,494 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2014 The FutCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#undef printf
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
#define printf OutputDebugStringF
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
void ThreadRPCServer2(void* parg);
static std::string strRPCUserColonPass;
const Object emptyobj;
void ThreadRPCServer3(void* parg);
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 12346 : 2346;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64_t AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > MAX_MONEY)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64_t nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64_t amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
//
// Utilities: convert hex-encoded Values
// (throws error if not hex).
//
uint256 ParseHashV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex)) // Note: IsHex("") is false
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
uint256 result;
result.SetHex(strHex);
return result;
}
uint256 ParseHashO(const Object& o, string strKey)
{
return ParseHashV(find_value(o, strKey), strKey);
}
vector<unsigned char> ParseHexV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex))
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
vector<unsigned char> ParseHexO(const Object& o, string strKey)
{
return ParseHexV(find_value(o, strKey), strKey);
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"stop <detach>\n"
"<detach> is true or false to detach the database or not for this stop only\n"
"Stop FutCoin server (and possibly override the detachdb config value).");
// Shutdown will take long enough that the response should get back
if (params.size() > 0)
bitdb.SetDetach(params[0].get_bool());
StartShutdown();
return "FutCoin server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name function safemd unlocked
// ------------------------ ----------------------- ------ --------
{ "help", &help, true, true },
{ "stop", &stop, true, true },
{ "getbestblockhash", &getbestblockhash, true, false },
{ "getblockcount", &getblockcount, true, false },
{ "getconnectioncount", &getconnectioncount, true, false },
{ "getpeerinfo", &getpeerinfo, true, false },
{ "getdifficulty", &getdifficulty, true, false },
{ "getinfo", &getinfo, true, false },
{ "getsubsidy", &getsubsidy, true, false },
{ "getmininginfo", &getmininginfo, true, false },
{ "getstakinginfo", &getstakinginfo, true, false },
{ "getnewaddress", &getnewaddress, true, false },
{ "getnewpubkey", &getnewpubkey, true, false },
{ "getaccountaddress", &getaccountaddress, true, false },
{ "setaccount", &setaccount, true, false },
{ "getaccount", &getaccount, false, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false },
{ "sendtoaddress", &sendtoaddress, false, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false },
{ "backupwallet", &backupwallet, true, false },
{ "keypoolrefill", &keypoolrefill, true, false },
{ "walletpassphrase", &walletpassphrase, true, false },
{ "walletpassphrasechange", &walletpassphrasechange, false, false },
{ "walletlock", &walletlock, true, false },
{ "encryptwallet", &encryptwallet, false, false },
{ "validateaddress", &validateaddress, true, false },
{ "validatepubkey", &validatepubkey, true, false },
{ "getbalance", &getbalance, false, false },
{ "move", &movecmd, false, false },
{ "sendfrom", &sendfrom, false, false },
{ "sendmany", &sendmany, false, false },
{ "addmultisigaddress", &addmultisigaddress, false, false },
{ "addredeemscript", &addredeemscript, false, false },
{ "getrawmempool", &getrawmempool, true, false },
{ "getblock", &getblock, false, false },
{ "getblockbynumber", &getblockbynumber, false, false },
{ "getblockhash", &getblockhash, false, false },
{ "gettransaction", &gettransaction, false, false },
{ "listtransactions", &listtransactions, false, false },
{ "listaddressgroupings", &listaddressgroupings, false, false },
{ "signmessage", &signmessage, false, false },
{ "verifymessage", &verifymessage, false, false },
{ "getwork", &getwork, true, false },
{ "getworkex", &getworkex, true, false },
{ "listaccounts", &listaccounts, false, false },
{ "settxfee", &settxfee, false, false },
{ "getblocktemplate", &getblocktemplate, true, false },
{ "submitblock", &submitblock, false, false },
{ "listsinceblock", &listsinceblock, false, false },
{ "dumpprivkey", &dumpprivkey, false, false },
{ "dumpwallet", &dumpwallet, true, false },
{ "importwallet", &importwallet, false, false },
{ "importprivkey", &importprivkey, false, false },
{ "listunspent", &listunspent, false, false },
{ "getrawtransaction", &getrawtransaction, false, false },
{ "createrawtransaction", &createrawtransaction, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false },
{ "decodescript", &decodescript, false, false },
{ "signrawtransaction", &signrawtransaction, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false },
{ "getcheckpoint", &getcheckpoint, true, false },
{ "reservebalance", &reservebalance, false, true},
{ "checkwallet", &checkwallet, false, true},
{ "repairwallet", &repairwallet, false, true},
{ "resendtx", &resendtx, false, true},
{ "makekeypair", &makekeypair, false, true},
{ "sendalert", &sendalert, false, false},
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: FutCoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: FutCoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: FutCoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
while (true)
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Read header
int nLen = ReadHTTPHeader(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return nStatus;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ThreadRPCServer(void* parg)
{
// Make this thread recognisable as the RPC listener
RenameThread("FutCoin-rpclist");
try
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
ThreadRPCServer2(parg);
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(&e, "ThreadRPCServer()");
} catch (...) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(NULL, "ThreadRPCServer()");
}
printf("ThreadRPCServer exited\n");
}
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted
&& acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn
&& !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
// start HTTP client thread
else if (!NewThread(ThreadRPCServer3, conn)) {
printf("Failed to create RPC server client thread\n");
delete conn;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
void ThreadRPCServer2(void* parg)
{
printf("ThreadRPCServer started\n");
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use FutCoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n %s\n"
"It is recommended you use the following random password:\n"
"rpcuser=FutCoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"FutCoin Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
_("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
const bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
if (fUseSSL)
{
context.set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
boost::signals2::signal<void ()> StopRequests;
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
while (!fShutdown)
io_service.run_one();
vnThreadsRunning[THREAD_RPCLISTENER]++;
StopRequests();
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
static CCriticalSection cs_THREAD_RPCHANDLER;
void ThreadRPCServer3(void* parg)
{
// Make this thread recognisable as the RPC handler
RenameThread("FutCoin-rpchand");
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]++;
}
AcceptedConnection *conn = (AcceptedConnection *) parg;
bool fRun = true;
while (true)
{
if (fShutdown || !fRun)
{
conn->close();
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
--vnThreadsRunning[THREAD_RPCHANDLER];
}
return;
}
map<string, string> mapHeaders;
string strRequest;
ReadHTTP(conn->stream(), mapHeaders, strRequest);
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]--;
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->unlocked)
result = pcmd->actor(params, false);
else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive reply
map<string, string> mapHeaders;
string strReply;
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getblockbynumber" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendalert" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "sendalert" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendalert" && n > 4) ConvertTo<boost::int64_t>(params[4]);
if (strMethod == "sendalert" && n > 5) ConvertTo<boost::int64_t>(params[5]);
if (strMethod == "sendalert" && n > 6) ConvertTo<boost::int64_t>(params[6]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "keypoolrefill" && n > 0) ConvertTo<boost::int64_t>(params[0]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (std::exception& e)
{
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...)
{
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| Futcoin/Futcoin | src/bitcoinrpc.cpp | C++ | mit | 48,271 |
interface CalculatePositionOptions {
horizontalPosition: string;
verticalPosition: string;
matchTriggerWidth: boolean;
previousHorizontalPosition?: string;
previousVerticalPosition?: string;
renderInPlace: boolean;
dropdown: any;
}
export type CalculatePositionResultStyle = {
top?: number;
left?: number;
right?: number;
width?: number;
height?: number;
[key: string]: string | number | undefined;
};
export type CalculatePositionResult = {
horizontalPosition: string;
verticalPosition: string;
style: CalculatePositionResultStyle;
};
export type CalculatePosition = (
trigger: Element,
content: HTMLElement,
destination: HTMLElement,
options: CalculatePositionOptions
) => CalculatePositionResult;
export let calculateWormholedPosition: CalculatePosition = (
trigger,
content,
destination,
{
horizontalPosition,
verticalPosition,
matchTriggerWidth,
previousHorizontalPosition,
previousVerticalPosition,
}
) => {
// Collect information about all the involved DOM elements
let scroll = { left: window.pageXOffset, top: window.pageYOffset };
let {
left: triggerLeft,
top: triggerTop,
width: triggerWidth,
height: triggerHeight,
} = trigger.getBoundingClientRect();
let { height: dropdownHeight, width: dropdownWidth } =
content.getBoundingClientRect();
let viewportWidth = document.body.clientWidth || window.innerWidth;
let style: CalculatePositionResultStyle = {};
// Apply containers' offset
let anchorElement = destination.parentNode as HTMLElement;
let anchorPosition = window.getComputedStyle(anchorElement).position;
while (
anchorPosition !== 'relative' &&
anchorPosition !== 'absolute' &&
anchorElement.tagName.toUpperCase() !== 'BODY'
) {
anchorElement = anchorElement.parentNode as HTMLElement;
anchorPosition = window.getComputedStyle(anchorElement).position;
}
if (anchorPosition === 'relative' || anchorPosition === 'absolute') {
let rect = anchorElement.getBoundingClientRect();
triggerLeft = triggerLeft - rect.left;
triggerTop = triggerTop - rect.top;
let { offsetParent } = anchorElement;
if (offsetParent) {
triggerLeft -= offsetParent.scrollLeft;
triggerTop -= offsetParent.scrollTop;
}
}
// Calculate drop down width
dropdownWidth = matchTriggerWidth ? triggerWidth : dropdownWidth;
if (matchTriggerWidth) {
style.width = dropdownWidth;
}
// Calculate horizontal position
let triggerLeftWithScroll = triggerLeft + scroll.left;
if (horizontalPosition === 'auto' || horizontalPosition === 'auto-left') {
// Calculate the number of visible horizontal pixels if we were to place the
// dropdown on the left and right
let leftVisible =
Math.min(viewportWidth, triggerLeft + dropdownWidth) -
Math.max(0, triggerLeft);
let rightVisible =
Math.min(viewportWidth, triggerLeft + triggerWidth) -
Math.max(0, triggerLeft + triggerWidth - dropdownWidth);
if (dropdownWidth > leftVisible && rightVisible > leftVisible) {
// If the drop down won't fit left-aligned, and there is more space on the
// right than on the left, then force right-aligned
horizontalPosition = 'right';
} else if (dropdownWidth > rightVisible && leftVisible > rightVisible) {
// If the drop down won't fit right-aligned, and there is more space on
// the left than on the right, then force left-aligned
horizontalPosition = 'left';
} else {
// Keep same position as previous
horizontalPosition = previousHorizontalPosition || 'left';
}
} else if (horizontalPosition === 'auto-right') {
// Calculate the number of visible horizontal pixels if we were to place the
// dropdown on the left and right
let leftVisible =
Math.min(viewportWidth, triggerLeft + dropdownWidth) -
Math.max(0, triggerLeft);
let rightVisible =
Math.min(viewportWidth, triggerLeft + triggerWidth) -
Math.max(0, triggerLeft + triggerWidth - dropdownWidth);
if (dropdownWidth > rightVisible && leftVisible > rightVisible) {
// If the drop down won't fit right-aligned, and there is more space on the
// left than on the right, then force left-aligned
horizontalPosition = 'left';
} else if (dropdownWidth > leftVisible && rightVisible > leftVisible) {
// If the drop down won't fit left-aligned, and there is more space on
// the right than on the left, then force right-aligned
horizontalPosition = 'right';
} else {
// Keep same position as previous
horizontalPosition = previousHorizontalPosition || 'right';
}
}
if (horizontalPosition === 'right') {
style.right = viewportWidth - (triggerLeftWithScroll + triggerWidth);
} else if (horizontalPosition === 'center') {
style.left = triggerLeftWithScroll + (triggerWidth - dropdownWidth) / 2;
} else {
style.left = triggerLeftWithScroll;
}
// Calculate vertical position
let triggerTopWithScroll = triggerTop;
/**
* Fixes bug where the dropdown always stays on the same position on the screen when
* the <body> is relatively positioned
*/
let isBodyPositionRelative =
window.getComputedStyle(document.body).getPropertyValue('position') ===
'relative';
if (!isBodyPositionRelative) {
triggerTopWithScroll += scroll.top;
}
if (verticalPosition === 'above') {
style.top = triggerTopWithScroll - dropdownHeight;
} else if (verticalPosition === 'below') {
style.top = triggerTopWithScroll + triggerHeight;
} else {
let viewportBottom = scroll.top + window.innerHeight;
let enoughRoomBelow =
triggerTopWithScroll + triggerHeight + dropdownHeight < viewportBottom;
let enoughRoomAbove = triggerTop > dropdownHeight;
if (!enoughRoomBelow && !enoughRoomAbove) {
verticalPosition = 'below';
} else if (
previousVerticalPosition === 'below' &&
!enoughRoomBelow &&
enoughRoomAbove
) {
verticalPosition = 'above';
} else if (
previousVerticalPosition === 'above' &&
!enoughRoomAbove &&
enoughRoomBelow
) {
verticalPosition = 'below';
} else if (!previousVerticalPosition) {
verticalPosition = enoughRoomBelow ? 'below' : 'above';
} else {
verticalPosition = previousVerticalPosition;
}
style.top =
triggerTopWithScroll +
(verticalPosition === 'below' ? triggerHeight : -dropdownHeight);
}
return { horizontalPosition, verticalPosition, style };
};
export let calculateInPlacePosition: CalculatePosition = (
trigger,
content,
_destination,
{ horizontalPosition, verticalPosition }
) => {
let dropdownRect;
let positionData: CalculatePositionResult = {
horizontalPosition: 'left',
verticalPosition: 'below',
style: {},
};
if (horizontalPosition === 'auto') {
let triggerRect = trigger.getBoundingClientRect();
dropdownRect = content.getBoundingClientRect();
let viewportRight = window.pageXOffset + window.innerWidth;
positionData.horizontalPosition =
triggerRect.left + dropdownRect.width > viewportRight ? 'right' : 'left';
} else if (horizontalPosition === 'center') {
let { width: triggerWidth } = trigger.getBoundingClientRect();
let { width: dropdownWidth } = content.getBoundingClientRect();
positionData.style = { left: (triggerWidth - dropdownWidth) / 2 };
} else if (horizontalPosition === 'auto-right') {
let triggerRect = trigger.getBoundingClientRect();
let dropdownRect = content.getBoundingClientRect();
positionData.horizontalPosition =
triggerRect.right > dropdownRect.width ? 'right' : 'left';
} else if (horizontalPosition === 'right') {
positionData.horizontalPosition = 'right';
}
if (verticalPosition === 'above') {
positionData.verticalPosition = verticalPosition;
dropdownRect = dropdownRect || content.getBoundingClientRect();
positionData.style.top = -dropdownRect.height;
} else {
positionData.verticalPosition = 'below';
}
return positionData;
};
export function getScrollParent(element: Element) {
let style = window.getComputedStyle(element);
let excludeStaticParent = style.position === 'absolute';
let overflowRegex = /(auto|scroll)/;
if (style.position === 'fixed') return document.body;
for (
let parent: Element | null = element;
(parent = parent.parentElement);
) {
style = window.getComputedStyle(parent);
if (excludeStaticParent && style.position === 'static') {
continue;
}
if (
overflowRegex.test(style.overflow + style.overflowY + style.overflowX)
) {
return parent;
}
}
return document.body;
}
let calculatePosition: CalculatePosition = (
trigger,
content,
destination,
options
) => {
if (options.renderInPlace) {
return calculateInPlacePosition(trigger, content, destination, options);
} else {
return calculateWormholedPosition(trigger, content, destination, options);
}
};
export default calculatePosition;
| cibernox/ember-basic-dropdown | addon/utils/calculate-position.ts | TypeScript | mit | 9,067 |
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Metadata\Resource\Factory;
use ApiPlatform\Metadata\Resource\ResourceNameCollection;
/**
* Creates a resource name collection value object.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
interface ResourceNameCollectionFactoryInterface
{
/**
* Creates the resource name collection.
*/
public function create(): ResourceNameCollection;
}
| api-platform/core | src/Metadata/Resource/Factory/ResourceNameCollectionFactoryInterface.php | PHP | mit | 652 |
using System;
using System.Collections.Generic;
using System.Reflection;
using Xunit.Sdk;
namespace Oryza.TestBase.Xunit.Extensions
{
public class ClassData : DataAttribute
{
private readonly Type _type;
public ClassData(Type type)
{
if (!typeof (IEnumerable<object[]>).IsAssignableFrom(type))
{
throw new Exception("Type mismatch. Must implement IEnumerable<object[]>.");
}
_type = type;
}
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
return (IEnumerable<object[]>) Activator.CreateInstance(_type);
}
}
} | sonbua/Oryza | src/Oryza.TestBase/Xunit.Extensions/ClassData.cs | C# | mit | 682 |
__inline('ajax.js');
__inline('amd.js');
__inline('appendToHead.js');
__inline('bind.js');
__inline('copyProperties.js');
__inline('counter.js');
__inline('derive.js');
__inline('each.js');
__inline('hasOwnProperty.js');
__inline('inArray.js');
__inline('isArray.js');
__inline('isEmpty.js');
__inline('isFunction.js');
__inline('JSON.js');
__inline('nextTick.js');
__inline('queueCall.js');
__inline('slice.js');
__inline('toArray.js');
__inline('type.js');
| hao123-fe/her-runtime | src/javascript/util/util.js | JavaScript | mit | 459 |
package dsl
import (
"fmt"
"github.com/emicklei/melrose/core"
"github.com/emicklei/melrose/notify"
)
// At is called from expr after patching []. One-based
func (v variable) At(index int) interface{} {
m, ok := v.store.Get(v.Name)
if !ok {
return nil
}
if intArray, ok := m.([]int); ok {
if index < 1 || index > len(intArray) {
return nil
}
return intArray[index-1]
}
if indexable, ok := m.(core.Indexable); ok {
return indexable.At(index)
}
if sequenceable, ok := m.(core.Sequenceable); ok {
return core.BuildSequence(sequenceable.S().At(index))
}
return nil
}
// AtVariable is called from expr after patching [].
func (v variable) AtVariable(index variable) interface{} {
indexVal := core.Int(index)
if indexVal == 0 {
return nil
}
return v.At(indexVal)
}
// dispatchSubFrom v(l) - r
func (v variable) dispatchSub(r interface{}) interface{} {
if vr, ok := r.(core.HasValue); ok {
// int
il, lok := resolveInt(v)
ir, rok := resolveInt(vr)
if lok && rok {
return il - ir
}
}
if ir, ok := r.(int); ok {
// int
il, lok := resolveInt(v)
if lok {
return il - ir
}
}
notify.Panic(fmt.Errorf("subtraction failed [%v (%T) - %v (%T)]", v, v, r, r))
return nil
}
// dispatchSubFrom l - v(r)
func (v variable) dispatchSubFrom(l interface{}) interface{} {
if vl, ok := l.(core.HasValue); ok {
// int
il, lok := resolveInt(vl)
ir, rok := resolveInt(v)
if lok && rok {
return il - ir
}
}
if il, ok := l.(int); ok {
// int
ir, rok := resolveInt(v)
if rok {
return il - ir
}
}
notify.Panic(fmt.Errorf("subtraction failed [%v (%T) - %v (%T)]", l, l, v, v))
return nil
}
func (v variable) dispatchAdd(r interface{}) interface{} {
if vr, ok := r.(core.HasValue); ok {
// int
il, lok := resolveInt(v)
ir, rok := resolveInt(vr)
if lok && rok {
return il + ir
}
}
if ir, ok := r.(int); ok {
il, lok := resolveInt(v)
if lok {
return il + ir
}
}
notify.Panic(fmt.Errorf("addition failed [%v (%T) + %v (%T)]", r, r, v, v))
return nil
}
// func (v variable) dispatchMultiply(r interface{}) interface{} {
// if vr, ok := r.(core.HasValue); ok {
// // int
// il, lok := resolveInt(v)
// ir, rok := resolveInt(vr)
// if lok && rok {
// return il * ir
// }
// }
// if ir, ok := r.(int); ok {
// il, lok := resolveInt(v)
// if lok {
// return il * ir
// }
// }
// notify.Panic(fmt.Errorf("multiplication failed [%v (%T) * %v (%T)]", r, r, v, v))
// return nil
// }
func resolveInt(v core.HasValue) (int, bool) {
vv := v.Value()
if i, ok := vv.(int); ok {
return i, true
}
if vvv, ok := vv.(core.HasValue); ok {
return resolveInt(vvv)
}
return 0, false
}
| emicklei/melrose | dsl/var_delegates.go | GO | mit | 2,696 |
'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var util = require('util');
var async = require('./async');
/**
* Read a directory recursively.
* The directory will be read depth-first and will return paths relative
* to the base directory. It will only result in file names, not directories.
*
* @function
* @param {string} dir The directory to read
* @param {function} cb The callback to call when complete. Receives error
* and array of relative file paths.
*/
var readdirRecursive = module.exports.readdirRecursive = function(dir, cb) {
var remaining = ['.'];
var result = [];
var next = function() {
var relativeDirPath = remaining.shift();
var dirPath = path.join(dir, relativeDirPath);
fs.readdir(dirPath, function(err, files) {
if (err) { return cb(err); }
async.each(files, function(file, done) {
if (file[0] === '.') { return done(); }
var filePath = path.join(dirPath, file);
var relativeFilePath = path.join(relativeDirPath, file);
fs.stat(filePath, function(err, stats) {
if (err) { return done(err); }
if (stats.isDirectory()) { remaining.push(relativeFilePath); }
else { result.push(relativeFilePath); }
done();
});
}, function(err) {
if (err) { return cb(err); }
if (remaining.length === 0) {
cb(null, result.sort());
}
else { next(); }
});
});
};
next();
};
/**
* Test if files are equal.
*
* @param {string} fileA Path to first file
* @param {string} fileB Path to second file
* @param {function} cb Callback to call when finished check. Receives error
* and boolean.
*/
var filesEqual = module.exports.filesEqual = function(fileA, fileB, cb) {
var options = { encoding: 'utf8' };
fs.readFile(fileA, options, function(err, contentsA) {
if (err) { return cb(err); }
fs.readFile(fileB, options, function(err, contentsB) {
if (err) { return cb(err); }
cb(null, contentsA === contentsB);
});
})
};
/**
* Recursively test if directories are equal.
*
* @param {string} dirA Path to first dir
* @param {string} dirB Path to second dir
* @param {function} cb Callback to call when finished check. Receives error
* and boolean.
*/
module.exports.directoriesEqual = function(directoryA, directoryB, cb) {
readdirRecursive(directoryA, function(err, directoryAContents) {
if (err) { return cb(err); }
readdirRecursive(directoryB, function(err, directoryBContents) {
if (err) { return cb(err); }
if (directoryAContents.length !== directoryBContents.length) {
cb(null, false);
}
else {
directoryAContents = directoryAContents.sort();
directoryBContents = directoryBContents.sort();
if (!_.isEqual(directoryAContents, directoryBContents)) {
cb(null, false);
}
else {
var result = true;
async.each(directoryAContents, function(relativePath, done) {
var aFilePath = path.join(directoryA, relativePath);
var bFilePath = path.join(directoryB, relativePath);
filesEqual(aFilePath, bFilePath, function(err, singleResult) {
if (err) { return done(err); }
result = singleResult && result;
done();
});
}, function(err) {
if (err) { return cb(err); }
cb(null, result);
});
}
}
});
});
};
/**
* Make a directory and all the directories that lead to it.
*
* @function
* @param {string} path Path to the directory to make
* @param {function} cb The callback to call once created. This just
* receives an error.
*/
module.exports.mkdirp = function(dirPath, cb) {
var attempt = [dirPath];
var next = function() {
var attemptPath = attempt.pop();
fs.mkdir(attemptPath, function(err) {
if (err && (
err.code === 'EISDIR' ||
err.code === 'EEXIST')) { cb(); }
else if (err && err.code === 'ENOENT') {
attempt.push(attemptPath);
attempt.push(path.dirname(attemptPath));
next();
}
else if (err) { cb(err); }
else if (attempt.length) { next(); }
else if (attemptPath === '/') {
cb(new Error(util.format('Could not make path to %s', dirPath)));
}
else { cb(); }
});
};
next();
};
| wbyoung/jsi-blowtorch | lib/fs-extras.js | JavaScript | mit | 4,456 |
class Bitcask
require 'zlib'
require 'stringio'
$LOAD_PATH << File.expand_path(File.dirname(__FILE__))
require 'bitcask/hint_file'
require 'bitcask/data_file'
require 'bitcask/keydir'
require 'bitcask/errors'
require 'bitcask/version'
include Enumerable
TOMBSTONE = "bitcask_tombstone"
# Opens a bitcask backed by the given directory.
attr_accessor :keydir
attr_reader :dir
def initialize(dir)
@dir = dir
@keydir = Bitcask::Keydir.new
end
# Uses the keydir to get an object from the bitcask. Returns a
# value.
def [](key)
index = @keydir[key] or return nil
@keydir.data_files[index.file_id][index.value_pos, index.value_sz].value
end
# Close filehandles and keydir
def close
close_filehandles
close_keydir
end
# Close all filehandles loaded by the keydir.
def close_filehandles
@keydir.data_files.each do |data_file|
data_file.close
if h = data_file.instance_variable_get('@hint_file')
h.close
end
end
end
# Close the keydir.
def close_keydir
@keydir = nil
end
# Returns a list of all data filenames in this bitcask, sorted from oldest
# to newest.
def data_file_names
Dir.glob(File.join(@dir, '*.data')).sort! do |a, b|
a.to_i <=> b.to_i
end
end
# Returns a list of Bitcask::DataFiles in chronological order.
def data_files
data_file_names.map! do |filename|
Bitcask::DataFile.new filename
end
end
# Iterates over all keys in keydir. Yields key, value pairs.
def each
@keydir.each do |key, index|
entry = @keydir.data_files[index.file_id][index.value_pos, index.value_sz]
yield [entry.key, entry.value]
end
end
# Keydir keys.
def keys
keydir.keys
end
# Populate the keydir.
def load
data_files.each do |d|
if h = d.hint_file
load_hint_file h
else
load_data_file d
end
end
end
# Load a DataFile into the keydir.
def load_data_file(data_file)
# Determine data_file index.
@keydir.data_files |= [data_file]
file_id = @keydir.data_files.index data_file
pos = 0
data_file.each do |entry|
# Check for existing newer entry in keydir
if (cur = @keydir[entry.key]).nil? or entry.tstamp >= cur.tstamp
@keydir[entry.key] = Keydir::Entry.new(
file_id,
data_file.pos - pos,
pos,
entry.tstamp
)
end
pos = data_file.pos
end
end
# Load a HintFile into the keydir.
def load_hint_file(hint_file)
# Determine data_file index.
@keydir.data_files |= [hint_file.data_file]
file_id = @keydir.data_files.index hint_file.data_file
hint_file.each do |entry|
# Check for existing newer entry in keydir
if (cur = @keydir[entry.key]).nil? or entry.tstamp >= cur.tstamp
@keydir[entry.key] = Keydir::Entry.new(
file_id,
entry.value_sz,
entry.value_pos,
entry.tstamp
)
end
end
end
# Keydir size.
def size
@keydir.size
end
end
| aphyr/bitcask-ruby | lib/bitcask.rb | Ruby | mit | 3,087 |
'use strict'
/*
MIT License
Copyright (c) 2016 Ilya Shaisultanov
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.
*/
var dgram = require('dgram')
, EE = require('events').EventEmitter
, util = require('util')
, ip = require('ip')
, debug = require('debug')
, os = require('os')
, async = require('async')
, extend = require('extend')
, SsdpHeader = require('./ssdpHeader')
var httpHeader = /HTTP\/\d{1}\.\d{1} \d+ .*/
, ssdpHeader = /^([^:]+):\s*(.*)$/
/* consts */
var c = require('./const')
var nodeVersion = process.version.substr(1)
, moduleVersion = require('../package.json').version
, moduleName = require('../package.json').name
/**
* Options:
*
* @param {Object} opts
* @param {String} opts.ssdpSig SSDP signature
* @param {String} opts.ssdpIp SSDP multicast group
* @param {String} opts.ssdpPort SSDP port
* @param {Number} opts.ssdpTtl Multicast TTL
* @param {Number} opts.adInterval Interval at which to send out advertisement (ms)
* @param {String} opts.description Path to SSDP description file
* @param {String} opts.udn SSDP Unique Device Name
* @param {Object} opts.headers Additional headers
* @param {Array} opts.interfaces Names of interfaces to use. When set, other interfaces are ignored.
*
* @param {Number} opts.ttl Packet TTL
* @param {Boolean} opts.allowWildcards Allow wildcards in M-SEARCH packets (non-standard)
*
* @returns {SSDP}
* @constructor
*/
function SSDP(opts) {
var self = this
if (!(this instanceof SSDP)) return new SSDP(opts)
this._subclass = this._subclass || 'node-ssdp:base'
opts = opts || {}
this._logger = opts.customLogger || debug(this._subclass)
EE.call(self)
this._init(opts)
}
util.inherits(SSDP, EE)
/**
* Initializes instance properties.
* @param opts
* @private
*/
SSDP.prototype._init = function (opts) {
this._ssdpSig = opts.ssdpSig || getSsdpSignature()
this._explicitSocketBind = opts.explicitSocketBind
this._interfaces = opts.interfaces
this._reuseAddr = opts.reuseAddr === undefined ? true : opts.reuseAddr
// User shouldn't need to set these
this._ssdpIp = opts.ssdpIp || c.SSDP_DEFAULT_IP
this._ssdpPort = opts.ssdpPort || c.SSDP_DEFAULT_PORT
this._ssdpTtl = opts.ssdpTtl || 4
// port on which to listen for messages
// this generally should be left up to the system for SSDP Client
// For server, this will be set by the server constructor
// unless user sets a value.
this._sourcePort = opts.sourcePort || 0
this._adInterval = opts.adInterval || 10000
this._ttl = opts.ttl || 1800
if (typeof opts.location === 'function') {
Object.defineProperty(this, '_location', {
enumerable: true,
get: opts.location
})
} else if (typeof opts.location === 'object') {
this._locationProtocol = opts.location.protocol || 'http://'
this._locationPort = opts.location.port
this._locationPath = opts.location.path
} else {
// Probably should specify this explicitly
this._location = opts.location || 'http://' + ip.address() + ':' + 10293 + '/upnp/desc.html'
}
this._ssdpServerHost = this._ssdpIp + ':' + this._ssdpPort
this._usns = {}
this._udn = opts.udn || 'uuid:f40c2981-7329-40b7-8b04-27f187aecfb5'
this._extraHeaders = opts.headers || {}
this._allowWildcards = opts.allowWildcards
this._suppressRootDeviceAdvertisements = opts.suppressRootDeviceAdvertisements
}
/**
* Creates and returns UDP4 socket.
* Prior to node v0.12.x `dgram.createSocket` did not accept
* an object and socket reuse was not available; this method
* contains a crappy workaround to make version of node before 0.12
* to work correctly. See https://github.com/diversario/node-ssdp/pull/38
*
* @returns {Socket}
* @private
*/
SSDP.prototype._createSockets = function () {
var interfaces = os.networkInterfaces()
, self = this
this.sockets = {}
Object.keys(interfaces).forEach(function (iName) {
if (!self._interfaces || self._interfaces.indexOf(iName) > -1) {
self._logger('discovering all IPs from interface %s', iName)
interfaces[iName].forEach(function (ipInfo) {
if (ipInfo.internal == false && ipInfo.family == "IPv4") {
self._logger('Will use interface %s', iName)
var socket
if (parseFloat(process.version.replace(/\w/, '')) >= 0.12) {
socket = dgram.createSocket({type: 'udp4', reuseAddr: self._reuseAddr})
} else {
socket = dgram.createSocket('udp4')
}
if (socket) {
socket.unref()
self.sockets[ipInfo.address] = socket
}
}
})
}
})
if (Object.keys(this.sockets) == 0) {
throw new Error('No sockets available, cannot start.')
}
}
/**
* Advertise shutdown and close UDP socket.
*/
SSDP.prototype._stop = function () {
var self = this
if (!this.sockets) {
this._logger('Already stopped.')
return
}
Object.keys(this.sockets).forEach(function (ipAddress) {
var socket = self.sockets[ipAddress]
socket && socket.close()
self._logger('Stopped socket on %s', ipAddress)
})
this.sockets = null
this._socketBound = this._started = false
}
/**
* Configures UDP socket `socket`.
* Binds event listeners.
*/
SSDP.prototype._start = function (cb) {
var self = this
if (self._started) {
self._logger('Already started.')
return
}
if (!this.sockets) {
this._createSockets()
}
self._started = true
var interfaces = Object.keys(this.sockets)
async.each(interfaces, function (iface, next) {
var socket = self.sockets[iface]
socket.on('error', function onSocketError(err) {
self._logger('Socker error: %s', err.message)
})
socket.on('message', function onSocketMessage(msg, rinfo) {
self._parseMessage(msg, rinfo)
})
socket.on('listening', function onSocketListening() {
var addr = socket.address()
self._logger('SSDP listening: %o', {address: 'http://' + addr.address + ':' + addr.port, 'interface': iface})
try {
addMembership()
} catch (e) {
if (e.code === 'ENODEV' || e.code === 'EADDRNOTAVAIL') {
self._logger('Interface %s is not present to add multicast group membership. Scheduling a retry. Error: %s', addr, e.message)
delay().then(addMembership).catch(e => { throw e })
} else {
throw e
}
}
function addMembership() {
socket.addMembership(self._ssdpIp, iface) // TODO: specifying the interface in there might make a difference
socket.setMulticastTTL(self._ssdpTtl)
}
function delay() {
return new Promise((resolve) => {
setTimeout(resolve, 5000);
});
}
})
if (self._explicitSocketBind) {
socket.bind(self._sourcePort, iface, next)
} else {
socket.bind(self._sourcePort, next) // socket binds on 0.0.0.0
}
}, cb)
}
/**
* Routes a network message to the appropriate handler.
*
* @param msg
* @param rinfo
*/
SSDP.prototype._parseMessage = function (msg, rinfo) {
msg = msg.toString()
var type = msg.split('\r\n').shift()
// HTTP/#.# ### Response to M-SEARCH
if (httpHeader.test(type)) {
this._parseResponse(msg, rinfo)
} else {
this._parseCommand(msg, rinfo)
}
}
/**
* Parses SSDP command.
*
* @param msg
* @param rinfo
*/
SSDP.prototype._parseCommand = function parseCommand(msg, rinfo) {
var method = this._getMethod(msg)
, headers = this._getHeaders(msg)
switch (method) {
case c.NOTIFY:
this._notify(headers, msg, rinfo)
break
case c.M_SEARCH:
this._msearch(headers, msg, rinfo)
break
default:
this._logger('Unhandled command: %o', {'message': msg, 'rinfo': rinfo})
}
}
/**
* Handles NOTIFY command
* Emits `advertise-alive`, `advertise-bye` events.
*
* @param headers
* @param msg
* @param rinfo
*/
SSDP.prototype._notify = function (headers, msg, rinfo) {
if (!headers.NTS) {
this._logger('Missing NTS header: %o', headers)
return
}
switch (headers.NTS.toLowerCase()) {
// Device coming to life.
case c.SSDP_ALIVE:
this.emit(c.ADVERTISE_ALIVE, headers, rinfo)
break
// Device shutting down.
case c.SSDP_BYE:
this.emit(c.ADVERTISE_BYE, headers, rinfo)
break
default:
this._logger('Unhandled NOTIFY event: %o', {'message': msg, 'rinfo': rinfo})
}
}
/**
* Handles M-SEARCH command.
*
* @param headers
* @param msg
* @param rinfo
*/
SSDP.prototype._msearch = function (headers, msg, rinfo) {
this._logger('SSDP M-SEARCH event: %o', {'ST': headers.ST, 'address': rinfo.address, 'port': rinfo.port})
if (!headers.MAN || !headers.MX || !headers.ST) return
this._respondToSearch(headers.ST, rinfo)
}
/**
* Sends out a response to M-SEARCH commands.
*
* @param {String} serviceType Service type requested by a client
* @param {Object} rinfo Remote client's address
* @private
*/
SSDP.prototype._respondToSearch = function (serviceType, rinfo) {
var self = this
, peer_addr = rinfo.address
, peer_port = rinfo.port
, stRegex
, acceptor
// unwrap quoted string
if (serviceType[0] == '"' && serviceType[serviceType.length - 1] == '"') {
serviceType = serviceType.slice(1, -1)
}
if (self._allowWildcards) {
stRegex = new RegExp(serviceType.replace(/\*/g, '.*') + '$')
acceptor = function (usn, serviceType) {
return serviceType === c.SSDP_ALL || stRegex.test(usn)
}
} else {
acceptor = function (usn, serviceType) {
return serviceType === c.SSDP_ALL || usn === serviceType
}
}
Object.keys(self._usns).forEach(function (usn) {
var udn = self._usns[usn]
if (self._allowWildcards) {
udn = udn.replace(stRegex, serviceType)
}
if (acceptor(usn, serviceType)) {
var header = new SsdpHeader('200 OK', {
'ST': serviceType === c.SSDP_ALL ? usn : serviceType,
'USN': udn,
'CACHE-CONTROL': 'max-age=' + self._ttl,
'DATE': new Date().toUTCString(),
'SERVER': self._ssdpSig,
'EXT': ''
}, true)
header.setHeaders(self._extraHeaders)
if (self._location) {
header.setHeader('LOCATION', self._location)
} else {
header.overrideLocationOnSend()
}
self._logger('Sending a 200 OK for an M-SEARCH: %o', {'peer': peer_addr, 'port': peer_port})
self._send(header, peer_addr, peer_port, function (err, bytes) {
self._logger('Sent M-SEARCH response: %o', {'message': header.toString(), id: header.id()})
})
}
})
}
/**
* Parses SSDP response message.
*
* @param msg
* @param rinfo
*/
SSDP.prototype._parseResponse = function parseResponse(msg, rinfo) {
this._logger('SSDP response: %o', {'message': msg})
var headers = this._getHeaders(msg)
, statusCode = this._getStatusCode(msg)
this.emit('response', headers, statusCode, rinfo)
}
SSDP.prototype.addUSN = function (device) {
this._usns[device] = this._udn + '::' + device
}
SSDP.prototype._getMethod = function _getMethod(msg) {
var lines = msg.split("\r\n")
, type = lines.shift().split(' ')// command, such as "NOTIFY * HTTP/1.1"
, method = (type[0] || '').toLowerCase()
return method
}
SSDP.prototype._getStatusCode = function _getStatusCode(msg) {
var lines = msg.split("\r\n")
, type = lines.shift().split(' ')// command, such as "NOTIFY * HTTP/1.1"
, code = parseInt(type[1], 10)
return code
}
SSDP.prototype._getHeaders = function _getHeaders(msg) {
var lines = msg.split("\r\n")
var headers = {}
lines.forEach(function (line) {
if (line.length) {
var pairs = line.match(ssdpHeader)
if (pairs) headers[pairs[1].toUpperCase()] = pairs[2] // e.g. {'HOST': 239.255.255.250:1900}
}
})
return headers
}
SSDP.prototype._send = function (message, host, port, cb) {
var self = this
if (typeof host === 'function') {
cb = host
host = this._ssdpIp
port = this._ssdpPort
}
var ipAddresses = Object.keys(this.sockets)
async.each(ipAddresses, function (ipAddress, next) {
var socket = self.sockets[ipAddress]
var buf
if (message instanceof SsdpHeader) {
if (message.isOverrideLocationOnSend()) {
var location = self._locationProtocol + ipAddress + ':' + self._locationPort + self._locationPath
self._logger('Setting LOCATION header "%s" on message ID %s', location, message.id())
buf = message.toBuffer({'LOCATION': location})
} else {
buf = message.toBuffer()
}
} else {
buf = message
}
self._logger('Sending a message to %s:%s', host, port)
socket.send(buf, 0, buf.length, port, host, next)
}, cb)
}
function getSsdpSignature() {
return 'node.js/' + nodeVersion + ' UPnP/1.1 ' + moduleName + '/' + moduleVersion
}
module.exports = SSDP
| diversario/node-ssdp | lib/index.js | JavaScript | mit | 13,902 |
<?php
namespace App;
use App\Models\User;
use RuntimeException;
class UserSettingForm {
private string $setting_name;
private ?User $current_user;
private bool $can_save;
public const INPUT_MAP = [
'cg_defaultguide' => [
'type' => 'select',
'options' => [
'desc' => 'Choose your preferred color guide: ',
'optg' => 'Available guides',
'opts' => CGUtils::GUIDE_MAP,
'null_opt' => 'Guide Index',
],
],
'cg_itemsperpage' => [
'type' => 'number',
'options' => [
'desc' => 'Appearances per page',
'min' => 7,
'max' => 20,
],
],
'cg_hidesynon' => [
'type' => 'checkbox',
'options' => [
'perm' => 'staff',
'desc' => 'Hide synonym tags under appearances',
],
],
'cg_hideclrinfo' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Hide color details on appearance pages',
],
],
'cg_fulllstprev' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Display previews and alternate names on the full list',
],
],
'cg_nutshell' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Use joke character names (does not affect search)',
],
],
'p_vectorapp' => [
'type' => 'select',
'options' => [
'desc' => 'Publicly show my vector program of choice: ',
'optg' => 'Vectoring applications',
'opts' => CoreUtils::VECTOR_APPS,
],
],
'p_hidediscord' => [
'type' => 'checkbox',
'options' => [
'perm' => 'not_discord_member',
'desc' => 'Hide Discord server link from the sidebar',
],
],
'p_hidepcg' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Hide my Personal Color Guide from the public',
],
],
'p_homelastep' => [
'type' => 'checkbox',
'options' => [
'desc' => '<span class="typcn typcn-home"> Home</span> should open latest episode (instead of preferred color guide)',
],
],
'ep_hidesynopses' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Hide the synopsis section from episode pages',
],
],
'ep_noappprev' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Hide preview squares in front of related appearance names',
],
],
'ep_revstepbtn' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Reverse order of next/previous episode buttons',
],
],
'a_pcgearn' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Can earn PCG slots (from finishing requests)',
],
],
'a_pcgmake' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Can create PCG appearances',
],
],
'a_pcgsprite' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Can add sprites to PCG appearances',
],
],
'a_postreq' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Can post requests',
],
],
'a_postres' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Can post reservations',
],
],
'a_reserve' => [
'type' => 'checkbox',
'options' => [
'desc' => 'Can reserve requests',
],
],
];
public function __construct(string $setting_name, ?User $current_user = null, ?string $req_perm = null) {
if (!array_key_exists($setting_name, UserPrefs::DEFAULTS))
throw new RuntimeException('Could not instantiate '.__CLASS__." for non-existing setting $setting_name");
if (!isset(self::INPUT_MAP[$setting_name]))
throw new RuntimeException('Could not instantiate '.__CLASS__." for $setting_name: Missing INPUT_MAP entry");
$this->setting_name = $setting_name;
if ($current_user === null && Auth::$signed_in)
$current_user = Auth::$user;
$this->current_user = $current_user;
// By default only the user themselves can change this setting
if ($req_perm === null)
$this->can_save = Auth::$signed_in && $this->current_user->id === Auth::$user->id;
// If a permission is required, make sure the authenticated user has it
else $this->can_save = Permission::sufficient($req_perm);
}
private function _permissionCheck(string $check_name) {
switch ($check_name){
case 'discord_member':
case 'not_discord_member':
if ($this->current_user === null)
return false;
if ($this->current_user->isDiscordServerMember())
return $check_name === 'discord_member';
else return $check_name === 'not_discord_member';
default:
return true;
}
}
private function _getInput(string $type, array $options = []):string {
if (isset($options['perm'])){
if (isset(Permission::ROLES[$options['perm']])){
if (Permission::insufficient($options['perm']))
return '';
}
else {
if (!$this->_permissionCheck($options['perm']))
return '';
}
}
$disabled = !$this->can_save ? 'disabled' : '';
$value = UserPrefs::get($this->setting_name, $this->current_user);
switch ($type){
case 'select':
$select = '';
$optgroup = '';
if (isset($options['null_opt'])){
$selected = $value === null ? 'selected' : '';
$select .= "<option value='' $selected>".CoreUtils::escapeHTML($options['null_opt']).'</option>';
}
/** @noinspection ForeachSourceInspection */
foreach ($options['opts'] as $name => $label){
$selected = $value === $name ? 'selected' : '';
$opt_disabled = isset($options['optperm'][$name]) && !$this->_permissionCheck($options['optperm'][$name]) ? 'disabled' : '';
$optgroup .= "<option value='$name' $selected $opt_disabled>".CoreUtils::escapeHTML($label).'</option>';
}
$label = CoreUtils::escapeHTML($options['optg'], ENT_QUOTES);
$select .= "<optgroup label='$label'>$optgroup</optgroup>";
return "<select name='value' $disabled>$select</select>";
case 'number':
$min = isset($options['min']) ? "min='{$options['min']}'" : '';
$max = isset($options['max']) ? "max='{$options['max']}'" : '';
$value = CoreUtils::escapeHTML($value, ENT_QUOTES);
return "<input type='number' $min $max name='value' value='$value' step='1' $disabled>";
case 'checkbox':
$checked = $value ? ' checked' : '';
return "<input type='checkbox' name='value' value='1' $checked $disabled>";
}
}
public function render() {
$map = self::INPUT_MAP[$this->setting_name];
$input = $this->_getInput($map['type'], $map['options'] ?? []);
if ($input === '')
return '';
echo Twig::$env->render('user/_setting_form.html.twig', [
'map' => $map,
'input' => $input,
'can_save' => $this->can_save,
'setting_name' => $this->setting_name,
'current_user' => $this->current_user,
'signed_in' => Auth::$signed_in,
]);
}
}
| ponydevs/MLPVC-RR | app/UserSettingForm.php | PHP | mit | 7,139 |
using System.Web.Mvc;
namespace SOURCE.BackOffice.Web.Controllers.Modularity
{
public class BaseController : Controller
{
protected string Rubrique { get; set; }
protected string Page { get; set; }
protected string Secteur { get; set; }
public BaseController()
: base()
{
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
/*
List<ModuleModel> leftmodules = new List<ModuleModel>();
leftmodules.Add(new ModuleModel { BaseModuleName = "Nouveautes", ID = 12 });
ViewData["modules_gauche"] = (IEnumerable<ModuleModel>)leftmodules;
List<ModuleModel> rightmodules = new List<ModuleModel>();
rightmodules.Add(new ModuleModel { BaseModuleName = "Nouveautes", ID = 13 });
rightmodules.Add(new ModuleModel { BaseModuleName = "MeilleuresVentes", ID = 20 });
rightmodules.Add(new ModuleModel { BaseModuleName = "Nouveautes", ID = 14 });
ViewData["modules_droite"] = (IEnumerable<ModuleModel>)rightmodules;
if (RouteData.Values["secteur"] != null)
this.Secteur = RouteData.Values["secteur"].ToString();
else
this.Secteur = string.Empty;
if (RouteData.Values["subpage"] != null)
this.Rubrique = RouteData.Values["subpage"].ToString();
else
this.Rubrique = "Normes";
if (RouteData.Values["page"] != null)
this.Page = RouteData.Values["page"].ToString();
else
this.Page = "Home";
*/
}
}
}
| apo-j/Projects_Working | S/SOURCE/SOURCE.BackOffice/SOURCE.BackOffice.Web.Controllers/Modularity/BaseController.cs | C# | mit | 1,754 |
import signal
import subprocess
import sys
import time
import numba
import numpy as np
import SharedArray as sa
sys.path.append('./pymunk')
import pymunk as pm
max_creatures = 50
@numba.jit
def _find_first(vec, item):
for i in range(len(vec)):
if vec[i] == item:
return i
return -1
@numba.jit(nopython=True)
def random_circle_point():
theta = np.random.rand()*2*np.pi
x,y = 5*np.cos(theta), 5*np.sin(theta)
return x,y
class Culture(object):
def __init__(self):
try:
self.creature_parts = sa.create('creature_parts', (max_creatures*3, 12), dtype=np.float32)
except FileExistsError:
sa.delete('creature_parts')
self.creature_parts = sa.create('creature_parts', (max_creatures*3, 12), dtype=np.float32)
# X POSITION, Y POSITION
self.creature_parts[:, :2] = (30.0, 30.0)#np.random.random((max_creatures, 2)).astype(np.float32)*20.0 - 10.0
# ROTATION
self.creature_parts[:, 2] = np.random.random(max_creatures*3)*2*np.pi - np.pi
# SCALE
self.creature_parts[:, 3] = 0.5
# TEXTURE INDEX
self.creature_parts[:, 4] = np.random.randint(0, 10, max_creatures*3)
# COLOR ROTATION
self.creature_parts[:, 5] = np.random.randint(0, 4, max_creatures*3)/4.0
# SATURATION
self.creature_parts[:, 6] = 1.0
# ALPHA
self.creature_parts[:, 7] = 1.0
# TIME OFFSET (FOR ANIMATION
self.creature_parts[:, 8] = np.random.random(max_creatures).repeat(3)*2*np.pi
self.creature_parts[1::3, 8] += 0.4
self.creature_parts[2::3, 8] += 0.8
# BEAT ANIMATION FREQUENCY
self.creature_parts[:, 9] = 2.0
# SWIRL ANIMATON RADIUS
self.creature_parts[:, 10] = 2.3
# SWIRL ANIMATION FREQUENCY
self.creature_parts[:, 11] = 1.0
self.creature_data = np.zeros((max_creatures, 4))
self.creature_data[:, 1] = 1.0 # max_age
self.creature_data[:, 3] = 0.5 # creature size
self.pm_space = pm.Space()
self.pm_space.damping = 0.4
# self.pm_space.gravity = 0.0, -1.0
self.pm_body = []
self.pm_body_joint = []
self.pm_target = []
self.pm_target_spring = []
for i in range(max_creatures):
head = pm.Body(10.0, 5.0)
head.position = tuple(self.creature_parts[i, :2])
mid = pm.Body(1.0, 1.0)
mid.position = head.position + (0.0, -1.0)
tail = pm.Body(1.0, 1.0)
tail.position = head.position + (0.0, -2.0)
self.pm_body.append([head, mid, tail])
head_mid_joint1 = pm.constraint.SlideJoint(head, mid, (0.4, -0.3), (0.4, 0.3), 0.1, 0.2)
head_mid_joint2 = pm.constraint.SlideJoint(head, mid, (-0.4, -0.3), (-0.4, 0.3), 0.1, 0.2)
mid_tail_joint = pm.constraint.SlideJoint(mid, tail, (0.0, -0.1), (0.0, 0.1), 0.1, 0.5)
self.pm_body_joint.append([head_mid_joint1, head_mid_joint2, mid_tail_joint])
target = pm.Body(10.0, 10.0)
target.position = tuple(self.creature_parts[i, :2] + (0.0, 5.0))
self.pm_target.append(target)
head_offset = pm.vec2d.Vec2d((0.0, 0.8)) * float(0.5)
target_spring = pm.constraint.DampedSpring(head, target, head_offset, (0.0, 0.0), 0.0, 10.0, 15.0)
self.pm_target_spring.append(target_spring)
self.pm_space.add([head, mid, tail])
self.pm_space.add([head_mid_joint1, head_mid_joint2, mid_tail_joint])
self.pm_space.add([target_spring])
self.prev_update = time.perf_counter()
self.ct = time.perf_counter()
#self.dt = p0.0
def add_creature(self, type=None):
if type is None:
type = 0#np.random.randint(2)
print('adding creature {}'.format(type))
ind = _find_first(self.creature_data[:, 0], 0.0)
if ind != -1:
if type == 0: # Meduusa
new_pos = pm.vec2d.Vec2d(tuple(np.random.random(2)*20.0 - 10.0))
print('at position: ', new_pos)
head_offset = pm.vec2d.Vec2d((0.0, 0.8)) * 0.5
self.pm_target[ind].position = new_pos + head_offset
self.pm_body[ind][0].position = new_pos #creature_data[ind, :2] = new_pos
self.pm_body[ind][1].position = new_pos + (0.0, -0.5)
self.pm_body[ind][2].position = new_pos + (0.0, -1.0)
for i in range(3):
self.pm_body[ind][i].reset_forces()
self.pm_body[ind][i].velocity = 0.0, 0.0
self.creature_parts[ind*3+i, 3] = 0.5 # size/scale
self.creature_parts[ind*3+i, 6] = 1.0
self.creature_parts[ind*3+i, 4] = 2+i
self.creature_data[ind, :] = [1.0, np.random.random(1)*10+10, 0.0, 0.5] # Alive, max_age, age, size
if type == 1: # Ötö
pass
def update(self, dt):
self.ct = time.perf_counter()
if self.ct - self.prev_update > 5.0:
self.add_creature()
#i = np.random.randint(0, max_creatures)
#self.pm_target[i].position = tuple(np.random.random(2)*20.0 - 10.0)
self.prev_update = self.ct
alive = self.creature_data[:, 0]
max_age = self.creature_data[:, 1]
cur_age = self.creature_data[:, 2]
cur_age[:] += dt
self.creature_parts[:, 6] = np.clip(1.0 - (cur_age / max_age), 0.0, 1.0).repeat(3)
# dying_creatures = (alive == 1.0) & (cur_age > max_age)
self.creature_parts[:, 7] = np.clip(1.0 - (cur_age - max_age)/5.0, 0.0, 1.0).repeat(3)
dead_creatures = (alive == 1.0) & (cur_age > max_age + 5.0)
self.creature_data[dead_creatures, 0] = 0.0
self.pm_space.step(dt)
for i in range(max_creatures):
head_offset = pm.vec2d.Vec2d((0.0, 0.8)) * 0.5
if alive[i] == 1.0 and \
(self.pm_body[i][0].position - (self.pm_target[i].position - head_offset)).get_length() < 2.0:
self.pm_target[i].position += random_circle_point()
for j in range(3):
self.creature_parts[3*i+j, :2] = tuple(self.pm_body[i][j].position)
self.creature_parts[3*i+j, 2] = self.pm_body[i][j].angle
#self.creature_data[:, 2] += dt
@staticmethod
def cleanup():
print('Cleaning up')
sa.delete('creature_parts')
def main():
culture = Culture()
gfx_p = subprocess.Popen(['python', 'main.py'])
running = True
def signal_handler(signal_number, frame):
print('Received signal {} in frame {}'.format(signal_number, frame))
nonlocal running
running = False
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C to quit')
while running:
culture.update(0.01)
time.sleep(0.01)
if gfx_p.poll() == 0:
break
culture.cleanup()
if __name__ == "__main__":
main()
| brains-on-art/culture | culture_logic.py | Python | mit | 7,076 |
//go:build go1.16
// +build go1.16
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armazuredata
import "net/http"
// OperationsClientListResponse contains the response from method OperationsClient.List.
type OperationsClientListResponse struct {
OperationsClientListResult
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// OperationsClientListResult contains the result from method OperationsClient.List.
type OperationsClientListResult struct {
OperationListResult
}
// SQLServerRegistrationsClientCreateOrUpdateResponse contains the response from method SQLServerRegistrationsClient.CreateOrUpdate.
type SQLServerRegistrationsClientCreateOrUpdateResponse struct {
SQLServerRegistrationsClientCreateOrUpdateResult
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// SQLServerRegistrationsClientCreateOrUpdateResult contains the result from method SQLServerRegistrationsClient.CreateOrUpdate.
type SQLServerRegistrationsClientCreateOrUpdateResult struct {
SQLServerRegistration
}
// SQLServerRegistrationsClientDeleteResponse contains the response from method SQLServerRegistrationsClient.Delete.
type SQLServerRegistrationsClientDeleteResponse struct {
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// SQLServerRegistrationsClientGetResponse contains the response from method SQLServerRegistrationsClient.Get.
type SQLServerRegistrationsClientGetResponse struct {
SQLServerRegistrationsClientGetResult
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// SQLServerRegistrationsClientGetResult contains the result from method SQLServerRegistrationsClient.Get.
type SQLServerRegistrationsClientGetResult struct {
SQLServerRegistration
}
// SQLServerRegistrationsClientListByResourceGroupResponse contains the response from method SQLServerRegistrationsClient.ListByResourceGroup.
type SQLServerRegistrationsClientListByResourceGroupResponse struct {
SQLServerRegistrationsClientListByResourceGroupResult
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// SQLServerRegistrationsClientListByResourceGroupResult contains the result from method SQLServerRegistrationsClient.ListByResourceGroup.
type SQLServerRegistrationsClientListByResourceGroupResult struct {
SQLServerRegistrationListResult
}
// SQLServerRegistrationsClientListResponse contains the response from method SQLServerRegistrationsClient.List.
type SQLServerRegistrationsClientListResponse struct {
SQLServerRegistrationsClientListResult
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// SQLServerRegistrationsClientListResult contains the result from method SQLServerRegistrationsClient.List.
type SQLServerRegistrationsClientListResult struct {
SQLServerRegistrationListResult
}
// SQLServerRegistrationsClientUpdateResponse contains the response from method SQLServerRegistrationsClient.Update.
type SQLServerRegistrationsClientUpdateResponse struct {
SQLServerRegistrationsClientUpdateResult
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// SQLServerRegistrationsClientUpdateResult contains the result from method SQLServerRegistrationsClient.Update.
type SQLServerRegistrationsClientUpdateResult struct {
SQLServerRegistration
}
// SQLServersClientCreateOrUpdateResponse contains the response from method SQLServersClient.CreateOrUpdate.
type SQLServersClientCreateOrUpdateResponse struct {
SQLServersClientCreateOrUpdateResult
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// SQLServersClientCreateOrUpdateResult contains the result from method SQLServersClient.CreateOrUpdate.
type SQLServersClientCreateOrUpdateResult struct {
SQLServer
}
// SQLServersClientDeleteResponse contains the response from method SQLServersClient.Delete.
type SQLServersClientDeleteResponse struct {
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// SQLServersClientGetResponse contains the response from method SQLServersClient.Get.
type SQLServersClientGetResponse struct {
SQLServersClientGetResult
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// SQLServersClientGetResult contains the result from method SQLServersClient.Get.
type SQLServersClientGetResult struct {
SQLServer
}
// SQLServersClientListByResourceGroupResponse contains the response from method SQLServersClient.ListByResourceGroup.
type SQLServersClientListByResourceGroupResponse struct {
SQLServersClientListByResourceGroupResult
// RawResponse contains the underlying HTTP response.
RawResponse *http.Response
}
// SQLServersClientListByResourceGroupResult contains the result from method SQLServersClient.ListByResourceGroup.
type SQLServersClientListByResourceGroupResult struct {
SQLServerListResult
}
| Azure/azure-sdk-for-go | sdk/resourcemanager/azuredata/armazuredata/zz_generated_response_types.go | GO | mit | 5,207 |
#
# Author:: MJ Rossetti (@s2t2)
# Cookbook Name:: trailmix
# Recipe:: mail
#
# Install sendmail package.
package "sendmail"
package "sendmail-cf"
# Upload sendmail configuration files.
template "/etc/mail/local-host-names" do
source "mail/local-host-names.erb"
owner "root"
group "root"
end
template "/etc/mail/sendmail.mc" do
source "mail/sendmail.mc.erb"
owner "root"
group "root"
end
# Configure sendmail according to configuration files.
bash "regenerate sendmail.cf from sendmail.mc" do
code "/etc/mail/make"
user "root"
end
# Restart sendmail to apply changes in configuration.
bash "restart sendmail service" do
code "/etc/init.d/sendmail reload"
user "root"
end
| s2t2/trailmix-solo | site-cookbooks/trailmix/recipes/mail.rb | Ruby | mit | 700 |
package main.java.util;
/**
*
* @author mancim
*/
public class Sorter implements SortUtil,AscSortUtil{
}
| stoiandan/msg-code | Marius/Day6/src/main/java/util/Sorter.java | Java | mit | 118 |
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("03Megapixels")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03Megapixels")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("482789e3-146d-429e-b686-dc45003a8a9d")]
// 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")]
| Avarea/Programming-Fundamentals | IntroAndSyntax/03Megapixels/Properties/AssemblyInfo.cs | C# | mit | 1,395 |
# frozen_string_literal: true
class FixSangerSequencingSubmissionCascadesForOracle < ActiveRecord::Migration[4.2]
def change
# Oracle does not support on_update so we need to remove and re-add it to keep
# consistent with the MySQL installations
remove_foreign_key :sanger_sequencing_samples, column: :submission_id
add_foreign_key :sanger_sequencing_samples, :sanger_sequencing_submissions, column: :submission_id, on_delete: :cascade
end
end
| tablexi/nucore-open | vendor/engines/sanger_sequencing/db/migrate/20160802202924_fix_sanger_sequencing_submission_cascades_for_oracle.rb | Ruby | mit | 467 |
var express = require('express');
var scraptcha = require('scraptcha');
// Scraptcha images source information.
var imageInformation = {path: __dirname + "/images/green/",
filePrefix: "i_cha_",
fileExtension: ".gif"};
// Initialize the Scraptcha data.
scraptcha.initialize(imageInformation);
// Static file server.
var server = new express();
server.use(express.static(__dirname));
server.listen(8800);
console.log("Server is listening on http://localhost:8800");
// Gets the scratcha code sequence. "id" compensates for a browser update bug.
server.get('/scraptcha/:id', function (req, res) {
res.send(scraptcha.getHTMLSnippet());
});
// Returns validation response.
server.get('/scraptchaValidate/:data', function (req, res) {
res.send(scraptcha.verify(req));
}); | deckerld/scraptcha | test/file-server.js | JavaScript | mit | 847 |
package observerSampleJavaAPI;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
NameArrayObservable na = new NameArrayObservable();
NameArrayObserver nav = new NameArrayObserver();
na.addObserver(nav);
Scanner sc = new Scanner(System.in);
System.out.print("Index (0-9): ");
int index = sc.nextInt();
System.out.print("Name: ");
String name = sc.next();
na.setName(name, index);
}
}
| dmpe/Semester2and5-Examples | src-semester2/observerSampleJavaAPI/Main.java | Java | mit | 467 |
package securbank.authentication;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import securbank.services.AuthenticationService;
@Component
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Autowired
private AuthenticationService authService;
@Override
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
// Get the role of logged in user
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String role = auth.getAuthorities().toString();
if(role==null){
return "/";
}
return authService.getRedirectUrlFromRole(role);
}
}
| Nikh13/securbank | src/main/java/securbank/authentication/CustomAuthenticationSuccessHandler.java | Java | mit | 1,123 |
from ..osid import records as osid_records
class HierarchyRecord(osid_records.OsidRecord):
"""A record for a ``Hierarchy``.
The methods specified by the record type are available through the
underlying object.
"""
class HierarchyQueryRecord(osid_records.OsidRecord):
"""A record for a ``HierarchyQuery``.
The methods specified by the record type are available through the
underlying object.
"""
class HierarchyFormRecord(osid_records.OsidRecord):
"""A record for a ``HierarchyForm``.
The methods specified by the record type are available through the
underlying object.
"""
class HierarchySearchRecord(osid_records.OsidRecord):
"""A record for a ``HierarchySearch``.
The methods specified by the record type are available through the
underlying object.
"""
| birdland/dlkit-doc | dlkit/hierarchy/records.py | Python | mit | 848 |
/**
* @ignore
* Add indent and outdent command identifier for KISSY Editor.
* @author yiminghe@gmail.com
*/
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
KISSY.add(function (S, require) {
var Editor = require('editor');
var ListUtils = require('./list-utils');
var listNodeNames = {ol: 1, ul: 1},
Walker = Editor.Walker,
Dom = S.DOM,
Node = S.Node,
UA = S.UA,
isNotWhitespaces = Walker.whitespaces(true),
INDENT_CSS_PROPERTY = 'margin-left',
INDENT_OFFSET = 40,
INDENT_UNIT = 'px',
isNotBookmark = Walker.bookmark(false, true);
function isListItem(node) {
return node.nodeType === Dom.NodeType.ELEMENT_NODE && Dom.nodeName(node) === 'li';
}
function indentList(range, listNode, type) {
// Our starting and ending points of the range might be inside some blocks under a list item...
// So before playing with the iterator, we need to expand the block to include the list items.
var startContainer = range.startContainer,
endContainer = range.endContainer;
while (startContainer && !startContainer.parent().equals(listNode)) {
startContainer = startContainer.parent();
}
while (endContainer && !endContainer.parent().equals(listNode)) {
endContainer = endContainer.parent();
}
if (!startContainer || !endContainer) {
return;
}
// Now we can iterate over the individual items on the same tree depth.
var block = startContainer,
itemsToMove = [],
stopFlag = false;
while (!stopFlag) {
if (block.equals(endContainer)) {
stopFlag = true;
}
itemsToMove.push(block);
block = block.next();
}
if (itemsToMove.length < 1) {
return;
}
// Do indent or outdent operations on the array model of the list, not the
// list's Dom tree itself. The array model demands that it knows as much as
// possible about the surrounding lists, we need to feed it the further
// ancestor node that is still a list.
var listParents = listNode._4eParents(true, undefined);
listParents.each(function (n, i) {
listParents[i] = n;
});
for (var i = 0; i < listParents.length; i++) {
if (listNodeNames[ listParents[i].nodeName() ]) {
listNode = listParents[i];
break;
}
}
var indentOffset = type === 'indent' ? 1 : -1,
startItem = itemsToMove[0],
lastItem = itemsToMove[ itemsToMove.length - 1 ],
database = {};
// Convert the list Dom tree into a one dimensional array.
var listArray = ListUtils.listToArray(listNode, database);
// Apply indenting or outdenting on the array.
// listarray_index 为 item 在数组中的下标,方便计算
var baseIndent = listArray[ lastItem.data('listarray_index') ].indent;
for (i = startItem.data('listarray_index');
i <= lastItem.data('listarray_index'); i++) {
listArray[ i ].indent += indentOffset;
// Make sure the newly created sublist get a brand-new element of the same type. (#5372)
var listRoot = listArray[ i ].parent;
listArray[ i ].parent =
new Node(listRoot[0].ownerDocument.createElement(listRoot.nodeName()));
}
/*
嵌到下层的li
<li>鼠标所在开始</li>
<li>ss鼠标所在结束ss
<ul>
<li></li>
<li></li>
</ul>
</li>
baseIndent 为鼠标所在结束的嵌套层次,
如果下面的比结束li的indent大,那么证明是嵌在结束li里面的,也要缩进
一直处理到大于或等于,跳出了当前嵌套
*/
for (i = lastItem.data('listarray_index') + 1;
i < listArray.length && listArray[i].indent > baseIndent; i++) {
listArray[i].indent += indentOffset;
}
// Convert the array back to a Dom forest (yes we might have a few subtrees now).
// And replace the old list with the new forest.
var newList = ListUtils.arrayToList(listArray, database, null, 'p');
// Avoid nested <li> after outdent even they're visually same,
// recording them for later refactoring.(#3982)
var pendingList = [];
var parentLiElement;
if (type === 'outdent') {
if (( parentLiElement = listNode.parent() ) &&
parentLiElement.nodeName() === 'li') {
var children = newList.listNode.childNodes, count = children.length,
child;
for (i = count - 1; i >= 0; i--) {
if (( child = new Node(children[i]) ) &&
child.nodeName() === 'li') {
pendingList.push(child);
}
}
}
}
if (newList) {
Dom.insertBefore(newList.listNode[0] || newList.listNode,
listNode[0] || listNode);
listNode.remove();
}
// Move the nested <li> to be appeared after the parent.
if (pendingList && pendingList.length) {
for (i = 0; i < pendingList.length; i++) {
var li = pendingList[ i ],
followingList = li;
// Nest preceding <ul>/<ol> inside current <li> if any.
while (( followingList = followingList.next() ) &&
followingList.nodeName() in listNodeNames) {
// IE requires a filler NBSP for nested list inside empty list item,
// otherwise the list item will be inaccessiable. (#4476)
/*jshint loopfunc:true*/
if (UA.ie && !li.first(function (node) {
return isNotWhitespaces(node) && isNotBookmark(node);
}, 1)) {
li[0].appendChild(range.document.createTextNode('\u00a0'));
}
li[0].appendChild(followingList[0]);
}
Dom.insertAfter(li[0], parentLiElement[0]);
}
}
// Clean up the markers.
Editor.Utils.clearAllMarkers(database);
}
function indentBlock(range, type) {
var iterator = range.createIterator(),
block;
// enterMode = 'p';
iterator.enforceRealBlocks = true;
iterator.enlargeBr = true;
while ((block = iterator.getNextParagraph())) {
indentElement(block, type);
}
}
function indentElement(element, type) {
var currentOffset = parseInt(element.style(INDENT_CSS_PROPERTY), 10);
if (isNaN(currentOffset)) {
currentOffset = 0;
}
currentOffset += ( type === 'indent' ? 1 : -1 ) * INDENT_OFFSET;
if (currentOffset < 0) {
return false;
}
currentOffset = Math.max(currentOffset, 0);
currentOffset = Math.ceil(currentOffset / INDENT_OFFSET) * INDENT_OFFSET;
element.css(INDENT_CSS_PROPERTY, currentOffset ? currentOffset + INDENT_UNIT : '');
if (element[0].style.cssText === '') {
element.removeAttr('style');
}
return true;
}
function indentEditor(editor, type) {
var selection = editor.getSelection(),
range = selection && selection.getRanges()[0];
if (!range) {
return;
}
var startContainer = range.startContainer,
endContainer = range.endContainer,
rangeRoot = range.getCommonAncestor(),
nearestListBlock = rangeRoot;
while (nearestListBlock && !( nearestListBlock[0].nodeType === Dom.NodeType.ELEMENT_NODE &&
listNodeNames[ nearestListBlock.nodeName() ] )) {
nearestListBlock = nearestListBlock.parent();
}
var walker;
// Avoid selection anchors under list root.
// <ul>[<li>...</li>]</ul> => <ul><li>[...]</li></ul>
//注:firefox 永远不会出现
//注2:哪种情况会出现?
if (nearestListBlock && startContainer[0].nodeType === Dom.NodeType.ELEMENT_NODE &&
startContainer.nodeName() in listNodeNames) {
walker = new Walker(range);
walker.evaluator = isListItem;
range.startContainer = walker.next();
}
if (nearestListBlock && endContainer[0].nodeType === Dom.NodeType.ELEMENT_NODE &&
endContainer.nodeName() in listNodeNames) {
walker = new Walker(range);
walker.evaluator = isListItem;
range.endContainer = walker.previous();
}
var bookmarks = selection.createBookmarks(true);
if (nearestListBlock) {
var firstListItem = nearestListBlock.first();
while (firstListItem && firstListItem.nodeName() !== 'li') {
firstListItem = firstListItem.next();
}
var rangeStart = range.startContainer,
indentWholeList = firstListItem[0] === rangeStart[0] || firstListItem.contains(rangeStart);
// Indent the entire list if cursor is inside the first list item. (#3893)
if (!( indentWholeList &&
indentElement(nearestListBlock, type) )) {
indentList(range, nearestListBlock, type);
}
}
else {
indentBlock(range, type);
}
selection.selectBookmarks(bookmarks);
}
function addCommand(editor, cmdType) {
if (!editor.hasCommand(cmdType)) {
editor.addCommand(cmdType, {
exec: function (editor) {
editor.execCommand('save');
indentEditor(editor, cmdType);
editor.execCommand('save');
editor.notifySelectionChange();
}
});
}
}
return {
checkOutdentActive: function (elementPath) {
var blockLimit = elementPath.blockLimit;
if (elementPath.contains(listNodeNames)) {
return true;
} else {
var block = elementPath.block || blockLimit;
return block && block.style(INDENT_CSS_PROPERTY);
}
},
addCommand: addCommand
};
}); | tedyhy/SCI | kissy-1.4.9/src/editor/sub-modules/plugin/dent-cmd/src/dent-cmd.js | JavaScript | mit | 10,700 |
package main
import (
"database/sql"
"fmt"
"github.com/jrallison/go-workers"
"github.com/lib/pq"
"log"
"time"
)
func WorkerExtractPgerror(err error) (*string, error) {
pgerr, ok := err.(pq.PGError)
if ok {
msg := pgerr.Get('M')
return &msg, nil
}
if err.Error() == "driver: bad connection" {
msg := "could not connect to database"
return &msg, nil
}
return nil, err
}
// WorkerCoerceType returns a coerced version of the raw
// database value in, which we get from scanning into
// interface{}s. We expect queries from the following
// Postgres types to result in the following return values:
// [Postgres] -> [Go: in] -> [Go: WorkerCoerceType'd]
// text []byte string
// ???
func WorkerCoerceType(in interface{}) interface{} {
switch in := in.(type) {
case []byte:
return string(in)
default:
return in
}
}
// WorkerQuery queries the pin db at pinDbUrl and updates the
// passed pin according to the results/errors. System errors
// are returned.
func WorkerQuery(p *Pin, pinDbUrl string) error {
log.Printf("worker.query.start pin_id=%s", p.Id)
applicationName := fmt.Sprintf("pgpin.pin.%s", p.Id)
pinDbConn := fmt.Sprintf("%s?application_name=%s&statement_timeout=%d&connect_timeout=%d",
pinDbUrl, applicationName, ConfigPinStatementTimeout/time.Millisecond, ConfigDatabaseConnectTimeout/time.Millisecond)
pinDb, err := sql.Open("postgres", pinDbConn)
if err != nil {
p.ResultsError, err = WorkerExtractPgerror(err)
return err
}
resultsRows, err := pinDb.Query(p.Query)
if err != nil {
p.ResultsError, err = WorkerExtractPgerror(err)
return err
}
defer func() { Must(resultsRows.Close()) }()
resultsFieldsData, err := resultsRows.Columns()
if err != nil {
p.ResultsError, err = WorkerExtractPgerror(err)
return err
}
resultsRowsData := make([][]interface{}, 0)
resultsRowsSeen := 0
for resultsRows.Next() {
resultsRowsSeen += 1
if resultsRowsSeen > ConfigPinResultsRowsMax {
message := "too many rows in query results"
p.ResultsError = &message
return nil
}
resultsRowData := make([]interface{}, len(resultsFieldsData))
resultsRowPointers := make([]interface{}, len(resultsFieldsData))
for i, _ := range resultsRowData {
resultsRowPointers[i] = &resultsRowData[i]
}
err := resultsRows.Scan(resultsRowPointers...)
if err != nil {
p.ResultsError, err = WorkerExtractPgerror(err)
return err
}
for i, _ := range resultsRowData {
resultsRowData[i] = WorkerCoerceType(resultsRowData[i])
}
resultsRowsData = append(resultsRowsData, resultsRowData)
}
err = resultsRows.Err()
if err != nil {
p.ResultsError, err = WorkerExtractPgerror(err)
return err
}
p.ResultsFields = MustNewPgJson(resultsFieldsData)
p.ResultsRows = MustNewPgJson(resultsRowsData)
log.Printf("worker.query.finish pin_id=%s", p.Id)
return nil
}
func WorkerProcess(jobId string, pinId string) error {
log.Printf("worker.job.start job_id=%s pin_id=%s", jobId, pinId)
pin, err := PinGet(pinId)
if err != nil {
return err
}
pinDbUrl, err := PinDbUrl(pin)
if err != nil {
return err
}
startedAt := time.Now()
pin.QueryStartedAt = &startedAt
err = WorkerQuery(pin, pinDbUrl)
if err != nil {
return err
}
finishedAt := time.Now()
pin.QueryFinishedAt = &finishedAt
err = PinUpdate(pin)
if err != nil {
return err
}
log.Printf("worker.job.finish job_id=%s pin_id=%s", jobId, pinId)
return nil
}
func WorkerProcessWrapper(msg *workers.Msg) {
jobId := msg.Jid()
pinId, err := msg.Args().String()
Must(err)
err = WorkerProcess(jobId, pinId)
if err != nil {
log.Printf("worker.job.error job_id=%s pin_id=%s %s", jobId, pinId, err)
}
}
func WorkerStart() {
log.Printf("worker.start")
PgStart()
RedisStart()
workers.Process("pins", WorkerProcessWrapper, ConfigWorkerPoolSize)
workers.Run()
}
| mmcgrana/pgpin | worker.go | GO | mit | 3,817 |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculus.com/licenses/LICENSE-3.3
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#if !UNITY_5 || UNITY_5_0
#error Oculus Utilities require Unity 5.1 or higher.
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
using VR = UnityEngine.VR;
/// <summary>
/// Configuration data for Oculus virtual reality.
/// </summary>
public class OVRManager : MonoBehaviour
{
public enum TrackingOrigin
{
EyeLevel = OVRPlugin.TrackingOrigin.EyeLevel,
FloorLevel = OVRPlugin.TrackingOrigin.FloorLevel,
}
/// <summary>
/// Gets the singleton instance.
/// </summary>
public static OVRManager instance { get; private set; }
/// <summary>
/// Gets a reference to the active display.
/// </summary>
public static OVRDisplay display { get; private set; }
/// <summary>
/// Gets a reference to the active sensor.
/// </summary>
public static OVRTracker tracker { get; private set; }
private static bool _profileIsCached = false;
private static OVRProfile _profile;
/// <summary>
/// Gets the current profile, which contains information about the user's settings and body dimensions.
/// </summary>
public static OVRProfile profile
{
get {
if (!_profileIsCached)
{
_profile = new OVRProfile();
_profile.TriggerLoad();
while (_profile.state == OVRProfile.State.LOADING)
System.Threading.Thread.Sleep(1);
if (_profile.state != OVRProfile.State.READY)
Debug.LogWarning("Failed to load profile.");
_profileIsCached = true;
}
return _profile;
}
}
private bool _isPaused;
private IEnumerable<Camera> disabledCameras;
float prevTimeScale;
private bool paused
{
get { return _isPaused; }
set {
if (value == _isPaused)
return;
// Sample code to handle VR Focus
// if (value)
// {
// prevTimeScale = Time.timeScale;
// Time.timeScale = 0.01f;
// disabledCameras = GameObject.FindObjectsOfType<Camera>().Where(c => c.isActiveAndEnabled);
// foreach (var cam in disabledCameras)
// cam.enabled = false;
// }
// else
// {
// Time.timeScale = prevTimeScale;
// if (disabledCameras != null) {
// foreach (var cam in disabledCameras)
// cam.enabled = true;
// }
// disabledCameras = null;
// }
_isPaused = value;
}
}
/// <summary>
/// Occurs when an HMD attached.
/// </summary>
public static event Action HMDAcquired;
/// <summary>
/// Occurs when an HMD detached.
/// </summary>
public static event Action HMDLost;
/// <summary>
/// Occurs when an HMD is put on the user's head.
/// </summary>
public static event Action HMDMounted;
/// <summary>
/// Occurs when an HMD is taken off the user's head.
/// </summary>
public static event Action HMDUnmounted;
/// <summary>
/// Occurs when VR Focus is acquired.
/// </summary>
public static event Action VrFocusAcquired;
/// <summary>
/// Occurs when VR Focus is lost.
/// </summary>
public static event Action VrFocusLost;
/// <summary>
/// Occurs when the active Audio Out device has changed and a restart is needed.
/// </summary>
public static event Action AudioOutChanged;
/// <summary>
/// Occurs when the active Audio In device has changed and a restart is needed.
/// </summary>
public static event Action AudioInChanged;
/// <summary>
/// Occurs when the sensor gained tracking.
/// </summary>
public static event Action TrackingAcquired;
/// <summary>
/// Occurs when the sensor lost tracking.
/// </summary>
public static event Action TrackingLost;
/// <summary>
/// Occurs when HSW dismissed.
/// </summary>
public static event Action HSWDismissed;
private static bool _isHmdPresentCached = false;
private static bool _isHmdPresent = false;
private static bool _wasHmdPresent = false;
/// <summary>
/// If true, a head-mounted display is connected and present.
/// </summary>
public static bool isHmdPresent
{
get {
if (!_isHmdPresentCached)
{
_isHmdPresentCached = true;
_isHmdPresent = OVRPlugin.hmdPresent;
}
return _isHmdPresent;
}
private set {
_isHmdPresentCached = true;
_isHmdPresent = value;
}
}
/// <summary>
/// Gets the audio output device identifier.
/// </summary>
/// <description>
/// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use.
/// </description>
public static string audioOutId
{
get { return OVRPlugin.audioOutId; }
}
/// <summary>
/// Gets the audio input device identifier.
/// </summary>
/// <description>
/// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use.
/// </description>
public static string audioInId
{
get { return OVRPlugin.audioInId; }
}
private static bool _hasVrFocusCached = false;
private static bool _hasVrFocus = false;
private static bool _hadVrFocus = false;
/// <summary>
/// If true, the app has VR Focus.
/// </summary>
public static bool hasVrFocus
{
get {
if (!_hasVrFocusCached)
{
_hasVrFocusCached = true;
_hasVrFocus = OVRPlugin.hasVrFocus;
}
return _hasVrFocus;
}
private set {
_hasVrFocusCached = true;
_hasVrFocus = value;
}
}
private static bool _isHSWDisplayedCached = false;
private static bool _isHSWDisplayed = false;
private static bool _wasHSWDisplayed;
/// <summary>
/// If true, then the Oculus health and safety warning (HSW) is currently visible.
/// </summary>
public static bool isHSWDisplayed
{
get {
if (!isHmdPresent)
return false;
if (!_isHSWDisplayedCached)
{
_isHSWDisplayedCached = true;
_isHSWDisplayed = OVRPlugin.hswVisible;
}
return _isHSWDisplayed;
}
private set {
_isHSWDisplayedCached = true;
_isHSWDisplayed = value;
}
}
/// <summary>
/// If the HSW has been visible for the necessary amount of time, this will make it disappear.
/// </summary>
public static void DismissHSWDisplay()
{
if (!isHmdPresent)
return;
OVRPlugin.DismissHSW();
}
/// <summary>
/// If true, chromatic de-aberration will be applied, improving the image at the cost of texture bandwidth.
/// </summary>
public bool chromatic
{
get {
if (!isHmdPresent)
return false;
return OVRPlugin.chromatic;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.chromatic = value;
}
}
/// <summary>
/// If true, both eyes will see the same image, rendered from the center eye pose, saving performance.
/// </summary>
public bool monoscopic
{
get {
if (!isHmdPresent)
return true;
return OVRPlugin.monoscopic;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.monoscopic = value;
}
}
/// <summary>
/// If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism.
/// </summary>
public bool queueAhead = true;
/// <summary>
/// If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware.
/// </summary>
public bool useRecommendedMSAALevel = true;
/// <summary>
/// If true, dynamic resolution will be enabled
/// </summary>
public bool enableAdaptiveResolution = false;
/// <summary>
/// Max RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = ture );
/// </summary>
[RangeAttribute(0.5f, 2.0f)]
public float maxRenderScale = 1.0f;
/// <summary>
/// Min RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = ture );
/// </summary>
[RangeAttribute(0.5f, 2.0f)]
public float minRenderScale = 0.7f;
/// <summary>
/// The number of expected display frames per rendered frame.
/// </summary>
public int vsyncCount
{
get {
if (!isHmdPresent)
return 1;
return OVRPlugin.vsyncCount;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.vsyncCount = value;
}
}
/// <summary>
/// Gets the current battery level.
/// </summary>
/// <returns><c>battery level in the range [0.0,1.0]</c>
/// <param name="batteryLevel">Battery level.</param>
public static float batteryLevel
{
get {
if (!isHmdPresent)
return 1f;
return OVRPlugin.batteryLevel;
}
}
/// <summary>
/// Gets the current battery temperature.
/// </summary>
/// <returns><c>battery temperature in Celsius</c>
/// <param name="batteryTemperature">Battery temperature.</param>
public static float batteryTemperature
{
get {
if (!isHmdPresent)
return 0f;
return OVRPlugin.batteryTemperature;
}
}
/// <summary>
/// Gets the current battery status.
/// </summary>
/// <returns><c>battery status</c>
/// <param name="batteryStatus">Battery status.</param>
public static int batteryStatus
{
get {
if (!isHmdPresent)
return -1;
return (int)OVRPlugin.batteryStatus;
}
}
/// <summary>
/// Gets the current volume level.
/// </summary>
/// <returns><c>volume level in the range [0,1].</c>
public static float volumeLevel
{
get {
if (!isHmdPresent)
return 0f;
return OVRPlugin.systemVolume;
}
}
/// <summary>
/// Gets or sets the current CPU performance level (0-2). Lower performance levels save more power.
/// </summary>
public static int cpuLevel
{
get {
if (!isHmdPresent)
return 2;
return OVRPlugin.cpuLevel;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.cpuLevel = value;
}
}
/// <summary>
/// Gets or sets the current GPU performance level (0-2). Lower performance levels save more power.
/// </summary>
public static int gpuLevel
{
get {
if (!isHmdPresent)
return 2;
return OVRPlugin.gpuLevel;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.gpuLevel = value;
}
}
/// <summary>
/// If true, the CPU and GPU are currently throttled to save power and/or reduce the temperature.
/// </summary>
public static bool isPowerSavingActive
{
get {
if (!isHmdPresent)
return false;
return OVRPlugin.powerSaving;
}
}
[SerializeField]
private OVRManager.TrackingOrigin _trackingOriginType = OVRManager.TrackingOrigin.EyeLevel;
/// <summary>
/// Defines the current tracking origin type.
/// </summary>
public OVRManager.TrackingOrigin trackingOriginType
{
get {
if (!isHmdPresent)
return _trackingOriginType;
return (OVRManager.TrackingOrigin)OVRPlugin.GetTrackingOriginType();
}
set {
if (!isHmdPresent)
return;
if (OVRPlugin.SetTrackingOriginType((OVRPlugin.TrackingOrigin)value))
{
// Keep the field exposed in the Unity Editor synchronized with any changes.
_trackingOriginType = value;
}
}
}
/// <summary>
/// If true, head tracking will affect the position of each OVRCameraRig's cameras.
/// </summary>
public bool usePositionTracking = true;
/// <summary>
/// If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras.
/// </summary>
public bool useIPDInPositionTracking = true;
/// <summary>
/// If true, each scene load will cause the head pose to reset.
/// </summary>
public bool resetTrackerOnLoad = false;
/// <summary>
/// True if the current platform supports virtual reality.
/// </summary>
public bool isSupportedPlatform { get; private set; }
private static bool _isUserPresentCached = false;
private static bool _isUserPresent = false;
private static bool _wasUserPresent = false;
/// <summary>
/// True if the user is currently wearing the display.
/// </summary>
public bool isUserPresent
{
get {
if (!_isUserPresentCached)
{
_isUserPresentCached = true;
_isUserPresent = OVRPlugin.userPresent;
}
return _isUserPresent;
}
private set {
_isUserPresentCached = true;
_isUserPresent = value;
}
}
private static bool prevAudioOutIdIsCached = false;
private static bool prevAudioInIdIsCached = false;
private static string prevAudioOutId = string.Empty;
private static string prevAudioInId = string.Empty;
private static bool wasPositionTracked = false;
[SerializeField]
[HideInInspector]
internal static bool runInBackground = false;
#region Unity Messages
private void Awake()
{
// Only allow one instance at runtime.
if (instance != null)
{
enabled = false;
DestroyImmediate(this);
return;
}
instance = this;
Debug.Log("Unity v" + Application.unityVersion + ", " +
"Oculus Utilities v" + OVRPlugin.wrapperVersion + ", " +
"OVRPlugin v" + OVRPlugin.version + ", " +
"SDK v" + OVRPlugin.nativeSDKVersion + ".");
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if (SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
Debug.LogWarning("VR rendering requires Direct3D11. Your graphics device: " + SystemInfo.graphicsDeviceType);
#endif
// Detect whether this platform is a supported platform
RuntimePlatform currPlatform = Application.platform;
isSupportedPlatform |= currPlatform == RuntimePlatform.Android;
//isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer;
isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor;
isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer;
isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor;
isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer;
if (!isSupportedPlatform)
{
Debug.LogWarning("This platform is unsupported");
return;
}
#if UNITY_ANDROID && !UNITY_EDITOR
// We want to set up our touchpad messaging system
OVRTouchpad.Create();
// Turn off chromatic aberration by default to save texture bandwidth.
chromatic = false;
#endif
if (display == null)
display = new OVRDisplay();
if (tracker == null)
tracker = new OVRTracker();
if (resetTrackerOnLoad)
display.RecenterPose();
// Disable the occlusion mesh by default until open issues with the preview window are resolved.
OVRPlugin.occlusionMesh = false;
OVRPlugin.ignoreVrFocus = runInBackground;
}
private void Update()
{
#if !UNITY_EDITOR
paused = !OVRPlugin.hasVrFocus;
#endif
if (OVRPlugin.shouldQuit)
Application.Quit();
if (OVRPlugin.shouldRecenter)
OVRManager.display.RecenterPose();
if (trackingOriginType != _trackingOriginType)
trackingOriginType = _trackingOriginType;
tracker.isEnabled = usePositionTracking;
OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking;
// Dispatch HMD events.
isHmdPresent = OVRPlugin.hmdPresent;
if (isHmdPresent)
{
OVRPlugin.queueAheadFraction = (queueAhead) ? 0.25f : 0f;
}
if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel)
{
QualitySettings.antiAliasing = display.recommendedMSAALevel;
Debug.Log ("MSAA level: " + QualitySettings.antiAliasing);
}
if (_wasHmdPresent && !isHmdPresent)
{
try
{
if (HMDLost != null)
HMDLost();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!_wasHmdPresent && isHmdPresent)
{
try
{
if (HMDAcquired != null)
HMDAcquired();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
_wasHmdPresent = isHmdPresent;
// Dispatch HMD mounted events.
isUserPresent = OVRPlugin.userPresent;
if (_wasUserPresent && !isUserPresent)
{
try
{
if (HMDUnmounted != null)
HMDUnmounted();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!_wasUserPresent && isUserPresent)
{
try
{
if (HMDMounted != null)
HMDMounted();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
_wasUserPresent = isUserPresent;
// Dispatch VR Focus events.
hasVrFocus = OVRPlugin.hasVrFocus;
if (_hadVrFocus && !hasVrFocus)
{
try
{
if (VrFocusLost != null)
VrFocusLost();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!_hadVrFocus && hasVrFocus)
{
try
{
if (VrFocusAcquired != null)
VrFocusAcquired();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
_hadVrFocus = hasVrFocus;
// Changing effective rendering resolution dynamically according performance
#if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) && UNITY_5 && !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3)
if (enableAdaptiveResolution)
{
if (VR.VRSettings.renderScale < maxRenderScale)
{
// Allocate renderScale to max to avoid re-allocation
VR.VRSettings.renderScale = maxRenderScale;
}
else
{
// Adjusting maxRenderScale in case app started with a larger renderScale value
maxRenderScale = Mathf.Max(maxRenderScale, VR.VRSettings.renderScale);
}
float minViewportScale = minRenderScale / VR.VRSettings.renderScale;
float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / VR.VRSettings.renderScale;
recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f);
VR.VRSettings.renderViewportScale = recommendedViewportScale;
}
#endif
// Dispatch Audio Device events.
string audioOutId = OVRPlugin.audioOutId;
if (!prevAudioOutIdIsCached)
{
prevAudioOutId = audioOutId;
prevAudioOutIdIsCached = true;
}
else if (audioOutId != prevAudioOutId)
{
try
{
if (AudioOutChanged != null)
AudioOutChanged();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
prevAudioOutId = audioOutId;
}
string audioInId = OVRPlugin.audioInId;
if (!prevAudioInIdIsCached)
{
prevAudioInId = audioInId;
prevAudioInIdIsCached = true;
}
else if (audioInId != prevAudioInId)
{
try
{
if (AudioInChanged != null)
AudioInChanged();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
prevAudioInId = audioInId;
}
// Dispatch tracking events.
if (wasPositionTracked && !tracker.isPositionTracked)
{
try
{
if (TrackingLost != null)
TrackingLost();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!wasPositionTracked && tracker.isPositionTracked)
{
try
{
if (TrackingAcquired != null)
TrackingAcquired();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
wasPositionTracked = tracker.isPositionTracked;
// Dispatch HSW events.
isHSWDisplayed = OVRPlugin.hswVisible;
if (isHSWDisplayed && Input.anyKeyDown)
DismissHSWDisplay();
if (!isHSWDisplayed && _wasHSWDisplayed)
{
try
{
if (HSWDismissed != null)
HSWDismissed();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
_wasHSWDisplayed = isHSWDisplayed;
display.Update();
OVRInput.Update();
}
private void LateUpdate()
{
OVRHaptics.Process();
}
/// <summary>
/// Leaves the application/game and returns to the launcher/dashboard
/// </summary>
public void ReturnToLauncher()
{
// show the platform UI quit prompt
OVRManager.PlatformUIConfirmQuit();
}
#endregion
public static void PlatformUIConfirmQuit()
{
if (!isHmdPresent)
return;
OVRPlugin.ShowUI(OVRPlugin.PlatformUI.ConfirmQuit);
}
public static void PlatformUIGlobalMenu()
{
if (!isHmdPresent)
return;
OVRPlugin.ShowUI(OVRPlugin.PlatformUI.GlobalMenu);
}
}
| michel-zimmer/smartpad-hoverboard | Assets/OVR/Scripts/OVRManager.cs | C# | mit | 20,634 |
"""
homeassistant.components.device_tracker.tplink
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a TP-Link router for device
presence.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.tplink.html
"""
import base64
import logging
from datetime import timedelta
import re
import threading
import requests
from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD
from homeassistant.helpers import validate_config
from homeassistant.util import Throttle
from homeassistant.components.device_tracker import DOMAIN
# Return cached results if last scan was less then this time ago
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
def get_scanner(hass, config):
""" Validates config and returns a TP-Link scanner. """
if not validate_config(config,
{DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
_LOGGER):
return None
scanner = Tplink3DeviceScanner(config[DOMAIN])
if not scanner.success_init:
scanner = Tplink2DeviceScanner(config[DOMAIN])
if not scanner.success_init:
scanner = TplinkDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None
class TplinkDeviceScanner(object):
"""
This class queries a wireless router running TP-Link firmware
for connected devices.
"""
def __init__(self, config):
host = config[CONF_HOST]
username, password = config[CONF_USERNAME], config[CONF_PASSWORD]
self.parse_macs = re.compile('[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-' +
'[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}')
self.host = host
self.username = username
self.password = password
self.last_results = {}
self.lock = threading.Lock()
self.success_init = self._update_info()
def scan_devices(self):
"""
Scans for new devices and return a list containing found device ids.
"""
self._update_info()
return self.last_results
# pylint: disable=no-self-use
def get_device_name(self, device):
"""
The TP-Link firmware doesn't save the name of the wireless device.
"""
return None
@Throttle(MIN_TIME_BETWEEN_SCANS)
def _update_info(self):
"""
Ensures the information from the TP-Link router is up to date.
Returns boolean if scanning successful.
"""
with self.lock:
_LOGGER.info("Loading wireless clients...")
url = 'http://{}/userRpm/WlanStationRpm.htm'.format(self.host)
referer = 'http://{}'.format(self.host)
page = requests.get(url, auth=(self.username, self.password),
headers={'referer': referer})
result = self.parse_macs.findall(page.text)
if result:
self.last_results = [mac.replace("-", ":") for mac in result]
return True
return False
class Tplink2DeviceScanner(TplinkDeviceScanner):
"""
This class queries a wireless router running newer version of TP-Link
firmware for connected devices.
"""
def scan_devices(self):
"""
Scans for new devices and return a list containing found device ids.
"""
self._update_info()
return self.last_results.keys()
# pylint: disable=no-self-use
def get_device_name(self, device):
"""
The TP-Link firmware doesn't save the name of the wireless device.
"""
return self.last_results.get(device)
@Throttle(MIN_TIME_BETWEEN_SCANS)
def _update_info(self):
"""
Ensures the information from the TP-Link router is up to date.
Returns boolean if scanning successful.
"""
with self.lock:
_LOGGER.info("Loading wireless clients...")
url = 'http://{}/data/map_access_wireless_client_grid.json' \
.format(self.host)
referer = 'http://{}'.format(self.host)
# Router uses Authorization cookie instead of header
# Let's create the cookie
username_password = '{}:{}'.format(self.username, self.password)
b64_encoded_username_password = base64.b64encode(
username_password.encode('ascii')
).decode('ascii')
cookie = 'Authorization=Basic {}' \
.format(b64_encoded_username_password)
response = requests.post(url, headers={'referer': referer,
'cookie': cookie})
try:
result = response.json().get('data')
except ValueError:
_LOGGER.error("Router didn't respond with JSON. "
"Check if credentials are correct.")
return False
if result:
self.last_results = {
device['mac_addr'].replace('-', ':'): device['name']
for device in result
}
return True
return False
class Tplink3DeviceScanner(TplinkDeviceScanner):
"""
This class queries the Archer C9 router running version 150811 or higher
of TP-Link firmware for connected devices.
"""
def __init__(self, config):
self.stok = ''
self.sysauth = ''
super(Tplink3DeviceScanner, self).__init__(config)
def scan_devices(self):
"""
Scans for new devices and return a list containing found device ids.
"""
self._update_info()
return self.last_results.keys()
# pylint: disable=no-self-use
def get_device_name(self, device):
"""
The TP-Link firmware doesn't save the name of the wireless device.
We are forced to use the MAC address as name here.
"""
return self.last_results.get(device)
def _get_auth_tokens(self):
"""
Retrieves auth tokens from the router.
"""
_LOGGER.info("Retrieving auth tokens...")
url = 'http://{}/cgi-bin/luci/;stok=/login?form=login' \
.format(self.host)
referer = 'http://{}/webpages/login.html'.format(self.host)
# if possible implement rsa encryption of password here
response = requests.post(url,
params={'operation': 'login',
'username': self.username,
'password': self.password},
headers={'referer': referer})
try:
self.stok = response.json().get('data').get('stok')
_LOGGER.info(self.stok)
regex_result = re.search('sysauth=(.*);',
response.headers['set-cookie'])
self.sysauth = regex_result.group(1)
_LOGGER.info(self.sysauth)
return True
except ValueError:
_LOGGER.error("Couldn't fetch auth tokens!")
return False
@Throttle(MIN_TIME_BETWEEN_SCANS)
def _update_info(self):
"""
Ensures the information from the TP-Link router is up to date.
Returns boolean if scanning successful.
"""
with self.lock:
if (self.stok == '') or (self.sysauth == ''):
self._get_auth_tokens()
_LOGGER.info("Loading wireless clients...")
url = 'http://{}/cgi-bin/luci/;stok={}/admin/wireless?form=statistics' \
.format(self.host, self.stok)
referer = 'http://{}/webpages/index.html'.format(self.host)
response = requests.post(url,
params={'operation': 'load'},
headers={'referer': referer},
cookies={'sysauth': self.sysauth})
try:
json_response = response.json()
if json_response.get('success'):
result = response.json().get('data')
else:
if json_response.get('errorcode') == 'timeout':
_LOGGER.info("Token timed out. "
"Relogging on next scan.")
self.stok = ''
self.sysauth = ''
return False
else:
_LOGGER.error("An unknown error happened "
"while fetching data.")
return False
except ValueError:
_LOGGER.error("Router didn't respond with JSON. "
"Check if credentials are correct.")
return False
if result:
self.last_results = {
device['mac'].replace('-', ':'): device['mac']
for device in result
}
return True
return False
| pottzer/home-assistant | homeassistant/components/device_tracker/tplink.py | Python | mit | 9,226 |
require 'rails_helper'
feature 'User can visit the home page' do
scenario 'and see upcoming events on the home page' do
events = create_list(:event_with_registrations, 2)
visit root_path
expect(page).to have_content('Upcoming events')
expect(page).to have_content(events.first.title)
expect(page).to have_content(events.second.title)
end
scenario 'Can access sign in / sign up page' do
visit root_path
expect(page).to have_content('Sign in')
end
scenario 'can view sign in form' do
visit new_user_session_path
expect(page).to have_content('Enter your e-mail')
expect(page).to have_content('Login')
expect(page).to have_content('Sign up')
expect(page).to have_content('Forgot your password?')
expect(page).to have_content("Didn't receive confirmation instructions?")
end
scenario 'can view sign up form with all appropriate fields' do
visit new_user_registration_path
expect(page).to have_content('Sign up')
expect(find_by_id('user_name').native.attributes['placeholder'].value).to eq 'Enter name'
expect(find_by_id('user_gender').native.children[0].children.text).to eq 'Select gender'
expect(find_by_id('user_age').native.children[0].children.text).to eq 'Select your age'
expect(find_by_id('user_grade').native.children[0].children.text).to eq 'Select your grade'
expect(find_by_id('user_locality_id').native.children[0].children.text).to eq 'Select locality'
expect(find_by_id('user_email').native.attributes['placeholder'].value).to eq 'Enter email'
expect(find_by_id('user_password').native.attributes['placeholder'].value).to eq 'Enter password'
expect(find_by_id('user_password_confirmation').native.attributes['placeholder'].value).to eq 'Enter password confirmation'
end
end
| stephen144/ypreg | spec/features/user_visits_site_spec.rb | Ruby | mit | 1,800 |
// Modify the previous program to skip duplicates:
// n=4, k=2 → (1 2), (1 3), (1 4), (2 3), (2 4), (3 4)
namespace CombinationsWithouthDuplicates
{
using System;
public class CombinationsWithouthDuplicates
{
public static void Main()
{
Console.WriteLine("Enter n:");
int endNum = int.Parse(Console.ReadLine());
Console.WriteLine("Enter k:");
int k = int.Parse(Console.ReadLine());
int startNum = 1;
int index = 1;
int[] arr = new int[k];
GenerateCombinations(arr, index, startNum, endNum);
}
private static void GenerateCombinations(int[] arr, int index, int startNum, int endNum)
{
if (index >= arr.Length)
{
Console.WriteLine("({0})", string.Join(", ", arr));
}
else
{
for (int i = startNum; i <= endNum; i++)
{
arr[index] = i;
GenerateCombinations(arr, index + 1, i + 1, endNum);
}
}
}
}
} | marianamn/Telerik-Academy-Activities | Homeworks/15. DSA/02. Recursion/CombinationsWithouthDuplicates/CombinationsWithouthDuplicates.cs | C# | mit | 1,140 |
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class ResponseTimeMonitorData {
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "_class")]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Timestamp
/// </summary>
[DataMember(Name="timestamp", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "timestamp")]
public int? Timestamp { get; set; }
/// <summary>
/// Gets or Sets Average
/// </summary>
[DataMember(Name="average", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "average")]
public int? Average { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class ResponseTimeMonitorData {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Timestamp: ").Append(Timestamp).Append("\n");
sb.Append(" Average: ").Append(Average).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
}
}
| cliffano/swaggy-jenkins | clients/csharp-dotnet2/generated/src/main/CsharpDotNet2/Org/OpenAPITools/Model/ResponseTimeMonitorData.cs | C# | mit | 1,733 |
/**
* Copyright (c) LambdaCraft Modding Team, 2013
* 版权许可:LambdaCraft 制作小组, 2013.
* http://lambdacraft.half-life.cn/
*
* LambdaCraft is open-source. It is distributed under the terms of the
* LambdaCraft Open Source License. It grants rights to read, modify, compile
* or run the code. It does *NOT* grant the right to redistribute this software
* or its modifications in any form, binary or source, except if expressively
* granted by the copyright holder.
*
* LambdaCraft是完全开源的。它的发布遵从《LambdaCraft开源协议》你允许阅读,修改以及调试运行
* 源代码, 然而你不允许将源代码以另外任何的方式发布,除非你得到了版权所有者的许可。
*/
package cn.lambdacraft.crafting.block.generator;
import ic2.api.energy.tile.IEnergySource;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import cn.lambdacraft.core.block.TileElectrical;
/**
* @author WeAthFolD, Rikka
*
*/
public abstract class TileGeneratorBase extends TileElectrical implements IEnergySource {
public final int maxStorage, tier;
public int currentEnergy;
/**
* The generator production in this tick
*/
public int production;
public TileGeneratorBase(int tier, int store) {
this.maxStorage = store;
this.tier = tier;
}
@Override
public void updateEntity() {
super.updateEntity();
}
/**
* Reads a tile entity from NBT.
*/
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
this.currentEnergy = nbt.getInteger("energy");
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
nbt.setInteger("energy", currentEnergy);
}
@Override
public boolean emitsEnergyTo(TileEntity paramTileEntity, ForgeDirection paramDirection) {
return true;
}
}
| LambdaInnovation/LambdaCraft-Legacy | src/main/java/cn/lambdacraft/crafting/block/generator/TileGeneratorBase.java | Java | mit | 2,075 |
<?php
// NOTE for template develoepers: SQL and most other databases are either latin characters only, or Unicode for their
// identifiers, so you don't need to worry about encoding issues for identifiers.
?>
// this function is required for objects that implement the
// IteratorAggregate interface
public function getIterator()
{
$iArray = array();
<?php foreach ($objTable->ColumnArray as $objColumn) { ?>
if (isset($this->__blnValid[self::<?= strtoupper($objColumn->Name) ?>_FIELD])) {
$iArray['<?= $objColumn->PropertyName ?>'] = $this-><?= $objColumn->VariableName ?>;
}
<?php } ?>
return new ArrayIterator($iArray);
}
/**
* @deprecated. Just call json_encode on the object. See the jsonSerialize function for the result.
/*/
public function getJson()
{
return json_encode($this->getIterator());
}
/**
* Default "toJsObject" handler
* Specifies how the object should be displayed in JQuery UI lists and menus. Note that these lists use
* value and label differently.
*
* value = The short form of what to display in the list and selection.
* label = [optional] If defined, is what is displayed in the menu
* id = Primary key of object.
*
* @return string
*/
public function toJsObject ()
{
return JavaScriptHelper::toJsObject(array('value' => $this->__toString(), 'id' => <?php if ( count($objTable->PrimaryKeyColumnArray) == 1 ) { ?> $this-><?= $objTable->PrimaryKeyColumnArray[0]->VariableName ?> <?php } ?><?php if ( count($objTable->PrimaryKeyColumnArray) > 1 ) { ?> array(<?php foreach ($objTable->PrimaryKeyColumnArray as $objColumn) { ?> $this-><?= $objColumn->VariableName ?>, <?php } ?><?php GO_BACK(2); ?>) <?php } ?>));
}
/**
* Default "jsonSerialize" handler
* Specifies how the object should be serialized using json_encode.
* Control the values that are output by using QQ::Select to control which
* fields are valid, and QQ::Expand to control embedded objects.
* WARNING: If an object is found in short-term cache, it will be used instead of the queried object and may
* contain data fields that were fetched earlier. To really control what fields exist in this object, preceed
* any query calls (like Load or QueryArray), with a call to <?= $objTable->ClassName ?>::ClearCache()
*
* @return array An array that is json serializable
*/
public function jsonSerialize ()
{
$a = [];
<?php foreach ($objTable->ColumnArray as $objColumn) { ?>
<?php if (($objColumn->Reference) && (!$objColumn->Reference->IsType)) { ?>
if (isset($this-><?= $objColumn->Reference->VariableName ?>)) {
$a['<?= $objColumn->Reference->Name ?>'] = $this-><?= $objColumn->Reference->VariableName ?>;
} elseif (isset($this->__blnValid[self::<?= strtoupper($objColumn->Name) ?>_FIELD])) {
$a['<?= $objColumn->Name ?>'] = $this-><?= $objColumn->VariableName ?>;
}
<?php } else { ?>
if (isset($this->__blnValid[self::<?= strtoupper($objColumn->Name) ?>_FIELD])) {
<?php if ($objColumn->DbType == \QCubed\Database\FieldType::BLOB) { // binary value ?>
$a['<?= $objColumn->Name ?>'] = base64_encode($this-><?= $objColumn->VariableName ?>);
<?php }
elseif ($objColumn->VariableType == \QCubed\Type::STRING && __APPLICATION_ENCODING_TYPE__ != 'UTF-8') { ?>
$a['<?= $objColumn->Name ?>'] = JavsScriptHelper::MakeJsonEncodable($this-><?= $objColumn->VariableName ?>);
<?php }
else {?>
$a['<?= $objColumn->Name ?>'] = $this-><?= $objColumn->VariableName ?>;
<?php } ?>
}
<?php } ?>
<?php } ?>
<?php foreach ($objTable->ReverseReferenceArray as $objReverseReference) { ?>
<?php if ($objReverseReference->Unique) { ?>
if (isset($this-><?= $objReverseReference->ObjectMemberVariable ?>)) {
$a['<?= \QCubed\QString::UnderscoreFromCamelCase($objReverseReference->ObjectDescription) ?>'] = $this-><?= $objReverseReference->ObjectMemberVariable ?>;
}
<?php } else { ?>
if (isset($this->_obj<?= $objReverseReference->ObjectDescription ?>)) {
$a['<?= \QCubed\QString::UnderscoreFromCamelCase($objReverseReference->ObjectDescription) ?>'] = $this->_obj<?= $objReverseReference->ObjectDescription ?>;
} elseif (isset($this->_obj<?= $objReverseReference->ObjectDescription ?>Array)) {
$a['<?= \QCubed\QString::UnderscoreFromCamelCase($objReverseReference->ObjectDescription) ?>'] = $this->_obj<?= $objReverseReference->ObjectDescription ?>Array;
}
<?php } ?>
<?php } ?>
<?php foreach ($objTable->ManyToManyReferenceArray as $objReference) { ?>
<?php
$objAssociatedTable = $objCodeGen->GetTable($objReference->AssociatedTable);
$varPrefix = (is_a($objAssociatedTable, '\QCubed\Codegen\TypeTable') ? '_int' : '_obj');
?>
if (isset($this-><?= $varPrefix . $objReference->ObjectDescription ?>)) {
$a['<?= \QCubed\QString::UnderscoreFromCamelCase($objReference->ObjectDescription) ?>'] = $this-><?= $varPrefix . $objReference->ObjectDescription ?>;
} elseif (isset($this-><?= $varPrefix . $objReference->ObjectDescription ?>Array)) {
$a['<?= \QCubed\QString::UnderscoreFromCamelCase($objReference->ObjectDescription) ?>'] = $this-><?= $varPrefix . $objReference->ObjectDescription ?>Array;
}
<?php } ?>
return $a;
}
| spekary/qcubed-orm | codegen/templates/db_orm/class_gen/json_methods.tpl.php | PHP | mit | 5,513 |
// Utility namespace for InPhO JavaScript. Contains dynamic URL builder.
var inpho = inpho || {};
inpho.util = inpho.util || {};
/* inpho.util.url
* Takes a path for the inpho rest API and builds an absolute URL based on the
* current host and protocol.
*
* // running on http://inphodev.cogs.indiana.edu:8080
* > inpho.util.url('/entity.json')
* http://inphodev.cogs.indiana.edu:8080/entity.json
* */
inpho.util.base_url = null;
inpho.util.url = function(api_call) {
if (inpho.util.base_url == null)
return window.location.protocol + "//" + window.location.host + api_call;
else
return inpho.util.base_url + api_call;
}
inpho.util.getCookieValueForName = function(cookieName) {
console.log("Getting list of cookies...");
var cookies = document.cookie.split(";");
for(var i = 0; i < cookies.length; i++) {
var pair = cookies[i].split("=");
console.log("Cookie " + i + ": name(" + pair[0] + "), value(" + pair[1] + ")");
if($.trim(pair[0]) === $.trim(cookieName)) {
console.log("Success! Cookie found: " + cookieName);
return pair[1];
}
}
console.log("Error! Cookie not found: " + cookieName);
return null;
}
inpho.util.getURLParamsAndValues = function() {
var paramsAndValues = [];
var queryString = window.location.href.slice(window.location.href.indexOf('?') + 1);
var keyValPairs = queryString.split('&');
console.log("Parsing query string: " + queryString);
for(var i = 0; i < keyValPairs.length; i++) {
var pair = keyValPairs[i].split('=');
if(pair.length == 2) {
paramsAndValues.push(pair[0]);
paramsAndValues[pair[0]] = pair[1];
}
else {
console.log("Error: invalid URL query string");
}
}
return paramsAndValues;
}
inpho.util.getValueForURLParam = function(param) {
var paramsAndValues = inpho.util.getURLParamsAndValues();
if(paramsAndValues.length == 0)
return null;
return paramsAndValues[param];
}
| iSumitG/topic-explorer | www/lib/inpho/util.js | JavaScript | mit | 1,940 |
namespace TestingPerformance
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Address
{
public Address()
{
Employees = new HashSet<Employee>();
}
public int AddressID { get; set; }
[Required]
[StringLength(100)]
public string AddressText { get; set; }
public int? TownID { get; set; }
public virtual Town Town { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
}
| TsvetanKT/TelerikHomeworks | Databases/09.EntityFrameworkPerformance/TestingPerformance/TelerikAcademyEntities/Address.cs | C# | mit | 672 |
'use strict';
var EMBED_WIDTH = 600;
var EMBED_HEIGHT = 300;
var mustache = require('mustache'),
url = require('url');
var cache = require('./cache');
exports.getEmbedCode = function getEmbedCode(_, request, response) {
var params = url.parse(request.url, true).query;
if (!params.url) {
respond('', 400, response);
return;
}
//Check for format issues
if (params.format && params.format !== 'json') {
respond('Not implemented. Please use JSON', 501, response);
return;
}
var data = cache.summary;
data.height = EMBED_HEIGHT;
data.width = EMBED_WIDTH;
cache.summary.host = request.headers.host;
/*eslint-disable camelcase */
//For now, respond to any url request the same way
var embedCode = {
//As per the spec at http://oembed.com/
/* type (required)
The resource type. Valid values, along with value-specific
parameters, are described below. */
type: 'rich',
/*version (required)
The oEmbed version number. This must be 1.0.*/
version: 1.0,
/*author_name (optional)
The name of the author/owner of the resource. */
author_name: 'Sock Drawer',
/*author_url (optional)
A URL for the author/owner of the resource.*/
author_url: 'https://github.com/SockDrawer',
/*html (required)
The HTML required to display the resource.
The HTML should have no padding or margins.
Consumers may wish to load the HTML in an off-domain iframe
to avoid XSS vulnerabilities.
The markup should be valid XHTML 1.0 Basic. */
html: mustache.render(cache.templates.embedTemplate,
data, cache.templates),
/*width (required)
The width in pixels required to display the HTML.*/
width: EMBED_WIDTH,
/*height (required)
The height in pixels required to display the HTML.*/
height: EMBED_HEIGHT
};
/*eslint-enable camelcase */
respond(JSON.stringify(embedCode), 200, response);
};
function respond(data, code, response) {
response.writeHead(code);
response.write(data, 'utf8');
response.end();
}
| SockDrawer/SockSite | oembed.js | JavaScript | mit | 1,976 |
module SnakeCase
VERSION = "0.0.1"
end
| FluffyJack/snake_case | lib/snake_case/version.rb | Ruby | mit | 41 |
// 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 "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 7612030 : 8511566;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 84000000.0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
if (pcmd->reqWallet && !pwalletMain)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop christcoin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "christcoin server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe reqWallet
// ------------------------ ----------------------- ---------- ---------- ---------
{ "help", &help, true, true, false },
{ "stop", &stop, true, true, false },
{ "getblockcount", &getblockcount, true, false, false },
{ "getbestblockhash", &getbestblockhash, true, false, false },
{ "getconnectioncount", &getconnectioncount, true, false, false },
{ "getpeerinfo", &getpeerinfo, true, false, false },
{ "addnode", &addnode, true, true, false },
{ "getaddednodeinfo", &getaddednodeinfo, true, true, false },
{ "getdifficulty", &getdifficulty, true, false, false },
{ "getnetworkhashps", &getnetworkhashps, true, false, false },
{ "getgenerate", &getgenerate, true, false, false },
{ "setgenerate", &setgenerate, true, false, true },
{ "gethashespersec", &gethashespersec, true, false, false },
{ "getinfo", &getinfo, true, false, false },
{ "getmininginfo", &getmininginfo, true, false, false },
{ "getnewaddress", &getnewaddress, true, false, true },
{ "getaccountaddress", &getaccountaddress, true, false, true },
{ "setaccount", &setaccount, true, false, true },
{ "getaccount", &getaccount, false, false, true },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
{ "sendtoaddress", &sendtoaddress, false, false, true },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
{ "backupwallet", &backupwallet, true, false, true },
{ "keypoolrefill", &keypoolrefill, true, false, true },
{ "walletpassphrase", &walletpassphrase, true, false, true },
{ "walletpassphrasechange", &walletpassphrasechange, false, false, true },
{ "walletlock", &walletlock, true, false, true },
{ "encryptwallet", &encryptwallet, false, false, true },
{ "validateaddress", &validateaddress, true, false, false },
{ "getbalance", &getbalance, false, false, true },
{ "move", &movecmd, false, false, true },
{ "sendfrom", &sendfrom, false, false, true },
{ "sendmany", &sendmany, false, false, true },
{ "addmultisigaddress", &addmultisigaddress, false, false, true },
{ "createmultisig", &createmultisig, true, true , false },
{ "getrawmempool", &getrawmempool, true, false, false },
{ "getblock", &getblock, false, false, false },
{ "getblockhash", &getblockhash, false, false, false },
{ "gettransaction", &gettransaction, false, false, true },
{ "listtransactions", &listtransactions, false, false, true },
{ "listaddressgroupings", &listaddressgroupings, false, false, true },
{ "signmessage", &signmessage, false, false, true },
{ "verifymessage", &verifymessage, false, false, false },
{ "getwork", &getwork, true, false, true },
{ "getworkex", &getworkex, true, false, true },
{ "listaccounts", &listaccounts, false, false, true },
{ "settxfee", &settxfee, false, false, true },
{ "getblocktemplate", &getblocktemplate, true, false, false },
{ "submitblock", &submitblock, false, false, false },
{ "setmininput", &setmininput, false, false, false },
{ "listsinceblock", &listsinceblock, false, false, true },
{ "dumpprivkey", &dumpprivkey, true, false, true },
{ "importprivkey", &importprivkey, false, false, true },
{ "listunspent", &listunspent, false, false, true },
{ "getrawtransaction", &getrawtransaction, false, false, false },
{ "createrawtransaction", &createrawtransaction, false, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false, false },
{ "signrawtransaction", &signrawtransaction, false, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false, false },
{ "gettxout", &gettxout, true, false, false },
{ "lockunspent", &lockunspent, false, false, true },
{ "listlockunspent", &listlockunspent, false, false, true },
{ "verifychain", &verifychain, true, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: christcoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: christcoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: christcoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use christcoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=christcoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"christcoin Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl");
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
rpc_io_service->stop();
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
if (pcmd->reqWallet && !pwalletMain)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else if (!pwalletMain) {
LOCK(cs_main);
result = pcmd->actor(params, false);
} else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| ChristCoin7/christcoin | src/bitcoinrpc.cpp | C++ | mit | 48,589 |
//https://gist.github.com/Ninputer/2227226 https://gist.github.com/chenshuo/2232954
//ÇëʵÏÖÏÂÃæµÄº¯Êý£¬ÊäÈë²ÎÊýbaseStrÊÇÒ»¸ö£¨¿ÉÒÔ¸ü¸ÄµÄ£©×Ö·û´®£¬Ç뽫ÆäÖÐËùÓÐÁ¬Ðø³öÏֵĶà¸ö¿Õ¸ñ¶¼Ìæ»»³ÉÒ»¸ö¿Õ¸ñ£¬µ¥Ò»¿Õ¸ñÐè±£Áô¡£
//ÇëÖ±½ÓʹÓÃbaseStrµÄ¿Õ¼ä£¬ÈçÐ迪±ÙеĴ洢¿Õ¼ä£¬²»Äܳ¬¹ýo(N)£¨×¢ÒâÊÇСo£¬NÊÇ×Ö·û´®µÄ³¤¶È£©¡£·µ»ØÖµÊÇÌæ»»ºóµÄ×Ö·û´®µÄ³¤¶È¡£
//ÑùÀý´úÂëΪC#£¬µ«¿ÉÒÔʹÓÃÈκÎÓïÑÔ¡£ÈçÐèʹÓÃÈκο⺯Êý£¬±ØÐëͬʱ¸ø³ö¿âº¯ÊýµÄʵÏÖ¡£
#include <algorithm>
#include <string.h>
#include <cassert>
struct AreBothSpaces
{
bool operator()(char x, char y) const
{
return x == ' ' && y == ' ';
}
};
//impl by chenshuo
int removeContinuousSpaces(char* const str)
{
size_t len = strlen(str); // or use std::string
char* end = str+len;
assert(*end == '\0');
char* last = std::unique(str, end, AreBothSpaces());
*last = '\0';
return last - str;
}
int main()
{
char inout[256] = "";
strcpy(inout, "");
removeContinuousSpaces(inout);
assert(strcmp(inout, "") == 0);
strcpy(inout, "a");
removeContinuousSpaces(inout);
assert(strcmp(inout, "a") == 0);
strcpy(inout, " a");
removeContinuousSpaces(inout);
assert(strcmp(inout, " a") == 0);
strcpy(inout, " a");
removeContinuousSpaces(inout);
assert(strcmp(inout, " a") == 0);
strcpy(inout, "a ");
removeContinuousSpaces(inout);
assert(strcmp(inout, "a ") == 0);
strcpy(inout, "a ");
removeContinuousSpaces(inout);
assert(strcmp(inout, "a ") == 0);
strcpy(inout, "abc def");
removeContinuousSpaces(inout);
assert(strcmp(inout, "abc def") == 0);
strcpy(inout, "abc def ghi");
removeContinuousSpaces(inout);
assert(strcmp(inout, "abc def ghi") == 0);
strcpy(inout, " a b d e ");
removeContinuousSpaces(inout);
assert(strcmp(inout, " a b d e ") == 0);
strcpy(inout, " ");
removeContinuousSpaces(inout);
assert(strcmp(inout, " ") == 0);
system("pause");
return 0;
} | lizhenghn123/myAlgorithmStudy | trim_continuous_space/trim_continuous_space.cpp | C++ | mit | 1,862 |
'use strict';
angular.module('myContacts.contacts', ['ngRoute', 'firebase'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/contacts', {
templateUrl: 'contacts/contacts.html',
controller: 'ContactsController'
});
}])
.controller('ContactsController', ['$scope', '$firebaseArray', function($scope, $firebaseArray) {
var ref = new Firebase('https://mycontactsforangjsprojects.firebaseio.com/contacts')
$scope.contacts = $firebaseArray(ref);
// console.log($scope.contacts);
$scope.showAddForm = function(){
clearFields();
$scope.addFormShow = true;
}
$scope.showEditForm = function(contact) {
$scope.editFormShow = true;
$scope.id = contact.$id;
$scope.name = contact.name;
$scope.email = contact.email;
$scope.company = contact.company;
$scope.work_phone = contact.phones[0].work;
$scope.home_phone = contact.phones[0].home;
$scope.mobile_phone = contact.phones[0].mobile;
$scope.street_address = contact.address[0].street_address;
$scope.city = contact.address[0].city;
$scope.state = contact.address[0].state;
$scope.zipcode = contact.address[0].zipcode;
}
$scope.hide= function(){
$scope.addFormShow = false;
$scope.contactShow = false;
$scope.editFormShow = false;
}
$scope.addFormSubmit = function(){
//assign values
if($scope.name){var name = $scope.name;} else {var name = null;}
if($scope.email){var email = $scope.email;} else {var email = null;}
if($scope.company){var company = $scope.company;} else {var company = null;}
if($scope.mobile_phone){var mobile_phone = $scope.mobile_phone;} else {var mobile_phone = null;}
if($scope.home_phone){var home_phone = $scope.home_phone;} else {var home_phone = null;}
if($scope.work_phone){var work_phone = $scope.work_phone;} else {var work_phone = null;}
if($scope.street_address){var street_address = $scope.street_address;} else {var street_address = null;}
if($scope.city){var city = $scope.city;} else {var city = null;}
if($scope.state){var state = $scope.state;} else {var state = null;}
if($scope.zipcode){var zipcode = $scope.zipcode;} else {var zipcode = null;}
//build object
$scope.contacts.$add({
name: name,
email: email,
company: company,
phones: [
{
mobile: mobile_phone,
home: home_phone,
work: work_phone
}
],
address: [
{
street_address: street_address,
city: city,
state: state,
zipcode: zipcode
}
]
}).then(function(ref){
var id = ref.key();
console.log('Added contact with ID: ' + id);
//clear the form
clearFields();
$scope.addFormShow = false;
$scope.msg = "Contact added!";
});
}
$scope.editFormSubmit = function() {
console.log('update contact...');
//obtain contact id
var id = $scope.id;
//get record
var record = $scope.contacts.$getRecord(id);
//assign values
record.name = $scope.name;
record.email = $scope.email;
record.company = $scope.company;
record.phones[0].work = $scope.work_phone;
record.phones[0].home = $scope.home_phone;
record.phones[0].mobile = $scope.mobile_phone;
record.address[0].street_address = $scope.street_address;
record.address[0].city = $scope.city;
record.address[0].state = $scope.state;
record.address[0].zipcode = $scope.zipcode;
// Save Contact
$scope.contacts.$save(record).then(function(ref){
console.log(ref.key);
});
clearFields();
$scope.editFormShow = false;
$scope.msg = "Contact Updated!";
}
$scope.showContact = function(contact) {
console.log(contact);
$scope.name = contact.name;
$scope.email = contact.email;
$scope.company = contact.company;
$scope.work_phone = contact.phones[0].work;
$scope.home_phone = contact.phones[0].home;
$scope.mobile_phone = contact.phones[0].mobile;
$scope.street_address = contact.address[0].street_address;
$scope.city = contact.address[0].city;
$scope.state = contact.address[0].state;
$scope.zipcode = contact.address[0].zipcode;
$scope.contactShow = true;
}
//Delete contact
$scope.deleteContact = function(contact){
$scope.contacts.$remove(contact);
$scope.msg = "Contact Removed.";
}
function clearFields() {
console.log('Clearing all fields...');
$scope.name = '';
$scope.email = '';
$scope.company = '';
$scope.mobile_phone = '';
$scope.home_phone = '';
$scope.work_phone = '';
$scope.street_address = '';
$scope.city = '';
$scope.state = '';
$scope.zipcode = '';
}
}]);
| joryschmidt/angular-contacts-app | app/contacts/contacts.js | JavaScript | mit | 4,767 |
import { omit, parse } from 'search-params'
import { MatchOptions, MatchResponse, RouteNode } from './RouteNode'
import { TestMatch } from 'path-parser'
const getPath = (path: string): string => path.split('?')[0]
const getSearch = (path: string): string => path.split('?')[1] || ''
const matchChildren = (
nodes: RouteNode[],
pathSegment: string,
currentMatch: MatchResponse,
options: MatchOptions = {},
consumedBefore?: string
): MatchResponse | null => {
const {
queryParamsMode = 'default',
strictTrailingSlash = false,
strongMatching = true,
caseSensitive = false
} = options
const isRoot = nodes.length === 1 && nodes[0].name === ''
// for (child of node.children) {
for (const child of nodes) {
// Partially match path
let match: TestMatch | null = null
let remainingPath
let segment = pathSegment
if (consumedBefore === '/' && child.path === '/') {
// when we encounter repeating slashes we add the slash
// back to the URL to make it de facto pathless
segment = '/' + pathSegment
}
if (!child.children.length) {
match = child.parser!.test(segment, {
caseSensitive,
strictTrailingSlash,
queryParams: options.queryParams,
urlParamsEncoding: options.urlParamsEncoding
})
}
if (!match) {
match = child.parser!.partialTest(segment, {
delimited: strongMatching,
caseSensitive,
queryParams: options.queryParams,
urlParamsEncoding: options.urlParamsEncoding
})
}
if (match) {
// Remove consumed segment from path
let consumedPath = child.parser!.build(match, {
ignoreSearch: true,
urlParamsEncoding: options.urlParamsEncoding
})
if (!strictTrailingSlash && !child.children.length) {
consumedPath = consumedPath.replace(/\/$/, '')
}
// Can't create a regexp from the path because it might contain a
// regexp character.
if (segment.toLowerCase().indexOf(consumedPath.toLowerCase()) === 0) {
remainingPath = segment.slice(consumedPath.length)
} else {
remainingPath = segment
}
if (!strictTrailingSlash && !child.children.length) {
remainingPath = remainingPath.replace(/^\/\?/, '?')
}
const { querystring } = omit(
getSearch(segment.replace(consumedPath, '')),
child.parser!.queryParams,
options.queryParams
)
remainingPath =
getPath(remainingPath) + (querystring ? `?${querystring}` : '')
if (
!strictTrailingSlash &&
!isRoot &&
remainingPath === '/' &&
!/\/$/.test(consumedPath)
) {
remainingPath = ''
}
currentMatch.segments.push(child)
Object.keys(match).forEach(
param => (currentMatch.params[param] = match![param])
)
if (!isRoot && !remainingPath.length) {
// fully matched
return currentMatch
}
if (
!isRoot &&
queryParamsMode !== 'strict' &&
remainingPath.indexOf('?') === 0
) {
// unmatched queryParams in non strict mode
const remainingQueryParams = parse(
remainingPath.slice(1),
options.queryParams
) as any
Object.keys(remainingQueryParams).forEach(
name => (currentMatch.params[name] = remainingQueryParams[name])
)
return currentMatch
}
// Continue matching on non absolute children
const children = child.getNonAbsoluteChildren()
// If no children to match against but unmatched path left
if (!children.length) {
return null
}
// Else: remaining path and children
return matchChildren(
children,
remainingPath,
currentMatch,
options,
consumedPath
)
}
}
return null
}
export default matchChildren
| troch/route-node | src/matchChildren.ts | TypeScript | mit | 3,921 |
from ..models import Job
import datetime
class JobContainer():
def __init__(self):
self.organization = None
self.title = None
self.division = None
self.date_posted = None
self.date_closing = None
self.date_collected = None
self.url_detail = None
self.salary_waged = None
self.salary_amount = None
self.region = None
def is_unique(self):
""" Checks whether job (denoted by URL) already exists in DB.
Remember to use this function before doing any intense parsing operations.
"""
if not self.url_detail:
raise KeyError(
"Queried record uniqueness before detail URL set: {}".format(self))
else:
if len(Job.objects.filter(url_detail=self.url_detail)) == 0:
return True
else:
# print("Job already exists in DB: {}".format(self.url_detail))
return False
def cleanup(self):
self.title = self.title.title() if self.title.isupper() else self.title
self.salary_amount = 0 if self.salary_amount == None else self.salary_amount
# totally arbitray amount
self.salary_waged = True if self.salary_amount < 5000 else False
self.date_collected = datetime.date.today()
def validate(self):
field_dict = self.__dict__
attributes = {
k: v for k, v in field_dict.items() if not k.startswith("_")}
for k, v in attributes.items():
if v == None:
raise KeyError(
"Job {} was missing {}".format(self.url_detail, k))
def save(self):
""" Save job to DB, after final checks.
"""
if not self.is_unique(): # failsafe in case we forgot to check this earlier.
print(
"{} tried to save a job hat is not unique!".format(self.organization))
return
self.cleanup()
try:
self.validate()
except KeyError as err:
print("|| EXCEPTION ", err)
return
print("Saved job to DB: {}".format(self))
j = Job(organization=self.organization, title=self.title, division=self.division, date_posted=self.date_posted, date_closing=self.date_closing, url_detail=self.url_detail, salary_waged=self.salary_waged, salary_amount=self.salary_amount, region=self.region, date_collected=self.date_collected
)
try:
j.save()
except Exception as err:
print("|| Exception ", err)
def __str__(self):
return "{} at {}".format(self.title, self.organization)
| rgscherf/gainful2 | parsing/parsinglib/jobcontainer.py | Python | mit | 2,667 |
import { computed, reactive, toRefs } from '@vue/composition-api'
import { Frame as GameSetting } from '@xmcl/gamesetting'
import { useBusy, useSemaphore } from './useSemaphore'
import { useService, useServiceOnly } from './useService'
import { useStore } from './useStore'
import { useCurrentUser } from './useUser'
import { useMinecraftVersions } from './useVersion'
import { InstanceSchema as InstanceConfig, RuntimeVersions } from '/@shared/entities/instance.schema'
import { CurseforgeModpackResource, ModpackResource } from '/@shared/entities/resource'
import { ResourceType } from '/@shared/entities/resource.schema'
import { getExpectVersion } from '/@shared/entities/version'
import { InstanceGameSettingServiceKey } from '/@shared/services/InstanceGameSettingService'
import { InstanceIOServiceKey } from '/@shared/services/InstanceIOService'
import { InstanceLogServiceKey } from '/@shared/services/InstanceLogService'
import { CloneSaveOptions, DeleteSaveOptions, ImportSaveOptions, InstanceSavesServiceKey } from '/@shared/services/InstanceSavesService'
import { CreateOption, InstanceServiceKey } from '/@shared/services/InstanceService'
export function useInstanceBase() {
const { state } = useStore()
const path = computed(() => state.instance.path)
return { path }
}
/**
* Use the general info of the instance
*/
export function useInstance() {
const { getters, state } = useStore()
const path = computed(() => state.instance.path)
const name = computed(() => getters.instance.name)
const author = computed(() => getters.instance.author || '')
const description = computed(() => getters.instance.description)
const showLog = computed(() => getters.instance.showLog)
const hideLauncher = computed(() => getters.instance.hideLauncher)
const runtime = computed(() => getters.instance.runtime)
const java = computed(() => getters.instance.java)
const resolution = computed(() => getters.instance.resolution)
const minMemory = computed(() => getters.instance.minMemory)
const maxMemory = computed(() => getters.instance.maxMemory)
const vmOptions = computed(() => getters.instance.vmOptions)
const mcOptions = computed(() => getters.instance.mcOptions)
const url = computed(() => getters.instance.url)
const icon = computed(() => getters.instance.icon)
const lastAccessDate = computed(() => getters.instance.lastAccessDate)
const creationDate = computed(() => getters.instance.creationDate)
const server = computed(() => getters.instance.server)
const version = computed(() => getters.instance.version)
return {
path,
name,
author,
description,
showLog,
hideLauncher,
runtime,
version,
java,
resolution,
minMemory,
maxMemory,
vmOptions,
mcOptions,
url,
icon,
lastAccessDate,
creationDate,
server,
isServer: computed(() => getters.instance.server !== null),
refreshing: computed(() => useSemaphore('instance').value !== 0),
...useServiceOnly(InstanceServiceKey, 'editInstance', 'refreshServerStatus'),
...useServiceOnly(InstanceIOServiceKey, 'exportInstance'),
}
}
/**
* Hook of a view of all instances & some deletion/selection functions
*/
export function useInstances() {
const { getters } = useStore()
return {
instances: computed(() => getters.instances),
...useServiceOnly(InstanceServiceKey, 'mountInstance', 'deleteInstance', 'refreshServerStatusAll'),
...useServiceOnly(InstanceIOServiceKey, 'importInstance', 'linkInstance'),
}
}
/**
* Hook to create a general instance
*/
export function useInstanceCreation() {
const { gameProfile } = useCurrentUser()
const { createAndMount: createAndSelect } = useService(InstanceServiceKey)
const { release } = useMinecraftVersions()
const data = reactive({
name: '',
runtime: { forge: '', minecraft: release.value?.id || '', liteloader: '', fabricLoader: '', yarn: '' } as RuntimeVersions,
java: '',
showLog: false,
hideLauncher: true,
vmOptions: [] as string[],
mcOptions: [] as string[],
maxMemory: undefined as undefined | number,
minMemory: undefined as undefined | number,
author: gameProfile.value.name,
description: '',
resolution: undefined as undefined | CreateOption['resolution'],
url: '',
icon: '',
image: '',
blur: 4,
server: null as undefined | CreateOption['server'],
})
const refs = toRefs(data)
const required: Required<typeof refs> = toRefs(data) as any
return {
...required,
/**
* Commit this creation. It will create and select the instance.
*/
create() {
return createAndSelect(data)
},
/**
* Reset the change
*/
reset() {
data.name = ''
data.runtime = {
minecraft: release.value?.id || '',
forge: '',
liteloader: '',
fabricLoader: '',
yarn: '',
}
data.java = ''
data.showLog = false
data.hideLauncher = true
data.vmOptions = []
data.mcOptions = []
data.maxMemory = undefined
data.minMemory = undefined
data.author = gameProfile.value.name
data.description = ''
data.resolution = undefined
data.url = ''
data.icon = ''
data.image = ''
data.blur = 4
data.server = null
},
/**
* Use the same configuration as the input instance
* @param instance The instance will be copied
*/
use(instance: InstanceConfig) {
data.name = instance.name
data.runtime = { ...instance.runtime }
data.java = instance.java
data.showLog = instance.showLog
data.hideLauncher = instance.hideLauncher
data.vmOptions = [...instance.vmOptions]
data.mcOptions = [...instance.mcOptions]
data.maxMemory = instance.maxMemory
data.minMemory = instance.minMemory
data.author = instance.author
data.description = instance.description
data.url = instance.url
data.icon = instance.icon
data.server = instance.server ? { ...instance.server } : undefined
},
useModpack(resource: CurseforgeModpackResource | ModpackResource) {
if (resource.type === ResourceType.CurseforgeModpack) {
const metadata = resource.metadata
data.name = `${metadata.name} - ${metadata.version}`
data.runtime.minecraft = metadata.minecraft.version
if (metadata.minecraft.modLoaders.length > 0) {
for (const loader of metadata.minecraft.modLoaders) {
if (loader.id.startsWith('forge-')) {
data.runtime.forge = loader.id.substring('forge-'.length)
}
}
}
data.author = metadata.author
} else {
const metadata = resource.metadata
data.name = resource.name
data.runtime.minecraft = metadata.runtime.minecraft
data.runtime.forge = metadata.runtime.forge
data.runtime.fabricLoader = metadata.runtime.fabricLoader
}
},
}
}
export function useInstanceVersionBase() {
const { getters } = useStore()
const minecraft = computed(() => getters.instance.runtime.minecraft)
const forge = computed(() => getters.instance.runtime.forge)
const fabricLoader = computed(() => getters.instance.runtime.fabricLoader)
const yarn = computed(() => getters.instance.runtime.yarn)
return {
minecraft,
forge,
fabricLoader,
yarn,
}
}
export function useInstanceTemplates() {
const { getters, state } = useStore()
return {
instances: computed(() => getters.instances),
modpacks: computed(() => state.resource.modpacks),
}
}
export function useInstanceGameSetting() {
const { state } = useStore()
const { refresh: _refresh, edit, showInFolder } = useService(InstanceGameSettingServiceKey)
const refresh = () => _refresh()
const fancyGraphics = computed(() => state.instanceGameSetting.fancyGraphics)
const renderClouds = computed(() => state.instanceGameSetting.renderClouds)
const ao = computed(() => state.instanceGameSetting.ao)
const entityShadows = computed(() => state.instanceGameSetting.entityShadows)
const particles = computed(() => state.instanceGameSetting.particles)
const mipmapLevels = computed(() => state.instanceGameSetting.mipmapLevels)
const useVbo = computed(() => state.instanceGameSetting.useVbo)
const fboEnable = computed(() => state.instanceGameSetting.fboEnable)
const enableVsync = computed(() => state.instanceGameSetting.enableVsync)
const anaglyph3d = computed(() => state.instanceGameSetting.anaglyph3d)
return {
fancyGraphics,
renderClouds,
ao,
entityShadows,
particles,
mipmapLevels,
useVbo,
fboEnable,
enableVsync,
anaglyph3d,
showInFolder,
refreshing: useBusy('loadInstanceGameSettings'),
refresh,
commit(settings: GameSetting) {
edit(settings)
},
}
}
export function useInstanceSaves() {
const { state } = useStore()
const { cloneSave, deleteSave, exportSave, readAllInstancesSaves, importSave, mountInstanceSaves } = useService(InstanceSavesServiceKey)
const refresh = () => mountInstanceSaves(state.instance.path)
return {
refresh,
cloneSave: (options: CloneSaveOptions) => cloneSave(options).finally(refresh),
deleteSave: (options: DeleteSaveOptions) => deleteSave(options).finally(refresh),
exportSave,
readAllInstancesSaves,
importSave: (options: ImportSaveOptions) => importSave(options).finally(refresh),
path: computed(() => state.instance.path),
saves: computed(() => state.instanceSave.saves),
}
}
/**
* Use references of all the version info of this instance
*/
export function useInstanceVersion() {
const { getters } = useStore()
const folder = computed(() => getters.instanceVersion.id || 'unknown')
const id = computed(() => getExpectVersion(getters.instance.runtime))
return {
...useInstanceVersionBase(),
id,
folder,
}
}
export function useInstanceLogs() {
const { state } = useStore()
return {
path: computed(() => state.instance.path),
...useServiceOnly(InstanceLogServiceKey, 'getCrashReportContent', 'getLogContent', 'listCrashReports', 'listLogs', 'removeCrashReport', 'removeLog', 'showCrash', 'showLog'),
}
}
| InfinityStudio/ILauncher | src/renderer/hooks/useInstance.ts | TypeScript | mit | 10,224 |
require 'spec_helper'
describe Urmum do
it 'should have a version number' do
Urmum::VERSION.should_not be_nil
end
end
| dgmstuart/urmum | spec/urmum_spec.rb | Ruby | mit | 127 |
<?php
namespace App\Http\Controllers;
class PageController extends Controller
{
public function index($request, $response)
{
return $this->twigView->render($response, "auth/index.twig");
}
}
| Rodz3rd2/my-framework | app/Http/Controllers/PageController.php | PHP | mit | 198 |
# encoding: utf-8
require 'spec_helper'
RSpec.describe Github::Client::Gists, '#get' do
let(:gist_id) { 1 }
before {
stub_get(request_path).to_return(body: body, status: status,
headers: {content_type: "application/json; charset=utf-8"})
}
after { reset_authentication_for(subject) }
context "resource found" do
let(:request_path) { "/gists/#{gist_id}" }
let(:body) { fixture('gists/gist.json') }
let(:status) { 200 }
it { should respond_to :find }
it "fails to get resource without gist id" do
expect { subject.get }.to raise_error(ArgumentError)
end
it "gets the resource" do
subject.get gist_id
expect(a_get(request_path)).to have_been_made
end
it "gets gist information" do
gist = subject.get gist_id
expect(gist.id.to_i).to eq gist_id
expect(gist.user.login).to eq('octocat')
end
it "returns response wrapper" do
gist = subject.get(gist_id)
expect(gist).to be_a(Github::ResponseWrapper)
end
it_should_behave_like 'request failure' do
let(:requestable) { subject.get gist_id }
end
end
context 'resource found with sha' do
let(:sha) { 'aa5a315d61ae9438b18d' }
let(:request_path) { "/gists/#{gist_id}/#{sha}" }
let(:body) { fixture('gists/gist.json') }
let(:status) { 200 }
it "gets the resource" do
subject.get(gist_id, sha: sha)
expect(a_get(request_path)).to have_been_made
end
end
end # get
| samphilipd/github | spec/github/client/gists/get_spec.rb | Ruby | mit | 1,482 |
/**
* @title Check last password reset
* @overview Check the last time that a user changed his or her account password.
* @gallery true
* @category access control
*
* This rule will check the last time that a user changed his or her account password.
*
*/
function checkLastPasswordReset(user, context, callback) {
function daydiff(first, second) {
return (second - first) / (1000 * 60 * 60 * 24);
}
const last_password_change = user.last_password_reset || user.created_at;
if (daydiff(new Date(last_password_change), new Date()) > 30) {
return callback(new UnauthorizedError('please change your password'));
}
callback(null, user, context);
}
| auth0/rules | src/rules/check-last-password-reset.js | JavaScript | mit | 675 |
import { router } from 'router';
$('body').ready(function() {
router.start();
}); | fasttakerbg/Final-Project | public/scripts/main.js | JavaScript | mit | 87 |
using System;
using A4CoreBlog.Data.Services.Contracts;
using A4CoreBlog.Data.UnitOfWork;
using AutoMapper;
using A4CoreBlog.Data.Models;
using System.Linq;
using AutoMapper.QueryableExtensions;
namespace A4CoreBlog.Data.Services.Implementations
{
public class SystemImageService : ISystemImageService
{
private readonly IBlogSystemData _data;
public SystemImageService(IBlogSystemData data)
{
_data = data;
}
public T AddOrUpdate<T>(T model)
{
try
{
var dbModel = Mapper.Map<SystemImage>(model);
dbModel.CreatedOn = DateTime.Now;
_data.Images.Add(dbModel);
_data.SaveChanges();
model = Mapper.Map<T>(dbModel);
return model;
}
catch (Exception ex)
{
// TODO: return default T or null
return model;
}
}
public T Get<T>(int id)
{
var dbModel = _data.Images.GetById(id);
var resultModel = Mapper.Map<T>(dbModel);
return resultModel;
}
public IQueryable<T> GetCollection<T>()
{
var result = _data.Images.All()
.OrderByDescending(i => i.CreatedOn)
.ProjectTo<T>();
return result;
}
}
}
| yasenm/a4-netcore | A4CoreBlog/A4CoreBlog.Data.Services/Implementations/SystemImageService.cs | C# | mit | 1,409 |
/**
* Simple script to detect misc CSS @support's.
* If not... Redirect to: /upgrade
*
* To minify (example):
* uglifyjs detect_support.js -o detect_support.min.js -c -m
*/
(function detectSupport() {
var upradeURL = '/upgrade',
/**
* List your CSS @support tests.
* On the upgrade page, it will add to console.log():
* Your browser doesn't support “Foo Bar Variables”: @supports ($foo, Bar)
*/
cssObj = {
'CSS Variables': ['--var', 0],
//'Foo Bar Variables': ['$foo', 'bar'],
};
var redirect = (function() {
window.location = upradeURL;
});
for (var t in cssObj) {
if (window.CSS && window.CSS.supports && !window.CSS.supports(cssObj[t][0], cssObj[t][1])) {
sessionStorage.setItem('detect_support.js', 'Your browser doesn\'t support “' + t + '”: @supports (' + cssObj[t][0] + ', ' + cssObj[t][1] + ')');
redirect();
}
}
})();
/**
* In your upgrade page add:
*
* <script type="text/javascript">
* if (sessionStorage.getItem('detect_support.js')) {
* console.log(sessionStorage.getItem('detect_support.js'));
* sessionStorage.removeItem('detect_support.js');
* }
* </script>
*/ | iEFdev/browser-upgrade-page | upgrade/js/detect_support.js | JavaScript | mit | 1,304 |
module foo {
exports foo;
} | opengl-8080/Samples | java/java9/jigsaw/src/main/java/module-info.java | Java | mit | 33 |
package com.cezarykluczynski.stapi.auth.common.factory;
import com.cezarykluczynski.stapi.model.common.dto.RequestSortClauseDTO;
import com.cezarykluczynski.stapi.model.common.dto.RequestSortDTO;
import com.cezarykluczynski.stapi.model.common.dto.enums.RequestSortDirectionDTO;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
@Service
public class RequestSortDTOFactory {
public RequestSortDTO create() {
RequestSortDTO requestSortDTO = new RequestSortDTO();
RequestSortClauseDTO requestSortClauseDTO = new RequestSortClauseDTO();
requestSortClauseDTO.setDirection(RequestSortDirectionDTO.ASC);
requestSortClauseDTO.setName("id");
requestSortDTO.setClauses(Lists.newArrayList(requestSortClauseDTO));
return requestSortDTO;
}
}
| cezarykluczynski/stapi | auth/src/main/java/com/cezarykluczynski/stapi/auth/common/factory/RequestSortDTOFactory.java | Java | mit | 784 |
package com.bah.app;
import com.bah.ml.classifiers.Perceptron;
import org.apache.commons.cli.*;
import org.apache.log4j.BasicConfigurator;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class perceptron {
private static final Logger log = Logger.getLogger(perceptron.class.getName());
public static void main(String[] args) {
// Configure log4j
BasicConfigurator.configure();
final Options options = new Options();
options.addOption("h", "help", false, "show help");
options.addOption("m", "mode", true, "Sets the mode <test|train>");
options.addOption("d", "data", true, "Sets the data source (file or URL)");
options.addOption("k", "k-folds", true, "Sets the k-folds");
options.addOption("l", "learn-rate", true, "Sets the learning rate");
options.addOption("r", "learn-random", false, "Will use random value for learning rate after each iteration");
Option targetsOption = new Option("t", "target", true, "Specify which target to train/test, if not set all targets found will be trained/tested (max 256)");
targetsOption.setArgs(256);
options.addOption(targetsOption);
options.addOption("i", "iterations", false, "Specify Max iterations to run for training, defaults to 1000");
options.addOption("i", "min-error", false, "Specify minimum error while training, defaults to 0.05");
CommandLineParser parser = new BasicParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
if (cmd.hasOption("h")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("perceptron", options);
System.exit(0);
}
if (cmd.hasOption("m")) {
log.log(Level.INFO, "Using cli argument -m=" + cmd.getOptionValue("m"));
Perceptron perceptron = new Perceptron();
if (cmd.getOptionValue("m").toLowerCase().equals("train")) {
perceptron.setMode(Perceptron.Mode.TRAIN);
perceptron.setDataSource(cmd.getOptionValue("d"));
perceptron.setTargets(Arrays.asList(cmd.getOptionValues("t")));
perceptron.setkFolds(Integer.valueOf(cmd.getOptionValue("k", "10")));
if (cmd.hasOption("r")) {
perceptron.setRandomLearning(true);
} else {
perceptron.setRandomLearning(false);
perceptron.setLearningRate(Double.valueOf(cmd.getOptionValue("l", "0.5")));
}
perceptron.setMaxIterations(Integer.valueOf(cmd.getOptionValue("i", "1000")));
perceptron.setMinError(Double.valueOf(cmd.getOptionValue("e", "0.05")));
perceptron.run();
} else {
perceptron.setMode(Perceptron.Mode.TEST);
}
} else {
log.log(Level.SEVERE, "Missing m option");
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("Main", options);
System.exit(0);
}
} catch (ParseException e) {
log.log(Level.SEVERE, "Failed to parse command line properties", e);
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("Main", options);
System.exit(0);
}
}
} | jaybkun/machine-learning-library | src/main/java/com/bah/app/perceptron.java | Java | mit | 3,562 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace ParcelTracker
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
| Vyacheslav-1991/parceltracker | ParcelTracker/Program.cs | C# | mit | 487 |
using System.Collections.Generic;
namespace TemplateApp.Data.Models
{
public class Subsidiary : EntityBase
{
//
// Constructor
public Subsidiary()
{
Locations = new HashSet<Location>();
Subsidiaries = new HashSet<Subsidiary>();
Divisions = new HashSet<Division>();
}
//
// Currency
public Currency Currency { get; set; }
//
// Divisions
public virtual ICollection<Division> Divisions { get; set; }
//
// Identification (Primary Key)
public int Id { get; set; }
//
// Locations
public virtual ICollection<Location> Locations { get; set; }
//
// Subsidiaries
public virtual ICollection<Subsidiary> Subsidiaries { get; set; }
}
} | panchaldineshb/Sarabi | TemplateApp/TemplateApp.Data/Models/Subsidiary.cs | C# | mit | 843 |
'use strict';
describe('Controller: SitenewCtrl', function () {
// load the controller's module
beforeEach(module('uiApp'));
var SitenewCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
SitenewCtrl = $controller('SitenewCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
| Ecotrust/floodplain-restoration | ui/test/spec/controllers/sitenew.js | JavaScript | mit | 513 |
import React, {Component} from 'react';
import LanguageSwitcher from './LanguageSwitcher';
import Navigation from './Navigation';
import $ from 'jquery';
const Translate = require('react-i18nify').Translate;
export default class Menu extends Component{
constructor(){
super();
let self = this;
this.state = {currentPage: '#home', isOpen: 0};
this.bindSidebarCallback();
$("body").on("click", (event) => {
let countElementClicks = (counter, element) => counter + event.target.className.indexOf(element);
let elements = ['nav-item', 'menu-toggler', 'language-switcher', "lang", "toggler"];
let isClicked = elements.reduce(countElementClicks, elements.length);
if(isClicked == 0)
this.setState({isOpen: 0});
});
}
handleClick(e){
e.preventDefault();
var section = e.target.getAttribute('href') || e.target.parentNode.getAttribute('href');
Navigation.goTo(section);
}
toggleMenu(e){
e.preventDefault();
this.setState(prevState => ({ isOpen: !prevState.isOpen }));
}
bindSidebarCallback(){
let self = this;
function setStateOnResizeWindow(){
if($(this).width() <= 768)
self.setState((previousState) => ({isOpen: 0}));
}
$(window).resize(setStateOnResizeWindow);
setStateOnResizeWindow();
}
render(){
return (
<div className="menu">
<div className="container ">
<nav className={this.state.isOpen > 0 ? "nav-item is-open" : "nav-item"}>
<a href="#home" className="manguezal-logo-small" onClick={this.handleClick.bind(this)}> Manguez.al</a>
<a href="#" className={this.state.isOpen > 0 ? "menu-toggler menu-toggler__is-open" : "menu-toggler"} onClick={this.toggleMenu.bind(this)}> </a>
<div className="menu-group">
<a href="#welcome" onClick={this.handleClick.bind(this)}><Translate value="nav_about"/></a>
<a href="#startups" onClick={this.handleClick.bind(this)}><Translate value="nav_startups"/></a>
<a href="#events" onClick={this.handleClick.bind(this)}><Translate value="nav_events"/></a>
<a href="#newsletter" onClick={this.handleClick.bind(this)}><Translate value="nav_newsletter"/></a>
<a href="https://medium.com/comunidade-empreendedora-manguezal" target="_blank"><Translate value="nav_blog"/></a>
</div>
<LanguageSwitcher />
</nav>
</div>
</div>
)
}
} | lhew/manguezal-test | src/components/Menu.js | JavaScript | mit | 2,593 |
<?php if (!defined('PRETZEL_EXCEPTION_SERVER')) exit('No Pretzel No (Server) Exception');
class Pretzel_Exception_Server_IllegalValueForType extends Pretzel_Exception_Server
{
} | smotyn/Pretzel | src/Pretzel/Exception/Server/IllegalValueForType.php | PHP | mit | 180 |
define(
['polygonjs/math/Color'],
function (Color) {
"use strict";
var Surface = function (opts) {
opts = opts || {};
this.width = opts.width || 640;
this.height = opts.height || 480;
this.cx = this.width / 2;
this.cy = this.height / 2;
var canvas = this.createEl('canvas', {
style: 'background: black',
width: this.width,
height: this.height
});
var container = typeof opts.container === 'string' ?
document.getElementById(opts.container) :
opts.container;
container.appendChild(canvas);
this.container = container;
this.canvas = canvas;
this.context = canvas.getContext('2d');
return this;
};
Surface.create = function (opts) {
return new Surface(opts);
};
Surface.prototype = {
createEl: function (name, attrs) {
var el = document.createElement(name);
attrs = attrs || {};
for (var attr in attrs)
this.setAttr(el, attr, attrs[attr]);
return el;
},
setAttr: function (el, name, value) {
el.setAttribute(name, value);
},
setAttrNS: function (el, namespace, name, value) {
el.setAttributeNS(namespace, name, value);
},
clear: function () {
this.context.clearRect(0, 0, this.width, this.height);
},
polygon: function (points, color) {
var len = points.length;
if (len > 1) {
var ctx = this.context;
var a = points[0];
// var b = points[1];
// var tint = Color.create({r: 0.0, g: 0.05, b: 0.0});
// var gradient = ctx.createLinearGradient(
// a.x + this.cx, -a.y + this.cy,
// b.x + this.cx, -b.y + this.cy);
//
// gradient.addColorStop(0, color.clone().subtract(tint).clamp().getHexStyle());
// gradient.addColorStop(1, color.clone().add(tint).clamp().getHexStyle());
ctx.fillStyle = color.getHexStyle();
// ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(a.x + this.cx, -a.y + this.cy);
for (var i = 1; i < len; i++) {
a = points[i];
ctx.lineTo(a.x + this.cx, -a.y + this.cy);
}
ctx.closePath();
ctx.fill();
// ctx.stroke(); // Gets rid of seams but performance hit
}
},
line: function (from, to, color) {
var ctx = this.context;
ctx.strokeStyle = color.getHexStyle();
ctx.beginPath();
ctx.moveTo(from.x + this.cx, -from.x + this.cy);
ctx.lineTo(to.x + this.cx, -to.y + this.cy);
ctx.stroke();
},
render: function () {}
};
return Surface;
}
);
| WebSeed/PolygonJS | polygonjs/surfaces/CanvasSurface.js | JavaScript | mit | 3,361 |
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("05. BooleanVariable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("05. BooleanVariable")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("d66ea66d-c61a-4b5a-bc31-47890c5e80db")]
// 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")]
| g-yonchev/TelerikAcademy | Homeworks/C# 1/02.PrimitiveDataTypesHW/05. BooleanVariable/Properties/AssemblyInfo.cs | C# | mit | 1,414 |
import java.util.*;
public class PowerSet
{
public static Set<Set<Integer>> powerset(Set<Integer> set) {
Set<Set<Integer>> ps = new HashSet<Set<Integer>>();
if(set.isEmpty()) {
Set<Integer> emptySet = new HashSet<Integer>();
ps.add(emptySet);
return ps;
}
List<Integer> list = new ArrayList<Integer>(set);
Integer head = list.get(0);
Set<Integer> rest = new HashSet<Integer>(list.subList(1, list.size()));
for(Set<Integer> s: powerset(rest)) {
Set<Integer> newSet = new HashSet<Integer>();
newSet.add(head);
newSet.addAll(s);
ps.add(newSet);
ps.add(s);
}
return ps;
}
public static void main(String[] args) {
Set<Integer> sampleSet = new HashSet<Integer>();
sampleSet.add(new Integer(5));
sampleSet.add(new Integer(4));
sampleSet.add(new Integer(3));
sampleSet.add(new Integer(2));
sampleSet.add(new Integer(1));
System.out.println(sampleSet.toString());
System.out.println(powerset(sampleSet).toString());
}
}
| leejay-schmidt/java-libs | FunJavaPrograms/PowerSet.java | Java | mit | 1,040 |
// © 2015 skwas
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using ColossalFramework.Plugins;
using ColossalFramework.Steamworks;
using ICities;
namespace skwas.CitiesSkylines
{
/// <summary>
/// Base class for mod implementations. Takes mod info from the type and assembly (AssemblyInfo), and resolves into the actual plugin info.
/// </summary>
/// <remarks>
/// Use of this base class is only working for compiled DLL projects. It is also absolutely important you version your DLL using [assembly: AssemblyVersion("1.0.*")], otherwise the plugin resolving code won't work properly and might return the wrong mod location.
/// </remarks>
public abstract class ModBase
: IUserMod
{
private readonly Assembly _assembly;
private PluginManager.PluginInfo _pluginInfo;
protected ModBase()
{
_assembly = GetType().Assembly;
}
#region Implementation of IUserMod
/// <summary>
/// Gets the mod name.
/// </summary>
/// <remarks>Uses the class name if AssemblyTitleAttribute is missing.</remarks>
public virtual string Name
{
get
{
var attr = GetAssemblyAttribute<AssemblyTitleAttribute>();
return string.Format("{0} v{1}",
attr == null ? GetType().Name : attr.Title,
Version
);
}
}
/// <summary>
/// Gets the in-game mod description (includes author name if available).
/// </summary>
/// <remarks>Explicitly implemented, the author name is only added to the game description.</remarks>
string IUserMod.Description
{
get
{
return string.IsNullOrEmpty(Author)
? Description
: string.Format("{0}\nby {1}", Description, Author);
}
}
#endregion
/// <summary>
/// Gets the mod description.
/// </summary>
public virtual string Description
{
get
{
var attr = GetAssemblyAttribute<AssemblyDescriptionAttribute>();
return attr == null ? null : attr.Description;
}
}
/// <summary>
/// Gets the mod author.
/// </summary>
public virtual string Author
{
get
{
var attr = GetAssemblyAttribute<AssemblyCompanyAttribute>();
return attr == null ? null : attr.Company;
}
}
/// <summary>
/// Gets the mod version.
/// </summary>
public virtual Version Version
{
get { return _assembly.GetName().Version; }
}
/// <summary>
/// Gets the mod path.
/// </summary>
public virtual string ModPath { get { return PluginInfo == null ? null : PluginInfo.modPath; } }
private string _modDllPath;
/// <summary>
/// Gets the mod dll path.
/// </summary>
public virtual string ModDllPath {
get
{
var modPath = ModPath; // Prefetch, forces load of plugin info.
return _modDllPath ?? modPath;
}
}
/// <summary>
/// Gets the steam workshop id of the mod/plugin. In local installations, returns PublishedFileId.invalid.
/// </summary>
public virtual PublishedFileId SteamWorkshopId { get { return PluginInfo == null ? PublishedFileId.invalid : PluginInfo.publishedFileID; } }
/// <summary>
/// Gets the plugin info for this mod (and caches it in local variable).
/// </summary>
protected virtual PluginManager.PluginInfo PluginInfo
{
get { return _pluginInfo ?? (_pluginInfo = GetPluginInfo()); }
}
/// <summary>
/// Helper to read assembly info.
/// </summary>
/// <typeparam name="T">The custom attribute to read from the assembly.</typeparam>
/// <returns></returns>
protected T GetAssemblyAttribute<T>()
{
var attributes = _assembly.GetCustomAttributes(typeof (T), false);
if (attributes.Length == 0) return default(T);
return (T)attributes[0];
}
/// <summary>
/// Enumerates plugins to find our plugin definition. This can be used to also determine save location when using Steam workshop (in which case path is different).
/// </summary>
/// <returns></returns>
private PluginManager.PluginInfo GetPluginInfo()
{
try
{
var currentAssemblyName = _assembly.GetName().FullName;
foreach (var p in PluginManager.instance.GetPluginsInfo())
{
if (!p.isBuiltin)
{
// Enumerate all assemblies in modPath, until we find the one matching the current assembly.
foreach (var assemblyName in Directory.GetFiles(p.modPath, "*.dll", SearchOption.TopDirectoryOnly)
.Select(AssemblyName.GetAssemblyName)
.Where(assemblyName => assemblyName.FullName.Equals(currentAssemblyName, StringComparison.OrdinalIgnoreCase)))
{
// This is our assembly!
_modDllPath = new Uri(assemblyName.CodeBase).LocalPath;
return p;
}
}
}
throw new FileNotFoundException(string.Format("The plugin assembly '{0}' could not be resolved.", currentAssemblyName));
}
catch (Exception ex)
{
Log.Error(ex.ToString());
throw; // Note: the plugin will fail if it can't find the assembly.
}
}
}
}
| skwasjer/CSModBase | ModBase.cs | C# | mit | 4,864 |
package nona.gameengine2d.maths;
public class Vector4f extends Vector {
public Vector4f() {
super(4);
}
public Vector4f(float x, float y, float z, float w) {
super(x, y, z, w);
}
public Vector4f(float[] v) {
super(v);
}
public Vector4f(Vector4f r) {
super(r);
}
@Override
public Vector normalized() {
Vector4f result = new Vector4f(this);
result.div(length());
return result;
}
}
| LeonardVollmann/GameEngine2D | src/nona/gameengine2d/maths/Vector4f.java | Java | mit | 421 |
'use strict';
var handler = {
fragments: null,
tab: null,
tabId: 0,
windowId: 0,
captureCmd: '',
initContextMenu: function () {},
queryActiveTab: function (callback) {
chrome.tabs.query({
active: true,
lastFocusedWindow: true
}, function (tabs) {
var tab = tabs && tabs[0] || {};
handler.tab = tab;
handler.tabId = tab.id;
handler.windowId = tab.windowId;
callback && callback(tab);
});
},
checkContentScript: function () {
handler.queryActiveTab(function () {
handler.executeScript({
file: "js/isLoaded.js"
});
});
},
injectContentScript: function () {
handler.executeScript({ file: "js/content.js" }, function () {
handler.onContentReady();
});
},
executeScript: function (details, callback) {
if (handler.tabId) {
chrome.tabs.executeScript(handler.tabId, details, callback);
}
},
onContentReady: function () {
if (handler.captureCmd) {
handler.sendCaptureCmd(handler.captureCmd);
handler.captureCmd = '';
}
},
sendCaptureCmd: function (cmd) {
handler.queryActiveTab(function (tab) {
chrome.tabs.sendMessage(tab.id, {
action: cmd
});
});
},
captureElement: function () {
// capture the selected html element
handler.captureCmd = 'captureElement';
handler.checkContentScript();
},
captureRegion: function () {
// capture the crop region
handler.captureCmd = 'captureRegion';
handler.checkContentScript();
},
captureEntire: function () {
// capture entire page
handler.captureCmd = 'captureEntire';
handler.checkContentScript();
},
captureVisible: function () {
// capture the visible part of page
handler.captureCmd = 'captureVisible';
handler.checkContentScript();
},
captureWindow: function () {
// capture desktop window
},
editContent: function () {
// TODO: 更好的编辑模式提示,可离开编辑模式
handler.queryActiveTab(function () {
handler.executeScript({
allFrames: true,
code: 'document.designMode="on"'
}, function () {
alert('Now you can edit this page');
});
});
},
clearFragments: function () {
handler.fragments = null;
},
onFragment: function (message, sender) {
chrome.tabs.captureVisibleTab(sender.tab.windowId, {
format: 'png'
}, function (dataURI) {
var fragments = handler.fragments;
var fragment = message.fragment;
fragment.dataURI = dataURI;
if (!fragments) {
fragments = handler.fragments = [];
}
fragments.push(fragment);
chrome.tabs.sendMessage(sender.tab.id, { action: 'nextFragment' });
});
},
onCaptureEnd: function (message, sender) {
var fragments = handler.fragments;
if (fragments && fragments.length) {
var fragment = fragments[0];
var totalWidth = fragment.totalWidth;
var totalHeight = fragment.totalHeight;
if (fragment.ratio !== 1) {
totalWidth *= fragment.ratio;
totalHeight *= fragment.ratio;
}
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = Math.round(totalWidth);
canvas.height = Math.round(totalHeight);
var totalCount = fragments.length;
var loadedCount = 0;
fragments.forEach(function (data) {
var image = new Image();
var ratio = data.ratio;
var sx = Math.round(data.sx * ratio);
var sy = Math.round(data.sy * ratio);
var dx = Math.round(data.dx * ratio);
var dy = Math.round(data.dy * ratio);
var width = Math.round(data.width * ratio);
var height = Math.round(data.height * ratio);
image.onload = function () {
context.drawImage(image,
sx, sy,
width, height,
dx, dy,
width, height
);
loadedCount++;
if (loadedCount === totalCount) {
handler.clearFragments();
var croppedDataUrl = canvas.toDataURL('image/png');
chrome.tabs.create({
url: croppedDataUrl,
windowId: sender.tab.windowId
});
}
};
image.src = data.dataURI;
});
}
console.log(fragments);
},
};
// handle message from tabs
chrome.runtime.onMessage.addListener(function (message, sender, callback) {
console.log(message);
if (!sender || sender.id !== chrome.runtime.id || !sender.tab) {
return;
}
var action = message.action;
if (action && handler[action]) {
return handler[action](message, sender, callback);
}
});
| bubkoo/crx-element-capture | src/js/background.js | JavaScript | mit | 4,787 |
<?php return array(
'plugin.connectedSite.ConnectedServices'=>'Services connectés',
);
| christophehurpeau/Springbok-Framework-Plugins | connectedSite/config/lang.fr.php | PHP | mit | 89 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ASPPatterns.Chap5.DependencyInjection.Model
{
public class Product
{
public void AdjustPriceWith(IProductDiscountStrategy discount)
{
}
}
}
| liqipeng/helloGithub | Book-Code/ASP.NET Design Pattern/ASPPatternsc05/ASPPatterns.Chap5.DependencyInjection/ASPPatterns.Chap5.DependencyInjection.Model/Product.cs | C# | mit | 289 |
class Tagging
include DataMapper::Resource
property :id, Serial
property :tag_id, Integer, :nullable => false
property :taggable_id, Integer, :nullable => false
property :taggable_type, String, :nullable => false
property :tag_context, String, :nullable => false
belongs_to :tag
def taggable
eval("#{taggable_type}.get!(#{taggable_id})") if taggable_type and taggable_id
end
end
| bterlson/dm-more | dm-tags/lib/dm-tags/tagging.rb | Ruby | mit | 428 |
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("_01.Odd_lines")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("_01.Odd_lines")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("f38f3389-37f3-493e-b2ba-8642c2d400b6")]
// 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")]
| todorm85/TelerikAcademy | Courses/Programming/C# Part 2/08. Text Files/01. Odd lines/Properties/AssemblyInfo.cs | C# | mit | 1,402 |
package com.vk.api.sdk.objects.users;
import com.google.gson.annotations.SerializedName;
import java.util.Objects;
/**
* UserXtrCounters object
*/
public class UserXtrCounters extends UserFull {
@SerializedName("counters")
private UserCounters counters;
public UserCounters getCounters() {
return counters;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), counters);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
UserXtrCounters userXtrCounters = (UserXtrCounters) o;
return Objects.equals(counters, userXtrCounters.counters);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("UserXtrCounters{");
sb.append("counters=").append(counters);
sb.append('}');
return sb.toString();
}
}
| kokorin/vk-java-sdk | sdk/src/main/java/com/vk/api/sdk/objects/users/UserXtrCounters.java | Java | mit | 1,010 |
declare module "electron-builder-http/out/CancellationToken" {
/// <reference types="node" />
import { EventEmitter } from "events"
export class CancellationToken extends EventEmitter {
private parentCancelHandler
private _cancelled
readonly cancelled: boolean
private _parent
parent: CancellationToken
constructor(parent?: CancellationToken)
cancel(): void
private onCancel(handler)
createPromise<R>(callback: (resolve: (thenableOrResult?: R) => void, reject: (error?: Error) => void, onCancel: (callback: () => void) => void) => void): Promise<R>
private removeParentCancelHandler()
dispose(): void
}
export class CancellationError extends Error {
constructor()
}
}
declare module "electron-builder-http/out/ProgressCallbackTransform" {
/// <reference types="node" />
import { Transform } from "stream"
import { CancellationToken } from "electron-builder-http/out/CancellationToken"
export interface ProgressInfo {
total: number
delta: number
transferred: number
percent: number
bytesPerSecond: number
}
export class ProgressCallbackTransform extends Transform {
private readonly total
private readonly cancellationToken
private readonly onProgress
private start
private transferred
private delta
private nextUpdate
constructor(total: number, cancellationToken: CancellationToken, onProgress: (info: ProgressInfo) => any)
_transform(chunk: any, encoding: string, callback: Function): void
_flush(callback: Function): void
}
}
declare module "electron-builder-http/out/publishOptions" {
export type PublishProvider = "github" | "bintray" | "s3" | "generic"
export type AllPublishOptions = string | GithubOptions | S3Options | GenericServerOptions | BintrayOptions
export type Publish = AllPublishOptions | Array<AllPublishOptions> | null
/**
* Can be specified in the [config](https://github.com/electron-userland/electron-builder/wiki/Options#Config) or any platform- or target- specific options.
*
* If `GH_TOKEN` is set — defaults to `[{provider: "github"}]`.
*
* If `BT_TOKEN` is set and `GH_TOKEN` is not set — defaults to `[{provider: "bintray"}]`.
*/
export interface PublishConfiguration {
/**
* The provider.
*/
readonly provider: PublishProvider
/**
* The owner.
*/
readonly owner?: string | null
readonly token?: string | null
}
/**
* GitHub options.
*
* GitHub [personal access token](https://help.github.com/articles/creating-an-access-token-for-command-line-use/) is required. You can generate by going to [https://github.com/settings/tokens/new](https://github.com/settings/tokens/new). The access token should have the repo scope/permission.
* Define `GH_TOKEN` environment variable.
*/
export interface GithubOptions extends PublishConfiguration {
/**
* The repository name. [Detected automatically](#github-repository-and-bintray-package).
*/
readonly repo?: string | null
/**
* Whether to use `v`-prefixed tag name.
* @default true
*/
readonly vPrefixedTagName?: boolean
/**
* The host (including the port if need).
* @default github.com
*/
readonly host?: string | null
/**
* The protocol. GitHub Publisher supports only `https`.
* @default https
*/
readonly protocol?: "https" | "http" | null
/**
* The access token to support auto-update from private github repositories. Never specify it in the configuration files. Only for [setFeedURL](module:electron-updater/out/AppUpdater.AppUpdater+setFeedURL).
*/
readonly token?: string | null
/**
* Whether to use private github auto-update provider if `GH_TOKEN` environment variable is set.
* @see https://github.com/electron-userland/electron-builder/wiki/Auto-Update#private-github-update-repo
*/
readonly private?: boolean | null
}
export function githubUrl(options: GithubOptions): string
/**
* Generic (any HTTP(S) server) options.
*/
export interface GenericServerOptions extends PublishConfiguration {
/**
* The base url. e.g. `https://bucket_name.s3.amazonaws.com`. You can use `${os}` (expanded to `mac`, `linux` or `win` according to target platform) and `${arch}` macros.
*/
readonly url: string
/**
* The channel.
* @default latest
*/
readonly channel?: string | null
}
/**
* Amazon S3 options. `https` must be used, so, if you use direct Amazon S3 endpoints, format `https://s3.amazonaws.com/bucket_name` [must be used](http://stackoverflow.com/a/11203685/1910191). And do not forget to make files/directories public.
*
* AWS credentials are required, please see [getting your credentials](http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-your-credentials.html).
* Define `AWS_SECRET_ACCESS_KEY` and `AWS_ACCESS_KEY_ID` [environment variables](http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-environment.html). Or in the [~/.aws/credentials](http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-shared.html).
*/
export interface S3Options extends PublishConfiguration {
/**
* The bucket name.
*/
readonly bucket: string
/**
* The directory path.
* @default /
*/
readonly path?: string | null
/**
* The region. Is determined and set automatically when publishing.
*/
readonly region?: string | null
/**
* The channel.
* @default latest
*/
readonly channel?: string | null
/**
* The ACL.
* @default public-read
*/
readonly acl?: "private" | "public-read" | null
/**
* The type of storage to use for the object.
* @default STANDARD
*/
readonly storageClass?: "STANDARD" | "REDUCED_REDUNDANCY" | "STANDARD_IA" | null
}
export function s3Url(options: S3Options): string
/**
* Bintray options.
*/
export interface BintrayOptions extends PublishConfiguration {
/**
* The Bintray package name.
*/
readonly package?: string | null
/**
* The Bintray repository name.
* @default generic
*/
readonly repo?: string | null
/**
* The Bintray user account. Used in cases where the owner is an organization.
*/
readonly user?: string | null
}
export interface VersionInfo {
/**
* The version.
*/
readonly version: string
}
export interface UpdateInfo extends VersionInfo {
readonly path: string
readonly githubArtifactName?: string | null
readonly sha2: string
/**
* The release name.
*/
readonly releaseName?: string | null
/**
* The release notes.
*/
readonly releaseNotes?: string | null
/**
* The release date.
*/
readonly releaseDate: string
}
}
declare module "electron-builder-http" {
/// <reference types="node" />
import { EventEmitter } from "events"
import { RequestOptions } from "http"
import { CancellationToken } from "electron-builder-http/out/CancellationToken"
import { ProgressInfo } from "electron-builder-http/out/ProgressCallbackTransform"
export interface RequestHeaders {
[key: string]: any
}
export interface Response extends EventEmitter {
statusCode?: number
statusMessage?: string
headers: any
setEncoding(encoding: string): void
}
export interface DownloadOptions {
readonly headers?: RequestHeaders | null
readonly skipDirCreation?: boolean
readonly sha2?: string | null
readonly cancellationToken: CancellationToken
onProgress?(progress: ProgressInfo): void
}
export class HttpExecutorHolder {
private _httpExecutor
httpExecutor: HttpExecutor<any, any>
}
export const executorHolder: HttpExecutorHolder
export function download(url: string, destination: string, options?: DownloadOptions | null): Promise<string>
export class HttpError extends Error {
readonly response: {
statusMessage?: string | undefined
statusCode?: number | undefined
headers?: {
[key: string]: string[]
} | undefined
}
description: any | null
constructor(response: {
statusMessage?: string | undefined
statusCode?: number | undefined
headers?: {
[key: string]: string[]
} | undefined
}, description?: any | null)
}
export abstract class HttpExecutor<REQUEST_OPTS, REQUEST> {
protected readonly maxRedirects: number
request<T>(options: RequestOptions, cancellationToken: CancellationToken, data?: {
[name: string]: any
} | null): Promise<T>
protected abstract doApiRequest<T>(options: REQUEST_OPTS, cancellationToken: CancellationToken, requestProcessor: (request: REQUEST, reject: (error: Error) => void) => void, redirectCount: number): Promise<T>
abstract download(url: string, destination: string, options: DownloadOptions): Promise<string>
protected handleResponse(response: Response, options: RequestOptions, cancellationToken: CancellationToken, resolve: (data?: any) => void, reject: (error: Error) => void, redirectCount: number, requestProcessor: (request: REQUEST, reject: (error: Error) => void) => void): void
protected abstract doRequest(options: any, callback: (response: any) => void): any
protected doDownload(requestOptions: any, destination: string, redirectCount: number, options: DownloadOptions, callback: (error: Error | null) => void, onCancel: (callback: () => void) => void): void
protected addTimeOutHandler(request: any, callback: (error: Error) => void): void
}
export function request<T>(options: RequestOptions, cancellationToken: CancellationToken, data?: {
[name: string]: any
} | null): Promise<T>
export function configureRequestOptions(options: RequestOptions, token?: string | null, method?: "GET" | "DELETE" | "PUT"): RequestOptions
export function dumpRequestOptions(options: RequestOptions): string
}
declare module "electron-builder-http/out/bintray" {
import { BintrayOptions } from "electron-builder-http/out/publishOptions"
import { CancellationToken } from "electron-builder-http/out/CancellationToken"
export function bintrayRequest<T>(path: string, auth: string | null, data: {
[name: string]: any
} | null | undefined, cancellationToken: CancellationToken, method?: "GET" | "DELETE" | "PUT"): Promise<T>
export interface Version {
readonly name: string
readonly package: string
}
export interface File {
name: string
path: string
sha1: string
sha256: string
}
export class BintrayClient {
private readonly cancellationToken
private readonly basePath
readonly auth: string | null
readonly repo: string
readonly owner: string
readonly user: string
readonly packageName: string
constructor(options: BintrayOptions, cancellationToken: CancellationToken, apiKey?: string | null)
getVersion(version: string): Promise<Version>
getVersionFiles(version: string): Promise<Array<File>>
createVersion(version: string): Promise<any>
deleteVersion(version: string): Promise<any>
}
}
| eyang414/superFriend | electronApp/node_modules/electron-builder-http/out/electron-builder-http.d.ts | TypeScript | mit | 11,265 |
<?php
/* :menu:show.html.twig */
class __TwigTemplate_c6c87740e1e23e28cd7ec08186f946f29f7e280dd27072f88536dcc022e66357 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("base.html.twig", ":menu:show.html.twig", 1);
$this->blocks = array(
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "base.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_body($context, array $blocks = array())
{
// line 4
echo " <h1>Menu</h1>
<div align=\"right\">
<a href=\"";
// line 9
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("menu_index", array("id" => $this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "id", array()))), "html", null, true);
echo "\">Volver
<span class=\"glyphicon glyphicon-arrow-left\"></span>
</a>
</div>
<div class=\"page-container\">
<div class=\"row\">
<div class=\"col-md-12\">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class=\"portlet light bordered\">
<div class=\"portlet-title\">
<div class=\"caption font-green\">
<i class=\"icon-settings font-green\"></i>
<span class=\"caption-subject bold uppercase\"></span>
</div>
</div>
<div class=\"portlet-body\">
<table class=\"table table-striped table-bordered table-hover dt-responsive\" width=\"100%\" id=\"sample_2\">
<tr>
<th>Descripcion</th>
<td>";
// line 29
echo $this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "descripcion", array());
echo "</td>
</tr>
<tr>
<th>Visible</th>
<td>";
// line 34
if ($this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "visible", array())) {
echo "Sí";
} else {
echo "No";
}
echo "</td>
</tr>
<tr>
<th>Posicion</th>
<td>";
// line 38
if ($this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "posicion", array())) {
echo "Sí";
} else {
echo "No";
}
echo "</td>
</tr>
<tr>
<th>Enlace</th>
<td>";
// line 42
if ($this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "enlace", array())) {
echo "Sí";
} else {
echo "No";
}
echo "</td>
</tr>
<tr>
<th>Id</th>
<td>";
// line 47
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "id", array()), "html", null, true);
echo "</td>
</tr>
</table>
</div>
</div>
<!-- END EXAMPLE TABLE PORTLET-->
</div>
</div>
<!-- END CONTENT BODY -->
</div>
<div align=\"right\">
";
// line 63
echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["delete_form"]) ? $context["delete_form"] : null), 'form_start');
echo "
<a href=\"";
// line 64
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("menu_edit", array("id" => $this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "id", array()))), "html", null, true);
echo "\" class=\"btn btn-info\" role=\"button\">Editar</a>
<input type=\"submit\" class=\"btn btn-danger\" value=\"Eliminar\">
<!--input type=\"submit\" value=\"Eliminar\"-->
</button>
";
// line 69
echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["delete_form"]) ? $context["delete_form"] : null), 'form_end');
echo "
</div>
";
}
public function getTemplateName()
{
return ":menu:show.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 134 => 69, 126 => 64, 122 => 63, 103 => 47, 91 => 42, 80 => 38, 69 => 34, 61 => 29, 38 => 9, 31 => 4, 28 => 3, 11 => 1,);
}
}
/* {% extends 'base.html.twig' %}*/
/* */
/* {% block body %}*/
/* <h1>Menu</h1>*/
/* */
/* */
/* */
/* <div align="right">*/
/* <a href="{{ path('menu_index', { 'id': menu.id }) }}">Volver*/
/* <span class="glyphicon glyphicon-arrow-left"></span>*/
/* </a> */
/* </div>*/
/* <div class="page-container">*/
/* */
/* <div class="row">*/
/* <div class="col-md-12">*/
/* <!-- BEGIN EXAMPLE TABLE PORTLET-->*/
/* <div class="portlet light bordered">*/
/* <div class="portlet-title">*/
/* <div class="caption font-green">*/
/* <i class="icon-settings font-green"></i>*/
/* <span class="caption-subject bold uppercase"></span>*/
/* </div> */
/* </div> */
/* <div class="portlet-body">*/
/* <table class="table table-striped table-bordered table-hover dt-responsive" width="100%" id="sample_2">*/
/* <tr>*/
/* <th>Descripcion</th>*/
/* <td>{{ menu.descripcion | raw}}</td>*/
/* </tr>*/
/* */
/* <tr>*/
/* <th>Visible</th>*/
/* <td>{% if menu.visible %}Sí{% else %}No{% endif %}</td>*/
/* </tr>*/
/* <tr>*/
/* <th>Posicion</th>*/
/* <td>{% if menu.posicion %}Sí{% else %}No{% endif %}</td>*/
/* </tr>*/
/* <tr>*/
/* <th>Enlace</th>*/
/* <td>{% if menu.enlace %}Sí{% else %}No{% endif %}</td>*/
/* </tr>*/
/* */
/* <tr>*/
/* <th>Id</th>*/
/* <td>{{ menu.id }}</td>*/
/* </tr>*/
/* </table>*/
/* */
/* </div>*/
/* </div> */
/* <!-- END EXAMPLE TABLE PORTLET-->*/
/* </div>*/
/* */
/* </div>*/
/* <!-- END CONTENT BODY -->*/
/* </div> */
/* */
/* */
/* <div align="right">*/
/* */
/* {{ form_start(delete_form) }}*/
/* <a href="{{ path('menu_edit', { 'id': menu.id }) }}" class="btn btn-info" role="button">Editar</a>*/
/* */
/* <input type="submit" class="btn btn-danger" value="Eliminar">*/
/* <!--input type="submit" value="Eliminar"-->*/
/* </button>*/
/* {{ form_end(delete_form) }} */
/* */
/* </div>*/
/* */
/* */
/* */
/* */
/* */
/* {% endblock %}*/
/* */
| mwveliz/sitio | app/prod/cache/twig/b4/b462afc70965e9a17df2a81b97874458452b1f180b2dd42f516196f0e7c44238.php | PHP | mit | 9,504 |
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\View\Widget;
use Cake\View\Form\ContextInterface;
use Cake\View\Helper\IdGeneratorTrait;
use Cake\View\StringTemplate;
/**
* Input widget class for generating multiple checkboxes.
*/
class MultiCheckboxWidget implements WidgetInterface
{
use IdGeneratorTrait;
/**
* Template instance to use.
*
* @var \Cake\View\StringTemplate
*/
protected $_templates;
/**
* Label widget instance.
*
* @var \Cake\View\Widget\LabelWidget
*/
protected $_label;
/**
* Render multi-checkbox widget.
*
* This class uses the following templates:
*
* - `checkbox` Renders checkbox input controls. Accepts
* the `name`, `value` and `attrs` variables.
* - `checkboxWrapper` Renders the containing div/element for
* a checkbox and its label. Accepts the `input`, and `label`
* variables.
* - `multicheckboxWrapper` Renders a wrapper around grouped inputs.
* - `multicheckboxTitle` Renders the title element for grouped inputs.
*
* @param \Cake\View\StringTemplate $templates Templates list.
* @param \Cake\View\Widget\LabelWidget $label Label widget instance.
*/
public function __construct(StringTemplate $templates, LabelWidget $label)
{
$this->_templates = $templates;
$this->_label = $label;
}
/**
* Render multi-checkbox widget.
*
* Data supports the following options.
*
* - `name` The name attribute of the inputs to create.
* `[]` will be appended to the name.
* - `options` An array of options to create checkboxes out of.
* - `val` Either a string/integer or array of values that should be
* checked. Can also be a complex options set.
* - `disabled` Either a boolean or an array of checkboxes to disable.
* - `escape` Set to false to disable HTML escaping.
* - `options` An associative array of value=>labels to generate options for.
* - `idPrefix` Prefix for generated ID attributes.
*
* ### Options format
*
* The options option can take a variety of data format depending on
* the complexity of HTML you want generated.
*
* You can generate simple options using a basic associative array:
*
* ```
* 'options' => ['elk' => 'Elk', 'beaver' => 'Beaver']
* ```
*
* If you need to define additional attributes on your option elements
* you can use the complex form for options:
*
* ```
* 'options' => [
* ['value' => 'elk', 'text' => 'Elk', 'data-foo' => 'bar'],
* ]
* ```
*
* This form **requires** that both the `value` and `text` keys be defined.
* If either is not set options will not be generated correctly.
*
* @param array $data The data to generate a checkbox set with.
* @param \Cake\View\Form\ContextInterface $context The current form context.
* @return string
*/
public function render(array $data, ContextInterface $context): string
{
$data += [
'name' => '',
'escape' => true,
'options' => [],
'disabled' => null,
'val' => null,
'idPrefix' => null,
'templateVars' => [],
'label' => true,
];
$this->_idPrefix = $data['idPrefix'];
$this->_clearIds();
return implode('', $this->_renderInputs($data, $context));
}
/**
* Render the checkbox inputs.
*
* @param array $data The data array defining the checkboxes.
* @param \Cake\View\Form\ContextInterface $context The current form context.
* @return array An array of rendered inputs.
*/
protected function _renderInputs(array $data, ContextInterface $context): array
{
$out = [];
foreach ($data['options'] as $key => $val) {
// Grouped inputs in a fieldset.
if (is_string($key) && is_array($val) && !isset($val['text'], $val['value'])) {
$inputs = $this->_renderInputs(['options' => $val] + $data, $context);
$title = $this->_templates->format('multicheckboxTitle', ['text' => $key]);
$out[] = $this->_templates->format('multicheckboxWrapper', [
'content' => $title . implode('', $inputs),
]);
continue;
}
// Standard inputs.
$checkbox = [
'value' => $key,
'text' => $val,
];
if (is_array($val) && isset($val['text'], $val['value'])) {
$checkbox = $val;
}
if (!isset($checkbox['templateVars'])) {
$checkbox['templateVars'] = $data['templateVars'];
}
if (!isset($checkbox['label'])) {
$checkbox['label'] = $data['label'];
}
if (!empty($data['templateVars'])) {
$checkbox['templateVars'] = array_merge($data['templateVars'], $checkbox['templateVars']);
}
$checkbox['name'] = $data['name'];
$checkbox['escape'] = $data['escape'];
$checkbox['checked'] = $this->_isSelected((string)$checkbox['value'], $data['val']);
$checkbox['disabled'] = $this->_isDisabled((string)$checkbox['value'], $data['disabled']);
if (empty($checkbox['id'])) {
if (isset($data['id'])) {
$checkbox['id'] = $data['id'] . '-' . trim(
$this->_idSuffix((string)$checkbox['value']),
'-'
);
} else {
$checkbox['id'] = $this->_id($checkbox['name'], (string)$checkbox['value']);
}
}
$out[] = $this->_renderInput($checkbox + $data, $context);
}
return $out;
}
/**
* Render a single checkbox & wrapper.
*
* @param array $checkbox An array containing checkbox key/value option pairs
* @param \Cake\View\Form\ContextInterface $context Context object.
* @return string
*/
protected function _renderInput(array $checkbox, ContextInterface $context): string
{
$input = $this->_templates->format('checkbox', [
'name' => $checkbox['name'] . '[]',
'value' => $checkbox['escape'] ? h($checkbox['value']) : $checkbox['value'],
'templateVars' => $checkbox['templateVars'],
'attrs' => $this->_templates->formatAttributes(
$checkbox,
['name', 'value', 'text', 'options', 'label', 'val', 'type']
),
]);
if ($checkbox['label'] === false && strpos($this->_templates->get('checkboxWrapper'), '{{input}}') === false) {
$label = $input;
} else {
$labelAttrs = is_array($checkbox['label']) ? $checkbox['label'] : [];
$labelAttrs += [
'for' => $checkbox['id'],
'escape' => $checkbox['escape'],
'text' => $checkbox['text'],
'templateVars' => $checkbox['templateVars'],
'input' => $input,
];
if ($checkbox['checked']) {
$labelAttrs = (array)$this->_templates->addClass($labelAttrs, 'selected');
}
$label = $this->_label->render($labelAttrs, $context);
}
return $this->_templates->format('checkboxWrapper', [
'templateVars' => $checkbox['templateVars'],
'label' => $label,
'input' => $input,
]);
}
/**
* Helper method for deciding what options are selected.
*
* @param string $key The key to test.
* @param array|string|null $selected The selected values.
* @return bool
*/
protected function _isSelected(string $key, $selected): bool
{
if ($selected === null) {
return false;
}
if (!is_array($selected)) {
return $key === (string)$selected;
}
$strict = !is_numeric($key);
return in_array($key, $selected, $strict);
}
/**
* Helper method for deciding what options are disabled.
*
* @param string $key The key to test.
* @param mixed $disabled The disabled values.
* @return bool
*/
protected function _isDisabled(string $key, $disabled): bool
{
if ($disabled === null || $disabled === false) {
return false;
}
if ($disabled === true || is_string($disabled)) {
return true;
}
$strict = !is_numeric($key);
return in_array($key, $disabled, $strict);
}
/**
* @inheritDoc
*/
public function secureFields(array $data): array
{
return [$data['name']];
}
}
| dakota/cakephp | src/View/Widget/MultiCheckboxWidget.php | PHP | mit | 9,482 |
package de.henningBrinkmann.mybatisSample.mapper;
import org.apache.ibatis.annotations.Select;
import de.henningBrinkmann.mybatisSample.xmltv.Description;
public interface DescriptionMapper {
void insertDescription(Description description);
@Select("SELECT * FROM mybatissample.description WHERE `value` = #{value};")
Description findDescriptionByValue(String value);
}
| hebrinkmann/mybatis | src/main/java/de/henningBrinkmann/mybatisSample/mapper/DescriptionMapper.java | Java | mit | 378 |
package com.chernowii.hero4;
import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class OCVideo extends Activity {
public static String getFileContents(final File file) throws IOException {
final InputStream inputStream = new FileInputStream(file);
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
final StringBuilder stringBuilder = new StringBuilder();
boolean done = false;
while (!done) {
final String line = reader.readLine();
done = (line == null);
if (line != null) {
stringBuilder.append(line);
}
}
reader.close();
inputStream.close();
return stringBuilder.toString();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ocvideo);
String yourFilePath = this.getFilesDir() + "/" + "camconfig.txt";
File yourFile = new File( yourFilePath );
try {
String password = getFileContents(yourFile);
new HttpAsyncTask().execute("http://10.5.5.9/camera/CM?t=" + password + "&p=%00");
} catch (IOException e) {
e.printStackTrace();
}
Intent intentTwo = new Intent(this, MainActivity.class);
startActivity(intentTwo);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_ocvideo, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Done!", Toast.LENGTH_SHORT).show();
;
}
}
}
| KonradIT/goprohero | GoProHERO4Controller/app/src/main/java/com/chernowii/hero4/OCVideo.java | Java | mit | 4,726 |
const isAsync = (caller) => caller && caller.ASYNC;
module.exports = api => {
const ASYNC = api.caller(isAsync);
return {
babelrc: false,
plugins: [
['./babel-plugin-$-identifiers-and-imports', { ASYNC }],
['macros', { async: { ASYNC } }],
// use dead code elimination to clean up if(false) {} and if(true) {}
['minify-dead-code-elimination', { keepFnName: true, keepFnArgs: true, keepClassName: true }],
],
}
}
| sithmel/iter-tools | generate/babel-generate.config.js | JavaScript | mit | 456 |
using System;
using System.Linq;
using System.Threading.Tasks;
using Baseline;
using Marten.Testing.Events;
using Marten.Testing.Events.Projections;
using Marten.Testing.Harness;
using Shouldly;
namespace Marten.Testing.Examples
{
public class event_store_quickstart
{
public void capture_events()
{
#region sample_event-store-quickstart
var store = DocumentStore.For(_ =>
{
_.Connection(ConnectionSource.ConnectionString);
_.Events.Projections.SelfAggregate<QuestParty>();
});
var questId = Guid.NewGuid();
using (var session = store.OpenSession())
{
var started = new QuestStarted { Name = "Destroy the One Ring" };
var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Sam");
// Start a brand new stream and commit the new events as
// part of a transaction
session.Events.StartStream<Quest>(questId, started, joined1);
session.SaveChanges();
// Append more events to the same stream
var joined2 = new MembersJoined(3, "Buckland", "Merry", "Pippen");
var joined3 = new MembersJoined(10, "Bree", "Aragorn");
var arrived = new ArrivedAtLocation { Day = 15, Location = "Rivendell" };
session.Events.Append(questId, joined2, joined3, arrived);
session.SaveChanges();
}
#endregion sample_event-store-quickstart
#region sample_event-store-start-stream-with-explicit-type
using (var session = store.OpenSession())
{
var started = new QuestStarted { Name = "Destroy the One Ring" };
var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Sam");
// Start a brand new stream and commit the new events as
// part of a transaction
session.Events.StartStream(typeof(Quest), questId, started, joined1);
}
#endregion sample_event-store-start-stream-with-explicit-type
#region sample_event-store-start-stream-with-no-type
using (var session = store.OpenSession())
{
var started = new QuestStarted { Name = "Destroy the One Ring" };
var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Sam");
// Start a brand new stream and commit the new events as
// part of a transaction
// no stream type will be stored in database
session.Events.StartStream(questId, started, joined1);
}
#endregion sample_event-store-start-stream-with-no-type
#region sample_events-fetching-stream
using (var session = store.OpenSession())
{
var events = session.Events.FetchStream(questId);
events.Each(evt =>
{
Console.WriteLine($"{evt.Version}.) {evt.Data}");
});
}
#endregion sample_events-fetching-stream
#region sample_events-aggregate-on-the-fly
using (var session = store.OpenSession())
{
// questId is the id of the stream
var party = session.Events.AggregateStream<QuestParty>(questId);
Console.WriteLine(party);
var party_at_version_3 = session.Events
.AggregateStream<QuestParty>(questId, 3);
var party_yesterday = session.Events
.AggregateStream<QuestParty>(questId, timestamp: DateTime.UtcNow.AddDays(-1));
}
#endregion sample_events-aggregate-on-the-fly
using (var session = store.OpenSession())
{
var party = session.Load<QuestParty>(questId);
Console.WriteLine(party);
}
}
#region sample_using-fetch-stream
public void load_event_stream(IDocumentSession session, Guid streamId)
{
// Fetch *all* of the events for this stream
var events1 = session.Events.FetchStream(streamId);
// Fetch the events for this stream up to and including version 5
var events2 = session.Events.FetchStream(streamId, 5);
// Fetch the events for this stream at this time yesterday
var events3 = session.Events
.FetchStream(streamId, timestamp: DateTime.UtcNow.AddDays(-1));
}
public async Task load_event_stream_async(IDocumentSession session, Guid streamId)
{
// Fetch *all* of the events for this stream
var events1 = await session.Events.FetchStreamAsync(streamId);
// Fetch the events for this stream up to and including version 5
var events2 = await session.Events.FetchStreamAsync(streamId, 5);
// Fetch the events for this stream at this time yesterday
var events3 = await session.Events
.FetchStreamAsync(streamId, timestamp: DateTime.UtcNow.AddDays(-1));
}
#endregion sample_using-fetch-stream
#region sample_load-a-single-event
public void load_a_single_event_synchronously(IDocumentSession session, Guid eventId)
{
// If you know what the event type is already
var event1 = session.Events.Load<MembersJoined>(eventId);
// If you do not know what the event type is
var event2 = session.Events.Load(eventId);
}
public async Task load_a_single_event_asynchronously(IDocumentSession session, Guid eventId)
{
// If you know what the event type is already
var event1 = await session.Events.LoadAsync<MembersJoined>(eventId);
// If you do not know what the event type is
var event2 = await session.Events.LoadAsync(eventId);
}
#endregion sample_load-a-single-event
#region sample_using_live_transformed_events
public void using_live_transformed_events(IDocumentSession session)
{
var started = new QuestStarted { Name = "Find the Orb" };
var joined = new MembersJoined { Day = 2, Location = "Faldor's Farm", Members = new string[] { "Garion", "Polgara", "Belgarath" } };
var slayed1 = new MonsterSlayed { Name = "Troll" };
var slayed2 = new MonsterSlayed { Name = "Dragon" };
MembersJoined joined2 = new MembersJoined { Day = 5, Location = "Sendaria", Members = new string[] { "Silk", "Barak" } };
session.Events.StartStream<Quest>(started, joined, slayed1, slayed2);
session.SaveChanges();
// Our MonsterDefeated documents are created inline
// with the SaveChanges() call above and are available
// for querying
session.Query<MonsterDefeated>().Count()
.ShouldBe(2);
}
#endregion sample_using_live_transformed_events
}
}
| JasperFx/Marten | src/Marten.Testing/Examples/event_store_quickstart.cs | C# | mit | 7,180 |
import React from 'react';
import PropTypes from 'prop-types';
import Post from './Post';
const Posts = ({ posts }) => (
<div>
{posts
.filter(post => post.frontmatter.title.length > 0)
.map((post, index) => <Post key={index} post={post} />)}
</div>
);
Posts.propTypes = {
posts: PropTypes.arrayOf(PropTypes.object),
};
export default Posts;
| kbariotis/kostasbariotis.com | src/components/blog/Posts.js | JavaScript | mit | 367 |
require 'bio-ucsc'
describe "Bio::Ucsc::Hg18::BurgeRnaSeqGemMapperAlignBreastAllRawSignal" do
describe "#find_by_interval" do
context "given range chr1:1-10,000" do
it 'returns a record (r.chrom == "chr1")' do
Bio::Ucsc::Hg18::DBConnection.default
Bio::Ucsc::Hg18::DBConnection.connect
i = Bio::GenomicInterval.parse("chr1:1-10,000")
r = Bio::Ucsc::Hg18::BurgeRnaSeqGemMapperAlignBreastAllRawSignal.find_by_interval(i)
r.chrom.should == "chr1"
end
end
end
end
| misshie/bioruby-ucsc-api | spec/hg18/burgernaseqgemmapperalignbreastallrawsignal_spec.rb | Ruby | mit | 527 |
/**
The MIT License (MIT) * Copyright (c) 2016 铭飞科技
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/package com.mingsoft.people.dao;
import org.apache.ibatis.annotations.Param;
import com.mingsoft.base.dao.IBaseDao;
/**
*
*
* <p>
* <b>铭飞MS平台</b>
* </p>
*
* <p>
* Copyright: Copyright (c) 2014 - 2015
* </p>
*
* <p>
* Company:景德镇铭飞科技有限公司
* </p>
*
* @author 刘继平
*
* @version 300-001-001
*
* <p>
* 版权所有 铭飞科技
* </p>
*
* <p>
* Comments:用户信息持久化层接口,继承IBaseDao
* </p>
*
* <p>
* Create Date:2014-9-4
* </p>
*
* <p>
* Modification history:
* </p>
*/
public interface IPeopleUserDao extends IBaseDao {
/**
* 根据用户id集合批量删除用户
* @param peopleIds 用户id集合
*/
public void deletePeopleUsers(@Param("peopleIds") int[] peopleIds);
}
| shentt3214/mcms | src/main/java/com/mingsoft/people/dao/IPeopleUserDao.java | Java | mit | 1,907 |
from BeautifulSoup import BeautifulSoup as b
from collections import Counter
import urllib2, numpy
import matplotlib.pyplot as plt
response = urllib2.urlopen('http://en.wikipedia.org/wiki/List_of_Question_Time_episodes')
html = response.read()
soup = b(html)
people = []
tables = soup.findAll('table','wikitable')[2:] #First two tables are other content
year_headers = soup.findAll('h2')[2:-4] # Likewise with headers
years = []
for year in year_headers:
spans = year.findAll('span')
years.append(int(spans[0].text))
for i, table in enumerate(tables[-10:]):
print i
for row in table.findAll('tr'):
cols = row.findAll('td')
if len(cols) >= 3:
names = cols[2]
nstring = names.getText().split(',')
for name in nstring:
people.append(name)
else:
continue
counts = Counter(people)
order = numpy.argsort(counts.values())
names = numpy.array(counts.keys())[order][::-1]
appearances = numpy.array(counts.values())[order][::-1]
N = 20
app_percentage = (appearances[:N] / float(numpy.sum(appearances[:N]))) * 100
index = numpy.arange(N)+0.25
bar_width = 0.5
"""
PLOT THAT SHIT
"""
Fig = plt.figure(figsize=(10,6))
Ax = Fig.add_subplot(111)
Apps = Ax.bar(index,app_percentage,bar_width, color='dodgerblue',alpha=0.8,linewidth=0)
Ax.set_xticks(index+ 0.5*bar_width)
Ax.set_xticklabels(names[:N],rotation=90)
Ax.set_ylabel('Appearance Percentage')
amin,amax = numpy.min(app_percentage), numpy.max(app_percentage)
def autolabel(Bars):
# attach some text labels
for Bar in Bars:
height = Bar.get_height()
Ax.text(Bar.get_x()+Bar.get_width()/2., 1.03*height, '%.1f'%float(height),
ha='center', va='bottom',fontsize=9)
autolabel(Apps)
Ax.set_ylim([amin-1,amax+1])
Ax.set_title('Top '+str(N)+' QT guests')
Fig.subplots_adjust(bottom=0.26,right=0.95,left=0.07)
Fig.savefig('QTappearances.png',fmt='png')
plt.show() | dunkenj/DimbleData | QTstats.py | Python | mit | 1,981 |
'use strict';
const Promise = require('bluebird');
const { Transform } = require('readable-stream');
const vfs = require('vinyl-fs');
module.exports = function assets(src, dest, options = {}) {
const { parser, env } = options;
Reflect.deleteProperty(options, 'parser');
Reflect.deleteProperty(options, 'env');
const opts = Object.assign({ allowEmpty: true }, options);
return new Promise((resolve, reject) => {
let stream = vfs.src(src, opts);
if (parser) {
const transform = new Transform({
objectMode: true,
transform: (file, enc, cb) => {
parser(file, enc, env);
return cb(null, file);
},
});
stream = stream.pipe(transform);
}
stream.pipe(vfs.dest(dest)).on('error', reject).on('finish', resolve);
});
};
| oddbird/sassdoc-theme-herman | lib/utils/assets.js | JavaScript | mit | 801 |
// 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 <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "db.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, hashGenesisBlockOfficial )
;
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, hashGenesisBlockTestNet )
;
bool CheckHardened(int nHeight, const uint256& hash)
{
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
// nexus: synchronized checkpoint (centrally broadcasted)
uint256 hashSyncCheckpoint = 0;
uint256 hashPendingCheckpoint = 0;
CSyncCheckpoint checkpointMessage;
CSyncCheckpoint checkpointMessagePending;
uint256 hashInvalidCheckpoint = 0;
CCriticalSection cs_hashSyncCheckpoint;
// nexus: get last synchronized checkpoint
CBlockIndex* GetLastSyncCheckpoint()
{
LOCK(cs_hashSyncCheckpoint);
if (!mapBlockIndex.count(hashSyncCheckpoint))
error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
else
return mapBlockIndex[hashSyncCheckpoint];
return NULL;
}
// nexus: only descendant of current sync-checkpoint is allowed
bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
{
if (!mapBlockIndex.count(hashSyncCheckpoint))
return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
if (!mapBlockIndex.count(hashCheckpoint))
return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
{
// Received an older checkpoint, trace back from current checkpoint
// to the same height of the received checkpoint to verify
// that current checkpoint should be a descendant block
CBlockIndex* pindex = pindexSyncCheckpoint;
while (pindex->nHeight > pindexCheckpointRecv->nHeight)
if (!(pindex = pindex->pprev))
return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
if (pindex->GetBlockHash() != hashCheckpoint)
{
hashInvalidCheckpoint = hashCheckpoint;
return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
}
return false; // ignore older checkpoint
}
// Received checkpoint should be a descendant block of the current
// checkpoint. Trace back to the same height of current checkpoint
// to verify.
CBlockIndex* pindex = pindexCheckpointRecv;
while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
if (!(pindex = pindex->pprev))
return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
if (pindex->GetBlockHash() != hashSyncCheckpoint)
{
hashInvalidCheckpoint = hashCheckpoint;
return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
}
return true;
}
bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
{
CTxDB txdb;
txdb.TxnBegin();
if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
{
txdb.TxnAbort();
return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
}
if (!txdb.TxnCommit())
return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
txdb.Close();
Checkpoints::hashSyncCheckpoint = hashCheckpoint;
return true;
}
bool AcceptPendingSyncCheckpoint()
{
LOCK(cs_hashSyncCheckpoint);
if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
{
if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
{
hashPendingCheckpoint = 0;
checkpointMessagePending.SetNull();
return false;
}
CTxDB txdb;
CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
if (!pindexCheckpoint->IsInMainChain())
{
CBlock block;
if (!block.ReadFromDisk(pindexCheckpoint))
return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
if (!block.SetBestChain(txdb, pindexCheckpoint))
{
hashInvalidCheckpoint = hashPendingCheckpoint;
return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
}
}
txdb.Close();
if (!WriteSyncCheckpoint(hashPendingCheckpoint))
return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
hashPendingCheckpoint = 0;
checkpointMessage = checkpointMessagePending;
checkpointMessagePending.SetNull();
printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
// relay the checkpoint
if (!checkpointMessage.IsNull())
{
BOOST_FOREACH(CNode* pnode, vNodes)
checkpointMessage.RelayTo(pnode);
}
return true;
}
return false;
}
// Automatically select a suitable sync-checkpoint
uint256 AutoSelectSyncCheckpoint()
{
// Proof-of-work blocks are immediately checkpointed
// to defend against 51% attack which rejects other miners block
// Select the last proof-of-work block
const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
// Search forward for a block within max span and maturity window
while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
pindex = pindex->pnext;
return pindex->GetBlockHash();
}
// Check against synchronized checkpoint
bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
{
if (fTestNet) return true; // Testnet has no checkpoints
int nHeight = pindexPrev->nHeight + 1;
LOCK(cs_hashSyncCheckpoint);
// sync-checkpoint should always be accepted block
assert(mapBlockIndex.count(hashSyncCheckpoint));
const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
if (nHeight > pindexSync->nHeight)
{
// trace back to same height as sync-checkpoint
const CBlockIndex* pindex = pindexPrev;
while (pindex->nHeight > pindexSync->nHeight)
if (!(pindex = pindex->pprev))
return error("CheckSync: pprev null - block index structure failure");
if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
return false; // only descendant of sync-checkpoint can pass check
}
if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
return false; // same height with sync-checkpoint
if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
return false; // lower height than sync-checkpoint
return true;
}
bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
{
LOCK(cs_hashSyncCheckpoint);
if (hashPendingCheckpoint == 0)
return false;
if (hashBlock == hashPendingCheckpoint)
return true;
if (mapOrphanBlocks.count(hashPendingCheckpoint)
&& hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
return true;
return false;
}
// nexus: reset synchronized checkpoint to last hardened checkpoint
bool ResetSyncCheckpoint()
{
LOCK(cs_hashSyncCheckpoint);
const uint256& hash = mapCheckpoints.rbegin()->second;
if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
{
// checkpoint block accepted but not yet in main chain
printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
CTxDB txdb;
CBlock block;
if (!block.ReadFromDisk(mapBlockIndex[hash]))
return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
{
return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
}
txdb.Close();
}
else if(!mapBlockIndex.count(hash))
{
// checkpoint block not yet accepted
hashPendingCheckpoint = hash;
checkpointMessagePending.SetNull();
printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
}
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
{
if (!WriteSyncCheckpoint(hash))
return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
return true;
}
}
return false;
}
void AskForPendingSyncCheckpoint(CNode* pfrom)
{
LOCK(cs_hashSyncCheckpoint);
if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
}
bool SetCheckpointPrivKey(std::string strPrivKey)
{
// Test signing a sync-checkpoint with genesis block
CSyncCheckpoint checkpoint;
checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedSyncCheckpoint)checkpoint;
checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
CKey key;
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
return false;
// Test signing successful, proceed
CSyncCheckpoint::strMasterPrivKey = strPrivKey;
return true;
}
bool SendSyncCheckpoint(uint256 hashCheckpoint)
{
CSyncCheckpoint checkpoint;
checkpoint.hashCheckpoint = hashCheckpoint;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedSyncCheckpoint)checkpoint;
checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
if (CSyncCheckpoint::strMasterPrivKey.empty())
return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
CKey key;
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
if(!checkpoint.ProcessSyncCheckpoint(NULL))
{
printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
return false;
}
// Relay checkpoint
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
return true;
}
// Is the sync-checkpoint outside maturity window?
bool IsMatureSyncCheckpoint()
{
LOCK(cs_hashSyncCheckpoint);
// sync-checkpoint should always be accepted block
assert(mapBlockIndex.count(hashSyncCheckpoint));
const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
}
// Is the sync-checkpoint too old?
bool IsSyncCheckpointTooOld(unsigned int nSeconds)
{
LOCK(cs_hashSyncCheckpoint);
// sync-checkpoint should always be accepted block
assert(mapBlockIndex.count(hashSyncCheckpoint));
const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
}
}
// nexus: sync-checkpoint master key
const std::string CSyncCheckpoint::strMasterPubKey = "0489cab128b9f39a3e514a12c07a7644fa1808662195edcf2d4671b1cce76868b7f2f588a9dfad5753be3cd6b8e9518be439c936e2bad93a25bb6d32300fab41c3";
std::string CSyncCheckpoint::strMasterPrivKey = "";
// nexus: verify signature of sync-checkpoint message
bool CSyncCheckpoint::CheckSignature()
{
CKey key;
if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
// Now unserialize the data
CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
sMsg >> *(CUnsignedSyncCheckpoint*)this;
return true;
}
// nexus: process synchronized checkpoint
bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
{
if (!CheckSignature())
return false;
LOCK(Checkpoints::cs_hashSyncCheckpoint);
if (!mapBlockIndex.count(hashCheckpoint))
{
// We haven't received the checkpoint chain, keep the checkpoint as pending
Checkpoints::hashPendingCheckpoint = hashCheckpoint;
Checkpoints::checkpointMessagePending = *this;
printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
// Ask this guy to fill in what we're missing
if (pfrom)
{
pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
// ask directly as well in case rejected earlier by duplicate
// proof-of-stake because getblocks may not get it this time
pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
}
return false;
}
if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
return false;
CTxDB txdb;
CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
if (!pindexCheckpoint->IsInMainChain())
{
// checkpoint chain received but not yet main chain
CBlock block;
if (!block.ReadFromDisk(pindexCheckpoint))
return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
if (!block.SetBestChain(txdb, pindexCheckpoint))
{
Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
}
}
txdb.Close();
if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
Checkpoints::checkpointMessage = *this;
Checkpoints::hashPendingCheckpoint = 0;
Checkpoints::checkpointMessagePending.SetNull();
printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
return true;
}
| Skryptex/Nexus-Proof-of-Stake-Coin | src/checkpoints.cpp | C++ | mit | 18,523 |
package berkeleydb
/*
#cgo LDFLAGS: -ldb
#include <db.h>
#include "bdb.h"
*/
import "C"
type Environment struct {
environ *C.DB_ENV
}
func NewEnvironment() (*Environment, error) {
var env *C.DB_ENV
err := C.db_env_create(&env, 0)
if err > 0 {
return nil, createError(err)
}
return &Environment{env}, nil
}
func (env *Environment) Open(path string, flags C.u_int32_t, fileMode int) error {
mode := C.u_int32_t(fileMode)
err := C.go_env_open(env.environ, C.CString(path), flags, mode)
return createError(err)
}
func (env *Environment) Close() error {
err := C.go_env_close(env.environ, 0)
return createError(err)
}
| technosophos/perkdb | berkeleydb/environment.go | GO | mit | 633 |
<div class="form-group has-warning">
{!! Form::label(
App\Import\Flap\POS_Member\Import::OPTIONS_CATEGORY,
'*任務名稱',
['class' => 'control-label'])
!!}
{!! Form::text(
'name',
$task->name,
['id'=> 'name', 'class' => 'form-control', 'required' => true, 'placeholder' => '請輸入任務名稱'])
!!}
<p class="help-block">{{'任務名稱必須唯一,不可重複'}}</p>
</div>
@if (NULL === $task->id)
<div class="form-group has-warning">
{!! Form::label('file', '*選擇匯入檔案', ['class' => 'control-label']) !!}
<input type="text" readonly class="form-control" placeholder="Browse...">
{!! Form::file(
'file',
['id'=>'excel', 'class' => 'form-control', 'accept' => 'application/vnd.ms-excel'])
!!}
<p class="help-block">{{'請選擇沒有密碼鎖定的 .xls 檔案,並且只留下一個工作表'}}</p>
</div>
@endif
<div class="form-group has-warning">
{!! Form::label(
App\Import\Flap\POS_Member\Import::OPTIONS_CATEGORY,
'*會員類別',
['class' => 'control-label'])
!!}
{!! Form::text(
App\Import\Flap\POS_Member\Import::OPTIONS_CATEGORY,
$task->category,
['id'=>App\Import\Flap\POS_Member\Import::OPTIONS_CATEGORY, 'class' => 'form-control', 'required' => true, 'placeholder' => '請輸入會員類別代號'])
!!}
<p class="help-block">{{'Example: 126'}}</p>
</div>
<div class="form-group has-warning">
{!! Form::label(
App\Import\Flap\POS_Member\Import::OPTIONS_DISTINCTION,
'*會員區別',
['class' => 'control-label'])
!!}
{!! Form::text(
App\Import\Flap\POS_Member\Import::OPTIONS_DISTINCTION,
$task->distinction,
['id'=>App\Import\Flap\POS_Member\Import::OPTIONS_DISTINCTION, 'class' => 'form-control', 'required' => true, 'placeholder' => '請輸入會員區別代號'])
!!}
<p class="help-block">{{'Example: 126-75'}}</p>
</div>
<div class="form-group">
{!! Form::label(
App\Import\Flap\POS_Member\Import::OPTIONS_INSERTFLAG,
'請參考提示輸入旗標',
['class' => 'control-label'])
!!}
{!! Form::text(
App\Import\Flap\POS_Member\Import::OPTIONS_INSERTFLAG,
$task->getInsertFlagString(),
['id'=>App\Import\Flap\POS_Member\Import::OPTIONS_INSERTFLAG, 'class' => 'form-control'])
!!}
<p class="help-block"><b>11:A 5:B</b> (旗標 11 設定為A, 旗標 5 設定為 B,使用空白區隔)</p>
</div>
<div class="form-group">
{!! Form::label(
App\Import\Flap\POS_Member\Import::OPTIONS_UPDATEFLAG,
'請參考提示輸入重覆比對旗標',
['class' => 'control-label'])
!!}
{!! Form::text(
App\Import\Flap\POS_Member\Import::OPTIONS_UPDATEFLAG,
$task->getUpdateFlagString(),
['id'=> App\Import\Flap\POS_Member\Import::OPTIONS_UPDATEFLAG, 'class' => 'form-control'])
!!}
<p class="help-block"><b>12:A 5:B</b> (旗標 12 設定為 A, 旗標 5 設定為 B,使用空白區隔)</p>
</div>
<div class="form-group">
{!! Form::label(
App\Import\Flap\POS_Member\Import::OPTIONS_OBMEMO,
'請輸入客經二備註',
['class' => 'control-label'])
!!}
{!! Form::text(
App\Import\Flap\POS_Member\Import::OPTIONS_OBMEMO,
$task->memo,
['id'=> App\Import\Flap\POS_Member\Import::OPTIONS_OBMEMO, 'class' => 'form-control'])
!!}
</div>
<div class="form-group">
{!! Form::submit(NULL === $task->id ? '匯入' : '確認', ['class' => 'btn btn-raised btn-primary btn-sm']) !!}
</div> | jocoonopa/lubri | resources/views/flap/posmember/import_task/_formAct.blade.php | PHP | mit | 3,704 |
<?php
namespace Vibs\EvesymBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Industryactivityproducts
*
* @ORM\Table(name="industryActivityProducts", indexes={@ORM\Index(name="ix_industryActivityProducts_typeID", columns={"typeID"}), @ORM\Index(name="ix_industryActivityProducts_productTypeID", columns={"productTypeID"}), @ORM\Index(name="activityID", columns={"activityID"})})
* @ORM\Entity
*/
class Industryactivityproducts
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var integer
*
* @ORM\Column(name="quantity", type="integer", nullable=true)
*/
private $quantity;
/**
* @var \Vibs\EvesymBundle\Entity\Ramactivities
*
* @ORM\ManyToOne(targetEntity="Vibs\EvesymBundle\Entity\Ramactivities")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="activityID", referencedColumnName="activityID")
* })
*/
private $activityid;
/**
* @var \Vibs\EvesymBundle\Entity\Invtypes
*
* @ORM\ManyToOne(targetEntity="Vibs\EvesymBundle\Entity\Invtypes")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="typeID", referencedColumnName="typeID")
* })
*/
private $typeid;
/**
* @var \Vibs\EvesymBundle\Entity\Invtypes
*
* @ORM\ManyToOne(targetEntity="Vibs\EvesymBundle\Entity\Invtypes")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="productTypeID", referencedColumnName="typeID")
* })
*/
private $producttypeid;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set quantity
*
* @param integer $quantity
*
* @return Industryactivityproducts
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity
*
* @return integer
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* Set activityid
*
* @param \Vibs\EvesymBundle\Entity\Ramactivities $activityid
*
* @return Industryactivityproducts
*/
public function setActivityid(\Vibs\EvesymBundle\Entity\Ramactivities $activityid = null)
{
$this->activityid = $activityid;
return $this;
}
/**
* Get activityid
*
* @return \Vibs\EvesymBundle\Entity\Ramactivities
*/
public function getActivityid()
{
return $this->activityid;
}
/**
* Set typeid
*
* @param \Vibs\EvesymBundle\Entity\Invtypes $typeid
*
* @return Industryactivityproducts
*/
public function setTypeid(\Vibs\EvesymBundle\Entity\Invtypes $typeid = null)
{
$this->typeid = $typeid;
return $this;
}
/**
* Get typeid
*
* @return \Vibs\EvesymBundle\Entity\Invtypes
*/
public function getTypeid()
{
return $this->typeid;
}
/**
* Set producttypeid
*
* @param \Vibs\EvesymBundle\Entity\Invtypes $producttypeid
*
* @return Industryactivityproducts
*/
public function setProducttypeid(\Vibs\EvesymBundle\Entity\Invtypes $producttypeid = null)
{
$this->producttypeid = $producttypeid;
return $this;
}
/**
* Get producttypeid
*
* @return \Vibs\EvesymBundle\Entity\Invtypes
*/
public function getProducttypeid()
{
return $this->producttypeid;
}
}
| vladibalan/evesym | Entity/Industryactivityproducts.php | PHP | mit | 3,604 |
class Admin::ToursController < Admin::ApplicationController
before_action :set_tour, only: [:show, :edit, :update, :destroy]
def index
@tours = Tour.includes(:city).newest.page(params[:page])
end
def show;end
def new
@tour = Tour.new
end
def edit
end
def create
@tour = Tour.new(tour_params)
if @tour.save
redirect_to admin_tours_path, notice: 'Tour succefully added'
else
redirect_to admin_tours_path, alert: 'Something wrong in add procedure'
end
end
def update
if @tour.update(tour_params)
redirect_to admin_tours_path, notice: 'Tour succefully updated'
else
redirect_to admin_tours_path, alert: 'Something wrong in update procedure'
end
end
def destroy
if @tour.destroy
redirect_to admin_tours_path, notice: 'Tour deleted'
else
redirect_to admin_tours_path, alert: 'Something wrong in delete procedure'
end
end
private
def set_tour
@tour = Tour.find(params[:id])
end
def tour_params
params.require(:tour).permit(:name, :description, :city_id)
end
end
| mpakus/excurso | app/controllers/admin/tours_controller.rb | Ruby | mit | 1,106 |
<?php
/**
* This file is part of Laravel Desktop Notifier.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NunoMaduro\LaravelDesktopNotifier;
use Joli\JoliNotif\Notification as BaseNotification;
use NunoMaduro\LaravelDesktopNotifier\Contracts\Notification as NotificationContract;
/**
* The concrete implementation of the notification.
*
* @author Nuno Maduro <enunomaduro@gmail.com>
*/
class Notification extends BaseNotification implements NotificationContract
{
}
| nunomaduro/laravel-desktop-notifier | src/Notification.php | PHP | mit | 620 |
'use strict';
function injectJS(src, cb) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.onreadystatechange = script.onload = function () {
var readyState = script.readyState;
if (!readyState || readyState == 'loaded' || readyState == 'complete' || readyState == 'uninitialized') {
cb && cb();
script.onload = script.onreadystatechange = script.onerror = null;
}
};
script.src = src;
document.body.appendChild(script);
}
| elpadi/js-library | dist/utils.js | JavaScript | mit | 496 |
/**
* Created by desen on 2017/7/24.
*/
function isArray(value) {
if (typeof Array.isArray === "function") {
return Array.isArray(value);
} else {
return Object.prototype.toString.call(value) === "[object Array]";
}
}
// 进行虚拟DOm的类型的判断
function isVtext(vNode) {
return true;
}
| enmeen/2017studyPlan | someDemo/虚拟DOM实现/util.js | JavaScript | mit | 307 |
package mankind;
public class Worker extends Human {
Double weekSalary;
Double workHoursPerDay;
public Worker(String firstName, String lastName, Double weekSalary, Double workHoursPerDay) {
super(firstName, lastName);
this.weekSalary = weekSalary;
this.workHoursPerDay = workHoursPerDay;
}
public Double getWeekSalary() {
return this.weekSalary;
}
public Double getWorkHoursPerDay() {
return this.workHoursPerDay;
}
public Double getSalaryPerHour() {
return this.weekSalary / (this.workHoursPerDay * 7);
}
}
| akkirilov/SoftUniProject | 04_DB Frameworks_Hibernate+Spring Data/03_OOP Principles EX/src/mankind/Worker.java | Java | mit | 539 |