repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
isneezy/confere.js | test/Validators.js | 9545 | import ConfereJs from '../src/Confere'
import validators from '../src/validators'
var assert = require('assert')
var expect = require('expect.js')
describe('Validators', function () {
describe('required', done => {
it('should validate without error', done => {
validators.required('name', 'Ivan').then(done).catch(done)
})
it('should validate with error', done => {
validators.required('name', '').then(done).catch(result => {
expect(result).to.be.an(Error)
expect(result.field).to.be('name')
done()
})
})
})
describe('boolean', done => {
it('should validate without error', done => {
validators.required('remember-me', '1').then(done).catch(done)
})
it('should validate with error', done => {
validators.required('remember-me', 'trua').then(done).catch(result => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('dates', () => {
describe('date', () => {
it('should validate without error', done => {
validators.date('birth_date', '1992-02-13', [], ConfereJs.getDefaults()).then(done).catch(done)
})
it('should validate with error', done => {
validators.date('birth_date', '1992/02/12', [], ConfereJs.getDefaults()).then(() => {
done(new Error(/Does not validate with error/))
}).catch(result => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('after', () => {
it('should validate without error', done => {
validators.after('birth_date', '1992-02-13', ['1992-02-12'], ConfereJs.getDefaults()).then(done).catch(done)
})
it('should validate with error', done => {
validators.after('birth_date', '1992-02-13', ['1992-02-14'], ConfereJs.getDefaults()).then(() => {
done(new Error(/Does not validate with error/))
}).catch(result => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('after_or_equal', () => {
it('should validate without error', done => {
validators.after_or_equal('birth_date', '1992-02-13', ['1992-02-13'], ConfereJs.getDefaults())
.then(validators.after_or_equal('birth_date', '1992-02-13', ['1992-01-13'], ConfereJs.getDefaults()))
.then(done).catch(done)
})
it('should validate with error', done => {
validators.after_or_equal('birth_date', '1992-02-13', ['1992-02-14'], ConfereJs.getDefaults()).then(() => {
done(new Error('Did not trow error'))
}).catch((result) => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('before', () => {
it('should validate without error', done => {
validators.before('birth_date', '1992-02-13', ['1992-02-14'], ConfereJs.getDefaults()).then(done).catch(done)
})
it('should validate with error', done => {
validators.before('birth_date', '1992-02-13', ['1992-02-12'], ConfereJs.getDefaults()).then(() => {
done(new Error(/Does not validate with error/))
}).catch(result => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('before_or_equal', () => {
it('should validate without error', done => {
validators.before_or_equal('birth_date', '1992-02-13', ['1992-02-14'], ConfereJs.getDefaults())
.then(validators.before_or_equal('birth_date', '1992-02-13', ['1992-02-13'], ConfereJs.getDefaults()))
.then(done).catch(done)
})
it('should validate with error', done => {
validators.before_or_equal('birth_date', '1992-02-13', ['1992-02-12'], ConfereJs.getDefaults()).then(() => {
done(new Error(/Does not validate with error/))
}).catch(result => {
expect(result).to.be.an(Error)
done()
})
})
})
})
describe('Strings', () => {
describe('min', () => {
it('should validate without error', done => {
validators.min('email', 'Ivan', [3]).then(done).catch(done)
})
it('should validate with error', done => {
validators.min('email', 'Ivan', [5]).then(() => {
done(new Error(/Does not validate with error/))
}).catch(result => {
expect(result).to.be.an(Error)
expect(result.field).to.be('email')
done()
})
})
})
describe('max', () => {
it('should validate without error', done => {
validators.max('email', 'Ivan', [4]).then(done).catch(done)
})
it('should validate with error', done => {
validators.max('email', 'Ivan', [3]).then(() => {
done(new Error(/Does not validate with error/))
}).catch(result => {
expect(result).to.be.a(Error)
expect(result.field).to.be('email')
done()
})
})
})
describe('email', () => {
it('should validate without error', done => {
validators.email('email', 'ivan@vilanculo.me').then(done).catch(done)
})
it('should validate with error', done => {
validators.email('email', 'ivan@vilanculo.me.').then(() => {
done(new Error(/Does not validate with error/))
}).catch(result => {
expect(result).to.be.an(Error)
expect(result.field).to.be('email')
done()
})
})
})
describe('alpha', () => {
it('should validate without error', done => {
validators.alpha('username', 'isneezy')
.then(validators.alpha('username', 'isnEEZy')).then(done).catch(done)
})
it('should validate with error', done => {
validators.alpha('username', '@isneezy').then(() => {
done(new Error('Did not throw error'))
}).catch((result) => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('alpha_dash', () => {
it('should validate without error', done => {
validators.alpha_dash('username', 'isne_ezy')
.then(validators.alpha_dash('username', 'isn_-EEZy')).then(done).catch(done)
})
it('should validate with error', done => {
validators.alpha('username', '@isneezy').then(() => {
done(new Error('Did not throw error'))
}).catch((result) => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('alpha_numeric', () => {
it('should validate without error', done => {
validators.alpha_dash('username', 'isneezy02')
.then(validators.alpha_dash('username', 'issEEZy221')).then(done).catch(done)
})
it('should validate with error', done => {
validators.alpha('username', '@isneezy_22').then(() => {
done(new Error('Did not throw error'))
}).catch((result) => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('between', () => {
it('should validate without error', done => {
validators.between('username', 'isneezy', [4, 16])
.then(validators.between('username', [1, 1, 1, 1, 1], [4, 16])).then(done).catch(done)
})
it('should validate with error', done => {
validators.between('username', 'isn', [4, 16])
.then(() => {
done(new Error('Did not throw error'))
})
.catch((result) => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('url', () => {
it('should validate without error', done => {
validators.url('website', 'http://ivan.vilanculo.me')
.then(validators.url('website', 'https://ivan.vilanculo.co.mz')).then(done).catch(done)
})
it('should validate with error', done => {
validators.url('website', 'htt://www.a@_-.com')
.then(() => {
done(new Error('Did not throw error'))
})
.catch((result) => {
expect(result).to.be.an(Error)
done()
})
})
})
})
describe('Numbers', () => {
describe('digits', () => {
it('should validate without error', done => {
validators.digits('number', 12345678901234, [14]).then(done).catch(done)
})
it('should validate with error', done => {
validators.digits('number', 1234567890123, [15]).then(() => {
done(new Error('Did not throw error'))
}).catch((result) => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('digits_between', () => {
it('should validate without error', done => {
validators.digits_between('number', 1234567890123, [10,14]).then(done).catch(done)
})
it('should validate with error', done => {
validators.digits_between('number', 123456789, [10,14]).then(() => {
done(new Error('Did not throw error'))
}).catch((result) => {
expect(result).to.be.an(Error)
done()
})
})
})
describe('integer', () => {
it('should validate without error', done => {
validators.integer('number', '12345678901234').then(done).catch(done)
})
it('should validate with error', done => {
validators.integer('number', '123456a7890123a').then(() => {
done(new Error('Did not throw error'))
}).catch((result) => {
expect(result).to.be.an(Error)
done()
})
})
})
})
}) | mit |
duritong/ruby-rhn_satellite | lib/rhn_satellite/activation_key.rb | 135 | module RhnSatellite
class ActivationKey < RhnSatellite::Connection::Base
collection 'activationkey.listActivationKeys'
end
end
| mit |
JamesRandall/WebAPI2MobileFacebookAuthentication | ExternalProviderAuthentication.Web/ExternalProviderAuthentication.Web/App_Start/RouteConfig.cs | 627 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace ExternalProviderAuthentication.Web
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| mit |
Efrem-berhe/Lost-and-Found | application/models/resolved_model.php | 751 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Community Auth - Examples Model
*
* Community Auth is an open source authentication application for CodeIgniter 3
*
* @package Community Auth
* @author Robert B Gottier
* @copyright Copyright (c) 2011 - 2017, Robert B Gottier. (http://brianswebdesign.com/)
* @license BSD - http://www.opensource.org/licenses/BSD-3-Clause
* @link http://community-auth.com
*/
class resolved_model extends CI_Model {
public function get(){
$this->db->select('*');
$this->db->from('customer_profiles');
$this->db->where('user_id',$this->auth_user_id);
$q = $this->db->get();
return $q->result();
}
}
| mit |
robertsj/ME701_examples | compiled/control_case.cc | 245 | #include <iostream>
using std::cout;
using std::endl;
int main()
{
int a = 1;
switch (a)
{
case 1:
cout << "a=1" << endl;
break;
case 2:
// do something
break;
default:
cout << "hi" << endl;
}
}
| mit |
NeoPhi/overlap | tools/disabledTestCheck.js | 1048 | var fs = require('fs');
var _ = require('underscore');
var wrench = require('wrench');
var path = require('path');
var EXT_TEST = /\.spec\.js$/;
var DISABLED_TEST = /^\s*(xdescribe|xit)\s*\(/m;
function extFilter(name) {
return EXT_TEST.test(name);
}
function testForDisabled(file) {
var data = fs.readFileSync(file).toString();
return DISABLED_TEST.test(data);
}
console.log('Checking files for disabled tests');
var filesWithDisabledTests = [];
_.each(['test', 'integration'], function(dir) {
var chain = _.chain([dir]);
chain = chain.filter(fs.existsSync);
chain = chain.map(wrench.readdirSyncRecursive);
chain = chain.flatten();
chain = chain.map(function(file) {
return path.join(dir, file);
});
chain = chain.filter(extFilter);
chain = chain.filter(testForDisabled);
filesWithDisabledTests = filesWithDisabledTests.concat(chain.value());
});
if (filesWithDisabledTests.length > 0) {
console.log('*** ERROR Files with disabled tests:');
console.log(filesWithDisabledTests.join('\n'));
process.exit(1);
}
| mit |
datashade/datashade-android | src/android/protype/datashade/StudentTest.java | 156 | package android.protype.datashade;
class StudentTest extends Student
{
StudentTest()
{
super("Grady", "Jones");
this.AddGoal( new GoalTest() );
}
} | mit |
bploetz/roper | spec/lib/roper/repository_spec.rb | 342 | require "spec_helper"
describe Roper::Repository do
after :each do
Roper::Repository.repositories.delete(:repo1)
end
let(:repo1) { Object.new }
let(:repo2) { Object.new }
it "registers repositories under a key" do
Roper::Repository.register(:repo1, repo1)
expect(Roper::Repository.for(:repo1)).to eq(repo1)
end
end
| mit |
zhangf911/mio | test/test_unix_echo_server.rs | 8654 | use mio::*;
use mio::net::*;
use mio::net::pipe::*;
use mio::buf::{ByteBuf, SliceBuf};
use mio::util::Slab;
use std::io::TempDir;
use mio::event as evt;
type TestEventLoop = EventLoop<usize, ()>;
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
struct EchoConn {
sock: UnixSocket,
buf: ByteBuf,
token: Token,
interest: evt::Interest
}
impl EchoConn {
fn new(sock: UnixSocket) -> EchoConn {
EchoConn {
sock: sock,
buf: ByteBuf::new(2048),
token: Token(-1),
interest: evt::HUP
}
}
fn writable(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {
debug!("CON : writing buf = {:?}", self.buf.bytes());
match self.sock.write(&mut self.buf) {
Ok(NonBlock::WouldBlock) => {
debug!("client flushing buf; WOULDBLOCK");
self.interest.insert(evt::WRITABLE);
}
Ok(NonBlock::Ready(r)) => {
debug!("CONN : we wrote {} bytes!", r);
self.buf.clear();
self.interest.insert(evt::READABLE);
self.interest.remove(evt::WRITABLE);
}
Err(e) => debug!("not implemented; client err={:?}", e),
}
event_loop.reregister(&self.sock, self.token, self.interest, evt::PollOpt::edge())
}
fn readable(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {
match self.sock.read(&mut self.buf) {
Ok(NonBlock::WouldBlock) => {
panic!("We just got readable, but were unable to read from the socket?");
}
Ok(NonBlock::Ready(r)) => {
debug!("CONN : we read {} bytes!", r);
self.interest.remove(evt::READABLE);
self.interest.insert(evt::WRITABLE);
}
Err(e) => {
debug!("not implemented; client err={:?}", e);
self.interest.remove(evt::READABLE);
}
};
// prepare to provide this to writable
self.buf.flip();
debug!("CON : read buf = {:?}", self.buf.bytes());
event_loop.reregister(&self.sock, self.token, self.interest, evt::PollOpt::edge())
}
}
struct EchoServer {
sock: UnixAcceptor,
conns: Slab<EchoConn>
}
impl EchoServer {
fn accept(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {
debug!("server accepting socket");
let sock = self.sock.accept().unwrap().unwrap();
let conn = EchoConn::new(sock,);
let tok = self.conns.insert(conn)
.ok().expect("could not add connectiont o slab");
// Register the connection
self.conns[tok].token = tok;
event_loop.register_opt(&self.conns[tok].sock, tok, evt::READABLE, evt::PollOpt::edge())
.ok().expect("could not register socket with event loop");
Ok(())
}
fn conn_readable(&mut self, event_loop: &mut TestEventLoop, tok: Token) -> MioResult<()> {
debug!("server conn readable; tok={:?}", tok);
self.conn(tok).readable(event_loop)
}
fn conn_writable(&mut self, event_loop: &mut TestEventLoop, tok: Token) -> MioResult<()> {
debug!("server conn writable; tok={:?}", tok);
self.conn(tok).writable(event_loop)
}
fn conn<'a>(&'a mut self, tok: Token) -> &'a mut EchoConn {
&mut self.conns[tok]
}
}
struct EchoClient {
sock: UnixSocket,
msgs: Vec<&'static str>,
tx: SliceBuf<'static>,
rx: SliceBuf<'static>,
buf: ByteBuf,
token: Token,
interest: evt::Interest
}
// Sends a message and expects to receive the same exact message, one at a time
impl EchoClient {
fn new(sock: UnixSocket, tok: Token, mut msgs: Vec<&'static str>) -> EchoClient {
let curr = msgs.remove(0);
EchoClient {
sock: sock,
msgs: msgs,
tx: SliceBuf::wrap(curr.as_bytes()),
rx: SliceBuf::wrap(curr.as_bytes()),
buf: ByteBuf::new(2048),
token: tok,
interest: evt::Interest::empty()
}
}
fn readable(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {
debug!("client socket readable");
match self.sock.read(&mut self.buf) {
Ok(NonBlock::WouldBlock) => {
panic!("We just got readable, but were unable to read from the socket?");
}
Ok(NonBlock::Ready(r)) => {
debug!("CLIENT : We read {} bytes!", r);
}
Err(e) => {
panic!("not implemented; client err={:?}", e);
}
};
// prepare for reading
self.buf.flip();
debug!("CLIENT : buf = {:?} -- rx = {:?}", self.buf.bytes(), self.rx.bytes());
while self.buf.has_remaining() {
let actual = self.buf.read_byte().unwrap();
let expect = self.rx.read_byte().unwrap();
assert!(actual == expect, "actual={}; expect={}", actual, expect);
}
self.buf.clear();
self.interest.remove(evt::READABLE);
if !self.rx.has_remaining() {
self.next_msg(event_loop).unwrap();
}
event_loop.reregister(&self.sock, self.token, self.interest, evt::PollOpt::edge())
}
fn writable(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {
debug!("client socket writable");
match self.sock.write(&mut self.tx) {
Ok(NonBlock::WouldBlock) => {
debug!("client flushing buf; WOULDBLOCK");
self.interest.insert(evt::WRITABLE);
}
Ok(NonBlock::Ready(r)) => {
debug!("CLIENT : we wrote {} bytes!", r);
self.interest.insert(evt::READABLE);
self.interest.remove(evt::WRITABLE);
}
Err(e) => debug!("not implemented; client err={:?}", e)
}
event_loop.reregister(&self.sock, self.token, self.interest, evt::PollOpt::edge())
}
fn next_msg(&mut self, event_loop: &mut TestEventLoop) -> MioResult<()> {
if self.msgs.is_empty() {
event_loop.shutdown();
return Ok(());
}
let curr = self.msgs.remove(0);
debug!("client prepping next message");
self.tx = SliceBuf::wrap(curr.as_bytes());
self.rx = SliceBuf::wrap(curr.as_bytes());
self.interest.insert(evt::WRITABLE);
event_loop.reregister(&self.sock, self.token, self.interest, evt::PollOpt::edge())
}
}
struct EchoHandler {
server: EchoServer,
client: EchoClient,
}
impl EchoHandler {
fn new(srv: UnixAcceptor, client: UnixSocket, msgs: Vec<&'static str>) -> EchoHandler {
EchoHandler {
server: EchoServer {
sock: srv,
conns: Slab::new_starting_at(Token(2), 128)
},
client: EchoClient::new(client, CLIENT, msgs)
}
}
}
impl Handler<usize, ()> for EchoHandler {
fn readable(&mut self, event_loop: &mut TestEventLoop, token: Token, hint: evt::ReadHint) {
assert_eq!(hint, evt::DATAHINT);
match token {
SERVER => self.server.accept(event_loop).unwrap(),
CLIENT => self.client.readable(event_loop).unwrap(),
i => self.server.conn_readable(event_loop, i).unwrap()
};
}
fn writable(&mut self, event_loop: &mut TestEventLoop, token: Token) {
match token {
SERVER => panic!("received writable for token 0"),
CLIENT => self.client.writable(event_loop).unwrap(),
_ => self.server.conn_writable(event_loop, token).unwrap()
};
}
}
#[test]
pub fn test_unix_echo_server() {
debug!("Starting TEST_UNIX_ECHO_SERVER");
let mut event_loop = EventLoop::new().unwrap();
let tmp_dir = TempDir::new("test_unix_echo_server").unwrap();
let tmp_sock_path = tmp_dir.path().join(Path::new("sock"));
let addr = SockAddr::from_path(tmp_sock_path);
let srv = UnixSocket::stream().unwrap();
let srv = srv.bind(&addr).unwrap()
.listen(256).unwrap();
info!("listen for connections");
event_loop.register_opt(&srv, SERVER, evt::READABLE, evt::PollOpt::edge()).unwrap();
let sock = UnixSocket::stream().unwrap();
// Connect to the server
event_loop.register_opt(&sock, CLIENT, evt::WRITABLE, evt::PollOpt::edge()).unwrap();
sock.connect(&addr).unwrap();
// Start the event loop
event_loop.run(EchoHandler::new(srv, sock, vec!["foo", "bar"]))
.ok().expect("failed to execute event loop");
}
| mit |
CDLUC3/stash | stash_datacite/app/mailers/stash_datacite/user_mailer.rb | 875 | module StashDatacite
# app/mailers/stash_datacite/user_mailer.rb
class UserMailer < ApplicationMailer
default from: APP_CONFIG['feedback_email_from'],
return_path: 'dash2-dev@ucop.edu'
# an example call:
# UserMailer.notification(['catdog@mailinator.com', 'dogdog@mailinator.com'],
# 'that frosty mug taste', 'test_mail').deliver
def notification(email_address, subject, message_template, locals)
@vars = locals
mail(
to: to_address_from(email_address),
subject: subject.to_s,
from: APP_CONFIG['feedback_email_from'],
reply_to: APP_CONFIG['feedback_email_from'],
template_name: message_template
)
end
def to_address_from(email_address)
return email_address unless email_address.is_a?(Array)
email_address.join(',')
end
end
end
| mit |
imazen/repositext | spec/repositext/service/score_subtitle_alignment_using_stid_spec.rb | 657 | require_relative '../../helper'
class Repositext
class Service
class Filename
describe ScoreSubtitleAlignmentUsingStid do
describe 'call' do
[
['1234', '1234', 10],
['1234', '2345', -11],
].each do |left_stid, right_stid, xpect|
it "handles #{ left_stid.inspect }, #{ right_stid.inspect }" do
ScoreSubtitleAlignmentUsingStid.call(
left_stid: left_stid,
right_stid: right_stid,
default_gap_penalty: -10,
)[:result].must_equal(xpect)
end
end
end
end
end
end
end
| mit |
hi-ko-wi/SharpTk | SharpTk/NumericExt.cs | 1003 | // --------------------------------------------------------------------------------------------------------------------
// Copyright (c) 2017-2017
// for information on the creator and copyright owner, please see the author list bellow and the assembly
// information file.
// -
// All rights are reserved. Reproduction or transmission in whole or in part, any form or by any means, electronic,
// mechanical or otherwise, is prohibited without the prior written consent of the copyright owner.
// -
// File: NumericExt.cs
// Part of: Tranquility
// -
// Author: Haiko Wick (Haiko Wick)
// Modified: 2017-04-02 08:53
// --------------------------------------------------------------------------------------------------------------------
using System;
namespace SharpTk
{
public static class NumericTk
{
public static bool TkIsOne(this decimal? input, bool defaultValue = false)
=> !input.HasValue ? defaultValue : Math.Abs(value: input.Value) - 1 == 0;
}
} | mit |
piecoin/picoin | src/util.cpp | 36611 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "sync.h"
#include "strlcpy.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fRequestShutdown = false;
bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64> vTimeOffsets(200,0);
bool fReopenDebugLog = false;
// Init openssl library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
// Init
class CInit
{
public:
CInit()
{
// Init openssl library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown openssl library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64 nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64 nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
printf("RandAddSeed() %d bytes\n", nSize);
}
#endif
}
uint64 GetRand(uint64 nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
uint64 nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
inline int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0;
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else
{
// print to debug.log
static FILE* fileout = NULL;
if (!fileout)
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
}
if (fileout)
{
static bool fStartedNewLine = true;
static boost::mutex mutexDebugLog;
boost::mutex::scoped_lock scoped_lock(mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const std::string &format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
loop
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
loop
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64 n_abs = (n > 0 ? n : -n);
int64 quotient = n_abs/COIN;
int64 remainder = n_abs%COIN;
string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
// Right-trim excess 0's before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64& nRet)
{
string strWhole;
int64 nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64 nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64 nWhole = atoi64(strWhole);
int64 nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
static signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
loop
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
char psz[10000];
strlcpy(psz, argv[i], sizeof(psz));
char* pszValue = (char*)"";
if (strchr(psz, '='))
{
pszValue = strchr(psz, '=');
*pszValue++ = '\0';
}
#ifdef WIN32
_strlwr(psz);
if (psz[0] == '/')
psz[0] = '-';
#endif
if (psz[0] != '-')
break;
mapArgs[psz] = pszValue;
mapMultiArgs[psz].push_back(pszValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64 GetArg(const std::string& strArg, int64 nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
loop
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "picoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void LogException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n%s", message.c_str());
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\PiCoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\PiCoin
// Mac: ~/Library/Application Support/PiCoin
// Unix: ~/.picoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "PiCoin";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "PiCoin";
#else
// Unix
return pathRet / ".picoin";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
static bool cachedPath[2] = {false, false};
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (cachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && GetBoolArg("-testnet", false))
path /= "testnet3";
fs::create_directory(path);
cachedPath[fNetSpecific]=true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "picoin.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No picoin.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override picoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "picoin.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
int GetFilesize(FILE* file)
{
int nSavePos = ftell(file);
int nFilesize = -1;
if (fseek(file, 0, SEEK_END) == 0)
nFilesize = ftell(file);
fseek(file, nSavePos, SEEK_SET);
return nFilesize;
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && GetFilesize(file) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64 nMockTime = 0; // For unit testing
int64 GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64 nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64 nTimeOffset = 0;
int64 GetAdjustedTime()
{
return GetTime() + nTimeOffset;
}
void AddTimeData(const CNetAddr& ip, int64 nTime)
{
int64 nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64 nMedian = vTimeOffsets.median();
std::vector<int64> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 35 * 60) // changed maximum adjust to 35 mins to avoid letting peers change our time too much in case of an attack.
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64 nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong PiCoin will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("PiCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64 n, vSorted)
printf("%+"PRI64d" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
#elif defined(MAC_OSX)
pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
| mit |
npetzall/http-double | server/src/main/java/npetzall/httpdouble/server/registry/ServiceDoubleRegistry.java | 234 | package npetzall.httpdouble.server.registry;
import java.util.Map;
public interface ServiceDoubleRegistry {
ServiceDoubleRef getServiceDoubleByURLPath(String urlPath);
Map<String, ServiceDoubleRef> getAllServiceDoubles();
}
| mit |
TyreeJackson/atomic | Atomic.Net.Tests/Host/IIS/IISHttpHandler - tests.cs | 1425 | using System;
using System.Web;
using AtomicNet.IIS;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace AtomicNet.tests
{
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[TestClass]
public class IISHttpHandlerTests
{
private Mock<WebHandler.Router> mockRouter;
[TestInitialize]
public void Initialize()
{
this.mockRouter = new Mock<WebHandler.Router>();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void When_constructing_an_IISHttpHandler_the_router_argument_must_not_be_null()
{
var handler = new IISHttpHandler(null);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void When_calling_the_IHttpHandler_ProcessRequest_method_an_InvalidOperationException_should_be_thrown_as_this_handler_is_designed_to_be_exclusively_called_asynchronously()
{
var handler = new IISHttpHandler(this.mockRouter.Object);
((IHttpHandler) handler).ProcessRequest(null);
}
[TestMethod]
public void When_calling_the_IHttpHandler_IsResuable_the_value_should_be_false()
{
var handler = new IISHttpHandler(this.mockRouter.Object);
Assert.IsFalse(((IHttpHandler) handler).IsReusable);
}
}
}
| mit |
robust-team/angular-forms | test/group/data-table.model.spec.ts | 916 | import { assert } from 'chai';
import { DataTable } from '../../src/group';
import { Text } from '../../src/question';
import { Required } from '../../src/validation';
describe('AngularForms :: Group :: DataTable', () => {
it('should be instantiable', () => {
assert.ok(new DataTable('G-01', 'A simple group', [[], []], []));
});
it('should getQuestionByName method', () => {
const dataTable: DataTable = new DataTable('G-01', 'A simple group', [[new Text('Q-01', 'A simple question')]]);
assert.isTrue(dataTable.getQuestionByName('Q-01') instanceof Text);
});
it('should isRequired method', () => {
const dataTable1: DataTable = new DataTable('G-01', 'A simple group', [], [new Required('Required')]);
const dataTable2: DataTable = new DataTable('G-01', 'A simple group', [], []);
assert.isTrue(dataTable1.isRequired());
assert.isFalse(dataTable2.isRequired());
});
});
| mit |
itkg/core | tests/Itkg/Tests/Core/Command/Provider/ServiceCommandProviderTest.php | 2829 | <?php
/*
* This file is part of the Itkg\Core package.
*
* (c) Interakting - Business & Decision
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Itkg\Tests\Core\Command\Provider;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;
use Itkg\Core\Application;
use Itkg\Core\Config;
use Itkg\Core\ServiceContainer;
use Itkg\Core\Command\Provider\ServiceCommandProvider;
/**
* @author Pascal DENIS <pascal.denis@businessdecision.com>
*/
class ServiceCommandProviderTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ServiceContainer
*/
private $container;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->container = new Servicecontainer();
$this->container
->setApp(new Application())
->setConfig(new Config());
$this->container->register(new ServiceCommandProvider());
}
public function testRunner()
{
$this->loadDoctrine();
$this->assertInstanceOf('Itkg\Core\Command\DatabaseUpdate\RunnerInterface', $this->container['itkg-core.command.db_update.runner']);
}
/**
* @expectedException \Exception
*/
public function testDoctrineDependency()
{
$this->container['itkg-core.command.database_update.loader'];
}
public function testSetup()
{
$this->loadDoctrine();
$this->assertInstanceOf('Itkg\Core\Command\DatabaseUpdate\Setup', $this->container['itkg-core.command.db_update.setup']);
}
public function testDisplay()
{
$this->loadDoctrine();
$this->assertInstanceOf('Itkg\Core\Command\DatabaseUpdate\Display', $this->container['itkg-core.command.db_update.display']);
}
public function testDecorator()
{
$this->loadDoctrine();
$this->assertInstanceOf('Itkg\Core\Command\DatabaseUpdate\Query\Decorator', $this->container['itkg-core.command.db_update.decorator']);
}
public function testCommand()
{
$this->loadDoctrine();
$this->assertInstanceOf('Itkg\Core\Command\DatabaseUpdateCommand', $this->container['itkg-core.command.database_update']);
}
private function loadDoctrine()
{
$this->container['doctrine.connection'] = $this->container->share(function() {
$params = array(
'dbname' => 'DBNAME',
'user' => 'USER',
'password' => 'PWD',
'host' => '',
'driver' => 'oci8'
);
$config = new Configuration();
return DriverManager::getConnection($params, $config);
});
}
}
| mit |
diversiforge/bookvault | config/environments/production.rb | 3795 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Action Cable endpoint configuration
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Don't mount Action Cable in the main server process.
# config.action_cable.mount_path = nil
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
config.logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
end
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "bookvault_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end
| mit |
KobusGamification/Gamification | Gamification/SVNExtension/Badges/SVNLvUpThirty.cs | 1453 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Extension;
using Extension.Badge;
using MongoDB.Bson;
namespace SVNExtension.Badges
{
public class SVNLvUpThirty : IBadge
{
public ObjectId id { get; private set; }
public BadgeLevel Level { get; private set; }
public string Content { get; private set; }
public string IconPath { get; private set; }
public string Name { get; private set; }
public string ExtensionName { get; private set; }
public bool Secret { get; private set; }
public bool Gained { get; private set; }
public SVNLvUpThirty()
{
ExtensionName = "SVN";
Level = BadgeLevel.topaz;
Content = GetContent();
IconPath = ".\\res\\Badges\\SVN\\SVNLevelUpThirty.png";
Name = "Level 20!";
Secret = false;
Gained = false;
}
public string GetContent()
{
var content = "Reach Subversion level 30";
return content;
}
public void Compute(IUser user)
{
var exp = new SVNExperience("current", ".\\Experience\\UserLevel.prop", "Alias");
exp.AddModel((SVNModel)user.ExtensionPoint["SVNExtension"]);
if (exp.Level > 30)
{
Gained = true;
}
}
}
}
| mit |
ChristianGaertner/TextAdventure | src/de/cpgaertner/edu/inf/games/datacenter/command/interact/InteractCommandParser.java | 1309 | package de.cpgaertner.edu.inf.games.datacenter.command.interact;
import de.cpgaertner.edu.inf.api.adapter.Adapter;
import de.cpgaertner.edu.inf.api.command.Command;
import de.cpgaertner.edu.inf.api.level.Location;
import de.cpgaertner.edu.inf.api.parsing.CommandParser;
import lombok.Setter;
public class InteractCommandParser implements CommandParser {
@Setter protected Adapter adapter;
/**
* Returns a Command, when it can parse the input, null otherwise
*
* @param input string to parse
* @return Command | null
*/
@Override
public Command get(String input) {
// Early testing.
if (!input.startsWith(InteractCommand.NAME)) {
return null;
}
String[] split = input.split(" ");
if (split.length < 2) {
return null;
}
if (!split[0].equalsIgnoreCase(InteractCommand.NAME)) {
return null;
}
Location.Direction direction = Location.Direction.valueOf(
split[1].toUpperCase() // to uppercase, so it fits the enum!
);
return new InteractCommand(direction, adapter);
}
@Override
public String getHelp() {
return "interact [direction]: Interacts with a location. direction{north,east,south,west}";
}
}
| mit |
ReneMuetti/RFTools | src/main/java/mcjty/rftools/blocks/screens/ScreenRenderer.java | 6768 | package mcjty.rftools.blocks.screens;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import mcjty.rftools.RFTools;
import mcjty.rftools.blocks.screens.modulesclient.ClientScreenModule;
import mcjty.rftools.blocks.screens.network.PacketGetScreenData;
import mcjty.network.PacketHandler;
import mcjty.varia.Coordinate;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@SideOnly(Side.CLIENT)
public class ScreenRenderer extends TileEntitySpecialRenderer {
private static final ResourceLocation texture = new ResourceLocation(RFTools.MODID, "textures/blocks/screenFrame.png");
private final ModelScreen screenModel = new ModelScreen(false);
private final ModelScreen screenModelLarge = new ModelScreen(true);
@Override
public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f) {
GL11.glPushMatrix();
float f3;
int meta = tileEntity.getBlockMetadata();
f3 = 0.0F;
if (meta == 2) {
f3 = 180.0F;
}
if (meta == 4) {
f3 = 90.0F;
}
if (meta == 5) {
f3 = -90.0F;
}
GL11.glTranslatef((float) x + 0.5F, (float) y + 0.75F, (float) z + 0.5F);
GL11.glRotatef(-f3, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(0.0F, -0.2500F, -0.4375F);
ScreenTileEntity screenTileEntity = (ScreenTileEntity) tileEntity;
boolean lightingEnabled = GL11.glIsEnabled(GL11.GL_LIGHTING);
if (!screenTileEntity.isTransparent()) {
GL11.glDisable(GL11.GL_LIGHTING);
renderScreenBoard(screenTileEntity.isLarge(), screenTileEntity.getColor());
}
if (screenTileEntity.isPowerOn()) {
FontRenderer fontrenderer = this.func_147498_b();
ClientScreenModule.TransformMode mode = ClientScreenModule.TransformMode.NONE;
GL11.glDepthMask(false);
GL11.glDisable(GL11.GL_LIGHTING);
Map<Integer, Object[]> screenData = updateScreenData(screenTileEntity);
List<ClientScreenModule> modules = screenTileEntity.getClientScreenModules();
renderModules(fontrenderer, mode, modules, screenData, screenTileEntity.isLarge());
// GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
if (lightingEnabled) {
GL11.glEnable(GL11.GL_LIGHTING);
}
GL11.glDepthMask(true);
GL11.glPopMatrix();
}
private Map<Integer, Object[]> updateScreenData(ScreenTileEntity screenTileEntity) {
long millis = System.currentTimeMillis();
if ((millis - screenTileEntity.lastTime > 500) && screenTileEntity.isNeedsServerData()) {
screenTileEntity.lastTime = millis;
PacketHandler.INSTANCE.sendToServer(new PacketGetScreenData(screenTileEntity.xCoord, screenTileEntity.yCoord, screenTileEntity.zCoord, millis));
}
Map<Integer,Object[]> screenData = ScreenTileEntity.screenData.get(new Coordinate(screenTileEntity.xCoord, screenTileEntity.yCoord, screenTileEntity.zCoord));
if (screenData == null) {
screenData = Collections.EMPTY_MAP;
}
return screenData;
}
private void renderModules(FontRenderer fontrenderer, ClientScreenModule.TransformMode mode, List<ClientScreenModule> modules, Map<Integer, Object[]> screenData, boolean large) {
float f3, factor;
if (large) {
factor = 2.0f;
} else {
factor = 1.0f;
}
int currenty = 7;
int moduleIndex = 0;
for (ClientScreenModule module : modules) {
if (module != null) {
int height = module.getHeight();
// Check if this module has enough room
if (currenty + height <= 124) {
if (module.getTransformMode() != mode) {
if (mode != ClientScreenModule.TransformMode.NONE) {
GL11.glPopMatrix();
}
GL11.glPushMatrix();
mode = module.getTransformMode();
switch (mode) {
case TEXT:
GL11.glTranslatef(-0.5F, 0.5F, 0.07F);
f3 = 0.0075F;
GL11.glScalef(f3 * factor, -f3 * factor, f3);
GL11.glNormal3f(0.0F, 0.0F, -1.0F);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
break;
case TEXTLARGE:
GL11.glTranslatef(-0.5F, 0.5F, 0.07F);
f3 = 0.0075F * 2;
GL11.glScalef(f3 * factor, -f3 * factor, f3);
GL11.glNormal3f(0.0F, 0.0F, -1.0F);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
break;
case ITEM:
break;
default:
break;
}
}
module.render(fontrenderer, currenty, screenData.get(moduleIndex), factor);
currenty += height;
}
}
moduleIndex++;
}
if (mode != ClientScreenModule.TransformMode.NONE) {
GL11.glPopMatrix();
}
}
private void renderScreenBoard(boolean large, int color) {
this.bindTexture(texture);
GL11.glPushMatrix();
GL11.glScalef(1, -1, -1);
if (large) {
this.screenModelLarge.render();
} else {
this.screenModel.render();
}
GL11.glDepthMask(false);
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.setBrightness(240);
tessellator.setColorRGBA_I(color, 255);
// tessellator.setColorOpaque(0, 0, 0);
float r;
if (large) {
r = 1.46f;
} else {
r = .46f;
}
tessellator.addVertex(-.46f, r, -0.08f);
tessellator.addVertex(r, r, -0.08f);
tessellator.addVertex(r, -.46f, -0.08f);
tessellator.addVertex(-.46f, -.46f, -0.08f);
tessellator.draw();
GL11.glPopMatrix();
}
}
| mit |
chakrit/go-bunyan | format_sink_test.go | 2054 | package bunyan_test
import "os"
import "bytes"
import "time"
import "testing"
import . "github.com/chakrit/go-bunyan"
import a "github.com/stretchr/testify/assert"
var _ Sink = NewFormatSink(&bytes.Buffer{})
func TestNewFormatSink(t *testing.T) {
buffer := &bytes.Buffer{}
sink := NewFormatSink(buffer)
a.NotNil(t, sink, "format sink ctor returns null.")
}
func TestFormatSink_Write_Time(t *testing.T) {
input := "2014-03-02T00:33:59+07:00"
time_, e := time.Parse(time.RFC3339, input)
a.NoError(t, e)
expected := "[2014-03-02T00:33:59+07:00]\n"
checkFormat(t, NewSimpleRecord("time", input), expected)
checkFormat(t, NewSimpleRecord("time", time_), expected)
}
func TestFormatSink_Write_Level(t *testing.T) {
expected := " INFO: \n"
checkFormat(t, NewSimpleRecord("level", float64(30)), expected)
checkFormat(t, NewSimpleRecord("level", int(30)), expected)
checkFormat(t, NewSimpleRecord("level", INFO), expected)
}
func TestFormatSink_Write_Pid(t *testing.T) {
expected := "/35330\n"
checkFormat(t, NewSimpleRecord("pid", float64(35330)), expected)
checkFormat(t, NewSimpleRecord("pid", int(35330)), expected)
checkFormat(t, NewSimpleRecord("pid", "35330"), expected)
checkFormat(t, NewSimpleRecord("pid", 35330), expected)
}
func ExampleFormatSink() {
t, e := time.Parse(time.RFC3339, "2014-03-02T00:33:59+07:00")
if e != nil {
panic(e)
}
record := Record(map[string]interface{}{
"v": 0,
"pid": 6503,
"hostname": "go-bunyan.local",
"time": t,
"address": ":8080",
"level": INFO,
"msg": "starting up...",
"name": "bunyan",
})
e = NewFormatSink(os.Stdout).Write(record)
if e != nil {
panic(e)
}
// Output:
// [2014-03-02T00:33:59+07:00] INFO: bunyan/6503 on go-bunyan.local: starting up...
// address: ":8080"
}
func checkFormat(t *testing.T, record Record, expected string) {
buffer := &bytes.Buffer{}
sink := NewFormatSink(buffer)
e := sink.Write(record)
a.NoError(t, e)
a.Equal(t, expected, string(buffer.Bytes()), "format sink output is wrong.")
}
| mit |
xtina-starr/reaction | src/__generated__/PaymentMultipleCreditCardsQuery.graphql.ts | 6925 | /* tslint:disable */
import { ConcreteRequest } from "relay-runtime";
import { UserSettingsPayments_me$ref } from "./UserSettingsPayments_me.graphql";
export type PaymentMultipleCreditCardsQueryVariables = {};
export type PaymentMultipleCreditCardsQueryResponse = {
readonly me: ({
readonly " $fragmentRefs": UserSettingsPayments_me$ref;
}) | null;
};
export type PaymentMultipleCreditCardsQuery = {
readonly response: PaymentMultipleCreditCardsQueryResponse;
readonly variables: PaymentMultipleCreditCardsQueryVariables;
};
/*
query PaymentMultipleCreditCardsQuery {
me {
...UserSettingsPayments_me
__id
}
}
fragment UserSettingsPayments_me on Me {
__id
id
creditCards(first: 100) {
edges {
node {
__id
id
brand
last_digits
expiration_year
expiration_month
__typename
}
cursor
}
pageInfo {
endCursor
hasNextPage
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = {
"kind": "ScalarField",
"alias": null,
"name": "__id",
"args": null,
"storageKey": null
},
v1 = {
"kind": "ScalarField",
"alias": null,
"name": "id",
"args": null,
"storageKey": null
};
return {
"kind": "Request",
"operationKind": "query",
"name": "PaymentMultipleCreditCardsQuery",
"id": null,
"text": "query PaymentMultipleCreditCardsQuery {\n me {\n ...UserSettingsPayments_me\n __id\n }\n}\n\nfragment UserSettingsPayments_me on Me {\n __id\n id\n creditCards(first: 100) {\n edges {\n node {\n __id\n id\n brand\n last_digits\n expiration_year\n expiration_month\n __typename\n }\n cursor\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n}\n",
"metadata": {},
"fragment": {
"kind": "Fragment",
"name": "PaymentMultipleCreditCardsQuery",
"type": "Query",
"metadata": null,
"argumentDefinitions": [],
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "me",
"storageKey": null,
"args": null,
"concreteType": "Me",
"plural": false,
"selections": [
{
"kind": "FragmentSpread",
"name": "UserSettingsPayments_me",
"args": null
},
v0
]
}
]
},
"operation": {
"kind": "Operation",
"name": "PaymentMultipleCreditCardsQuery",
"argumentDefinitions": [],
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "me",
"storageKey": null,
"args": null,
"concreteType": "Me",
"plural": false,
"selections": [
v0,
v1,
{
"kind": "LinkedField",
"alias": null,
"name": "creditCards",
"storageKey": "creditCards(first:100)",
"args": [
{
"kind": "Literal",
"name": "first",
"value": 100,
"type": "Int"
}
],
"concreteType": "CreditCardConnection",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "edges",
"storageKey": null,
"args": null,
"concreteType": "CreditCardEdge",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "node",
"storageKey": null,
"args": null,
"concreteType": "CreditCard",
"plural": false,
"selections": [
v0,
v1,
{
"kind": "ScalarField",
"alias": null,
"name": "brand",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "last_digits",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "expiration_year",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "expiration_month",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "__typename",
"args": null,
"storageKey": null
}
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "cursor",
"args": null,
"storageKey": null
}
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "pageInfo",
"storageKey": null,
"args": null,
"concreteType": "PageInfo",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "endCursor",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "hasNextPage",
"args": null,
"storageKey": null
}
]
}
]
},
{
"kind": "LinkedHandle",
"alias": null,
"name": "creditCards",
"args": [
{
"kind": "Literal",
"name": "first",
"value": 100,
"type": "Int"
}
],
"handle": "connection",
"key": "UserSettingsPayments_creditCards",
"filters": []
}
]
}
]
}
};
})();
(node as any).hash = '4348fdc464691dd048d0144667d6d3b1';
export default node;
| mit |
VKCOM/vk-java-sdk | sdk/src/main/java/com/vk/api/sdk/objects/donut/DonatorSubscriptionInfoStatus.java | 644 | // Autogenerated from vk-api-schema. Please don't edit it manually.
package com.vk.api.sdk.objects.donut;
import com.google.gson.annotations.SerializedName;
import com.vk.api.sdk.queries.EnumParam;
public enum DonatorSubscriptionInfoStatus implements EnumParam {
@SerializedName("active")
ACTIVE("active"),
@SerializedName("expiring")
EXPIRING("expiring");
private final String value;
DonatorSubscriptionInfoStatus(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return value.toLowerCase();
}
}
| mit |
dmitrya2e/filtration-bundle | Filter/Filter/AbstractFilter.php | 27386 | <?php
/*
* This file is part of the Da2e FiltrationBundle package.
*
* (c) Dmitry Abrosimov <abrosimovs@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Da2e\FiltrationBundle\Filter\Filter;
use Da2e\FiltrationBundle\CallableFunction\Validator\AppendFormFieldsFunctionValidator;
use Da2e\FiltrationBundle\CallableFunction\Validator\ApplyFiltersFunctionValidator;
use Da2e\FiltrationBundle\CallableFunction\Validator\CallableFunctionValidatorInterface;
use Da2e\FiltrationBundle\CallableFunction\Validator\ConvertValueFunctionValidator;
use Da2e\FiltrationBundle\CallableFunction\Validator\HasAppliedValueFunctionValidator;
use Da2e\FiltrationBundle\Exception\CallableFunction\Validator\CallableFunctionValidatorException;
use Da2e\FiltrationBundle\Exception\Filter\Filter\FilterException;
use Da2e\FiltrationBundle\Exception\Filter\Filter\InvalidArgumentException;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Base abstract class with maximum functionality for bundles all default filters.
* The class has all possible capabilities:
* - option setting
* - form representation
* - custom callable functions
*
* If you want to make your own custom filter, you can extend this class for convenience.
* However, if you find that it takes too much functions, which you do not actually need,
* you are free to not use it and the only thing that is essentially important **is to implement FilterInterface**.
*
* @author Dmitry Abrosimov <abrosimovs@gmail.com>
* @abstract
*/
abstract class AbstractFilter implements
FilterInterface,
FilterOptionInterface,
FilterHasFormInterface,
CustomApplyFilterInterface,
CustomAppendFormFieldsInterface
{
/**
* Internal name of the filter:
* - used in form name assignment
* - the filter may be retrieved from collection by this name
*
* @var string
*/
protected $name;
/**
* The name of the field in external data sources:
* - raw MySQL
* - Doctrine ORM/MongoDB mapped property
* - ...
*
* @var string
*/
protected $fieldName = '';
/**
* A title of the filter (used as a label of the form).
*
* @var string Empty by default
*/
protected $title = '';
/**
* Form representation options.
*
* @var array $formOptions An empty array by default
*/
protected $formOptions = [];
/**
* Defines if the filter has form representation.
*
* @var bool True by default
*/
protected $hasForm = true;
/**
* The name of the form field type (makes sense to set only if a filter has a form).
*
* **Must be set in child classes.**
*
* @var string
*/
protected $formFieldType = '';
/**
* Custom applyFilter() function.
* Should be the type of "callable".
*
* @var null|callable Null by default
*/
protected $applyFilterFunction = null;
/**
* Custom appendFormFields() function.
* Should be the type of "callable".
*
* @var null|callable Null by default
*/
protected $appendFormFieldsFunction = null;
/**
* Custom function for checking if the filter has been applied.
* Should be the type of "callable".
*
* @var null|callable Null by default
*/
protected $hasAppliedValueFunction = null;
/**
* Custom function for raw value conversion.
* Should be the type of "callable".
*
* @var null|callable Null by default
*/
protected $convertValueFunction = null;
/**
* Filter applied raw value (set by form, for example, or manually):
* - string
* - Collection
* - Entity
* - etc
*
* The value type depends on specific Filter.
* **This value must not be used for filtration. Use AbstractFilter::getConvertedValue() method instead.**
*
* @see AbstractFilter::getConvertedValue()
* @var mixed|null Null by default
*/
protected $value = null;
/**
* The default value for the filter, which is used as value for a forms "data" key.
*
* @var mixed|null Null by default
*/
protected $defaultValue = null;
/**
* The value which is converted from raw value.
* This is the "clean" and workable form of value, which must be used for filtration.
*
* The value is being converted while executing method AbstractFilter::convertValue().
*
* @see AbstractFilter::convertValue()
* @var mixed|null Null by default
*/
protected $convertedValue = null;
/**
* A flag which defines if the value has been already converted, just to prevent double conversion.
*
* @var bool False by default
*/
protected $valueHasBeenConverted = false;
/**
* The default name of the property containing raw value (defaults to AbstractFilter::$value).
*
* @var string "value" by default
*/
protected $valuePropertyName = 'value';
/**
* Callable function "append form fields" validator.
*
* @var bool|CallableFunctionValidatorInterface|ApplyFiltersFunctionValidator
*/
protected $callableValidatorAppendFormFields = false;
/**
* Callable function "apply filters" validator.
*
* @var bool|CallableFunctionValidatorInterface|ApplyFiltersFunctionValidator
*/
protected $callableValidatorApplyFilters = false;
/**
* Callable function "has applied values" validator.
*
* @var bool|CallableFunctionValidatorInterface|HasAppliedValueFunctionValidator
*/
protected $callableValidatorHasAppliedValue = false;
/**
* Callable function "convert value" validator.
*
* @var bool|CallableFunctionValidatorInterface|ConvertValueFunctionValidator
*/
protected $callableValidatorConvertValue = false;
/**
* @param null|string $name Filter name
*/
public function __construct($name = null)
{
if (!empty($name)) {
$this->setName($name);
}
// Configure the filter before any other work is done.
$this->configure();
}
/**
* {@inheritDoc}
*/
public static function getValidOptions()
{
return [
// Base options
'name' => [
'setter' => 'setName',
'empty' => false,
'type' => 'string',
],
'field_name' => [
'setter' => 'setFieldName',
'empty' => false,
'type' => 'string',
],
'default_value' => [
'setter' => 'setDefaultValue',
'empty' => true,
],
'value_property_name' => [
'setter' => 'setValuePropertyName',
'empty' => false,
'type' => 'string',
],
// Form related options
'title' => [
'setter' => 'setTitle',
'empty' => true,
'type' => 'string',
],
'form_options' => [
'setter' => 'setFormOptions',
'empty' => true,
'type' => 'array',
],
'has_form' => [
'setter' => 'setHasForm',
'empty' => false,
'type' => 'bool',
],
'form_field_type' => [
'setter' => 'setFormFieldType',
'empty' => false,
'type' => 'string',
],
// Custom callable functions
'apply_filter_function' => [
'setter' => 'setApplyFilterFunction',
'empty' => false,
'type' => 'callable',
],
'append_form_fields_function' => [
'setter' => 'setAppendFormFieldsFunction',
'empty' => false,
'type' => 'callable',
],
'has_applied_value_function' => [
'setter' => 'setHasAppliedValueFunction',
'empty' => false,
'type' => 'callable',
],
'convert_value_function' => [
'setter' => 'setConvertValueFunction',
'empty' => false,
'type' => 'callable',
],
// Custom callable function validators
'callable_validator_apply_filter' => [
'setter' => 'setCallableValidatorApplyFilter',
'empty' => false,
'type' => 'object',
'instance_of' => '\Da2e\FiltrationBundle\CallableFunction\Validator\CallableFunctionValidatorInterface',
],
'callable_validator_append_form_fields' => [
'setter' => 'setCallableValidatorAppendFormFields',
'empty' => false,
'type' => 'object',
'instance_of' => '\Da2e\FiltrationBundle\CallableFunction\Validator\CallableFunctionValidatorInterface',
],
'callable_validator_has_applied_value' => [
'setter' => 'setCallableValidatorHasAppliedValue',
'empty' => false,
'type' => 'object',
'instance_of' => '\Da2e\FiltrationBundle\CallableFunction\Validator\CallableFunctionValidatorInterface',
],
'callable_validator_convert_value' => [
'setter' => 'setCallableValidatorConvertValue',
'empty' => false,
'type' => 'object',
'instance_of' => '\Da2e\FiltrationBundle\CallableFunction\Validator\CallableFunctionValidatorInterface',
],
];
}
/**
* {@inheritDoc}
*
* @abstract
*/
abstract public function applyFilter($handler);
/**
* {@inheritDoc}
*
* @abstract
*/
abstract public function getType();
/**
* Converts raw value into appropriate form to work with.
* The converted value must be returned by the method.
*
* @return mixed The converted value
* @abstract
*/
abstract protected function convertValue();
/**
* {@inheritDoc}
*
* @throws FilterException if was not implemented in child filter
*/
public function appendFormFieldsToForm(FormBuilderInterface $formBuilder)
{
throw new FilterException('You must implement this method in child classes.');
}
/**
* Checks if the filter value was applied.
* Note, that the converted value is used for checking.
*
* If there is a custom function for checking if the filter value is applied,
* it will be executed instead of default checking.
* Note, that custom function must return boolean result of checking if the filter value has been applied.
*
* @see AbstractFilter::getConvertedValue()
* @see AbstractFilter::getHasAppliedValueFunction() for custom function for checking if the filter value is applied
*
* @return bool
*
* @throws FilterException On invalid custom function returned value
*/
public function hasAppliedValue()
{
$customFunction = $this->getHasAppliedValueFunction();
if (is_callable($customFunction)) {
$result = call_user_func($customFunction, $this);
if (!is_bool($result)) {
throw new FilterException('Returned value from callable function must be boolean.');
}
return $result;
}
$convertedValue = $this->getConvertedValue();
if (is_array($convertedValue)) {
return count($convertedValue) > 0;
}
if (is_string($convertedValue)) {
return $convertedValue !== '';
}
// Fallback to empty() function by default.
// If the value is int/float and it is equal to 0, it will be considered that the value has not been applied.
// To change this behaviour, please override this method.
return !empty($convertedValue);
}
/**
* Gets the converted value for specific filter.
* If the values has not been converted yet, the AbstractFilter::executeValueConversion() method will be executed.
*
* @see AbstractFilter::executeValueConversion()
* @return mixed
*/
public function getConvertedValue()
{
if ($this->valueHasBeenConverted === false) {
$this->convertedValue = $this->executeValueConversion();
$this->valueHasBeenConverted = true;
}
return $this->convertedValue;
}
/**
* {@inheritDoc}
*/
public function getName()
{
return $this->name;
}
/**
* {@inheritDoc}
*
* @return static
* @throws InvalidArgumentException On invalid argument
*/
public function setName($name)
{
if (!is_string($name) || $name === '') {
throw new InvalidArgumentException('"Name" argument must be a string and must not empty.');
}
$this->name = $name;
return $this;
}
/**
* Gets the field name for the external data source of the filter.
*
* @return string
*/
public function getFieldName()
{
return $this->fieldName;
}
/**
* {@inheritDoc}
*
* @return static
* @throws InvalidArgumentException On invalid argument
*/
public function setFieldName($fieldName)
{
if (!is_string($fieldName) || $fieldName === '') {
throw new InvalidArgumentException('"Field name" argument must be a string and must not empty.');
}
$this->fieldName = $fieldName;
return $this;
}
/**
* Gets the title of the filter.
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Sets the title of the filter.
*
* @param string $title
*
* @return static
* @throws InvalidArgumentException On invalid argument
*/
public function setTitle($title)
{
if (!is_string($title)) {
throw new InvalidArgumentException('"Title" argument must be a string.');
}
$this->title = $title;
return $this;
}
/**
* Sets form options.
* The option array is fully compatible with Symfony form options.
*
* @param array $formOptions
*
* @return static
*/
public function setFormOptions(array $formOptions)
{
$this->formOptions = $formOptions;
return $this;
}
/**
* Gets form options.
*
* @return array
*/
public function getFormOptions()
{
return $this->formOptions;
}
/**
* Sets custom "has applied value" function.
* The function must return boolean result (result of checking if the filter value has been applied).
*
* @param callable $function
*
* @see HasAppliedValueFunctionValidator
*
* @return static
* @throws CallableFunctionValidatorException On invalid callable arguments
*/
public function setHasAppliedValueFunction(callable $function)
{
$validator = $this->getCallableValidatorHasAppliedValue();
$validator->setCallableFunction($function);
if ($validator->isValid() === false) {
throw $validator->getException();
}
$this->hasAppliedValueFunction = $function;
return $this;
}
/**
* Gets a custom function (lambda) for checking if the filter was applied.
*
* @return null|callable
*/
public function getHasAppliedValueFunction()
{
return $this->hasAppliedValueFunction;
}
/**
* Sets custom "apply filter" function.
*
* @param callable $function
*
* @see ApplyFiltersFunctionValidator
*
* @return static
* @throws CallableFunctionValidatorException On invalid callable arguments
*/
public function setApplyFilterFunction(callable $function)
{
$validator = $this->getCallableValidatorApplyFilters();
$validator->setCallableFunction($function);
if ($validator->isValid() === false) {
throw $validator->getException();
}
$this->applyFilterFunction = $function;
return $this;
}
/**
* {@inheritDoc}
*
* @return null|callable
*/
public function getApplyFilterFunction()
{
return $this->applyFilterFunction;
}
/**
* Sets custom "append form fields" function.
*
* @param callable $function
*
* @see AppendFormFieldsFunctionValidator
*
* @return static
* @throws CallableFunctionValidatorException On invalid callable arguments
*/
public function setAppendFormFieldsFunction(callable $function)
{
$validator = $this->getCallableValidatorAppendFormFields();
$validator->setCallableFunction($function);
if ($validator->isValid() === false) {
throw $validator->getException();
}
$this->appendFormFieldsFunction = $function;
return $this;
}
/**
* {@inheritDoc}
*
* @return null|callable
*/
public function getAppendFormFieldsFunction()
{
return $this->appendFormFieldsFunction;
}
/**
* Sets custom "convert value" function.
*
* @param callable $function
*
* @see ConvertValueFunctionValidator
*
* @return static
* @throws CallableFunctionValidatorException On invalid callable arguments
*/
public function setConvertValueFunction(callable $function)
{
$validator = $this->getCallableValidatorConvertValue();
$validator->setCallableFunction($function);
if ($validator->isValid() === false) {
throw $validator->getException();
}
$this->convertValueFunction = $function;
return $this;
}
/**
* Gets a custom function (lambda) for value conversion. The function must have an input signature with 1 argument:
* - filter object (instance of \Da2e\FiltrationBundle\Filter\Filter\FilterInterface)
*
* @return null|callable
*/
public function getConvertValueFunction()
{
return $this->convertValueFunction;
}
/**
* Defines if the filter has a form representation.
*
* @param boolean $hasForm
*
* @return static
* @throws InvalidArgumentException On invalid argument
*/
public function setHasForm($hasForm)
{
if (!is_bool($hasForm)) {
throw new InvalidArgumentException('"Has form" argument must be boolean.');
}
$this->hasForm = $hasForm;
return $this;
}
/**
* {@inheritDoc}
*
* @return boolean
*/
public function hasForm()
{
return $this->hasForm;
}
/**
* Gets the raw value of the filter.
*
* @return mixed
*/
public function getValue()
{
return $this->value;
}
/**
* Sets the raw value of the filter (via form or manually).
*
* @param mixed $value
*
* @return static
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Sets the default value of the filter.
*
* @param mixed $value
*
* @return static
*/
public function setDefaultValue($value)
{
$this->defaultValue = $value;
return $this;
}
/**
* Gets the default value of the filter.
*
* @return mixed
*/
public function getDefaultValue()
{
return $this->defaultValue;
}
/**
* Sets the name of the property which contains the raw value.
*
* @param string $valuePropertyName
*
* @return static
* @throws InvalidArgumentException On invalid argument
*/
public function setValuePropertyName($valuePropertyName)
{
if (!is_string($valuePropertyName) || $valuePropertyName === '') {
throw new InvalidArgumentException('"Value property name" argument must be a string and must not empty.');
}
if (!property_exists($this, $valuePropertyName)) {
throw new InvalidArgumentException(sprintf('Property "%s" does not exist.', $valuePropertyName));
}
$this->valuePropertyName = $valuePropertyName;
return $this;
}
/**
* Gets the name of the property which contains the raw value.
*
* @return string
*/
public function getValuePropertyName()
{
return $this->valuePropertyName;
}
/**
* Gets form field type.
*
* @return string
*/
public function getFormFieldType()
{
return $this->formFieldType;
}
/**
* Sets form field type.
*
* @param string $formFieldType
*
* @return static
* @throws InvalidArgumentException On invalid argument
*/
public function setFormFieldType($formFieldType)
{
if (!is_string($formFieldType) || $formFieldType === '') {
throw new InvalidArgumentException('"Form field type" argument must be a string and must not empty.');
}
$this->formFieldType = $formFieldType;
return $this;
}
/**
* Sets "append form fields" callable function validator.
*
* @return CallableFunctionValidatorInterface|AppendFormFieldsFunctionValidator
*/
public function getCallableValidatorAppendFormFields()
{
if ($this->callableValidatorAppendFormFields === false) {
$this->callableValidatorAppendFormFields = new AppendFormFieldsFunctionValidator();
}
return $this->callableValidatorAppendFormFields;
}
/**
* Sets "append form fields" callable function validator.
*
* @param CallableFunctionValidatorInterface $callableValidatorAppendFormFields
*
* @return static
*/
public function setCallableValidatorAppendFormFields(
CallableFunctionValidatorInterface $callableValidatorAppendFormFields
) {
$this->callableValidatorAppendFormFields = $callableValidatorAppendFormFields;
return $this;
}
/**
* Gets "apply filters" callable function validator.
*
* @return CallableFunctionValidatorInterface|ApplyFiltersFunctionValidator
*/
public function getCallableValidatorApplyFilters()
{
if ($this->callableValidatorApplyFilters === false) {
$this->callableValidatorApplyFilters = new ApplyFiltersFunctionValidator();
}
return $this->callableValidatorApplyFilters;
}
/**
* Sets "apply filters" callable function validator.
*
* @param CallableFunctionValidatorInterface $callableValidatorApplyFilters
*
* @return static
*/
public function setCallableValidatorApplyFilters(CallableFunctionValidatorInterface $callableValidatorApplyFilters)
{
$this->callableValidatorApplyFilters = $callableValidatorApplyFilters;
return $this;
}
/**
* Gets "has applied value" callable function validator.
*
* @return CallableFunctionValidatorInterface|HasAppliedValueFunctionValidator
*/
public function getCallableValidatorHasAppliedValue()
{
if ($this->callableValidatorHasAppliedValue === false) {
$this->callableValidatorHasAppliedValue = new HasAppliedValueFunctionValidator();
}
return $this->callableValidatorHasAppliedValue;
}
/**
* Sets "has applied value" callable function validator.
*
* @param CallableFunctionValidatorInterface $callableValidatorHasAppliedValue
*
* @return static
*/
public function setCallableValidatorHasAppliedValue(
CallableFunctionValidatorInterface $callableValidatorHasAppliedValue
) {
$this->callableValidatorHasAppliedValue = $callableValidatorHasAppliedValue;
return $this;
}
/**
* Gets "convert value" callable function validator.
*
* @return CallableFunctionValidatorInterface|ConvertValueFunctionValidator
*/
public function getCallableValidatorConvertValue()
{
if ($this->callableValidatorConvertValue === false) {
$this->callableValidatorConvertValue = new ConvertValueFunctionValidator();
}
return $this->callableValidatorConvertValue;
}
/**
* Sets "convert value" callable function validator.
*
* @param CallableFunctionValidatorInterface $callableValidatorConvertValue
*
* @return static
*/
public function setCallableValidatorConvertValue(
CallableFunctionValidatorInterface $callableValidatorConvertValue
) {
$this->callableValidatorConvertValue = $callableValidatorConvertValue;
return $this;
}
/**
* Configures filter (being executed in filter constructor).
* If something needs to be configured before any work is done, it can be achieved via this method.
*
* @return static
*/
protected function configure()
{
return $this;
}
/**
* Executes raw value conversion into appropriate form to work with.
* If there is a custom function for value conversion, it will be executed.
* Otherwise standard abstract convertValue() method will be executed.
*
* @see AbstractFilter::getConvertValueFunction()
* @see AbstractFilter::convertValue()
*
* @return mixed
*/
protected function executeValueConversion()
{
$customFunction = $this->getConvertValueFunction();
if (is_callable($customFunction)) {
return call_user_func($customFunction, $this);
}
return $this->convertValue();
}
}
| mit |
Albeoris/Memoria | Assembly-CSharp/Global/ChocographUI.cs | 16697 | using System;
using System.Collections.Generic;
using Assets.Scripts.Common;
using Assets.Sources.Scripts.UI.Common;
using UnityEngine;
using Object = System.Object;
public class ChocographUI : UIScene
{
public override void Show(UIScene.SceneVoidDelegate afterFinished = null)
{
UIScene.SceneVoidDelegate sceneVoidDelegate = delegate
{
ButtonGroupState.SetPointerDepthToGroup(4, ChocographUI.ItemGroupButton);
ButtonGroupState.SetPointerOffsetToGroup(new Vector2(30f, 0f), ChocographUI.ItemGroupButton);
ButtonGroupState.SetPointerLimitRectToGroup(this.ChocographListPanel.GetComponent<UIWidget>(), (Single)this.chocographScrollList.ItemHeight, ChocographUI.ItemGroupButton);
ButtonGroupState.SetScrollButtonToGroup(this.chocoboScrollButton, ChocographUI.ItemGroupButton);
ButtonGroupState.RemoveCursorMemorize(ChocographUI.SubMenuGroupButton);
ButtonGroupState.ActiveGroup = ChocographUI.SubMenuGroupButton;
};
if (afterFinished != null)
{
sceneVoidDelegate = (UIScene.SceneVoidDelegate)Delegate.Combine(sceneVoidDelegate, afterFinished);
}
SceneDirector.FadeEventSetColor(FadeMode.Sub, Color.black);
base.Show(sceneVoidDelegate);
this.ClearLatestUI();
this.GetEventData();
this.DisplayChocoboAbilityInfo();
this.DisplayInventoryInfo();
this.DisplayChocographList();
if (FF9StateSystem.PCPlatform)
{
this.HelpDespLabelGameObject.SetActive(true);
}
else
{
this.HelpDespLabelGameObject.SetActive(false);
}
if (ChocographUI.CurrentSelectedChocograph != -1)
{
ButtonGroupState.SetCursorStartSelect(this.chocographItemList[ChocographUI.CurrentSelectedChocograph].Self, ChocographUI.ItemGroupButton);
this.DisplaySelected(ChocographUI.CurrentSelectedChocograph);
this.SetCancelButton(true);
this.chocographScrollList.ScrollToIndex(ChocographUI.CurrentSelectedChocograph);
}
else
{
ButtonGroupState.SetCursorStartSelect(this.chocographItemList[0].Self, ChocographUI.ItemGroupButton);
this.SetCancelButton(false);
this.chocographScrollList.ScrollToIndex(0);
}
this.chocoboScrollButton.DisplayScrollButton(false, false);
}
public override void Hide(UIScene.SceneVoidDelegate afterFinished = null)
{
UIScene.SceneVoidDelegate sceneVoidDelegate = delegate
{
PersistenSingleton<UIManager>.Instance.ChangeUIState(PersistenSingleton<UIManager>.Instance.HUDState);
};
if (afterFinished != null)
{
sceneVoidDelegate = (UIScene.SceneVoidDelegate)Delegate.Combine(sceneVoidDelegate, afterFinished);
}
base.Hide(sceneVoidDelegate);
this.RemoveCursorMemorize();
}
private void RemoveCursorMemorize()
{
ButtonGroupState.RemoveCursorMemorize(ChocographUI.ItemGroupButton);
}
public override Boolean OnKeyConfirm(GameObject go)
{
if (base.OnKeyConfirm(go))
{
if (ButtonGroupState.ActiveGroup == ChocographUI.SubMenuGroupButton)
{
this.currentMenu = this.GetSubMenuFromGameObject(go);
if (this.currentMenu == ChocographUI.SubMenu.Select)
{
FF9Sfx.FF9SFX_Play(103);
ButtonGroupState.RemoveCursorMemorize(ChocographUI.ItemGroupButton);
ButtonGroupState.ActiveGroup = ChocographUI.ItemGroupButton;
ButtonGroupState.SetSecondaryOnGroup(ChocographUI.SubMenuGroupButton);
ButtonGroupState.HoldActiveStateOnGroup(ChocographUI.SubMenuGroupButton);
}
else if (this.currentMenu == ChocographUI.SubMenu.Cancel)
{
if (this.hasSelectedItem)
{
FF9Sfx.FF9SFX_Play(107);
this.SetCancelButton(false);
FF9StateSystem.Common.FF9.hintmap_id = 0;
ChocographUI.CurrentSelectedChocograph = -1;
this.hasSelectedItem = false;
this.SelectedContentPanel.SetActive(false);
}
else
{
FF9Sfx.FF9SFX_Play(102);
}
}
}
else if (ButtonGroupState.ActiveGroup == ChocographUI.ItemGroupButton)
{
if (ButtonGroupState.ContainButtonInGroup(go, ChocographUI.ItemGroupButton))
{
Int32 id = go.GetComponent<ScrollItemKeyNavigation>().ID;
if (!this.hasMap[id])
{
FF9Sfx.FF9SFX_Play(102);
return true;
}
if (this.ability <= this.GetIconType(id))
{
FF9Sfx.FF9SFX_Play(102);
return true;
}
FF9Sfx.FF9SFX_Play(107);
ChocographUI.CurrentSelectedChocograph = id;
FF9StateSystem.Common.FF9.hintmap_id = 1 + ChocographUI.CurrentSelectedChocograph;
this.DisplaySelected(id);
this.SetCancelButton(true);
}
else
{
this.OnSecondaryGroupClick(go);
}
}
}
return true;
}
public override Boolean OnKeyCancel(GameObject go)
{
if (base.OnKeyCancel(go))
{
if (ButtonGroupState.ActiveGroup == ChocographUI.SubMenuGroupButton)
{
FF9Sfx.FF9SFX_Play(101);
this.Hide((UIScene.SceneVoidDelegate)null);
}
if (ButtonGroupState.ActiveGroup == ChocographUI.ItemGroupButton)
{
FF9Sfx.FF9SFX_Play(101);
ButtonGroupState.ActiveGroup = ChocographUI.SubMenuGroupButton;
this.HintContentPanel.SetActive(false);
}
}
return true;
}
public override Boolean OnItemSelect(GameObject go)
{
if (base.OnItemSelect(go) && ButtonGroupState.ActiveGroup == ChocographUI.ItemGroupButton)
{
this.currentSelectItemIndex = go.GetComponent<ScrollItemKeyNavigation>().ID;
if (this.hasMap[this.currentSelectItemIndex])
{
this.HintContentPanel.SetActive(true);
this.DisplayHint(this.currentSelectItemIndex);
}
else
{
this.HintContentPanel.SetActive(false);
}
ButtonGroupState.SetCursorStartSelect(go, ChocographUI.ItemGroupButton);
}
return true;
}
private void OnSecondaryGroupClick(GameObject go)
{
ButtonGroupState.HoldActiveStateOnGroup(go, ChocographUI.SubMenuGroupButton);
if (ButtonGroupState.ActiveGroup == ChocographUI.ItemGroupButton)
{
FF9Sfx.muteSfx = true;
this.OnKeyCancel(this.chocographItemList[this.currentSelectItemIndex].Self);
FF9Sfx.muteSfx = false;
this.OnKeyConfirm(go);
}
}
private Int32 GetIconType(Int32 id)
{
ChocographUI.Icon[] array = new ChocographUI.Icon[]
{
ChocographUI.Icon.Field,
ChocographUI.Icon.Field,
ChocographUI.Icon.Field,
ChocographUI.Icon.Field,
ChocographUI.Icon.Field,
ChocographUI.Icon.Field,
ChocographUI.Icon.Reef,
ChocographUI.Icon.Reef,
ChocographUI.Icon.Reef,
ChocographUI.Icon.Reef,
ChocographUI.Icon.Reef,
ChocographUI.Icon.Reef,
ChocographUI.Icon.Mountain,
ChocographUI.Icon.Mountain,
ChocographUI.Icon.Mountain,
ChocographUI.Icon.Mountain,
ChocographUI.Icon.Sea,
ChocographUI.Icon.Sea,
ChocographUI.Icon.Sea,
ChocographUI.Icon.Sea,
ChocographUI.Icon.Sky,
ChocographUI.Icon.Sky,
ChocographUI.Icon.Sky,
ChocographUI.Icon.Sky
};
return (Int32)array[id];
}
public static void UpdateEquipedHintMap()
{
if (FF9StateSystem.Common.FF9.hintmap_id > 24)
{
FF9StateSystem.Common.FF9.hintmap_id = 0;
ChocographUI.CurrentSelectedChocograph = -1;
}
else
{
ChocographUI.CurrentSelectedChocograph = FF9StateSystem.Common.FF9.hintmap_id - 1;
ChocographUI.CurrentSelectedChocograph = (Int32)((ChocographUI.CurrentSelectedChocograph >= 0) ? ChocographUI.CurrentSelectedChocograph : -1);
}
}
private void GetEventData()
{
this.hasMap.Clear();
this.hasGem.Clear();
ChocographUI.UpdateEquipedHintMap();
Int32 num = 0;
Int32 num2 = 0;
this.ability = (Int32)FF9StateSystem.EventState.gEventGlobal[191];
this.mapCount = 0;
this.gemCount = 0;
for (Int32 i = 0; i < 3; i++)
{
num |= (Int32)FF9StateSystem.EventState.gEventGlobal[187 + i] << i * 8;
num2 |= (Int32)FF9StateSystem.EventState.gEventGlobal[184 + i] << i * 8;
}
for (Int32 j = 0; j < 24; j++)
{
this.hasMap.Add((num & 1 << j) != 0);
if (this.hasMap[j])
{
this.mapCount++;
}
this.hasGem.Add((num2 & 1 << j) != 0);
if (this.hasGem[j])
{
this.gemCount++;
}
}
}
private void DisplayChocoboAbilityInfo()
{
for (Int32 i = 0; i < this.ability; i++)
{
this.ChocoboAbilityInfo.AbilitySpriteList[i].spriteName = this.GetAbilitySprite(i);
}
}
private void DisplayInventoryInfo()
{
this.InventoryNumber.text = this.mapCount.ToString();
this.LocationFoundNumber.text = this.gemCount.ToString();
}
private void ClearLatestUI()
{
this.HintContentPanel.SetActive(false);
this.SelectedContentPanel.SetActive(false);
this.ChocoboAbilityInfo.ClearAbility();
this.HintAbilityRequired.ClearAbility();
this.ClearChocoGraphList();
}
private void DisplayChocographList()
{
for (Int32 i = 0; i < this.chocographItemList.Count; i++)
{
ChocographUI.ChocographItem chocographItem = this.chocographItemList[i];
if (!this.hasMap[i])
{
chocographItem.Button.Help.Enable = false;
}
else
{
Boolean flag = this.ability > this.GetIconType(i);
chocographItem.Content.SetActive(true);
String iconSprite = this.GetIconSprite((ChocographUI.Icon)((!this.hasGem[i]) ? ((ChocographUI.Icon)((!flag) ? ChocographUI.Icon.BoxDisableClose : ChocographUI.Icon.BoxClose)) : ((ChocographUI.Icon)((!flag) ? ChocographUI.Icon.BoxDisableOpen : ChocographUI.Icon.BoxOpen))));
chocographItem.IconSprite.spriteName = iconSprite;
chocographItem.ItemName.text = FF9TextTool.ChocoboUIText(i + (Int32)FF9TextTool.ChocographNameStartIndex);
chocographItem.ItemName.color = ((!flag) ? FF9TextTool.Gray : FF9TextTool.White);
chocographItem.Button.Help.Enable = true;
chocographItem.Button.Help.TextKey = String.Empty;
if (flag)
{
chocographItem.Button.Help.TextKey = FF9TextTool.ChocoboUIText(i + (Int32)FF9TextTool.ChocographHelpStartIndex);
}
else
{
chocographItem.Button.Help.TextKey = FF9TextTool.ChocoboUIText(5);
}
}
}
}
private void ClearChocoGraphList()
{
for (Int32 i = 0; i < this.chocographItemList.Count; i++)
{
ChocographUI.ChocographItem chocographItem = this.chocographItemList[i];
chocographItem.Content.SetActive(false);
}
}
private String GetIconSprite(ChocographUI.Icon icon)
{
switch (icon)
{
case ChocographUI.Icon.BoxOpen:
return "chocograph_box_open";
case ChocographUI.Icon.BoxDisableOpen:
return "chocograph_box_open_null";
case ChocographUI.Icon.BoxClose:
return "chocograph_box_close";
case ChocographUI.Icon.BoxDisableClose:
return "chocograph_box_close_null";
default:
return String.Empty;
}
}
private void DisplayHint(Int32 currentOnSelectItemIndex)
{
this.HintAbilityRequired.ClearAbility();
this.HintMap.spriteName = "chocograph_map_" + currentOnSelectItemIndex.ToString("D" + 2);
this.HintText.text = FF9TextTool.ChocoboUIText(currentOnSelectItemIndex + (Int32)FF9TextTool.ChocographDetailStartIndex);
Int32 iconType = this.GetIconType(currentOnSelectItemIndex);
for (Int32 i = 0; i <= iconType; i++)
{
String abilitySprite = this.GetAbilitySprite((Int32)((this.ability <= i) ? 5 : i));
this.HintAbilityRequired.AbilitySpriteList[i].spriteName = abilitySprite;
}
}
private String GetAbilitySprite(Int32 iconIndex)
{
switch (iconIndex)
{
case 0:
return "chocograph_icon_field";
case 1:
return "chocograph_icon_reef";
case 2:
return "chocograph_icon_mt";
case 3:
return "chocograph_icon_sea";
case 4:
return "chocograph_icon_sky";
case 5:
return "chocograph_icon_unknown_null";
default:
return String.Empty;
}
}
private void SetCancelButton(Boolean isEnable)
{
if (isEnable)
{
this.CancelSubMenu.GetChild(1).GetComponent<UILabel>().color = FF9TextTool.White;
ButtonGroupState.SetButtonAnimation(this.CancelSubMenu, true);
}
else
{
this.CancelSubMenu.GetChild(1).GetComponent<UILabel>().color = FF9TextTool.Gray;
ButtonGroupState.SetButtonAnimation(this.CancelSubMenu, false);
}
}
private ChocographUI.SubMenu GetSubMenuFromGameObject(GameObject go)
{
if (go == this.SelectSubMenu)
{
return ChocographUI.SubMenu.Select;
}
if (go == this.CancelSubMenu)
{
return ChocographUI.SubMenu.Cancel;
}
return ChocographUI.SubMenu.None;
}
private void DisplaySelected(Int32 currentSelectedItemIndex)
{
this.hasSelectedItem = true;
this.SelectedContentPanel.SetActive(true);
this.SelectedMap.spriteName = "chocograph_map_" + currentSelectedItemIndex.ToString("0#");
this.SelectedItemIcon.spriteName = this.chocographItemList[currentSelectedItemIndex].IconSprite.spriteName;
this.SelectedItemLabel.text = this.chocographItemList[currentSelectedItemIndex].ItemName.text;
}
private void Awake()
{
base.FadingComponent = this.ScreenFadeGameObject.GetComponent<HonoFading>();
UIEventListener uieventListener = UIEventListener.Get(this.SelectSubMenu);
uieventListener.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(uieventListener.onClick, new UIEventListener.VoidDelegate(this.onClick));
UIEventListener uieventListener2 = UIEventListener.Get(this.CancelSubMenu);
uieventListener2.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(uieventListener2.onClick, new UIEventListener.VoidDelegate(this.onClick));
foreach (Object obj in this.ChocographListPanel.GetChild(1).GetChild(0).transform)
{
Transform transform = (Transform)obj;
this.chocographItemList.Add(new ChocographUI.ChocographItem(transform.gameObject));
UIEventListener uieventListener3 = UIEventListener.Get(transform.gameObject);
uieventListener3.onClick = (UIEventListener.VoidDelegate)Delegate.Combine(uieventListener3.onClick, new UIEventListener.VoidDelegate(this.onClick));
}
this.chocoboScrollButton = this.ChocographListPanel.GetChild(0).GetComponent<ScrollButton>();
this.chocographScrollList = this.ChocographListPanel.GetChild(1).GetComponent<SnapDragScrollView>();
this.ChocoboAbilityInfo = new ChocographUI.ChocoboAbility(this.ChocoboAbilityInfoPanel);
this.ChocoboAbilityInfo.ClearAbility();
this.HintAbilityRequired = new ChocographUI.ChocoboAbility(this.HintAbilityRequiredPanel);
this.HintAbilityRequired.ClearAbility();
}
private const Int32 HintMapMax = 24;
public static Int32 CurrentSelectedChocograph = -1;
public GameObject ScreenFadeGameObject;
public GameObject HelpDespLabelGameObject;
public GameObject ChocographListPanel;
public GameObject SelectedContentPanel;
public GameObject HintContentPanel;
public GameObject ChocoboAbilityInfoPanel;
public UILabel InventoryNumber;
public UILabel LocationFoundNumber;
public UISprite SelectedMap;
public UILabel SelectedItemLabel;
public UISprite SelectedItemIcon;
public UISprite HintMap;
public UILabel HintText;
public GameObject HintAbilityRequiredPanel;
public GameObject SelectSubMenu;
public GameObject CancelSubMenu;
private ChocographUI.SubMenu currentMenu;
private Int32 currentSelectItemIndex;
private static String SubMenuGroupButton = "Chocograph.SubMenu";
private static String ItemGroupButton = "Chocograph.Item";
private ChocographUI.ChocoboAbility ChocoboAbilityInfo;
private ChocographUI.ChocoboAbility HintAbilityRequired;
private List<ChocographUI.ChocographItem> chocographItemList = new List<ChocographUI.ChocographItem>();
private SnapDragScrollView chocographScrollList;
private ScrollButton chocoboScrollButton;
private Boolean hasSelectedItem;
private Int32 ability = 1;
private List<Boolean> hasMap = new List<Boolean>();
private List<Boolean> hasGem = new List<Boolean>();
private Int32 mapCount;
private Int32 gemCount;
public class ChocoboAbility
{
public ChocoboAbility(GameObject go)
{
this.AbilitySpriteList = new UISprite[]
{
go.GetChild(0).GetComponent<UISprite>(),
go.GetChild(1).GetComponent<UISprite>(),
go.GetChild(2).GetComponent<UISprite>(),
go.GetChild(3).GetComponent<UISprite>(),
go.GetChild(4).GetComponent<UISprite>()
};
}
public void ClearAbility()
{
UISprite[] abilitySpriteList = this.AbilitySpriteList;
for (Int32 i = 0; i < (Int32)abilitySpriteList.Length; i++)
{
UISprite uisprite = abilitySpriteList[i];
uisprite.spriteName = String.Empty;
}
}
public UISprite[] AbilitySpriteList;
}
public class ChocographItem
{
public ChocographItem(GameObject go)
{
this.Self = go;
this.Content = go.GetChild(0);
this.Button = go.GetComponent<ButtonGroupState>();
this.IconSprite = go.GetChild(0).GetChild(0).GetComponent<UISprite>();
this.ItemName = go.GetChild(0).GetChild(1).GetComponent<UILabel>();
}
public GameObject Self;
public GameObject Content;
public ButtonGroupState Button;
public UISprite IconSprite;
public UILabel ItemName;
}
private enum SubMenu
{
Select,
Cancel,
None
}
private enum Icon
{
Field,
Reef,
Mountain,
Sea,
Sky,
Unknown,
BoxOpen,
BoxDisableOpen,
BoxClose,
BoxDisableClose
}
}
| mit |
hdrezei/dotnetcore-rabbitmq | nyom/nyom.infra/Migrations/Crm/20170817180832_CrmMigration17082017-2.cs | 4946 | using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace nyom.infra.Migrations.Crm
{
public partial class CrmMigration170820172 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Campanhas",
columns: table => new
{
CampanhaId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
DataCriacao = table.Column<DateTime>(type: "datetime2", nullable: false),
DataInicio = table.Column<DateTime>(type: "datetime2", nullable: false),
Nome = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Publico = table.Column<int>(type: "int", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
TemplateId = table.Column<Guid>(type: "uniqueidentifier", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Campanhas", x => x.CampanhaId);
});
migrationBuilder.CreateTable(
name: "Empresas",
columns: table => new
{
EmpresaId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CNPJ = table.Column<string>(type: "nvarchar(max)", nullable: false),
Email = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Nome = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
RazaoSocial = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Telefone = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Empresas", x => x.EmpresaId);
});
migrationBuilder.CreateTable(
name: "Pessoas",
columns: table => new
{
PessoaId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Bairro = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
CEP = table.Column<string>(type: "varchar(8)", maxLength: 8, nullable: false),
CPF = table.Column<string>(type: "varchar(11)", maxLength: 11, nullable: false),
CampanhaId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Cidade = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
DataNascimento = table.Column<DateTime>(type: "datetime2", nullable: false),
Email = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Endereco = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Estado = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Nome = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Sobrenome = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Telefone = table.Column<string>(type: "varchar(11)", maxLength: 11, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Pessoas", x => x.PessoaId);
});
migrationBuilder.CreateTable(
name: "Templates",
columns: table => new
{
TemplateId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
DataCriacao = table.Column<DateTime>(type: "datetime2", nullable: false),
Mensagem = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Nome = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Status = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Templates", x => x.TemplateId);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Campanhas");
migrationBuilder.DropTable(
name: "Empresas");
migrationBuilder.DropTable(
name: "Pessoas");
migrationBuilder.DropTable(
name: "Templates");
}
}
}
| mit |
shuheikawai/robosys2015 | scripts/PlayMusicRobot.py | 246 | #!/usr/bin/env python
#For Raspberry Pi2
import rospy
from std_msgs.msg import String
def callback(message):
rospy.loginfo("%s",message.data)
rospy.init_node('PlayMusicRobot')
sub = rospy.Subscriber('HandOff',String,callback)
rospy.spin()
| mit |
wgcrouch/scrum-board | src/Itsallagile/UserBundle/DependencyInjection/ItsallagileUserExtension.php | 769 | <?php
namespace Itsallagile\UserBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class ItsallagileUserExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
| mit |
qweer28/library | application/views/page.php | 87 | <br>
<br>
<div class="col-md-offset-5">
<h1> 简易图书管理系统 </h1>
</div>
| mit |
Mewel/abbyy-to-alto | src/main/java/org/mycore/xml/alto/v2/ProcessingSoftwareType.java | 4012 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.04.18 at 03:28:59 PM CEST
//
package org.mycore.xml.alto.v2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* Information about a software application. Where applicable, the preferred method for determining this information is by selecting Help --> About.
*
* <p>Java class for processingSoftwareType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="processingSoftwareType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="softwareCreator" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="softwareName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="softwareVersion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="applicationDescription" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "processingSoftwareType", propOrder = {
"softwareCreator",
"softwareName",
"softwareVersion",
"applicationDescription"
})
public class ProcessingSoftwareType {
protected String softwareCreator;
protected String softwareName;
protected String softwareVersion;
protected String applicationDescription;
/**
* Gets the value of the softwareCreator property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSoftwareCreator() {
return softwareCreator;
}
/**
* Sets the value of the softwareCreator property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSoftwareCreator(String value) {
this.softwareCreator = value;
}
/**
* Gets the value of the softwareName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSoftwareName() {
return softwareName;
}
/**
* Sets the value of the softwareName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSoftwareName(String value) {
this.softwareName = value;
}
/**
* Gets the value of the softwareVersion property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSoftwareVersion() {
return softwareVersion;
}
/**
* Sets the value of the softwareVersion property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSoftwareVersion(String value) {
this.softwareVersion = value;
}
/**
* Gets the value of the applicationDescription property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getApplicationDescription() {
return applicationDescription;
}
/**
* Sets the value of the applicationDescription property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setApplicationDescription(String value) {
this.applicationDescription = value;
}
}
| mit |
ramonli/RabbitMQResearch | src/test/java/com/mpos/lottery/te/thirdpartyservice/amqp/RabbitFirehoseMessageConsumerMain.java | 1220 | package com.mpos.lottery.te.thirdpartyservice.amqp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitFirehoseMessageConsumerMain {
private static Log logger = LogFactory.getLog(RabbitFirehoseMessageConsumerMain.class);
public static final String EXCHANGE_NAME = "amq.rabbitmq.trace";
public static void main(String[] argv) throws Exception {
RabbitMessageConsumer main = new RabbitMessageConsumer("192.168.2.152", true,
"amqp", "amqp");
main.consume(EXCHANGE_NAME, RabbitMessagePublisher.class.getName(), new String[] { "publish.*",
"deliver.*" }, 1);
}
public static void deleteQueue() throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.2.152");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel = connection.createChannel();
channel.queueDelete(RabbitMessagePublisher.class.getName());
connection.close();
}
}
| mit |
vvromanov/hilo_utils | src/SignalWatcher.cpp | 2311 | #include <zconf.h>
#include <execinfo.h>
#include "SignalWatcher.h"
#include "LogBase.h"
on_signal_t *on_sighup = nullptr;
on_signal_t *on_sigusr1 = nullptr;
static ev_signal sigint;
static ev_signal sighup;
static ev_signal sigusr1;
static ev_signal sigterm;
static ev_signal sigquit;
static ev_signal sigsegv;
static const char *signame(int signum) {
#define S(s) case s: return #s;
switch (signum) {
S(SIGHUP)
S(SIGINT)
S(SIGQUIT)
S(SIGILL)
S(SIGTRAP)
S(SIGABRT)
S(SIGBUS)
S(SIGFPE)
S(SIGKILL)
S(SIGUSR1)
S(SIGSEGV)
S(SIGUSR2)
S(SIGPIPE)
S(SIGALRM)
S(SIGTERM)
#ifndef CYGWIN
S(SIGSTKFLT)
#endif
S(SIGCHLD)
S(SIGCONT)
S(SIGSTOP)
S(SIGTSTP)
S(SIGTTIN)
S(SIGTTOU)
S(SIGURG)
S(SIGXCPU)
S(SIGXFSZ)
S(SIGVTALRM)
S(SIGPROF)
S(SIGWINCH)
S(SIGIO)
S(SIGPWR)
S(SIGSYS)
default:
return "UNKNOWN";
}
#undef S
}
static void sig_cb(EV_P_ ev_signal *w, int revents) {
log_write(LOG_LEVEL_NOTICE, "Take %s [%d] signal", signame(w->signum), w->signum);
if (w->signum == SIGSEGV) {
size_t size;
void *array[100];
size = backtrace(array, 100);
backtrace_symbols_fd(array, size, STDERR_FILENO);
}
switch (w->signum) {
case SIGHUP:
if (on_sighup) {
on_sighup(w->signum);
}
break;
case SIGUSR1:
if (on_sigusr1) {
on_sigusr1(w->signum);
}
break;
default:
ev_unloop(EV_DEFAULT, EVUNLOOP_ALL);
}
}
void InitSignalWatcher() {
ev_signal_init(&sigint, sig_cb, SIGINT);
ev_signal_init(&sighup, sig_cb, SIGHUP);
ev_signal_init(&sigterm, sig_cb, SIGTERM);
ev_signal_init(&sigquit, sig_cb, SIGQUIT);
ev_signal_init(&sigsegv, sig_cb, SIGSEGV);
ev_signal_init(&sigusr1, sig_cb, SIGUSR1);
ev_signal_start(EV_DEFAULT_ &sigint);
ev_signal_start(EV_DEFAULT_ &sighup);
ev_signal_start(EV_DEFAULT_ &sigterm);
ev_signal_start(EV_DEFAULT_ &sigquit);
ev_signal_start(EV_DEFAULT_ &sigsegv);
ev_signal_start(EV_DEFAULT_ &sigusr1);
}
| mit |
tom-ogle/InterspireEmailMarketerClient | src/main/java/com/tomogle/iemclient/requests/subscribers/getsubscribers/response/GetSubscribersData.java | 819 | package com.tomogle.iemclient.requests.subscribers.getsubscribers.response;
import com.tomogle.iemclient.requests.lists.response.Item;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "data")
public class GetSubscribersData {
private Integer count;
private SubscriberList subscriberlist;
public GetSubscribersData() {
}
@XmlElement(name = "count")
public Integer getCount() {
return count;
}
public void setCount(final Integer count) {
this.count = count;
}
@XmlElement(name = "subscriberlist")
public SubscriberList getSubscriberlist() {
return subscriberlist;
}
public void setSubscriberlist(final SubscriberList subscriberlist) {
this.subscriberlist = subscriberlist;
}
}
| mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highstock/config/SeriesIkhStatesHoverMarkerStates.scala | 2098 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highstock]]
*/
package com.highstock.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>series<ikh>-states-hover-marker-states</code>
*/
@js.annotation.ScalaJSDefined
class SeriesIkhStatesHoverMarkerStates extends com.highcharts.HighchartsGenericObject {
/**
* <p>The normal state of a single point marker. Currently only used
* for setting animation when returning to normal state from hover.</p>
* @since 6.0.0
*/
val normal: js.Any = js.undefined
/**
* <p>The hover state for a single point marker.</p>
* @since 6.0.0
*/
val hover: js.Any = js.undefined
/**
* <p>The appearance of the point marker when selected. In order to
* allow a point to be selected, set the <code>series.allowPointSelect</code>
* option to true.</p>
* @since 6.0.0
*/
val select: js.Any = js.undefined
}
object SeriesIkhStatesHoverMarkerStates {
/**
* @param normal <p>The normal state of a single point marker. Currently only used. for setting animation when returning to normal state from hover.</p>
* @param hover <p>The hover state for a single point marker.</p>
* @param select <p>The appearance of the point marker when selected. In order to. allow a point to be selected, set the <code>series.allowPointSelect</code>. option to true.</p>
*/
def apply(normal: js.UndefOr[js.Any] = js.undefined, hover: js.UndefOr[js.Any] = js.undefined, select: js.UndefOr[js.Any] = js.undefined): SeriesIkhStatesHoverMarkerStates = {
val normalOuter: js.Any = normal
val hoverOuter: js.Any = hover
val selectOuter: js.Any = select
com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesIkhStatesHoverMarkerStates {
override val normal: js.Any = normalOuter
override val hover: js.Any = hoverOuter
override val select: js.Any = selectOuter
})
}
}
| mit |
arthurtcabral/crescer-2016-1 | modulo-ajax/CdZ/src/CdZ.MVC/Global.asax.cs | 596 | using CdZ.MVC.CustomModelBinders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace CdZ.MVC
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
ModelBinders.Binders.Add(typeof(double?), new DoubleModelBinder());
}
}
}
| mit |
MrIbby/PaperMario | src/main/java/io/github/mribby/papermario/item/ItemStoneCap.java | 1516 | package io.github.mribby.papermario.item;
import io.github.mribby.papermario.Game;
import io.github.mribby.papermario.PaperMarioMod;
import net.minecraft.entity.Entity;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public class ItemStoneCap extends ItemArmor implements IPaperMarioItem {
private static final Game[] GAMES = {Game.PM};
public ItemStoneCap() {
super(PaperMarioItems.STONE_CAP_MATERIAL, PaperMarioMod.proxy.getArmorRenderIndex("stone_cap"), 0);
setCreativeTab(Game.PM.getCreativeTab());
setUnlocalizedName(PaperMarioMod.MOD_ID + ".stoneCap");
setTextureName(PaperMarioMod.MOD_ID + ":stone_cap");
}
@Override
public Game[] getGames() {
return GAMES;
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) {
return PaperMarioMod.MOD_ID + ":textures/models/armor/stone_cap.png";
}
@Override
public void onArmorTick(World world, EntityPlayer player, ItemStack stack) {
player.getEntityAttribute(SharedMonsterAttributes.movementSpeed).applyModifier(PaperMarioItems.STONE_CAP_MODIFIER);
if (!world.isRemote && world.getTotalWorldTime() % 20 == 0) {
if (!player.capabilities.isCreativeMode) {
stack.damageItem(1, player);//TODO
}
}
}
}
| mit |
bpgabin/super-wow | Assets/Scripts/Rotate.cs | 215 | using UnityEngine;
using System.Collections;
public class Rotate : MonoBehaviour {
// Test
public Vector3 speed;
void Update () {
transform.Rotate(speed * Time.deltaTime);
}
}
| mit |
jhass/js_image_paths | lib/js_image_paths.rb | 124 | require "js_image_paths/version"
require "js_image_paths/engine"
require "js_image_paths/generator"
module JsImagePaths
end
| mit |
nrser/nrser-ruby | spec/lib/nrser/props/immutable/hash_spec.rb | 9288 | # Propertied Immutable Hashes
# ============================================================================
#
# The {NRSER::Props::Immutable::Hash} module can be mixed into subclasses of
# {Hamster::Hash} (an immutable {Hash}) to provide property encoding,
# decoding and reading backed by the elements of the hash itself.
#
# This is extremely similar to {NRSER::Props::Immutable::Vector} - which I
# wrote and tested first - so check their for more comments / details.
#
# Requirements
# ----------------------------------------------------------------------------
#
# We're going to use the {NRSER::Types} refinements to specify types for our
# props.
require 'nrser/refinements/types'
# And we're going to need the mixin module itself.
require 'nrser/props/immutable/hash'
#
# Refinements
# ----------------------------------------------------------------------------
#
# Declare that we're going to use the {NRSER::Types} refinements, which just
# provide the global `t` shortcut to {NRSER::Types}.
using NRSER::Types
#
# Examples
# ----------------------------------------------------------------------------
#
SPEC_FILE(
spec_path: __FILE__,
module: NRSER::Props::Immutable::Hash,
) do
SETUP "Simple 2D Integer Point" do
# ==========================================================================
# Complete Fixture Class
# --------------------------------------------------------------------------
#
# First, let's look at a working example:
#
subject :point_2d_int do
Class.new( Hamster::Hash ) do
include NRSER::Props::Immutable::Hash
# So that error messages look right. You don't need this in "regularly"
# defined classes.
def self.name; 'Point2DInt'; end
def self.inspect; name; end
# It's vital that we include the `key:` keyword argument, and that the
# values are non-negative integer indexes for the vector.
prop :x, type: t.int
prop :y, type: t.int
# Just for fun and to show the capabilities, define a `#to_s` to nicely
# print the point.
def to_s
"(#{ x }, #{ y })"
end
end
end
# and let's define our expectations for a successfully created point:
shared_examples "Point2DInt" do |x:, y:|
# It should be an instance of the class
it { is_expected.to be_a point_2d_int }
# as well as {Hamster::Vector}!
it { is_expected.to be_a Hamster::Hash }
# and it should have the `x` and `y` accessible as hash values via
# it's `#[]` method:
describe_method :[] do
describe_called_with :x do
it { is_expected.to be x }
end
describe_called_with :y do
it { is_expected.to be y }
end
end # Method [] Description
# as well as via the `#x` and `#y` attribute reader methods that
# {NRSER::Props} creates:
describe_attribute :x do
it { is_expected.to be x }
end
describe_attribute :y do
it { is_expected.to be y }
end
# Converting to an array should be equal to `[[:x, x], [:y, y]]`:
describe_attribute :to_a do
it { is_expected.to include [:x, x], [:y, y] }
end
# We should get a regular hash out of `#to_h`
describe_attribute :to_h do
it { is_expected.to eq x: x, y: y }
end
# We should see our custom `#to_s` value
describe_attribute :to_s do
it { is_expected.to eq "(#{ x }, #{ y })" }
end
end
SETUP "Creating a Point from `source`" do
# ========================================================================
# Our subject will be a Point2dInt created from a `source` value that we
# will define for each example.
subject do
point_2d_int.new source
end
describe_case "From an `{x: Integer, y: Integer}` literal `Hash`" do
# ------------------------------------------------------------------------
# Let the `source` be the {Hash} `{x: 1, y: 2}`.
describe_when source: {x: 1, y: 2} do
# Now we should be able to construct a point. Test that it behaves
# like we defined above:
it_behaves_like "Point2DInt", source
end
end
describe_case "From a `Hamster::Hash[x: Integer, y: Integer]`" do
# --------------------------------------------------------------------
#
# All that `#initialize` cares about is that it can access the `source`
# via `#[]` and that it can tell if it should use names or integer
# index by looking for `#each_pair` and `#each_index`, respectively.
#
describe_when source: Hamster::Hash[x: 1, y: 2] do
# Now we should be able to construct a point. Test that it behaves
# like we defined above:
it_behaves_like "Point2DInt", source.to_h
end
end
end # .new - Creating a Point
# ************************************************************************
describe_section "Deriving a new point from another" do
# ========================================================================
#
# Our point instances are immutable, but we can use {Hamster::Vector}'s
# methods for deriving new instances to derive new points.
#
# Let's create a point subject to start off with
subject do
point_2d_int.new x: 1, y: 2
end
# and we can play around with a few {Hamster::Vector} methods...
describe_method :put do
# Change the value at entry 0 to 2
describe_called_with :x, 2 do
it_behaves_like "Point2DInt", x: 2, y: 2
end # called with 0, 2
# Type checking should still be in effect, of course
describe_called_with :x, 'hey' do
it { expect { subject }.to raise_error TypeError }
end # called with 0, 'hey'
end # Method put Description
describe_method :map do
# We have to do some manual funkiness here 'cause
# `describe_called_with` doesn't take a block...
#
### TODO
#
# We should be able to handle this by passing a {NRSER::Message}
# to `describe_called_with`, but that's not yet implemented
# (RSpex need s a *lot* of work).
#
# describe_called_with(
# NRSER::Message.new { |value| value + 1 }
# ) do ...
#
# or something like that.
#
describe "add 1 to each entry" do
subject do
super().call { |key, value| [key, value + 1] }
end
it_behaves_like "Point2DInt", x: 2, y: 3
end
# Type checking should still be enforced
describe "try to turn entries into Strings" do
subject do
super().call { |key, value| [key, "value: #{ value }"] }
end
it do
expect { subject }.to raise_error TypeError
end
end # "try to turn entries into Strings"
end # Method map Description
describe_section "Adding extra keys and values" do
# ======================================================================
#
# At the moment, we *can* add *extra* keys and values to the point.
#
# Let's try adding a `:z` key with value `zee`
describe_method :put do
describe_called_with :z, 'zee' do
# It works! And the new point still behaves as expected.
it_behaves_like "Point2DInt", x: 1, y: 2
# but it *also* has a `:z` key with value `'zee'`, which is not
# type checked in any way because it has no corresponding prop
it "also has `z: 'zee`" do
expect( subject[:z] ).to eq 'zee'
end
### TODO
#
# In the future (soon?!), we will have options to configure how
# to handle extra values... thinking:
#
# 1. Allow (what happens now)
# 2. Prohibit (raise an error)
# 3. Discard (just toss them)
#
# Of course, we will still discard derived prop values found in
# the source so that we can always dump and re-load data values.
#
end # called with :z, 3
end # Method put Description
end # section Adding extra keys and values
# **********************************************************************
end # section Deriving a new point from another
# ************************************************************************
end # Simple 2D Integer Point
end
| mit |
sric0880/unity-framework | tools/flatc/src/UF/GameSave/Vec3.cs | 1144 | // <auto-generated>
// automatically generated by the FlatBuffers compiler, do not modify
// </auto-generated>
namespace UF.GameSave
{
using global::System;
using global::FlatBuffers;
public struct Vec3 : IFlatbufferObject
{
private Struct __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
public void __init(int _i, ByteBuffer _bb) { __p.bb_pos = _i; __p.bb = _bb; }
public Vec3 __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public float X { get { return __p.bb.GetFloat(__p.bb_pos + 0); } }
public void MutateX(float x) { __p.bb.PutFloat(__p.bb_pos + 0, x); }
public float Y { get { return __p.bb.GetFloat(__p.bb_pos + 4); } }
public void MutateY(float y) { __p.bb.PutFloat(__p.bb_pos + 4, y); }
public float Z { get { return __p.bb.GetFloat(__p.bb_pos + 8); } }
public void MutateZ(float z) { __p.bb.PutFloat(__p.bb_pos + 8, z); }
public static Offset<Vec3> CreateVec3(FlatBufferBuilder builder, float X, float Y, float Z) {
builder.Prep(4, 12);
builder.PutFloat(Z);
builder.PutFloat(Y);
builder.PutFloat(X);
return new Offset<Vec3>(builder.Offset);
}
};
}
| mit |
kohsuke/rngom | src/org/kohsuke/rngom/ast/builder/DataPatternBuilder.java | 1784 | /*
* Copyright (C) 2004-2011
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.kohsuke.rngom.ast.builder;
import org.kohsuke.rngom.ast.om.Location;
import org.kohsuke.rngom.ast.om.ParsedElementAnnotation;
import org.kohsuke.rngom.ast.om.ParsedPattern;
import org.kohsuke.rngom.parse.*;
public interface DataPatternBuilder<
P extends ParsedPattern,
E extends ParsedElementAnnotation,
L extends Location,
A extends Annotations<E,L,CL>,
CL extends CommentList<L>> {
void addParam(String name, String value, Context context, String ns, L loc, A anno) throws BuildException;
void annotation(E ea);
P makePattern(L loc, A anno) throws BuildException;
P makePattern(P except, L loc, A anno) throws BuildException;
}
| mit |
jelder/bownse | main.go | 1168 | package main
import (
"fmt"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
"github.com/phyber/negroni-gzip/gzip"
"net/http"
)
var (
client = &http.Client{}
)
func WebhookHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
state, err := ParseWebhook(r)
if err != nil {
http.Error(w, err.Error(), 422)
return
}
go func() {
handleOutboundRequest("NewRelic", NewRelicRequest(state))
}()
go func() {
handleOutboundRequest("Honeybadger", HoneybadgerRequest(state))
}()
go func() {
handleOutboundRequest("Slack", SlackRequest(state))
}()
w.WriteHeader(http.StatusAccepted)
}
func handleOutboundRequest(service string, req *http.Request) {
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Error: %s %+v\n", service, err)
} else {
fmt.Printf("OK: %s %+v\n", service, resp)
}
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/"+config.Secret, WebhookHandler).Methods("POST")
http.Handle("/", r)
n := negroni.Classic()
n.Use(gzip.Gzip(gzip.DefaultCompression))
n.UseHandler(r)
n.Run(config.ListenAddress)
}
| mit |
mcarvalho/pagarme-bad-code | index.js | 1499 | const http = require('http');
const { db, api } = require('./src')
db('localhost/bad-code')
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || '3000');
api.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(api);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
}
| mit |
cacheflowe/haxademic | src/com/haxademic/core/draw/textures/pgraphics/shared/PGraphicsWrapper.java | 630 | package com.haxademic.core.draw.textures.pgraphics.shared;
import com.haxademic.core.app.P;
import com.haxademic.core.draw.context.PG;
import processing.core.PGraphics;
public class PGraphicsWrapper {
public int width;
public int height;
public PGraphics pg;
public int lastUpdated;
public PGraphicsWrapper(int w, int h) {
width = w;
height = h;
pg = PG.newPG(w, h);
lastUpdated = -999;
}
public boolean available(int matchW, int matchH) {
return P.p.frameCount - lastUpdated > 10 &&
width == matchW &&
height == matchH;
}
public void setUpdated() {
lastUpdated = P.p.frameCount;
}
}
| mit |
markstiles/SitecoreCognitiveServices | src/Feature/OleChat/code/Areas/SitecoreCognitiveServices/Controllers/CognitiveOleChatController.cs | 5070 | using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using Newtonsoft.Json;
using Sitecore.ContentSearch;
using Sitecore.Data;
using Sitecore.Data.Managers;
using SitecoreCognitiveServices.Feature.OleChat.Areas.SitecoreCognitiveServices.Models;
using SitecoreCognitiveServices.Feature.OleChat.Dialog;
using SitecoreCognitiveServices.Feature.OleChat.Factories;
using SitecoreCognitiveServices.Feature.OleChat.Models;
using SitecoreCognitiveServices.Feature.OleChat.Setup;
using SitecoreCognitiveServices.Foundation.MSSDK.Models.Language.Luis.Connector;
using SitecoreCognitiveServices.Foundation.SCSDK.Wrappers;
namespace SitecoreCognitiveServices.Feature.OleChat.Areas.SitecoreCognitiveServices.Controllers {
public class CognitiveOleChatController : Controller
{
#region Constructor
protected readonly IConversationService ConversationService;
protected readonly IWebUtilWrapper WebUtil;
protected readonly ISitecoreDataWrapper DataWrapper;
protected readonly IOleSettings ChatSettings;
protected readonly ISetupInformationFactory SetupFactory;
protected readonly ISetupService SetupService;
protected readonly ItemContextParameters Parameters;
public CognitiveOleChatController(
IConversationService conversationService,
IWebUtilWrapper webUtil,
ISitecoreDataWrapper dataWrapper,
IOleSettings chatSettings,
ISetupInformationFactory setupFactory,
ISetupService setupService)
{
ConversationService = conversationService;
WebUtil = webUtil;
DataWrapper = dataWrapper;
ChatSettings = chatSettings;
SetupFactory = setupFactory;
SetupService = setupService;
Parameters = new ItemContextParameters()
{
Id = WebUtil.GetQueryString("id"),
Language = WebUtil.GetQueryString("language"),
Database = WebUtil.GetQueryString("db")
};
ThemeManager.GetImage("Office/32x32/man_8.png", 32, 32);
}
#endregion
#region Chat
public ActionResult OleChat()
{
return View("OleChat", Parameters);
}
public ActionResult Post([FromBody] Activity activity)
{
var s = JsonConvert.SerializeObject(activity.ChannelData);
var d = JsonConvert.DeserializeObject<List<string>>(s);
ItemContextParameters parameters = (d.Any())
? JsonConvert.DeserializeObject<ItemContextParameters>(d[0])
: new ItemContextParameters();
if (activity.Type == ActivityTypes.Message)
{
var response = ConversationService.HandleMessage(activity, parameters);
var reply = activity.CreateReply(response.Message, "en-US");
reply.ChannelData = new ChannelData
{
OptionSet = response.OptionsSet,
Selections = response.Selections,
Action = response.Action
};
return Json(reply);
}
return null;
}
#endregion
#region Setup
public ActionResult Setup()
{
if (!IsSitecoreUser())
return LoginPage();
var db = Sitecore.Configuration.Factory.GetDatabase(ChatSettings.MasterDatabase);
using (new DatabaseSwitcher(db))
{
ISetupInformation info = SetupFactory.Create();
return View("Setup", info);
}
}
public ActionResult SetupSubmit(bool overwriteOption, string luisApi, string luisApiEndpoint, string textAnalyticsApi, string textAnalyticsApiEndpoint)
{
if (!IsSitecoreUser())
return LoginPage();
List<string> items = new List<string>();
SetupService.SaveKeys(luisApi, luisApiEndpoint, textAnalyticsApi, textAnalyticsApiEndpoint);
var restoreResult = SetupService.RestoreOle(overwriteOption);
if(!restoreResult)
items.Add("Restore Ole");
var queryResult = SetupService.QueryOle();
if(!queryResult)
items.Add("Query Ole");
SetupService.PublishOleContent();
return Json(new
{
Failed = items.Count > 0,
Items = string.Join(",", items)
});
}
#endregion
#region Shared
public bool IsSitecoreUser()
{
return DataWrapper.ContextUser.IsAuthenticated
&& DataWrapper.ContextUser.Domain.Name.ToLower().Equals("sitecore");
}
public ActionResult LoginPage()
{
return new RedirectResult("/sitecore/login");
}
#endregion
}
} | mit |
joe-re/todoistize-mail | spec/todoistize_mail/mailer_spec.rb | 832 | require 'spec_helper'
describe TodoistizeMail::Mailer do
let(:host) { 'test.com' }
let(:port) { '111' }
let(:usessl) { true }
let(:imap) { double('imap') }
before { expect(Net::IMAP).to receive(:new).with(host, port, usessl).and_return(imap) }
describe '#login' do
let(:user) { 'test_user' }
let(:passwd) { 'passwd' }
before { expect(imap).to receive(:login).with(user, passwd) }
subject { described_class.new(host, port, usessl).login(user, passwd) }
it 'return myself' do
expect(subject.instance_of?(described_class)).to be true
end
end
describe '#logout' do
before { expect(imap).to receive(:logout) }
subject { described_class.new(host, port, usessl).logout }
it 'return myself' do
expect(subject.instance_of?(described_class)).to be true
end
end
end
| mit |
ByrdOfAFeather/AlphaTrion | Announcements/forms.py | 335 | from django import forms
from .models import Announcement
class AnnouncementForm(forms.ModelForm):
"""
Form to create an announcement object from :model:'Announcements.Announcement'
"""
class Meta:
model = Announcement
fields = '__all__'
widgets = {
'occuring_date': forms.DateInput(attrs={'class': 'datepicker'}),
}
| mit |
pilot/qa | src/Qa/UserBundle/Entity/User.php | 3239 | <?php
namespace Qa\UserBundle\Entity;
use Doctrine\ORM\Mapping as orm;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @orm\Entity
* @orm\Table(name="user")
*/
class User
{
/**
* @orm\Id
* @orm\Column(type="integer")
* @orm\GeneratedValue(strategy="AUTO")
*
* @var integer $id
*/
protected $id;
/**
* @orm\Column(type="string", length="255", name="name")
*
* @var string $name
*/
protected $name;
/**
* @orm\Column(type="string", length="255")
*
* @var string $email
*/
protected $email;
/**
* @orm\Column(type="string", length="255", nullable="true")
*
* @var string $avatar
*/
protected $avatar;
/**
* @orm\Column(type="datetime", name="created_at")
*
* @var DateTime $createdAt
*/
protected $createdAt;
/**
* @orm\OneToMany(targetEntity="Qa\QuestionBundle\Entity\Question", mappedBy="user")
* @orm\OrderBy({"createdAt" = "DESC"})
*
* @var ArrayCollection $questions
*/
protected $questions;
/**
* @orm\OneToMany(targetEntity="Openid", mappedBy="user")
*
* @var ArrayCollection $openids
*/
protected $openids;
//..
/**
* Get id
*
* @return integer $id
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* @return string $name
*/
public function getName()
{
return $this->name;
}
/**
* Set email
*
* @param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get email
*
* @return string $email
*/
public function getEmail()
{
return $this->email;
}
/**
* Set avatar
*
* @param string $avatar
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
}
/**
* Get avatar
*
* @return string $avatar
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* Set createdAt
*
* @param datetime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* Get createdAt
*
* @return datetime $createdAt
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Add openids
*
* @param Qa\UserBundle\Entity\Openid $openids
*/
public function addOpenids(\Qa\UserBundle\Entity\Openid $openids)
{
$this->openids[] = $openids;
}
/**
* Get openids
*
* @return Doctrine\Common\Collections\Collection $openids
*/
public function getOpenids()
{
return $this->openids;
}
/**
* Constructs a new instance of User
*/
public function __construct()
{
$this->questions = new ArrayCollection();
$this->openids = new ArrayCollection();
$this->createdAt = new \DateTime();
}
} | mit |
tonnystark/unishop | UniShop.Web/Models/ProductViewModel.cs | 1298 | using System;
namespace UniShop.Web.Models
{
[Serializable]
public class ProductViewModel
{
public int ID { set; get; }
public string Name { set; get; }
public string Alias { set; get; }
public int CategoryID { set; get; }
public string Image { set; get; }
public string MoreImages { set; get; }
public decimal Price { set; get; }
public decimal? PromotionPrice { set; get; }
public int? Warranty { set; get; }
public string Description { set; get; }
public string Content { set; get; }
public bool? HomeFlag { set; get; }
public bool? HotFlag { set; get; }
public int? ViewCount { set; get; }
public DateTime? CreatedDate { set; get; }
public string CreatedBy { set; get; }
public DateTime? UpdatedDate { set; get; }
public string UpdatedBy { set; get; }
public string MetaKeyword { set; get; }
public string MetaDescription { set; get; }
public bool Status { set; get; }
public string Tags { get; set; }
public int Quantity { get; set; }
public decimal OriginalPrice { get; set; }
public virtual ProductCategoryViewModel ProductCategory { set; get; }
}
} | mit |
eparimbelli/FeroGrammer | src/it/ferogrammer/process/Nucleotide.java | 454 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package it.ferogrammer.process;
import java.awt.Color;
/**
*
* @author enea
*/
public enum Nucleotide implements ColorableNucleotide{
A(Color.GREEN), C(Color.BLUE), T(Color.RED), G(Color.BLACK);
private Color color;
Nucleotide(Color col){
color = col;
}
public Color getColor() {
return color;
}
}
| mit |
GuiNaud/waww | client/src/app/components/tvDetail/factory.js | 749 | (function() {
'use strict';
function TvDetailService($http, $log) {
var service = {};
service.detailtv = [];
var key = 'bb7f1b623e15f1c323072c6f2c7c8a2d';
service.getOneMovie = function(movieID){
return $http.get('http://api.themoviedb.org/3/tv/' + movieID,{
params: {
api_key: key
}
})
.success(function(data){
service.detailtv = data;
})
.error(function(data){
console.log(data);
});
};
return service;
}
angular.module('service.detailtv', []).factory('TvDetailService', TvDetailService);
})();
| mit |
bhdm/wzc | src/Wzc/MainBundle/Form/PublicationType.php | 1761 | <?php
namespace Wzc\MainBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PublicationType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title',null, array('label' => 'Заголовок'))
->add('keywords',null, array('label' => 'Мета слова'))
->add('description',null, array('label' => 'Мета описание'))
->add('anons',null, array('label' => 'Анонс'))
->add('image','iphp_file', array('label' => 'Картинка'))
->add('body',null, array('label' => 'Контент страницы', 'attr' => array('class'=>'ckeditor')))
->add('enabled','choice', array(
'empty_value' => false,
'choices' => array(
'1' => 'Активна',
'0' => 'Не активна',
),
'label' => 'Активность',
'required' => false,
))
->add('submit', 'submit', array('label' => 'Сохранить'));
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Wzc\MainBundle\Entity\Publication'
));
}
/**
* @return string
*/
public function getName()
{
return 'wzc_mainbundle_publication';
}
}
| mit |
dmayer/idb | lib/gui/default_protection_class_group_widget.rb | 914 | module Idb
class DefaultProtectionClassGroupWidget < Qt::GroupBox
def initialize(args)
super(*args)
setTitle "Default Data Protection"
@layout = Qt::GridLayout.new
label = Qt::Label.new "<b>Default Data Protection</b>", self, 0
@val = Qt::Label.new "No default set in the entitlements of this app.", self, 0
@layout.addWidget label, 0, 0
@layout.addWidget @val, 0, 1
spacer_horizontal = Qt::SpacerItem.new 0, 1, Qt::SizePolicy::Expanding, Qt::SizePolicy::Fixed
@layout.addItem spacer_horizontal, 0, 2
setLayout @layout
end
def update
if $device.ios_version < 8
@val.setText "Only available for iOS 8+"
else
$selected_app.entitlements.each do |x|
if x[0].to_s == "com.apple.developer.default-data-protection"
@val.setText x[1].to_s
end
end
end
end
end
end
| mit |
tangcongyuan/WPI_CS542_rms | assets/grocery_crud/themes/flexigrid/js/flexigrid.js | 10063 | $(function(){
$('.quickSearchButton').click(function(){
$(this).closest('.flexigrid').find('.quickSearchBox').slideToggle('normal');
});
$('.ptogtitle').click(function(){
if ($(this).hasClass('vsble')) {
$(this).removeClass('vsble');
$(this).closest('.flexigrid').find('.main-table-box').slideDown("slow");
} else {
$(this).addClass('vsble');
$(this).closest('.flexigrid').find('.main-table-box').slideUp("slow");
}
});
var call_fancybox = function(){
$('.image-thumbnail').fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false
});
};
call_fancybox();
add_edit_button_listener();
$('.filtering_form').submit(function(){
var crud_page = parseInt($(this).closest('.flexigrid').find('.crud_page').val(), 10);
var last_page = parseInt($(this).closest('.flexigrid').find('.last-page-number').html(), 10);
if (crud_page > last_page) {
$(this).closest('.flexigrid').find('.crud_page').val(last_page);
}
if (crud_page <= 0) {
$(this).closest('.flexigrid').find('.crud_page').val('1');
}
var this_form = $(this);
var ajax_list_info_url = $(this).attr('data-ajax-list-info-url');
$(this).ajaxSubmit({
url: ajax_list_info_url,
dataType: 'json',
beforeSend: function(){
this_form.closest('.flexigrid').find('.ajax_refresh_and_loading').addClass('loading');
},
complete: function(){
this_form.closest('.flexigrid').find('.ajax_refresh_and_loading').removeClass('loading');
},
success: function(data){
this_form.closest('.flexigrid').find('.total_items').html( data.total_results);
displaying_and_pages(this_form.closest('.flexigrid'));
this_form.ajaxSubmit({
success: function(data){
this_form.closest('.flexigrid').find('.ajax_list').html(data);
call_fancybox();
add_edit_button_listener();
}
});
}
});
if ($('.flexigrid').length == 1) { //disable cookie storing for multiple grids in one page
createCookie('crud_page_'+unique_hash,crud_page,1);
createCookie('per_page_'+unique_hash,$('#per_page').val(),1);
createCookie('hidden_ordering_'+unique_hash,$('#hidden-ordering').val(),1);
createCookie('hidden_sorting_'+unique_hash,$('#hidden-sorting').val(),1);
createCookie('search_text_'+unique_hash,$(this).closest('.flexigrid').find('.search_text').val(),1);
createCookie('search_field_'+unique_hash,$('#search_field').val(),1);
}
return false;
});
$('.crud_search').click(function(){
$(this).closest('.flexigrid').find('.crud_page').val('1');
$(this).closest('.flexigrid').find('.filtering_form').trigger('submit');
});
$('.search_clear').click(function(){
$(this).closest('.flexigrid').find('.crud_page').val('1');
$(this).closest('.flexigrid').find('.search_text').val('');
$(this).closest('.flexigrid').find('.filtering_form').trigger('submit');
});
$('.per_page').change(function(){
$(this).closest('.flexigrid').find('.crud_page').val('1');
$(this).closest('.flexigrid').find('.filtering_form').trigger('submit');
});
$('.ajax_refresh_and_loading').click(function(){
$(this).closest('.flexigrid').find('.filtering_form').trigger('submit');
});
$('.first-button').click(function(){
$(this).closest('.flexigrid').find('.crud_page').val('1');
$(this).closest('.flexigrid').find('.filtering_form').trigger('submit');
});
$('.prev-button').click(function(){
if( $(this).closest('.flexigrid').find('.crud_page').val() != "1")
{
$(this).closest('.flexigrid').find('.crud_page').val( parseInt($(this).closest('.flexigrid').find('.crud_page').val(),10) - 1 );
$(this).closest('.flexigrid').find('.crud_page').trigger('change');
}
});
$('.last-button').click(function(){
$(this).closest('.flexigrid').find('.crud_page').val( $(this).closest('.flexigrid').find('.last-page-number').html());
$(this).closest('.flexigrid').find('.filtering_form').trigger('submit');
});
$('.next-button').click(function(){
$(this).closest('.flexigrid').find('.crud_page').val( parseInt($(this).closest('.flexigrid').find('.crud_page').val()) + 1 );
$(this).closest('.flexigrid').find('.crud_page').trigger('change');
});
$('.crud_page').change(function(){
$(this).closest('.flexigrid').find('.filtering_form').trigger('submit');
});
$('.ajax_list').on('click','.field-sorting', function(){
$(this).closest('.flexigrid').find('.hidden-sorting').val($(this).attr('rel'));
if ($(this).hasClass('asc')) {
$(this).closest('.flexigrid').find('.hidden-ordering').val('desc');
} else {
$(this).closest('.flexigrid').find('.hidden-ordering').val('asc');
}
$(this).closest('.flexigrid').find('.crud_page').val('1');
$(this).closest('.flexigrid').find('.filtering_form').trigger('submit');
});
$('.ajax_list').on('click','.delete-row', function(){
var delete_url = $(this).attr('href');
var this_container = $(this).closest('.flexigrid');
if( confirm( message_alert_delete ) )
{
$.ajax({
url: delete_url,
dataType: 'json',
success: function(data)
{
if(data.success)
{
this_container.find('.ajax_refresh_and_loading').trigger('click');
success_message(data.success_message);
}
else
{
error_message(data.error_message);
}
}
});
}
return false;
});
$('.ajax_list').on('click','.approve-icon', function(){
var delete_url = $(this).attr('href');
var this_container = $(this).closest('.flexigrid');
if( confirm( "Are you sure you want to approve?" ) )
{
$.ajax({
url: delete_url,
dataType: 'json',
success: function(data)
{
if(data.success)
{
this_container.find('.ajax_refresh_and_loading').trigger('click');
success_message(data.success_message);
}
else
{
error_message(data.error_message);
}
}
});
}
return false;
});
$('.ajax_list').on('click','.cancel-icon', function(){
var delete_url = $(this).attr('href');
var this_container = $(this).closest('.flexigrid');
if( confirm( "Are you sure you want to cancel? Your record will be deleted permanently!" ) )
{
$.ajax({
url: delete_url,
dataType: 'json',
success: function(data)
{
if(data.success)
{
this_container.find('.ajax_refresh_and_loading').trigger('click');
success_message(data.success_message);
}
else
{
error_message(data.error_message);
}
}
});
}
return false;
});
$('.export-anchor').click(function(){
var export_url = $(this).attr('data-url');
var form_input_html = '';
$.each($(this).closest('.flexigrid').find('.filtering_form').serializeArray(), function(i, field) {
form_input_html = form_input_html + '<input type="hidden" name="'+field.name+'" value="'+field.value+'">';
});
var form_on_demand = $("<form/>").attr("id","export_form").attr("method","post").attr("target","_blank")
.attr("action",export_url).html(form_input_html);
$(this).closest('.flexigrid').find('.hidden-operations').html(form_on_demand);
$(this).closest('.flexigrid').find('.hidden-operations').find('#export_form').submit();
});
$('.print-anchor').click(function(){
var print_url = $(this).attr('data-url');
var form_input_html = '';
$.each($(this).closest('.flexigrid').find('.filtering_form').serializeArray(), function(i, field) {
form_input_html = form_input_html + '<input type="hidden" name="'+field.name+'" value="'+field.value+'">';
});
var form_on_demand = $("<form/>").attr("id","print_form").attr("method","post").attr("action",print_url).html(form_input_html);
$(this).closest('.flexigrid').find('.hidden-operations').html(form_on_demand);
var _this_button = $(this);
$(this).closest('.flexigrid').find('#print_form').ajaxSubmit({
beforeSend: function(){
_this_button.find('.fbutton').addClass('loading');
_this_button.find('.fbutton>div').css('opacity','0.4');
},
complete: function(){
_this_button.find('.fbutton').removeClass('loading');
_this_button.find('.fbutton>div').css('opacity','1');
},
success: function(html_data){
$("<div/>").html(html_data).printElement();
}
});
});
$('.crud_page').numeric();
if ($('.flexigrid').length == 1) { //disable cookie storing for multiple grids in one page
var cookie_crud_page = readCookie('crud_page_'+unique_hash);
var cookie_per_page = readCookie('per_page_'+unique_hash);
var hidden_ordering = readCookie('hidden_ordering_'+unique_hash);
var hidden_sorting = readCookie('hidden_sorting_'+unique_hash);
var cookie_search_text = readCookie('search_text_'+unique_hash);
var cookie_search_field = readCookie('search_field_'+unique_hash);
if(cookie_crud_page !== null && cookie_per_page !== null)
{
$('#crud_page').val(cookie_crud_page);
$('#per_page').val(cookie_per_page);
$('#hidden-ordering').val(hidden_ordering);
$('#hidden-sorting').val(hidden_sorting);
$('#search_text').val(cookie_search_text);
$('#search_field').val(cookie_search_field);
if(cookie_search_text !== '')
$('#quickSearchButton').trigger('click');
$('#filtering_form').trigger('submit');
}
}
});
function displaying_and_pages(this_container)
{
if (this_container.find('.crud_page').val() == 0) {
this_container.find('.crud_page').val('1');
}
var crud_page = parseInt( this_container.find('.crud_page').val(), 10) ;
var per_page = parseInt( this_container.find('.per_page').val(), 10 );
var total_items = parseInt( this_container.find('.total_items').html(), 10 );
this_container.find('.last-page-number').html( Math.ceil( total_items / per_page) );
if (total_items == 0) {
this_container.find('.page-starts-from').html( '0');
} else {
this_container.find('.page-starts-from').html( (crud_page - 1)*per_page + 1 );
}
if (crud_page*per_page > total_items) {
this_container.find('.page-ends-to').html( total_items );
} else {
this_container.find('.page-ends-to').html( crud_page*per_page );
}
} | mit |
alvarlagerlof/temadagar-android | app/src/main/java/com/alvarlagerlof/temadagarapp/Search/SearchObject.java | 1229 | package com.alvarlagerlof.temadagarapp.Search;
/**
* Created by alvar on 2015-07-10.
*/
public class SearchObject {
public String id;
public String title;
public String date;
public String description;
public String introduced;
public Boolean international;
public String website;
public String fun_fact;
public String popularity;
public String color;
public static int type;
public SearchObject(String id,
String title,
String date,
String description,
String introduced,
Boolean international,
String website,
String fun_fact,
String popularity,
String color,
int type) {
this.id = id;
this.title = title;
this.date = date;
this.description = description;
this.introduced = introduced;
this.international = international;
this.website = website;
this.fun_fact = fun_fact;
this.popularity = popularity;
this.color = color;
this.type = type;
}
} | mit |
mtrovilho/serenity_now | lib/serenity_now/version.rb | 94 | ##
# Serenity module :)
#
module SerenityNow
##
# Gem version
#
VERSION = '1.0.0'
end
| mit |
TelerikAcademy/Data-Structures-and-Algorithms | Exams/2017/MiniExam3/3. Squares/solution.cs | 965 | using System;
using System.Numerics;
using System.Collections.Generic;
namespace Square
{
class Program
{
static void Main()
{
var n = int.Parse(Console.ReadLine());
var m = int.Parse(Console.ReadLine());
if(n < m)
{
var k = n;
n = m;
m = k;
}
var masks = new List<int>();
for(int i = 0; i < (1 << m); ++i)
{
if((i & (i >> 1)) > 0)
{
continue;
}
masks.Add(i);
}
var dp = new BigInteger[2, masks.Count];
dp[0, 0] = 1;
for(int row = 1; row <= n; ++row)
{
for(int i = 0; i < masks.Count; ++i)
{
var from = dp[(row - 1) % 2, i];
dp[(row - 1) % 2, i] = 0;
for(int j = 0; j < masks.Count; ++j)
{
if((masks[i] & masks[j]) > 0)
{
continue;
}
dp[row % 2, j] += from;
}
}
}
BigInteger result = 0;
for(int i = 0; i < masks.Count; ++i)
{
result += dp[n % 2, i];
}
Console.WriteLine(result);
}
}
}
| mit |
imerr/SFMLEngine | include/Engine/Factory.hpp | 2343 | #ifndef ENGINE_FACTORY_HPP
#define ENGINE_FACTORY_HPP
#include "Scene.hpp"
#include "SpriteNode.hpp"
#include <json/json.h>
#include <iostream>
#include <fstream>
#include <map>
namespace engine {
class Factory {
protected:
static std::map<std::string, std::function<Node*(Json::Value& root, Node* parent) >> m_types;
public:
static void RegisterType(std::string name, std::function<Node*(Json::Value& root, Node* parent)> callback);
static void RemoveType(std::string name);
static bool LoadJson(std::string filename, Json::Value& root);
template<class T, typename... args>
static T* create(std::string config, args... params) {
Json::Value root;
if (!LoadJson(config, root)) {
return nullptr;
}
T* d = createJson<T>(root, params...);
if (d) {
d->SetFilename(config);
}
return d;
}
template<class T, typename... args>
static T* createJson(Json::Value& root, args... params) {
T* thing = new T(params...);
if (thing->initialize(root)) {
if (root.isMember("children") && root["children"].isArray()) {
for (Json::ArrayIndex i = 0; i < root["children"].size(); i++) {
auto child = root["children"][i];
if (!child.isObject()) {
std::cerr << "Child has to be object" << std::endl;
continue;
}
Node* nchild = CreateChild(child, thing);
}
}
thing->OnInitializeDone();
return thing;
}
delete thing;
return nullptr;
}
template<class T>
static Node* CreateChildNode(Json::Value& root, Node* parent = nullptr) {
T* thing = new T(parent->GetScene());
// Do this so we can use it during initialize, SetParent only sets the pointer m_parent, which gets overwritten once we do AddNode anyways - if creation fails nothing happens
thing->SetParent(parent);
if (thing->initialize(root)) {
if (root.isMember("children")) {
if (!MakeChildren(root["children"], thing)) {
std::cerr << "Failed to make children" << std::endl;
}
}
return thing;
}
delete thing;
return nullptr;
}
static Node* CreateChild(Json::Value root, Node* parent);
static Node* CreateChildFromFile(std::string file, Node* parent);
static bool MakeChildren(Json::Value& c, Node* parent);
static void MergeJson(Json::Value& a, Json::Value& b);
private:
Factory() {
}
};
}
#endif
| mit |
elemgee/TBFoundation | Frameworks/TBFoundation/Sources/org/treasureboat/foundation/constants/TBFKnownFrameworkNames.java | 360 | package org.treasureboat.foundation.constants;
/**
* a class for known Framework names so we don't have to Hardcode the names
*/
public class TBFKnownFrameworkNames {
public static final String TBFOUNDATION = "TBFoundation";
public static final String TBCONTENTSDELIVERY = "TBContentsDelivery";
public static final String TBLIBRARY = "TBLibrary";
}
| mit |
QuintiGames/ShootingforA | Assets/Scripts/Player Controll/VirtualJoystickRight.cs | 255 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VirtualJoystickRight : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| mit |
alex-semenyuk/cactoos | src/test/java/org/cactoos/map/SolidMapTest.java | 2773 | /**
* The MIT License (MIT)
*
* Copyright (c) 2017 Yegor Bugayenko
*
* 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.cactoos.map;
import java.util.Map;
import org.cactoos.RunsInThreads;
import org.cactoos.Scalar;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test case for {@link SolidMap}.
*
* @author Yegor Bugayenko (yegor256@gmail.com)
* @version $Id$
* @since 0.24
* @checkstyle JavadocMethodCheck (500 lines)
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
public final class SolidMapTest {
@Test
public void behavesAsMap() {
MatcherAssert.assertThat(
"Can't behave as a map",
new SolidMap<Integer, Integer>(
new MapEntry<>(0, -1),
new MapEntry<>(1, 1)
),
new BehavesAsMap<>(0, 1)
);
}
@Test
public void worksInThreads() {
MatcherAssert.assertThat(
"Can't behave as a map in multiple threads",
map -> {
MatcherAssert.assertThat(map, new BehavesAsMap<>(0, 1));
return true;
},
new RunsInThreads<>(
new SolidMap<Integer, Integer>(
new MapEntry<>(0, -1),
new MapEntry<>(1, 1)
)
)
);
}
@Test
public void mapsToSameObjects() throws Exception {
final Map<Integer, Scalar<Integer>> map = new SolidMap<>(
input -> new MapEntry<>(input, () -> input),
1, -1, 0, 1
);
MatcherAssert.assertThat(
"Can't map only once",
map.get(0), Matchers.equalTo(map.get(0))
);
}
}
| mit |
baislsl/java-class-decompiler | src/main/java/com/baislsl/decompiler/instruction/LSHR.java | 342 | package com.baislsl.decompiler.instruction;
import com.baislsl.decompiler.engine.Frame;
import com.baislsl.decompiler.structure.attribute.Code;
public class LSHR extends OperationInstruction {
@Override
public Executable build(Code code, Frame frame) {
this.operator = ">>";
return super.build(code, frame);
}
}
| mit |
EquipeB/SOSFeevale | library/f5-framework/core/config.inc.php | 1505 | <?php
date_default_timezone_set('America/Sao_Paulo');
//Diretórios da aplicação, se for na raiz do servidor, utilizar apenas uma "/"
//define("DIRETORIO_BASE", "http://f5digital.noip.me");
define("DIRETORIO_BASE", "localhost");
define("DIRETORIO_INICIAL", "/sos-feevale/");
define("DIRETORIO_ADMIN", DIRETORIO_INICIAL."f5admin/");
//Informações do banco de dados
define("TIPO_BD", "mysql");
define("HOST_BD", "localhost");
define("NOME_BD", "sos_feevale_f5admin");
define("USUARIO_BD", "root");
define("SENHA_BD", "");
//MVC da aplicação
define("CONTROLLERS", "app/controllers/");
define("VIEWS", "app/views/");
define("MODELS", "app/models/");
//Caminho para arquivos do template
if(preg_match("/f5admin/i", $_SERVER[REQUEST_URI])){
define("HELPERS", "../library/f5-framework/helpers/");
define("CSS", DIRETORIO_ADMIN."web-files/css/");
define("JS", DIRETORIO_ADMIN."web-files/js/");
define("PLUGINS", DIRETORIO_ADMIN."web-files/plugins/");
define("IMG", DIRETORIO_ADMIN."web-files/img/");
define("UPLOADS", DIRETORIO_ADMIN."web-files/uploads/");
define("UPLOADS_SITE", DIRETORIO_INICIAL."web-files/uploads/");
}else{
define("HELPERS", "library/f5-framework/helpers/");
define("CSS", DIRETORIO_INICIAL."web-files/css/");
define("JS", DIRETORIO_INICIAL."web-files/js/");
define("PLUGINS", DIRETORIO_INICIAL."web-files/plugins/");
define("IMG", DIRETORIO_INICIAL."web-files/img/");
define("UPLOADS", DIRETORIO_INICIAL."web-files/uploads/");
} | mit |
stonghuuloc/g3c | public/js/traoDoi/module.js | 355 | 'user strict';
angular.module('g3cApp.traoDoi',['ngRoute'])
.config(['$routeProvider', function config($routeProvider){
$routeProvider.when('/traodoi',{
controller:'traoDoiCtrl',
templateUrl:'html/traodoi/traodoi.html'
}).
when('/traodoi/xacnhan',{
controller:'traoDoiCtrl',
templateUrl:'html/traodoi/xacNhanTraoDoi.html'
});
}]);
| mit |
bitconnectcoin/bitconnectcoin | src/util.cpp | 37969 | // Copyright (c) 2009-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 "util.h"
#include "sync.h"
#include "strlcpy.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fRequestShutdown = false;
bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64_t> vTimeOffsets(200,0);
bool fReopenDebugLog = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
inline int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0;
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
// print to debug.log
static FILE* fileout = NULL;
if (!fileout)
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
}
if (fileout)
{
static bool fStartedNewLine = true;
// This routine may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// allocate mutexDebugLog on the heap the first time this routine
// is called to avoid crashes during shutdown.
static boost::mutex* mutexDebugLog = NULL;
if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
while (true)
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
while (true)
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64_t n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
string str = strprintf("%"PRId64".%08"PRId64, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64_t& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64_t& nRet)
{
string strWhole;
int64_t nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64_t nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64_t nWhole = atoi64(strWhole);
int64_t nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
char psz[10000];
strlcpy(psz, argv[i], sizeof(psz));
char* pszValue = (char*)"";
if (strchr(psz, '='))
{
pszValue = strchr(psz, '=');
*pszValue++ = '\0';
}
#ifdef WIN32
_strlwr(psz);
if (psz[0] == '/')
psz[0] = '-';
#endif
if (psz[0] != '-')
break;
mapArgs[psz] = pszValue;
mapMultiArgs[psz].push_back(pszValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
while (true)
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "bitconnect";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\bitconnect
// Windows >= Vista: C:\Users\Username\AppData\Roaming\bitconnect
// Mac: ~/Library/Application Support/bitconnect
// Unix: ~/.bitconnect
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "bitconnect";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "bitconnect";
#else
// Unix
return pathRet / ".bitconnect";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
static bool cachedPath[2] = {false, false};
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (cachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && GetBoolArg("-testnet", false))
path /= "testnet";
fs::create_directory(path);
cachedPath[fNetSpecific]=true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "bitconnect.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "bitconnectd.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64_t nMockTime = 0; // For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64_t nTimeOffset = 0;
int64_t GetTimeOffset()
{
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
int64_t nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRId64" (%+"PRId64" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong bitconnect will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("bitconnect"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
printf("%+"PRId64" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRId64" (%+"PRId64" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
uint32_t insecure_rand_Rz = 11;
uint32_t insecure_rand_Rw = 11;
void seed_insecure_rand(bool fDeterministic)
{
//The seed values have some unlikely fixed points which we avoid.
if(fDeterministic)
{
insecure_rand_Rz = insecure_rand_Rw = 11;
} else {
uint32_t tmp;
do{
RAND_bytes((unsigned char*)&tmp,4);
}while(tmp==0 || tmp==0x9068ffffU);
insecure_rand_Rz=tmp;
do{
RAND_bytes((unsigned char*)&tmp,4);
}while(tmp==0 || tmp==0x464fffffU);
insecure_rand_Rw=tmp;
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
// This is XCode 10.6-and-later; bring back if we drop 10.5 support:
// #elif defined(MAC_OSX)
// pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
| mit |
muquit/mrdialog | test/test_mrdialog.rb | 224 | require 'helper'
class TestMrdialog < Test::Unit::TestCase
should "probably rename this file and start testing for real" do
flunk "hey buddy, you should probably rename this file and start testing for real"
end
end
| mit |
rosswhitfield/javelin | javelin/fourier.py | 20115 | """
=======
fourier
=======
This module define the Fourier class and other functions related to
the fourier transformation.
"""
import numpy as np
import pandas as pd
from javelin.grid import Grid
from javelin.utils import get_unitcell, get_positions, get_atomic_numbers
from javelin.fourier_cython import calculate_cython, approx_calculate_cython
class Fourier:
"""The Fourier class contains everything required to calculate the
diffuse scattering. The only required thing to be set is
:obj:`javelin.fourier.Fourier.structure`. There are defaults for
all other options including **grid**, **radiation**, **average**
structure subtraction and **lots** options.
:examples:
>>> from javelin.structure import Structure
>>> fourier = Fourier()
>>> print(fourier)
Radiation : neutron
Fourier volume : complete crystal
Aver. subtraction : False
<BLANKLINE>
Reciprocal layer :
lower left corner : [ 0. 0. 0.]
lower right corner : [ 1. 0. 0.]
upper left corner : [ 0. 1. 0.]
top left corner : [ 0. 0. 1.]
<BLANKLINE>
hor. increment : [ 0.01 0. 0. ]
vert. increment : [ 0. 0.01 0. ]
top increment : [ 0. 0. 1.]
<BLANKLINE>
# of points : 101 x 101 x 1
>>> results = fourier.calc(Structure())
>>> print(results) # doctest: +SKIP
<xarray.DataArray 'Intensity' ([ 1. 0. 0.]: 101, [ 0. 1. 0.]: 101, [ 0. 0. 1.]: 1)>
array([[[ 0.],
[ 0.],
...,
[ 0.],
[ 0.]],
<BLANKLINE>
[[ 0.],
[ 0.],
...,
[ 0.],
[ 0.]],
<BLANKLINE>
...,
[[ 0.],
[ 0.],
...,
[ 0.],
[ 0.]],
<BLANKLINE>
[[ 0.],
[ 0.],
...,
[ 0.],
[ 0.]]])
Coordinates:
* [ 1. 0. 0.] ([ 1. 0. 0.]) float64 0.0 0.01 0.02 0.03 0.04 0.05 0.06 ...
* [ 0. 1. 0.] ([ 0. 1. 0.]) float64 0.0 0.01 0.02 0.03 0.04 0.05 0.06 ...
* [ 0. 0. 1.] ([ 0. 0. 1.]) float64 0.0
Attributes:
units: r.l.u
"""
def __init__(self):
self._radiation = 'neutron'
self._lots = None
self._number_of_lots = None
self._average = False
self._magnetic = False
self._cython = True
self._approximate = True
self._fast = True
#: The **grid** attribute defines the reciprocal volume from
#: which the scattering will be calculated. Must of type
#: :class:`javelin.grid.Grid` And check
#: :class:`javelin.grid.Grid` for details on how to change the
#: grid.
self.grid = Grid()
def __str__(self):
return """Radiation : {}
Fourier volume : {}
Aver. subtraction : {}
Reciprocal layer :
{}""".format(self.radiation,
"complete crystal" if self.lots is None else "{} lots of {} x {} x {} unit cells"
.format(self.number_of_lots, *self.lots),
self.average,
self.grid)
@property
def radiation(self):
"""The radiation used
:getter: Returns the radiation selected
:setter: Sets the radiation
:type: str ('xray' or 'neutron')
"""
return self._radiation
@radiation.setter
def radiation(self, rad):
if rad not in ('neutron', 'xray'):
raise ValueError("radiation must be one of 'neutron' or 'xray'")
self._radiation = rad
@property
def lots(self):
"""The size of lots
:getter: Returns the lots size
:setter: Sets the lots size
:type: list of 3 integers or None
"""
return self._lots
@lots.setter
def lots(self, lots):
if lots is None:
self._lots = None
else:
lots = np.asarray(lots)
if len(lots) == 3:
self._lots = lots
else:
raise ValueError("Must provied 3 values for lots")
@property
def number_of_lots(self):
"""The number of lots to use
:getter: Returns the number of lots
:setter: Sets the number of lots
:type: int
"""
return self._number_of_lots
@number_of_lots.setter
def number_of_lots(self, value):
self._number_of_lots = value
@property
def average(self):
"""This sets the options of calculating average structure and
subtracted it from the simulated scattering
:getter: Returns bool of average structure subtraction option
:setter: Sets whether average structure is subtracted
:type: bool
"""
return self._average
@average.setter
def average(self, value):
if isinstance(value, bool):
self._average = value
else:
raise TypeError("Expected a bool, True or False")
@property
def magnetic(self):
"""This sets the options of calculating the magnetic scattering
instead of nuclear. This assume neutrons are being used.
:getter: Returns bool of magnetic scattering option
:setter: Sets whether magnetic sacttering is calculated
:type: bool
"""
return self._magnetic
@magnetic.setter
def magnetic(self, value):
if isinstance(value, bool):
self._magnetic = value
else:
raise TypeError("Expected a bool, True or False")
@property
def approximate(self):
"""This sets the options of calculating the approximate scattering
instead of exact. This is much quicker and is likely good enough for
most cases.
:getter: Returns bool of approximate scattering option
:setter: Sets whether approximate sacttering is calculated
:type: bool
"""
return self._approximate
@approximate.setter
def approximate(self, value):
if isinstance(value, bool):
self._approximate = value
else:
raise TypeError("Expected a bool, True or False")
def __get_q(self, unitcell):
qx, qy, qz = self.grid.get_q_meshgrid()
q = np.linalg.norm(np.array([qx.ravel(),
qy.ravel(),
qz.ravel()]).T @ unitcell.B, axis=1)
q.shape = qx.shape
return q*2*np.pi
def calc(self, structure):
"""Calculates the fourier transform
:param structure: The structure from which fourier transform
is calculated. The calculation work with any of the following
types of structures :class:`javelin.structure.Structure`,
:class:`ase.Atoms` or
:class:`diffpy.Structure.structure.Structure` but if you are
using average structure subtraction or the lots option it
needs to be :class:`javelin.structure.Structure` type.
:return: DataArray containing calculated diffuse scattering
:rtype: :class:`xarray.DataArray`
"""
if structure is None:
raise ValueError("You have not set a structure for this calculation")
if self.average:
aver = self._calculate_average(structure)
unitcell = get_unitcell(structure)
if self.lots is None:
atomic_numbers = get_atomic_numbers(structure)
positions = get_positions(structure)
if self.magnetic:
magmons = structure.get_magnetic_moments()
return create_xarray_dataarray(self._calculate_magnetic(atomic_numbers,
positions,
unitcell,
magmons), self.grid)
else:
results = self._calculate(atomic_numbers, positions, unitcell)
if self.average:
results -= aver
return create_xarray_dataarray(np.real(results*np.conj(results)), self.grid)
else: # needs to be Javelin structure, lots by unit cell
total = np.zeros(self.grid.bins)
levels = structure.atoms.index.levels
for lot in range(self.number_of_lots):
print(lot+1, 'out of', self.number_of_lots)
starti = np.random.randint(len(levels[0]))
startj = np.random.randint(len(levels[1]))
startk = np.random.randint(len(levels[2]))
ri = np.roll(levels[0], -starti)[:self.lots[0]]
rj = np.roll(levels[1], -startj)[:self.lots[1]]
rk = np.roll(levels[2], -startk)[:self.lots[2]]
atoms = structure.atoms.loc[ri, rj, rk, :]
atomic_numbers = atoms.Z.values
positions = (atoms[['x', 'y', 'z']].values +
np.asarray([np.mod(atoms.index.get_level_values(0).values-starti,
len(levels[0])),
np.mod(atoms.index.get_level_values(1).values-startj,
len(levels[1])),
np.mod(atoms.index.get_level_values(2).values-startk,
len(levels[2]))]).T)
if self.magnetic:
magmons = structure.magmons.loc[ri, rj, rk, :].values
total += self._calculate_magnetic(atomic_numbers, positions, unitcell, magmons)
else:
results = self._calculate(atomic_numbers, positions, unitcell)
if self.average:
results -= aver
total += np.real(results*np.conj(results))
scale = (structure.atoms.index.droplevel(3).drop_duplicates().size /
(self.number_of_lots*self.lots.prod()))
return create_xarray_dataarray(total*scale, self.grid)
def calc_average(self, structure):
"""Calculates the scattering from the avarage structure
:param structure: The structure from which fourier transform
is calculated. The calculation work with any of the following
types of structures :class:`javelin.structure.Structure`,
:class:`ase.Atoms` or
:class:`diffpy.Structure.structure.Structure` but if you are
using average structure subtraction or the lots option it
needs to be :class:`javelin.structure.Structure` type.
:return: DataArray containing calculated average scattering
:rtype: :class:`xarray.DataArray`
"""
if structure is None:
raise ValueError("You have not set a structure for this calculation")
aver = self._calculate_average(structure)
return create_xarray_dataarray(np.real(aver*np.conj(aver)), self.grid)
def _calculate_average(self, structure):
aver = self._calculate(get_atomic_numbers(structure),
structure.xyz, get_unitcell(structure))
aver /= structure.atoms.index.droplevel(3).drop_duplicates().size
# compute the interference function of the lot shape
if self.lots is None:
index = structure.atoms.index.droplevel(3).drop_duplicates()
else:
index = structure.atoms.loc[pd.RangeIndex(self.lots[0]),
pd.RangeIndex(self.lots[1]),
pd.RangeIndex(self.lots[2]),
:].index.droplevel(3).drop_duplicates()
aver *= self._calculate(np.zeros(len(index), dtype=np.int),
np.asarray([index.get_level_values(0).astype('double').values,
index.get_level_values(1).astype('double').values,
index.get_level_values(2).astype('double').values]).T,
use_ff=False)
return aver
def _calculate(self, atomic_numbers, positions, unitcell=None, use_ff=True):
if self._fast and not self._cython:
qx, qy, qz = self.grid.get_squashed_q_meshgrid()
else:
qx, qy, qz = self.grid.get_q_meshgrid()
qx *= (2*np.pi)
qy *= (2*np.pi)
qz *= (2*np.pi)
# Get unique list of atomic numbers
unique_atomic_numbers = np.unique(atomic_numbers)
results = np.zeros(self.grid.bins, dtype=np.complex)
# Loop of atom types
for atomic_number in unique_atomic_numbers:
try:
ff = get_ff(atomic_number, self.radiation, self.__get_q(unitcell)) if use_ff else 1
except KeyError as e:
print("Skipping fourier calculation for atom " + str(e) +
", unable to get scattering factors.")
continue
atom_positions = positions[np.where(atomic_numbers == atomic_number)]
temp_array = np.zeros(self.grid.bins, dtype=np.complex)
print("Working on atom number", atomic_number, "Total atoms:", len(atom_positions))
# Loop over atom positions of type atomic_number
if self._cython:
if self.approximate:
cex = np.exp(np.linspace(0, 2j*np.pi*(1-2**-16), 2**16))
approx_calculate_cython(self.grid.ll, self.grid.v1_delta,
self.grid.v2_delta, self.grid.v3_delta,
atom_positions, temp_array.real,
temp_array.imag, cex.real, cex.imag)
else:
calculate_cython(qx, qy, qz, atom_positions, temp_array.real, temp_array.imag)
else:
if self._fast:
for atom in atom_positions:
dotx = np.exp(qx*atom[0]*1j)
doty = np.exp(qy*atom[1]*1j)
dotz = np.exp(qz*atom[2]*1j)
temp_array += dotx * doty * dotz
else:
for atom in atom_positions:
dot = qx*atom[0] + qy*atom[1] + qz*atom[2]
temp_array += np.exp(dot*1j)
results += temp_array * ff # scale by form factor
return results
def _calculate_magnetic(self, atomic_numbers, positions, unitcell, magmons):
if self._fast:
qx, qy, qz = self.grid.get_squashed_q_meshgrid()
else:
qx, qy, qz = self.grid.get_q_meshgrid()
qx *= (2*np.pi)
qy *= (2*np.pi)
qz *= (2*np.pi)
q2 = self.__get_q(unitcell)**2
# Get unique list of atomic numbers
unique_atomic_numbers = np.unique(atomic_numbers)
# Loop of atom types
spinx = np.zeros(self.grid.bins, dtype=np.complex)
spiny = np.zeros(self.grid.bins, dtype=np.complex)
spinz = np.zeros(self.grid.bins, dtype=np.complex)
for atomic_number in unique_atomic_numbers:
try:
ff = get_mag_ff(atomic_number, self.__get_q(unitcell), ion=3)
except (AttributeError, KeyError) as e:
print("Skipping fourier calculation for atom " + str(e) +
", unable to get magnetic scattering factors.")
continue
atom_positions = positions[np.where(atomic_numbers == atomic_number)]
temp_spinx = np.zeros(self.grid.bins, dtype=np.complex)
temp_spiny = np.zeros(self.grid.bins, dtype=np.complex)
temp_spinz = np.zeros(self.grid.bins, dtype=np.complex)
print("Working on atom number", atomic_number, "Total atoms:", len(atom_positions))
# Loop over atom positions of type atomic_number
if self._fast:
for atom, spin in zip(atom_positions, magmons):
dotx = np.exp(qx*atom[0]*1j)
doty = np.exp(qy*atom[1]*1j)
dotz = np.exp(qz*atom[2]*1j)
exp_temp = dotx * doty * dotz
temp_spinx += exp_temp*spin[0]
temp_spiny += exp_temp*spin[1]
temp_spinz += exp_temp*spin[2]
else:
for atom, spin in zip(atom_positions, magmons):
dot = qx*atom[0] + qy*atom[1] + qz*atom[2]
exp_temp = np.exp(dot*1j)
temp_spinx += exp_temp*spin[0]
temp_spiny += exp_temp*spin[1]
temp_spinz += exp_temp*spin[2]
spinx += temp_spinx * ff
spiny += temp_spiny * ff
spinz += temp_spinz * ff
# Calculate vector rejection of spin onto q
# M - M.Q/|Q|^2 Q
scale = (spinx*qx + spiny*qy + spinz*qz)/q2
spinx = spinx - scale * qx
spiny = spiny - scale * qy
spinz = spinz - scale * qz
return np.real(spinx*np.conj(spinx) + spiny*np.conj(spiny) + spinz*np.conj(spinz))
def create_xarray_dataarray(values, grid):
"""Create a xarry DataArray from the input numpy array and grid
object.
:param values: Input array containing the scattering intensities
:type values: :class:`numpy.ndarray`
:param numbers: Grid object describing the array properties
:type numbers: :class:`javelin.grid.Grid`
:return: DataArray produced from the values and grid object
:rtype: :class:`xarray.DataArray`
"""
import xarray as xr
return xr.DataArray(data=values,
name="Intensity",
dims=(grid.get_axes_names()),
coords=(grid.r1, grid.r2, grid.r3),
attrs=(("units", grid.units),))
def get_ff(atomic_number, radiation, q=None):
"""Returns the form factor for a given atomic number, radiation and q
values
:param atomic_number: atomic number
:type atomic_number: int
:param radiation: type of radiation ('xray' or 'neutron')
:type radiation: str
:param q: value or values of q for which to get form factors
:type q: float, list, :class:`numpy.ndarray`
:return: form factors for given q
:rtype: float, :class:`numpy.ndarray`
:Examples:
>>> get_ff(8, 'neutron')
5.805
>>> get_ff(8, 'xray', q=2.0)
6.31826029176493
>>> get_ff(8, 'xray', q=[0.0, 3.5, 7.0])
array([ 7.999706 , 4.38417867, 2.08928068])
"""
import periodictable
if atomic_number < 1:
raise KeyError(atomic_number)
if radiation == 'neutron':
return periodictable.elements[atomic_number].neutron.b_c
elif radiation == 'xray':
return periodictable.elements[atomic_number].xray.f0(q)
else:
raise ValueError("Unknown radition: " + radiation)
def get_mag_ff(atomic_number, q, ion=0, j=0):
"""Returns the j0 magnetic form factor for a given atomic number,
radiation and q values
:param atomic_number: atomic number
:type atomic_number: int
:param q: value or values of q for which to get form factors
:type q: float, list, :class:`numpy.ndarray`
:param ion: charge of selected atom
:type ion: int
:param j: order of spherical Bessel function (0, 2, 4 or 6)
:type j: int
:return: magnetic form factor for given q
:rtype: float, :class:`numpy.ndarray`
:Examples:
>>> get_mag_ff(8, q=2, ion=1)
0.58510426376585045
>>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=2)
array([ 1. , 0.49729671, 0.09979243])
>>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=4)
array([ 0.9997 , 0.58273549, 0.13948496])
>>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=4, j=4)
array([ 0. , 0.0149604, 0.0759222])
"""
import periodictable
return getattr(periodictable.elements[atomic_number].magnetic_ff[ion], 'j'+str(j)+'_Q')(q)
| mit |
neoneye/newton-commander | source/copymove/test_copy/5001 rename source1/main.rb | 464 | def run
op = FileOperation.new
op.perform_copy do |source_name, target_name, name, collision_type|
operation = :replace
if name == 'file1.txt'
operation = [:rename_source, 'file1_new.txt']
end
operation
end
end
def verify_source
assert_source_file('file1.txt', /source/)
assert_source_nonexist('file1_new.txt')
end
def verify_target
assert_target_file('file1.txt', /target/)
assert_target_file('file1_new.txt', /source/)
end
| mit |
Grizzlybeardesignltd/davidcullimore | js/skrollr.js | 48699 | /*!
* skrollr core
*
* Alexander Prinzhorn - https://github.com/Prinzhorn/skrollr
*
* Free to use under terms of MIT license
*/
(function(window, document, undefined) {
'use strict';
/*
* Global api.
*/
var skrollr = {
get: function() {
return _instance;
},
//Main entry point.
init: function(options) {
return _instance || new Skrollr(options);
},
VERSION: '0.6.30'
};
//Minify optimization.
var hasProp = Object.prototype.hasOwnProperty;
var Math = window.Math;
var getStyle = window.getComputedStyle;
//They will be filled when skrollr gets initialized.
var documentElement;
var body;
var EVENT_TOUCHSTART = 'touchstart';
var EVENT_TOUCHMOVE = 'touchmove';
var EVENT_TOUCHCANCEL = 'touchcancel';
var EVENT_TOUCHEND = 'touchend';
var SKROLLABLE_CLASS = 'skrollable';
var SKROLLABLE_BEFORE_CLASS = SKROLLABLE_CLASS + '-before';
var SKROLLABLE_BETWEEN_CLASS = SKROLLABLE_CLASS + '-between';
var SKROLLABLE_AFTER_CLASS = SKROLLABLE_CLASS + '-after';
var SKROLLR_CLASS = 'skrollr';
var NO_SKROLLR_CLASS = 'no-' + SKROLLR_CLASS;
var SKROLLR_DESKTOP_CLASS = SKROLLR_CLASS + '-desktop';
var SKROLLR_MOBILE_CLASS = SKROLLR_CLASS + '-mobile';
var DEFAULT_EASING = 'linear';
var DEFAULT_DURATION = 1000;//ms
var DEFAULT_MOBILE_DECELERATION = 0.004;//pixel/ms²
var DEFAULT_SKROLLRBODY = 'skrollr-body';
var DEFAULT_SMOOTH_SCROLLING_DURATION = 200;//ms
var ANCHOR_START = 'start';
var ANCHOR_END = 'end';
var ANCHOR_CENTER = 'center';
var ANCHOR_BOTTOM = 'bottom';
//The property which will be added to the DOM element to hold the ID of the skrollable.
var SKROLLABLE_ID_DOM_PROPERTY = '___skrollable_id';
var rxTouchIgnoreTags = /^(?:input|textarea|button|select)$/i;
var rxTrim = /^\s+|\s+$/g;
//Find all data-attributes. data-[_constant]-[offset]-[anchor]-[anchor].
var rxKeyframeAttribute = /^data(?:-(_\w+))?(?:-?(-?\d*\.?\d+p?))?(?:-?(start|end|top|center|bottom))?(?:-?(top|center|bottom))?$/;
var rxPropValue = /\s*(@?[\w\-\[\]]+)\s*:\s*(.+?)\s*(?:;|$)/gi;
//Easing function names follow the property in square brackets.
var rxPropEasing = /^(@?[a-z\-]+)\[(\w+)\]$/;
var rxCamelCase = /-([a-z0-9_])/g;
var rxCamelCaseFn = function(str, letter) {
return letter.toUpperCase();
};
//Numeric values with optional sign.
var rxNumericValue = /[\-+]?[\d]*\.?[\d]+/g;
//Used to replace occurences of {?} with a number.
var rxInterpolateString = /\{\?\}/g;
//Finds rgb(a) colors, which don't use the percentage notation.
var rxRGBAIntegerColor = /rgba?\(\s*-?\d+\s*,\s*-?\d+\s*,\s*-?\d+/g;
//Finds all gradients.
var rxGradient = /[a-z\-]+-gradient/g;
//Vendor prefix. Will be set once skrollr gets initialized.
var theCSSPrefix = '';
var theDashedCSSPrefix = '';
//Will be called once (when skrollr gets initialized).
var detectCSSPrefix = function() {
//Only relevant prefixes. May be extended.
//Could be dangerous if there will ever be a CSS property which actually starts with "ms". Don't hope so.
var rxPrefixes = /^(?:O|Moz|webkit|ms)|(?:-(?:o|moz|webkit|ms)-)/;
//Detect prefix for current browser by finding the first property using a prefix.
if(!getStyle) {
return;
}
var style = getStyle(body, null);
for(var k in style) {
//We check the key and if the key is a number, we check the value as well, because safari's getComputedStyle returns some weird array-like thingy.
theCSSPrefix = (k.match(rxPrefixes) || (+k == k && style[k].match(rxPrefixes)));
if(theCSSPrefix) {
break;
}
}
//Did we even detect a prefix?
if(!theCSSPrefix) {
theCSSPrefix = theDashedCSSPrefix = '';
return;
}
theCSSPrefix = theCSSPrefix[0];
//We could have detected either a dashed prefix or this camelCaseish-inconsistent stuff.
if(theCSSPrefix.slice(0,1) === '-') {
theDashedCSSPrefix = theCSSPrefix;
//There's no logic behind these. Need a look up.
theCSSPrefix = ({
'-webkit-': 'webkit',
'-moz-': 'Moz',
'-ms-': 'ms',
'-o-': 'O'
})[theCSSPrefix];
} else {
theDashedCSSPrefix = '-' + theCSSPrefix.toLowerCase() + '-';
}
};
var polyfillRAF = function() {
var requestAnimFrame = window.requestAnimationFrame || window[theCSSPrefix.toLowerCase() + 'RequestAnimationFrame'];
var lastTime = _now();
if(_isMobile || !requestAnimFrame) {
requestAnimFrame = function(callback) {
//How long did it take to render?
var deltaTime = _now() - lastTime;
var delay = Math.max(0, 1000 / 60 - deltaTime);
return window.setTimeout(function() {
lastTime = _now();
callback();
}, delay);
};
}
return requestAnimFrame;
};
var polyfillCAF = function() {
var cancelAnimFrame = window.cancelAnimationFrame || window[theCSSPrefix.toLowerCase() + 'CancelAnimationFrame'];
if(_isMobile || !cancelAnimFrame) {
cancelAnimFrame = function(timeout) {
return window.clearTimeout(timeout);
};
}
return cancelAnimFrame;
};
//Built-in easing functions.
var easings = {
begin: function() {
return 0;
},
end: function() {
return 1;
},
linear: function(p) {
return p;
},
quadratic: function(p) {
return p * p;
},
cubic: function(p) {
return p * p * p;
},
swing: function(p) {
return (-Math.cos(p * Math.PI) / 2) + 0.5;
},
sqrt: function(p) {
return Math.sqrt(p);
},
outCubic: function(p) {
return (Math.pow((p - 1), 3) + 1);
},
//see https://www.desmos.com/calculator/tbr20s8vd2 for how I did this
bounce: function(p) {
var a;
if(p <= 0.5083) {
a = 3;
} else if(p <= 0.8489) {
a = 9;
} else if(p <= 0.96208) {
a = 27;
} else if(p <= 0.99981) {
a = 91;
} else {
return 1;
}
return 1 - Math.abs(3 * Math.cos(p * a * 1.028) / a);
}
};
/**
* Constructor.
*/
function Skrollr(options) {
documentElement = document.documentElement;
body = document.body;
detectCSSPrefix();
_instance = this;
options = options || {};
_constants = options.constants || {};
//We allow defining custom easings or overwrite existing.
if(options.easing) {
for(var e in options.easing) {
easings[e] = options.easing[e];
}
}
_edgeStrategy = options.edgeStrategy || 'set';
_listeners = {
//Function to be called right before rendering.
beforerender: options.beforerender,
//Function to be called right after finishing rendering.
render: options.render,
//Function to be called whenever an element with the `data-emit-events` attribute passes a keyframe.
keyframe: options.keyframe
};
//forceHeight is true by default
_forceHeight = options.forceHeight !== false;
if(_forceHeight) {
_scale = options.scale || 1;
}
_mobileDeceleration = options.mobileDeceleration || DEFAULT_MOBILE_DECELERATION;
_smoothScrollingEnabled = options.smoothScrolling !== false;
_smoothScrollingDuration = options.smoothScrollingDuration || DEFAULT_SMOOTH_SCROLLING_DURATION;
//Dummy object. Will be overwritten in the _render method when smooth scrolling is calculated.
_smoothScrolling = {
targetTop: _instance.getScrollTop()
};
//A custom check function may be passed.
_isMobile = ((options.mobileCheck || function() {
return (/Android|iPhone|iPad|iPod|BlackBerry/i).test(navigator.userAgent || navigator.vendor || window.opera);
})());
if(_isMobile) {
_skrollrBody = document.getElementById(options.skrollrBody || DEFAULT_SKROLLRBODY);
//Detect 3d transform if there's a skrollr-body (only needed for #skrollr-body).
if(_skrollrBody) {
_detect3DTransforms();
}
_initMobile();
_updateClass(documentElement, [SKROLLR_CLASS, SKROLLR_MOBILE_CLASS], [NO_SKROLLR_CLASS]);
} else {
_updateClass(documentElement, [SKROLLR_CLASS, SKROLLR_DESKTOP_CLASS], [NO_SKROLLR_CLASS]);
}
//Triggers parsing of elements and a first reflow.
_instance.refresh();
_addEvent(window, 'resize orientationchange', function() {
var width = documentElement.clientWidth;
var height = documentElement.clientHeight;
//Only reflow if the size actually changed (#271).
if(height !== _lastViewportHeight || width !== _lastViewportWidth) {
_lastViewportHeight = height;
_lastViewportWidth = width;
_requestReflow = true;
}
});
var requestAnimFrame = polyfillRAF();
//Let's go.
(function animloop(){
_render();
_animFrame = requestAnimFrame(animloop);
}());
return _instance;
}
/**
* (Re)parses some or all elements.
*/
Skrollr.prototype.refresh = function(elements) {
var elementIndex;
var elementsLength;
var ignoreID = false;
//Completely reparse anything without argument.
if(elements === undefined) {
//Ignore that some elements may already have a skrollable ID.
ignoreID = true;
_skrollables = [];
_skrollableIdCounter = 0;
elements = document.getElementsByTagName('*');
} else if(elements.length === undefined) {
//We also accept a single element as parameter.
elements = [elements];
}
elementIndex = 0;
elementsLength = elements.length;
for(; elementIndex < elementsLength; elementIndex++) {
var el = elements[elementIndex];
var anchorTarget = el;
var keyFrames = [];
//If this particular element should be smooth scrolled.
var smoothScrollThis = _smoothScrollingEnabled;
//The edge strategy for this particular element.
var edgeStrategy = _edgeStrategy;
//If this particular element should emit keyframe events.
var emitEvents = false;
//If we're reseting the counter, remove any old element ids that may be hanging around.
if(ignoreID && SKROLLABLE_ID_DOM_PROPERTY in el) {
delete el[SKROLLABLE_ID_DOM_PROPERTY];
}
if(!el.attributes) {
continue;
}
//Iterate over all attributes and search for key frame attributes.
var attributeIndex = 0;
var attributesLength = el.attributes.length;
for (; attributeIndex < attributesLength; attributeIndex++) {
var attr = el.attributes[attributeIndex];
if(attr.name === 'data-anchor-target') {
anchorTarget = document.querySelector(attr.value);
if(anchorTarget === null) {
throw 'Unable to find anchor target "' + attr.value + '"';
}
continue;
}
//Global smooth scrolling can be overridden by the element attribute.
if(attr.name === 'data-smooth-scrolling') {
smoothScrollThis = attr.value !== 'off';
continue;
}
//Global edge strategy can be overridden by the element attribute.
if(attr.name === 'data-edge-strategy') {
edgeStrategy = attr.value;
continue;
}
//Is this element tagged with the `data-emit-events` attribute?
if(attr.name === 'data-emit-events') {
emitEvents = true;
continue;
}
var match = attr.name.match(rxKeyframeAttribute);
if(match === null) {
continue;
}
var kf = {
props: attr.value,
//Point back to the element as well.
element: el,
//The name of the event which this keyframe will fire, if emitEvents is
eventType: attr.name.replace(rxCamelCase, rxCamelCaseFn)
};
keyFrames.push(kf);
var constant = match[1];
if(constant) {
//Strip the underscore prefix.
kf.constant = constant.substr(1);
}
//Get the key frame offset.
var offset = match[2];
//Is it a percentage offset?
if(/p$/.test(offset)) {
kf.isPercentage = true;
kf.offset = (offset.slice(0, -1) | 0) / 100;
} else {
kf.offset = (offset | 0);
}
var anchor1 = match[3];
//If second anchor is not set, the first will be taken for both.
var anchor2 = match[4] || anchor1;
//"absolute" (or "classic") mode, where numbers mean absolute scroll offset.
if(!anchor1 || anchor1 === ANCHOR_START || anchor1 === ANCHOR_END) {
kf.mode = 'absolute';
//data-end needs to be calculated after all key frames are known.
if(anchor1 === ANCHOR_END) {
kf.isEnd = true;
} else if(!kf.isPercentage) {
//For data-start we can already set the key frame w/o calculations.
//#59: "scale" options should only affect absolute mode.
kf.offset = kf.offset * _scale;
}
}
//"relative" mode, where numbers are relative to anchors.
else {
kf.mode = 'relative';
kf.anchors = [anchor1, anchor2];
}
}
//Does this element have key frames?
if(!keyFrames.length) {
continue;
}
//Will hold the original style and class attributes before we controlled the element (see #80).
var styleAttr, classAttr;
var id;
if(!ignoreID && SKROLLABLE_ID_DOM_PROPERTY in el) {
//We already have this element under control. Grab the corresponding skrollable id.
id = el[SKROLLABLE_ID_DOM_PROPERTY];
styleAttr = _skrollables[id].styleAttr;
classAttr = _skrollables[id].classAttr;
} else {
//It's an unknown element. Asign it a new skrollable id.
id = (el[SKROLLABLE_ID_DOM_PROPERTY] = _skrollableIdCounter++);
styleAttr = el.style.cssText;
classAttr = _getClass(el);
}
_skrollables[id] = {
element: el,
styleAttr: styleAttr,
classAttr: classAttr,
anchorTarget: anchorTarget,
keyFrames: keyFrames,
smoothScrolling: smoothScrollThis,
edgeStrategy: edgeStrategy,
emitEvents: emitEvents,
lastFrameIndex: -1
};
_updateClass(el, [SKROLLABLE_CLASS], []);
}
//Reflow for the first time.
_reflow();
//Now that we got all key frame numbers right, actually parse the properties.
elementIndex = 0;
elementsLength = elements.length;
for(; elementIndex < elementsLength; elementIndex++) {
var sk = _skrollables[elements[elementIndex][SKROLLABLE_ID_DOM_PROPERTY]];
if(sk === undefined) {
continue;
}
//Parse the property string to objects
_parseProps(sk);
//Fill key frames with missing properties from left and right
_fillProps(sk);
}
return _instance;
};
/**
* Transform "relative" mode to "absolute" mode.
* That is, calculate anchor position and offset of element.
*/
Skrollr.prototype.relativeToAbsolute = function(element, viewportAnchor, elementAnchor) {
var viewportHeight = documentElement.clientHeight;
var box = element.getBoundingClientRect();
var absolute = box.top;
//#100: IE doesn't supply "height" with getBoundingClientRect.
var boxHeight = box.bottom - box.top;
if(viewportAnchor === ANCHOR_BOTTOM) {
absolute -= viewportHeight;
} else if(viewportAnchor === ANCHOR_CENTER) {
absolute -= viewportHeight / 2;
}
if(elementAnchor === ANCHOR_BOTTOM) {
absolute += boxHeight;
} else if(elementAnchor === ANCHOR_CENTER) {
absolute += boxHeight / 2;
}
//Compensate scrolling since getBoundingClientRect is relative to viewport.
absolute += _instance.getScrollTop();
return (absolute + 0.5) | 0;
};
/**
* Animates scroll top to new position.
*/
Skrollr.prototype.animateTo = function(top, options) {
options = options || {};
var now = _now();
var scrollTop = _instance.getScrollTop();
var duration = options.duration === undefined ? DEFAULT_DURATION : options.duration;
//Setting this to a new value will automatically cause the current animation to stop, if any.
_scrollAnimation = {
startTop: scrollTop,
topDiff: top - scrollTop,
targetTop: top,
duration: duration,
startTime: now,
endTime: now + duration,
easing: easings[options.easing || DEFAULT_EASING],
done: options.done
};
//Don't queue the animation if there's nothing to animate.
if(!_scrollAnimation.topDiff) {
if(_scrollAnimation.done) {
_scrollAnimation.done.call(_instance, false);
}
_scrollAnimation = undefined;
}
return _instance;
};
/**
* Stops animateTo animation.
*/
Skrollr.prototype.stopAnimateTo = function() {
if(_scrollAnimation && _scrollAnimation.done) {
_scrollAnimation.done.call(_instance, true);
}
_scrollAnimation = undefined;
};
/**
* Returns if an animation caused by animateTo is currently running.
*/
Skrollr.prototype.isAnimatingTo = function() {
return !!_scrollAnimation;
};
Skrollr.prototype.isMobile = function() {
return _isMobile;
};
Skrollr.prototype.setScrollTop = function(top, force) {
_forceRender = (force === true);
if(_isMobile) {
_mobileOffset = Math.min(Math.max(top, 0), _maxKeyFrame);
} else {
window.scrollTo(0, top);
}
return _instance;
};
Skrollr.prototype.getScrollTop = function() {
if(_isMobile) {
return _mobileOffset;
} else {
return window.pageYOffset || documentElement.scrollTop || body.scrollTop || 0;
}
};
Skrollr.prototype.getMaxScrollTop = function() {
return _maxKeyFrame;
};
Skrollr.prototype.on = function(name, fn) {
_listeners[name] = fn;
return _instance;
};
Skrollr.prototype.off = function(name) {
delete _listeners[name];
return _instance;
};
Skrollr.prototype.destroy = function() {
var cancelAnimFrame = polyfillCAF();
cancelAnimFrame(_animFrame);
_removeAllEvents();
_updateClass(documentElement, [NO_SKROLLR_CLASS], [SKROLLR_CLASS, SKROLLR_DESKTOP_CLASS, SKROLLR_MOBILE_CLASS]);
var skrollableIndex = 0;
var skrollablesLength = _skrollables.length;
for(; skrollableIndex < skrollablesLength; skrollableIndex++) {
_reset(_skrollables[skrollableIndex].element);
}
documentElement.style.overflow = body.style.overflow = '';
documentElement.style.height = body.style.height = '';
if(_skrollrBody) {
skrollr.setStyle(_skrollrBody, 'transform', 'none');
}
_instance = undefined;
_skrollrBody = undefined;
_listeners = undefined;
_forceHeight = undefined;
_maxKeyFrame = 0;
_scale = 1;
_constants = undefined;
_mobileDeceleration = undefined;
_direction = 'down';
_lastTop = -1;
_lastViewportWidth = 0;
_lastViewportHeight = 0;
_requestReflow = false;
_scrollAnimation = undefined;
_smoothScrollingEnabled = undefined;
_smoothScrollingDuration = undefined;
_smoothScrolling = undefined;
_forceRender = undefined;
_skrollableIdCounter = 0;
_edgeStrategy = undefined;
_isMobile = false;
_mobileOffset = 0;
_translateZ = undefined;
};
/*
Private methods.
*/
var _initMobile = function() {
var initialElement;
var initialTouchY;
var initialTouchX;
var currentElement;
var currentTouchY;
var currentTouchX;
var lastTouchY;
var deltaY;
var initialTouchTime;
var currentTouchTime;
var lastTouchTime;
var deltaTime;
_addEvent(documentElement, [EVENT_TOUCHSTART, EVENT_TOUCHMOVE, EVENT_TOUCHCANCEL, EVENT_TOUCHEND].join(' '), function(e) {
var touch = e.changedTouches[0];
currentElement = e.target;
//We don't want text nodes.
while(currentElement.nodeType === 3) {
currentElement = currentElement.parentNode;
}
currentTouchY = touch.clientY;
currentTouchX = touch.clientX;
currentTouchTime = e.timeStamp;
if(!rxTouchIgnoreTags.test(currentElement.tagName)) {
e.preventDefault();
}
switch(e.type) {
case EVENT_TOUCHSTART:
//The last element we tapped on.
if(initialElement) {
initialElement.blur();
}
_instance.stopAnimateTo();
initialElement = currentElement;
initialTouchY = lastTouchY = currentTouchY;
initialTouchX = currentTouchX;
initialTouchTime = currentTouchTime;
break;
case EVENT_TOUCHMOVE:
//Prevent default event on touchIgnore elements in case they don't have focus yet.
if(rxTouchIgnoreTags.test(currentElement.tagName) && document.activeElement !== currentElement) {
e.preventDefault();
}
deltaY = currentTouchY - lastTouchY;
deltaTime = currentTouchTime - lastTouchTime;
_instance.setScrollTop(_mobileOffset - deltaY, true);
lastTouchY = currentTouchY;
lastTouchTime = currentTouchTime;
break;
default:
case EVENT_TOUCHCANCEL:
case EVENT_TOUCHEND:
var distanceY = initialTouchY - currentTouchY;
var distanceX = initialTouchX - currentTouchX;
var distance2 = distanceX * distanceX + distanceY * distanceY;
//Check if it was more like a tap (moved less than 7px).
if(distance2 < 49) {
if(!rxTouchIgnoreTags.test(initialElement.tagName)) {
initialElement.focus();
//It was a tap, click the element.
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent('click', true, true, e.view, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, 0, null);
initialElement.dispatchEvent(clickEvent);
}
return;
}
initialElement = undefined;
var speed = deltaY / deltaTime;
//Cap speed at 3 pixel/ms.
speed = Math.max(Math.min(speed, 3), -3);
var duration = Math.abs(speed / _mobileDeceleration);
var targetOffset = speed * duration + 0.5 * _mobileDeceleration * duration * duration;
var targetTop = _instance.getScrollTop() - targetOffset;
//Relative duration change for when scrolling above bounds.
var targetRatio = 0;
//Change duration proportionally when scrolling would leave bounds.
if(targetTop > _maxKeyFrame) {
targetRatio = (_maxKeyFrame - targetTop) / targetOffset;
targetTop = _maxKeyFrame;
} else if(targetTop < 0) {
targetRatio = -targetTop / targetOffset;
targetTop = 0;
}
duration = duration * (1 - targetRatio);
_instance.animateTo((targetTop + 0.5) | 0, {easing: 'outCubic', duration: duration});
break;
}
});
//Just in case there has already been some native scrolling, reset it.
window.scrollTo(0, 0);
documentElement.style.overflow = body.style.overflow = 'hidden';
};
/**
* Updates key frames which depend on others / need to be updated on resize.
* That is "end" in "absolute" mode and all key frames in "relative" mode.
* Also handles constants, because they may change on resize.
*/
var _updateDependentKeyFrames = function() {
var viewportHeight = documentElement.clientHeight;
var processedConstants = _processConstants();
var skrollable;
var element;
var anchorTarget;
var keyFrames;
var keyFrameIndex;
var keyFramesLength;
var kf;
var skrollableIndex;
var skrollablesLength;
var offset;
var constantValue;
//First process all relative-mode elements and find the max key frame.
skrollableIndex = 0;
skrollablesLength = _skrollables.length;
for(; skrollableIndex < skrollablesLength; skrollableIndex++) {
skrollable = _skrollables[skrollableIndex];
element = skrollable.element;
anchorTarget = skrollable.anchorTarget;
keyFrames = skrollable.keyFrames;
keyFrameIndex = 0;
keyFramesLength = keyFrames.length;
for(; keyFrameIndex < keyFramesLength; keyFrameIndex++) {
kf = keyFrames[keyFrameIndex];
offset = kf.offset;
constantValue = processedConstants[kf.constant] || 0;
kf.frame = offset;
if(kf.isPercentage) {
//Convert the offset to percentage of the viewport height.
offset = offset * viewportHeight;
//Absolute + percentage mode.
kf.frame = offset;
}
if(kf.mode === 'relative') {
_reset(element);
kf.frame = _instance.relativeToAbsolute(anchorTarget, kf.anchors[0], kf.anchors[1]) - offset;
_reset(element, true);
}
kf.frame += constantValue;
//Only search for max key frame when forceHeight is enabled.
if(_forceHeight) {
//Find the max key frame, but don't use one of the data-end ones for comparison.
if(!kf.isEnd && kf.frame > _maxKeyFrame) {
_maxKeyFrame = kf.frame;
}
}
}
}
//#133: The document can be larger than the maxKeyFrame we found.
_maxKeyFrame = Math.max(_maxKeyFrame, _getDocumentHeight());
//Now process all data-end keyframes.
skrollableIndex = 0;
skrollablesLength = _skrollables.length;
for(; skrollableIndex < skrollablesLength; skrollableIndex++) {
skrollable = _skrollables[skrollableIndex];
keyFrames = skrollable.keyFrames;
keyFrameIndex = 0;
keyFramesLength = keyFrames.length;
for(; keyFrameIndex < keyFramesLength; keyFrameIndex++) {
kf = keyFrames[keyFrameIndex];
constantValue = processedConstants[kf.constant] || 0;
if(kf.isEnd) {
kf.frame = _maxKeyFrame - kf.offset + constantValue;
}
}
skrollable.keyFrames.sort(_keyFrameComparator);
}
};
/**
* Calculates and sets the style properties for the element at the given frame.
* @param fakeFrame The frame to render at when smooth scrolling is enabled.
* @param actualFrame The actual frame we are at.
*/
var _calcSteps = function(fakeFrame, actualFrame) {
//Iterate over all skrollables.
var skrollableIndex = 0;
var skrollablesLength = _skrollables.length;
for(; skrollableIndex < skrollablesLength; skrollableIndex++) {
var skrollable = _skrollables[skrollableIndex];
var element = skrollable.element;
var frame = skrollable.smoothScrolling ? fakeFrame : actualFrame;
var frames = skrollable.keyFrames;
var framesLength = frames.length;
var firstFrame = frames[0];
var lastFrame = frames[frames.length - 1];
var beforeFirst = frame < firstFrame.frame;
var afterLast = frame > lastFrame.frame;
var firstOrLastFrame = beforeFirst ? firstFrame : lastFrame;
var emitEvents = skrollable.emitEvents;
var lastFrameIndex = skrollable.lastFrameIndex;
var key;
var value;
//If we are before/after the first/last frame, set the styles according to the given edge strategy.
if(beforeFirst || afterLast) {
//Check if we already handled this edge case last time.
//Note: using setScrollTop it's possible that we jumped from one edge to the other.
if(beforeFirst && skrollable.edge === -1 || afterLast && skrollable.edge === 1) {
continue;
}
//Add the skrollr-before or -after class.
if(beforeFirst) {
_updateClass(element, [SKROLLABLE_BEFORE_CLASS], [SKROLLABLE_AFTER_CLASS, SKROLLABLE_BETWEEN_CLASS]);
//This handles the special case where we exit the first keyframe.
if(emitEvents && lastFrameIndex > -1) {
_emitEvent(element, firstFrame.eventType, _direction);
skrollable.lastFrameIndex = -1;
}
} else {
_updateClass(element, [SKROLLABLE_AFTER_CLASS], [SKROLLABLE_BEFORE_CLASS, SKROLLABLE_BETWEEN_CLASS]);
//This handles the special case where we exit the last keyframe.
if(emitEvents && lastFrameIndex < framesLength) {
_emitEvent(element, lastFrame.eventType, _direction);
skrollable.lastFrameIndex = framesLength;
}
}
//Remember that we handled the edge case (before/after the first/last keyframe).
skrollable.edge = beforeFirst ? -1 : 1;
switch(skrollable.edgeStrategy) {
case 'reset':
_reset(element);
continue;
case 'ease':
//Handle this case like it would be exactly at first/last keyframe and just pass it on.
frame = firstOrLastFrame.frame;
break;
default:
case 'set':
var props = firstOrLastFrame.props;
for(key in props) {
if(hasProp.call(props, key)) {
value = _interpolateString(props[key].value);
//Set style or attribute.
if(key.indexOf('@') === 0) {
element.setAttribute(key.substr(1), value);
} else {
skrollr.setStyle(element, key, value);
}
}
}
continue;
}
} else {
//Did we handle an edge last time?
if(skrollable.edge !== 0) {
_updateClass(element, [SKROLLABLE_CLASS, SKROLLABLE_BETWEEN_CLASS], [SKROLLABLE_BEFORE_CLASS, SKROLLABLE_AFTER_CLASS]);
skrollable.edge = 0;
}
}
//Find out between which two key frames we are right now.
var keyFrameIndex = 0;
for(; keyFrameIndex < framesLength - 1; keyFrameIndex++) {
if(frame >= frames[keyFrameIndex].frame && frame <= frames[keyFrameIndex + 1].frame) {
var left = frames[keyFrameIndex];
var right = frames[keyFrameIndex + 1];
for(key in left.props) {
if(hasProp.call(left.props, key)) {
var progress = (frame - left.frame) / (right.frame - left.frame);
//Transform the current progress using the given easing function.
progress = left.props[key].easing(progress);
//Interpolate between the two values
value = _calcInterpolation(left.props[key].value, right.props[key].value, progress);
value = _interpolateString(value);
//Set style or attribute.
if(key.indexOf('@') === 0) {
element.setAttribute(key.substr(1), value);
} else {
skrollr.setStyle(element, key, value);
}
}
}
//Are events enabled on this element?
//This code handles the usual cases of scrolling through different keyframes.
//The special cases of before first and after last keyframe are handled above.
if(emitEvents) {
//Did we pass a new keyframe?
if(lastFrameIndex !== keyFrameIndex) {
if(_direction === 'down') {
_emitEvent(element, left.eventType, _direction);
} else {
_emitEvent(element, right.eventType, _direction);
}
skrollable.lastFrameIndex = keyFrameIndex;
}
}
break;
}
}
}
};
/**
* Renders all elements.
*/
var _render = function() {
if(_requestReflow) {
_requestReflow = false;
_reflow();
}
//We may render something else than the actual scrollbar position.
var renderTop = _instance.getScrollTop();
//If there's an animation, which ends in current render call, call the callback after rendering.
var afterAnimationCallback;
var now = _now();
var progress;
//Before actually rendering handle the scroll animation, if any.
if(_scrollAnimation) {
//It's over
if(now >= _scrollAnimation.endTime) {
renderTop = _scrollAnimation.targetTop;
afterAnimationCallback = _scrollAnimation.done;
_scrollAnimation = undefined;
} else {
//Map the current progress to the new progress using given easing function.
progress = _scrollAnimation.easing((now - _scrollAnimation.startTime) / _scrollAnimation.duration);
renderTop = (_scrollAnimation.startTop + progress * _scrollAnimation.topDiff) | 0;
}
_instance.setScrollTop(renderTop, true);
}
//Smooth scrolling only if there's no animation running and if we're not forcing the rendering.
else if(!_forceRender) {
var smoothScrollingDiff = _smoothScrolling.targetTop - renderTop;
//The user scrolled, start new smooth scrolling.
if(smoothScrollingDiff) {
_smoothScrolling = {
startTop: _lastTop,
topDiff: renderTop - _lastTop,
targetTop: renderTop,
startTime: _lastRenderCall,
endTime: _lastRenderCall + _smoothScrollingDuration
};
}
//Interpolate the internal scroll position (not the actual scrollbar).
if(now <= _smoothScrolling.endTime) {
//Map the current progress to the new progress using easing function.
progress = easings.sqrt((now - _smoothScrolling.startTime) / _smoothScrollingDuration);
renderTop = (_smoothScrolling.startTop + progress * _smoothScrolling.topDiff) | 0;
}
}
//Did the scroll position even change?
if(_forceRender || _lastTop !== renderTop) {
//Remember in which direction are we scrolling?
_direction = (renderTop > _lastTop) ? 'down' : (renderTop < _lastTop ? 'up' : _direction);
_forceRender = false;
var listenerParams = {
curTop: renderTop,
lastTop: _lastTop,
maxTop: _maxKeyFrame,
direction: _direction
};
//Tell the listener we are about to render.
var continueRendering = _listeners.beforerender && _listeners.beforerender.call(_instance, listenerParams);
//The beforerender listener function is able the cancel rendering.
if(continueRendering !== false) {
//Now actually interpolate all the styles.
_calcSteps(renderTop, _instance.getScrollTop());
//That's were we actually "scroll" on mobile.
if(_isMobile && _skrollrBody) {
//Set the transform ("scroll it").
skrollr.setStyle(_skrollrBody, 'transform', 'translate(0, ' + -(_mobileOffset) + 'px) ' + _translateZ);
}
//Remember when we last rendered.
_lastTop = renderTop;
if(_listeners.render) {
_listeners.render.call(_instance, listenerParams);
}
}
if(afterAnimationCallback) {
afterAnimationCallback.call(_instance, false);
}
}
_lastRenderCall = now;
};
/**
* Parses the properties for each key frame of the given skrollable.
*/
var _parseProps = function(skrollable) {
//Iterate over all key frames
var keyFrameIndex = 0;
var keyFramesLength = skrollable.keyFrames.length;
for(; keyFrameIndex < keyFramesLength; keyFrameIndex++) {
var frame = skrollable.keyFrames[keyFrameIndex];
var easing;
var value;
var prop;
var props = {};
var match;
while((match = rxPropValue.exec(frame.props)) !== null) {
prop = match[1];
value = match[2];
easing = prop.match(rxPropEasing);
//Is there an easing specified for this prop?
if(easing !== null) {
prop = easing[1];
easing = easing[2];
} else {
easing = DEFAULT_EASING;
}
//Exclamation point at first position forces the value to be taken literal.
value = value.indexOf('!') ? _parseProp(value) : [value.slice(1)];
//Save the prop for this key frame with his value and easing function
props[prop] = {
value: value,
easing: easings[easing]
};
}
frame.props = props;
}
};
/**
* Parses a value extracting numeric values and generating a format string
* for later interpolation of the new values in old string.
*
* @param val The CSS value to be parsed.
* @return Something like ["rgba(?%,?%, ?%,?)", 100, 50, 0, .7]
* where the first element is the format string later used
* and all following elements are the numeric value.
*/
var _parseProp = function(val) {
var numbers = [];
//One special case, where floats don't work.
//We replace all occurences of rgba colors
//which don't use percentage notation with the percentage notation.
rxRGBAIntegerColor.lastIndex = 0;
val = val.replace(rxRGBAIntegerColor, function(rgba) {
return rgba.replace(rxNumericValue, function(n) {
return n / 255 * 100 + '%';
});
});
//Handle prefixing of "gradient" values.
//For now only the prefixed value will be set. Unprefixed isn't supported anyway.
if(theDashedCSSPrefix) {
rxGradient.lastIndex = 0;
val = val.replace(rxGradient, function(s) {
return theDashedCSSPrefix + s;
});
}
//Now parse ANY number inside this string and create a format string.
val = val.replace(rxNumericValue, function(n) {
numbers.push(+n);
return '{?}';
});
//Add the formatstring as first value.
numbers.unshift(val);
return numbers;
};
/**
* Fills the key frames with missing left and right hand properties.
* If key frame 1 has property X and key frame 2 is missing X,
* but key frame 3 has X again, then we need to assign X to key frame 2 too.
*
* @param sk A skrollable.
*/
var _fillProps = function(sk) {
//Will collect the properties key frame by key frame
var propList = {};
var keyFrameIndex;
var keyFramesLength;
//Iterate over all key frames from left to right
keyFrameIndex = 0;
keyFramesLength = sk.keyFrames.length;
for(; keyFrameIndex < keyFramesLength; keyFrameIndex++) {
_fillPropForFrame(sk.keyFrames[keyFrameIndex], propList);
}
//Now do the same from right to fill the last gaps
propList = {};
//Iterate over all key frames from right to left
keyFrameIndex = sk.keyFrames.length - 1;
for(; keyFrameIndex >= 0; keyFrameIndex--) {
_fillPropForFrame(sk.keyFrames[keyFrameIndex], propList);
}
};
var _fillPropForFrame = function(frame, propList) {
var key;
//For each key frame iterate over all right hand properties and assign them,
//but only if the current key frame doesn't have the property by itself
for(key in propList) {
//The current frame misses this property, so assign it.
if(!hasProp.call(frame.props, key)) {
frame.props[key] = propList[key];
}
}
//Iterate over all props of the current frame and collect them
for(key in frame.props) {
propList[key] = frame.props[key];
}
};
/**
* Calculates the new values for two given values array.
*/
var _calcInterpolation = function(val1, val2, progress) {
var valueIndex;
var val1Length = val1.length;
//They both need to have the same length
if(val1Length !== val2.length) {
throw 'Can\'t interpolate between "' + val1[0] + '" and "' + val2[0] + '"';
}
//Add the format string as first element.
var interpolated = [val1[0]];
valueIndex = 1;
for(; valueIndex < val1Length; valueIndex++) {
//That's the line where the two numbers are actually interpolated.
interpolated[valueIndex] = val1[valueIndex] + ((val2[valueIndex] - val1[valueIndex]) * progress);
}
return interpolated;
};
/**
* Interpolates the numeric values into the format string.
*/
var _interpolateString = function(val) {
var valueIndex = 1;
rxInterpolateString.lastIndex = 0;
return val[0].replace(rxInterpolateString, function() {
return val[valueIndex++];
});
};
/**
* Resets the class and style attribute to what it was before skrollr manipulated the element.
* Also remembers the values it had before reseting, in order to undo the reset.
*/
var _reset = function(elements, undo) {
//We accept a single element or an array of elements.
elements = [].concat(elements);
var skrollable;
var element;
var elementsIndex = 0;
var elementsLength = elements.length;
for(; elementsIndex < elementsLength; elementsIndex++) {
element = elements[elementsIndex];
skrollable = _skrollables[element[SKROLLABLE_ID_DOM_PROPERTY]];
//Couldn't find the skrollable for this DOM element.
if(!skrollable) {
continue;
}
if(undo) {
//Reset class and style to the "dirty" (set by skrollr) values.
element.style.cssText = skrollable.dirtyStyleAttr;
_updateClass(element, skrollable.dirtyClassAttr);
} else {
//Remember the "dirty" (set by skrollr) class and style.
skrollable.dirtyStyleAttr = element.style.cssText;
skrollable.dirtyClassAttr = _getClass(element);
//Reset class and style to what it originally was.
element.style.cssText = skrollable.styleAttr;
_updateClass(element, skrollable.classAttr);
}
}
};
/**
* Detects support for 3d transforms by applying it to the skrollr-body.
*/
var _detect3DTransforms = function() {
_translateZ = 'translateZ(0)';
skrollr.setStyle(_skrollrBody, 'transform', _translateZ);
var computedStyle = getStyle(_skrollrBody);
var computedTransform = computedStyle.getPropertyValue('transform');
var computedTransformWithPrefix = computedStyle.getPropertyValue(theDashedCSSPrefix + 'transform');
var has3D = (computedTransform && computedTransform !== 'none') || (computedTransformWithPrefix && computedTransformWithPrefix !== 'none');
if(!has3D) {
_translateZ = '';
}
};
/**
* Set the CSS property on the given element. Sets prefixed properties as well.
*/
skrollr.setStyle = function(el, prop, val) {
var style = el.style;
//Camel case.
prop = prop.replace(rxCamelCase, rxCamelCaseFn).replace('-', '');
//Make sure z-index gets a <integer>.
//This is the only <integer> case we need to handle.
if(prop === 'zIndex') {
if(isNaN(val)) {
//If it's not a number, don't touch it.
//It could for example be "auto" (#351).
style[prop] = val;
} else {
//Floor the number.
style[prop] = '' + (val | 0);
}
}
//#64: "float" can't be set across browsers. Needs to use "cssFloat" for all except IE.
else if(prop === 'float') {
style.styleFloat = style.cssFloat = val;
}
else {
//Need try-catch for old IE.
try {
//Set prefixed property if there's a prefix.
if(theCSSPrefix) {
style[theCSSPrefix + prop.slice(0,1).toUpperCase() + prop.slice(1)] = val;
}
//Set unprefixed.
style[prop] = val;
} catch(ignore) {}
}
};
/**
* Cross browser event handling.
*/
var _addEvent = skrollr.addEvent = function(element, names, callback) {
var intermediate = function(e) {
//Normalize IE event stuff.
e = e || window.event;
if(!e.target) {
e.target = e.srcElement;
}
if(!e.preventDefault) {
e.preventDefault = function() {
e.returnValue = false;
e.defaultPrevented = true;
};
}
return callback.call(this, e);
};
names = names.split(' ');
var name;
var nameCounter = 0;
var namesLength = names.length;
for(; nameCounter < namesLength; nameCounter++) {
name = names[nameCounter];
if(element.addEventListener) {
element.addEventListener(name, callback, false);
} else {
element.attachEvent('on' + name, intermediate);
}
//Remember the events to be able to flush them later.
_registeredEvents.push({
element: element,
name: name,
listener: callback
});
}
};
var _removeEvent = skrollr.removeEvent = function(element, names, callback) {
names = names.split(' ');
var nameCounter = 0;
var namesLength = names.length;
for(; nameCounter < namesLength; nameCounter++) {
if(element.removeEventListener) {
element.removeEventListener(names[nameCounter], callback, false);
} else {
element.detachEvent('on' + names[nameCounter], callback);
}
}
};
var _removeAllEvents = function() {
var eventData;
var eventCounter = 0;
var eventsLength = _registeredEvents.length;
for(; eventCounter < eventsLength; eventCounter++) {
eventData = _registeredEvents[eventCounter];
_removeEvent(eventData.element, eventData.name, eventData.listener);
}
_registeredEvents = [];
};
var _emitEvent = function(element, name, direction) {
if(_listeners.keyframe) {
_listeners.keyframe.call(_instance, element, name, direction);
}
};
var _reflow = function() {
var pos = _instance.getScrollTop();
//Will be recalculated by _updateDependentKeyFrames.
_maxKeyFrame = 0;
if(_forceHeight && !_isMobile) {
//un-"force" the height to not mess with the calculations in _updateDependentKeyFrames (#216).
body.style.height = '';
}
_updateDependentKeyFrames();
if(_forceHeight && !_isMobile) {
//"force" the height.
body.style.height = (_maxKeyFrame + documentElement.clientHeight) + 'px';
}
//The scroll offset may now be larger than needed (on desktop the browser/os prevents scrolling farther than the bottom).
if(_isMobile) {
_instance.setScrollTop(Math.min(_instance.getScrollTop(), _maxKeyFrame));
} else {
//Remember and reset the scroll pos (#217).
_instance.setScrollTop(pos, true);
}
_forceRender = true;
};
/*
* Returns a copy of the constants object where all functions and strings have been evaluated.
*/
var _processConstants = function() {
var viewportHeight = documentElement.clientHeight;
var copy = {};
var prop;
var value;
for(prop in _constants) {
value = _constants[prop];
if(typeof value === 'function') {
value = value.call(_instance);
}
//Percentage offset.
else if((/p$/).test(value)) {
value = (value.slice(0, -1) / 100) * viewportHeight;
}
copy[prop] = value;
}
return copy;
};
/*
* Returns the height of the document.
*/
var _getDocumentHeight = function() {
var skrollrBodyHeight = 0;
var bodyHeight;
if(_skrollrBody) {
skrollrBodyHeight = Math.max(_skrollrBody.offsetHeight, _skrollrBody.scrollHeight);
}
bodyHeight = Math.max(skrollrBodyHeight, body.scrollHeight, body.offsetHeight, documentElement.scrollHeight, documentElement.offsetHeight, documentElement.clientHeight);
return bodyHeight - documentElement.clientHeight;
};
/**
* Returns a string of space separated classnames for the current element.
* Works with SVG as well.
*/
var _getClass = function(element) {
var prop = 'className';
//SVG support by using className.baseVal instead of just className.
if(window.SVGElement && element instanceof window.SVGElement) {
element = element[prop];
prop = 'baseVal';
}
return element[prop];
};
/**
* Adds and removes a CSS classes.
* Works with SVG as well.
* add and remove are arrays of strings,
* or if remove is ommited add is a string and overwrites all classes.
*/
var _updateClass = function(element, add, remove) {
var prop = 'className';
//SVG support by using className.baseVal instead of just className.
if(window.SVGElement && element instanceof window.SVGElement) {
element = element[prop];
prop = 'baseVal';
}
//When remove is ommited, we want to overwrite/set the classes.
if(remove === undefined) {
element[prop] = add;
return;
}
//Cache current classes. We will work on a string before passing back to DOM.
var val = element[prop];
//All classes to be removed.
var classRemoveIndex = 0;
var removeLength = remove.length;
for(; classRemoveIndex < removeLength; classRemoveIndex++) {
val = _untrim(val).replace(_untrim(remove[classRemoveIndex]), ' ');
}
val = _trim(val);
//All classes to be added.
var classAddIndex = 0;
var addLength = add.length;
for(; classAddIndex < addLength; classAddIndex++) {
//Only add if el not already has class.
if(_untrim(val).indexOf(_untrim(add[classAddIndex])) === -1) {
val += ' ' + add[classAddIndex];
}
}
element[prop] = _trim(val);
};
var _trim = function(a) {
return a.replace(rxTrim, '');
};
/**
* Adds a space before and after the string.
*/
var _untrim = function(a) {
return ' ' + a + ' ';
};
var _now = Date.now || function() {
return +new Date();
};
var _keyFrameComparator = function(a, b) {
return a.frame - b.frame;
};
/*
* Private variables.
*/
//Singleton
var _instance;
/*
A list of all elements which should be animated associated with their the metadata.
Exmaple skrollable with two key frames animating from 100px width to 20px:
skrollable = {
element: <the DOM element>,
styleAttr: <style attribute of the element before skrollr>,
classAttr: <class attribute of the element before skrollr>,
keyFrames: [
{
frame: 100,
props: {
width: {
value: ['{?}px', 100],
easing: <reference to easing function>
}
},
mode: "absolute"
},
{
frame: 200,
props: {
width: {
value: ['{?}px', 20],
easing: <reference to easing function>
}
},
mode: "absolute"
}
]
};
*/
var _skrollables;
var _skrollrBody;
var _listeners;
var _forceHeight;
var _maxKeyFrame = 0;
var _scale = 1;
var _constants;
var _mobileDeceleration;
//Current direction (up/down).
var _direction = 'down';
//The last top offset value. Needed to determine direction.
var _lastTop = -1;
//The last time we called the render method (doesn't mean we rendered!).
var _lastRenderCall = _now();
//For detecting if it actually resized (#271).
var _lastViewportWidth = 0;
var _lastViewportHeight = 0;
var _requestReflow = false;
//Will contain data about a running scrollbar animation, if any.
var _scrollAnimation;
var _smoothScrollingEnabled;
var _smoothScrollingDuration;
//Will contain settins for smooth scrolling if enabled.
var _smoothScrolling;
//Can be set by any operation/event to force rendering even if the scrollbar didn't move.
var _forceRender;
//Each skrollable gets an unique ID incremented for each skrollable.
//The ID is the index in the _skrollables array.
var _skrollableIdCounter = 0;
var _edgeStrategy;
//Mobile specific vars. Will be stripped by UglifyJS when not in use.
var _isMobile = false;
//The virtual scroll offset when using mobile scrolling.
var _mobileOffset = 0;
//If the browser supports 3d transforms, this will be filled with 'translateZ(0)' (empty string otherwise).
var _translateZ;
//Will contain data about registered events by skrollr.
var _registeredEvents = [];
//Animation frame id returned by RequestAnimationFrame (or timeout when RAF is not supported).
var _animFrame;
//Expose skrollr as either a global variable or a require.js module.
if(typeof define === 'function' && define.amd) {
define([], function () {
return skrollr;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = skrollr;
} else {
window.skrollr = skrollr;
}
}(window, document));
jQuery(document).ready(function(){
var s = skrollr.init({
edgeStrategy: 'set',
easing: {
WTF: Math.random,
inverted: function(p) {
return 1-p;
}
}
});
}); | mit |
mingchia-andy-liu/chrome-extension-nba | src/app/containers/Modal/reducers.js | 521 | import types from './types'
import modalType from './modal-types'
const initState = {
isOpen: false,
type: {
modalType: modalType.DEFAULT,
payload: {},
},
}
export default (state = initState, action) => {
switch (action.type) {
case types.TOGGLE_MODAL: {
return {
isOpen: !state.isOpen,
type: {
modalType: action.payload.modalType,
payload: {
...action.payload.custom,
},
},
}
}
default:
return state
}
}
| mit |
codeandcats/eggs-benny | src/commands/download.ts | 11982 | import * as path from 'path';
import { deleteFile, ensureDirectoryExists, getFileSize } from '../utils/files';
import * as commander from 'commander';
import { EggHead, Technology, Course, Lesson, LessonWithFileSize, CourseWithLessons, ProgressCallbacks } from '../egghead';
import * as chalk from 'chalk';
import { authenticate, displayCredentialsNotSet, createSpinner, getCourses, handleErrorAndExit, displayDownloadPathNotSet } from '../common';
import { Config } from '../config';
import * as linq from 'linq';
import * as minimatch from 'minimatch';
import { getFileSize as getRemoteFileSize } from '../utils/http';
import Promise = require('bluebird');
const { terminal } = require('terminal-kit');
import formatFileSize = require('filesize');
const CircularJson = require('circular-json');
import pad = require('pad');
import sanitizeFileName = require('sanitize-filename');
const NO_OP = () => {};
const NO_CONCURRENCY = { concurrency: 1 };
commander
.command('download')
.option('-t, --technology <technology-name>')
.option('-c, --course <course-name>')
.option('-o, --overwrite')
.option('-n, --no-verify')
.description('Downloads course(s)')
.action((cliOptions: CliOptions) => {
const options = parseOptions(cliOptions);
handleDownloadCommand(options);
});
export class TechnologyNotFound extends Error {
constructor(filterName: string) {
super(`No technology section found named "${filterName}"`);
}
}
export class CourseNotFound extends Error {
constructor(filterName: string) {
super(`No course found named "${filterName}"`);
}
}
export class FilterNotSpecified extends Error {
constructor() {
super('A technology or course name must be specified');
}
}
function handleDownloadCommand(options: ParsedOptions): PromiseLike<void> {
return Config.load().then(config => {
const filter = options.filter;
if (!config.data.email || !config.data.password) {
return displayCredentialsNotSet();
}
if (!config.data.downloadPath) {
return displayDownloadPathNotSet();
}
const egghead = new EggHead();
return authenticate(egghead, config.data.email, config.data.password)
.then(() => getCourses(egghead))
.then(technologies => {
if (!filter) {
return technologies;
}
technologies = filterTechnologiesAndCourses(filter, technologies);
return checkFoundMatchingCourses(filter, technologies);
})
.then(technologies => getLessons(egghead, technologies))
.then((technologies: Technology<CourseWithLessons<LessonWithFileSize>>[]) => {
displayMatchingCourses(technologies);
const confirm = (options.noVerify ? Promise.resolve(true) : confirmDownloadCourses(technologies));
return confirm.then(confirmed => {
if (!confirmed) {
return process.exit(0);
}
return downloadTechnologies(egghead, technologies, config.data.downloadPath);
});
})
.then(() => {
console.log(chalk.green('✔ Downloads Finished Successfully'));
console.log();
})
.then(NO_OP);
})
.then(() => process.exit(0))
.catch(handleErrorAndExit);
}
interface CliOptions {
technology?: string;
course?: string;
overwrite: boolean;
noVerify: boolean;
}
interface ParsedOptions {
filter: TechnologyFilter | CourseFilter | null;
overwrite: boolean;
noVerify: boolean;
}
function parseOptions(options: CliOptions): ParsedOptions {
const result: ParsedOptions = {
filter:
options.technology ? { type: 'technology', name: options.technology } :
options.course ? { type: 'course', name: options.course } :
null,
overwrite: options.overwrite,
noVerify: options.noVerify
};
return result;
}
interface TechnologyFilter {
type: 'technology',
name: string;
}
interface CourseFilter {
type: 'course',
name: string;
}
function filterTechnologiesAndCourses<TCourse extends Course>(filter: TechnologyFilter | CourseFilter, technologies: Technology<TCourse>[]) {
if (filter.type === 'technology') {
return linq
.from(technologies)
.where(technology => technology.name.toLowerCase().indexOf(filter.name.toLowerCase()) > -1)
.toArray();
} else {
return linq
.from(technologies)
.select(technology => {
return {
...technology,
courses: filterCourses(filter, technology.courses)
} as Technology<TCourse>;
})
.toArray();
}
}
function filterCourses<TCourse extends Course>(filter: CourseFilter, courses: TCourse[]): TCourse[] {
return linq
.from(courses)
.where(course => course.name.toLowerCase().indexOf(filter.name.toLowerCase()) > -1)
.toArray();
}
function checkFoundMatchingCourses<TCourse extends Course>(filter: TechnologyFilter | CourseFilter, technologies: Technology<TCourse>[]): Technology<TCourse>[] {
if (technologies.length == 0) {
if (filter.type === 'technology') {
throw new TechnologyNotFound(filter.name);
} else {
throw new CourseNotFound(filter.name);
}
}
return technologies;
}
function selectCourses<TCourse extends Course>(technologies: Technology<TCourse>[]) {
return linq
.from(technologies)
.selectMany(technology => technology.courses)
.toArray();
}
function countLessons(technologies: Technology<Course>[]): number {
return linq
.from(technologies)
.sum(technology => linq
.from(technology.courses)
.sum(course => course.lessonCount)
);
}
function displayMatchingCourses(technologies: Technology<CourseWithLessons<LessonWithFileSize>>[]) {
const courseCount = selectCourses(technologies).length;
console.log(`Found ${courseCount} matching courses`);
console.log();
let totalDownloadSize = 0;
for (const technology of technologies) {
const technologyFileSize = linq
.from(technology.courses)
.selectMany(course => course.lessons)
.sum(lesson => lesson.fileSize);
totalDownloadSize += technologyFileSize;
console.log(`${technology.name}` + chalk.yellow(` (${technology.courses.length} courses, ${formatFileSize(technologyFileSize)})`));
console.log();
for (const course of technology.courses) {
const courseFileSize = linq
.from(course.lessons)
.sum(lesson => lesson.fileSize);
console.log(` • ${course.name}` + chalk.yellow(` (${course.lessonCount} lessons, ${formatFileSize(courseFileSize)})`));
}
}
console.log();
console.log(`Total Download Size: ${chalk.yellow(formatFileSize(totalDownloadSize))}`);
}
function confirmDownloadCourses(technologies: Technology<Course>[]): PromiseLike<boolean> {
return new Promise((resolve, reject) => {
const courseCount = selectCourses(technologies).length;
console.log();
console.log('Download ' + (courseCount == 1 ? 'this course' : `these ${courseCount} courses? [y|n]`));
console.log();
terminal.yesOrNo({ yes: ['y', 'Y'], no: ['n', 'N'] }, (err: any, result: any) => {
return err ? reject(err) : resolve(result);
});
});
}
function getLessons<TCourse extends Course>(egghead: EggHead, technologies: Technology<TCourse>[]): PromiseLike<Technology<CourseWithLessons<LessonWithFileSize>>[]> {
const lessonCount = countLessons(technologies);
let checkedLessons = 0;
const spinner = createSpinner(`Retrieving lesson information (0/${lessonCount})...`);
const MAX_CONCURRENT_FILE_SIZE_REQUESTS = 10;
return Promise.map(technologies, technology => {
return Promise.map(technology.courses, course => {
return getCourseLessons(egghead, course).then(course => {
return Promise
.map(course.lessons, lesson => {
return getLessonFileSize(lesson).then(lesson => {
checkedLessons++;
spinner.text = `Retrieving lesson information (${checkedLessons}/${lessonCount})...`;
return lesson;
});
}, { concurrency: MAX_CONCURRENT_FILE_SIZE_REQUESTS })
.then(lessonsWithFileSizes => {
const result: CourseWithLessons<LessonWithFileSize> = {
...course,
lessons: lessonsWithFileSizes
};
return result;
});
});
}, NO_CONCURRENCY).then(courses => {
return <Technology<CourseWithLessons<LessonWithFileSize>>>{
...technology,
courses
};
});
}, NO_CONCURRENCY).then(result => {
spinner.succeed(`Retrieved lesson information (${checkedLessons}/${lessonCount})`);
console.log();
return result;
}, err => {
spinner.fail();
throw err;
});
}
function getCourseLessons(egghead: EggHead, course: Course): PromiseLike<CourseWithLessons<Lesson>> {
return egghead
.getCourseLessons(course.code)
.then(lessons => Promise.map(lessons, getLessonFileSize, NO_CONCURRENCY))
.then((lessons: LessonWithFileSize[]) => {
const result = {
...course as any,
lessons
};
return result;
});
}
function getLessonFileSize(lesson: Lesson): PromiseLike<LessonWithFileSize> {
return getRemoteFileSize(lesson.url).then(fileSize => {
return <LessonWithFileSize>{
...lesson,
fileSize
};
});
}
function downloadTechnologies(egghead: EggHead, technologies: Technology<CourseWithLessons<LessonWithFileSize>>[], downloadPath: string): Promise<void> {
const lessons = linq
.from(technologies)
.selectMany(technology => technology.courses.map(course => ({ technology, course })))
.selectMany(item => item.course.lessons.map(lesson => ({ ...item, lesson })))
.orderBy(item => item.technology.name)
.thenBy(item => item.course.name)
.thenBy(item => item.lesson.lessonNumber)
.toArray();
return Promise
.mapSeries(lessons, ({ technology, course, lesson }, index) => {
return downloadLesson(egghead, technology, course, lesson, downloadPath, index, lessons.length);
})
.then(NO_OP);
}
function checkFileAlreadyDownloaded(fileName: string, expectedFileSize: number): PromiseLike<boolean> {
return getFileSize(fileName).then(fileSize => {
if (expectedFileSize != fileSize) {
return deleteFile(fileName).then(() => false);
} else {
return true;
}
}, () => {
return false;
});
}
function downloadLesson(
egghead: EggHead,
technology: Technology<Course>,
course: Course,
lesson: LessonWithFileSize,
downloadPath: string,
downloadIndex: number,
downloadCount: number): PromiseLike<void> {
const technologyPath = getTechnologyPath(downloadPath, technology);
const coursePath = getCoursePath(technologyPath, course);
const lessonPath = getLessonFileName(coursePath, lesson);
return ensureDirectoryExists(coursePath).then(() => {
const lessonFileName = getLessonFileName(coursePath, lesson);
return checkFileAlreadyDownloaded(lessonFileName, lesson.fileSize).then(alreadyDownloaded => {
if (alreadyDownloaded) {
return;
}
const UPDATE_INTERVAL = 250;
let downloaded = 0;
let total = 0;
function getStatusText(verb: string) {
return `${verb} ${downloadIndex + 1}/${downloadCount}: ${lesson.name} (${formatFileSize(downloaded)}/${formatFileSize(lesson.fileSize)})`
}
const spinner = createSpinner(getStatusText('Downloading'));
const interval = setInterval(() => {
spinner.text = getStatusText('Downloading');
}, UPDATE_INTERVAL);
const progressOptions: ProgressCallbacks = {
update: (newDownloaded: number, newTotal: number) => {
downloaded = newDownloaded;
total = newTotal;
}
};
return egghead
.downloadFile(lesson.url, lessonFileName, progressOptions)
.then(() => {
clearInterval(interval);
spinner.succeed(getStatusText('Downloaded'));
console.log();
}, err => {
clearInterval(interval);
spinner.fail(getStatusText('Failed'));
console.log();
throw err;
});
});
});
}
function getTechnologyPath(downloadPath: string, technology: Technology<Course>) {
return path.join(downloadPath, technology.name);
}
function getCoursePath(technologyPath: string, course: Course) {
return path.join(technologyPath, course.name);
}
function getLessonFileName(coursePath: string, lesson: Lesson) {
const lessonNumber = pad(2, lesson.lessonNumber.toString(), '0');
const fileTitle = sanitizeFileName(`${lessonNumber} ${lesson.name}`, { replacement: ' ' }).replace(/\s+/g, ' ');
return path.join(coursePath, `${fileTitle}.mp4`);
}
| mit |
nikk-dzhurov/JS | HW2/Problem 9. Point in Circle and outside Rectangle.js | 831 | //Problem 9. Point in Circle and outside Rectangle
//Write an expression that checks for given point P(x, y) if it is within the circle
//K( (1,1), 3) and out of the rectangle R(top=1, left=-1, width=6, height=2).
//(x[i]*x[i] + y[i]*y[i]) <= radius*radius
var x = [1,2.5,0,2.5,2,4,2.5,2,1,-100];
var y = [2,2,1,1,0,0,1.5,1.5,2.5,-100];
var top = 1;
var left = -1;
var width=6;
var height=2;
var radius=3;
console.log('inside K & outside of R ?');
for (var i = 0; i < 10; i+=1) {
insideCircle = ((x[i]-1)*(x[i]-1) + (y[i]-1)*(y[i]-1)) <= radius*radius;
insideRectangle = x[i]<=left+width && x[i]>=left && y[i]<=top && y[i]>=top-height;
if(insideCircle==true && insideRectangle!=true){
console.log('x= ' + x[i] + ', y= '+ y[i] + ', Result: yes');
}
else {
console.log('x= ' + x[i] + ', y= '+ y[i] + ', Result: no');
}
} | mit |
OhMedrano/vanilla_guitar | src/Components/GuitarBody.js | 882 | import '../../css/style.scss';
import MakeElement from '../Tools/MakeElement.js';
let newElement = new MakeElement;
function GuitarBody(){
console.log('ayy');
return true
}
GuitarBody.prototype = {
homeBody : function() {
let body = newElement.createEle('div','home',[12,12,12,12],['guitarBodies','guitarContainers']);
body.innerHTML = '<div>This is home </div>';
return body
},
scaleBody : function(){
let body = newElement.createEle('div','visscale',[12,12,12,12],['guitarBodies', 'guitarContainers']);
body.innerHTML = `<div> ayyyyyyy</div>`;
console.log('from scaleBody ');
return body
},
harmBody : function() {
let body = newElement.createEle('div','visharm',[12,12,12,12],['guitarBodies', 'guitarContainers']);
body.innerHTML = `<div> supppp </div>`;
return body;
}
}
export default GuitarBody; | mit |
activecollab/jobsqueue | src/Queue/Queue.php | 524 | <?php
/*
* This file is part of the Active Collab Jobs Queue.
*
* (c) A51 doo <info@activecollab.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
declare(strict_types=1);
namespace ActiveCollab\JobsQueue\Queue;
use Psr\Log\LoggerInterface;
abstract class Queue implements QueueInterface
{
protected ?LoggerInterface $logger;
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger;
}
}
| mit |
Tr0nYx/AlphaTraderApiBundle | src/Api/Methods/SecurityOrderController.php | 4440 | <?php
namespace Alphatrader\ApiBundle\Api\Methods;
use Alphatrader\ApiBundle\Api\ApiClient;
/**
* Class SecurityOrderController
*
* @package Alphatrader\ApiBundle\Api\Methods
*/
class SecurityOrderController extends ApiClient
{
/**
* @param $secIdent
* @return \Alphatrader\ApiBundle\Model\Error|\Alphatrader\ApiBundle\Model\OrderBook
*/
public function getOrderbook($secIdent)
{
$data = $this->get('orderbook/'.$secIdent);
return $this->parseResponse($data, 'Alphatrader\ApiBundle\Model\OrderBook');
}
/**
* @param $secIdent
* @param $secAccId
* @return \Alphatrader\ApiBundle\Model\Error|\Alphatrader\ApiBundle\Model\SecurityOrder[]
*/
public function getOrderList($secIdent, $secAccId)
{
$data = $this->get('orderlist/'.$secIdent, ['securitiesAccountId' => $secAccId]);
return $this->parseResponse($data, 'ArrayCollection<Alphatrader\ApiBundle\Model\SecurityOrder>');
}
/**
* @param $secIdent
*
* @return \Alphatrader\ApiBundle\Model\SecurityOrder|\Alphatrader\ApiBundle\Model\Error
*/
public function getSecurityOrder($secIdent)
{
$data = $this->get('securityorders/'. $secIdent);
return $this->parseResponse($data, 'Alphatrader\ApiBundle\Model\SecurityOrder');
}
/**
* @param $secAccId
* @return \Alphatrader\ApiBundle\Model\Error|\Alphatrader\ApiBundle\Model\SecurityOrder[]
*/
public function getUnfilledOTCOrdersForSecuritiesAccount($secAccId)
{
$data = $this->get('securityorders/counterparty/'.$secAccId);
return $this->parseResponse($data, 'ArrayCollection<Alphatrader\ApiBundle\Model\SecurityOrder>');
}
/**
* @param $secAccId
* @return \Alphatrader\ApiBundle\Model\Error|\Alphatrader\ApiBundle\Model\SecurityOrder[]
*/
public function getUnfilledOTCOrdersBySecuritiesAccount($secAccId)
{
$data = $this->get('securityorders/counterparty/'.$secAccId);
return $this->parseResponse($data, 'ArrayCollection<Alphatrader\ApiBundle\Model\SecurityOrder>');
}
/**
* @param $secAccId
* @return \Alphatrader\ApiBundle\Model\Error|\Alphatrader\ApiBundle\Model\Message
*/
public function deleteAllOrders($secAccId)
{
$data = $this->delete('securityorders/', ['owner' => $secAccId]);
return $this->parseResponse($data, 'Alphatrader\ApiBundle\Model\Message');
}
/**
* @param $orderId
* @return \Alphatrader\ApiBundle\Model\Error|\Alphatrader\ApiBundle\Model\Message
*/
public function deleteOrder($orderId)
{
$data = $this->delete('securityorders/'.$orderId);
return $this->parseResponse($data, 'Alphatrader\ApiBundle\Model\Message');
}
/**
* @param $owner
* @param $secIdent
* @param $action
* @param $type
* @param $price
* @param $numberOfShares
* @param $counterparty
*
* @return \Alphatrader\ApiBundle\Model\SecurityOrder|\Alphatrader\ApiBundle\Model\Error
*/
public function createSecurityOrder($owner, $secIdent, $action, $type, $price, $numberOfShares, $counterparty)
{
$data = $this->post(
'securityorders/',
[
'owner' => $owner,
'securityIdentifier' => $secIdent,
'action' => $action,
'type' => $type,
'price' => $price,
'numberOfShares' => $numberOfShares,
'counterparty' => $counterparty
]
);
return $this->parseResponse($data, 'Alphatrader\ApiBundle\Model\SecurityOrder');
}
/**
* @param $owner
* @param $secIdent
* @param $numberOfShares
* @param $price
*
* @return \Alphatrader\ApiBundle\Model\OrderCheck|\Alphatrader\ApiBundle\Model\Error
*/
public function checkSecurityOrder($owner, $secIdent, $numberOfShares, $price)
{
$data = $this->get(
'securityorders/check/',
[
'owner' => $owner,
'securityIdentifier' => $secIdent,
'price' => $price,
'numberOfShares' => $numberOfShares
]
);
return $this->parseResponse($data, 'Alphatrader\ApiBundle\Model\OrderCheck');
}
}
| mit |
TeamYAGNI/LibrarySystem | LibrarySystem/LibrarySystem.Framework/Exceptions/UserAuthException.cs | 1400 | // <copyright file = "UserAuthException.cs" company="YAGNI">
// All rights reserved.
// </copyright>
// <summary>Holds implementation of UserAuthException class.</summary>
using System;
namespace LibrarySystem.Framework.Exceptions
{
/// <summary>
/// Represent a <see cref="UserAuthException"/> class, inheritant of <see cref="ApplicationException"/> class.
/// </summary>
public class UserAuthException : ApplicationException
{
/// <summary>
/// Initializes a new instance of the <see cref="UserAuthException"/> class.
/// </summary>
/// <param name="message">A message that describes the error.</param>
public UserAuthException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UserAuthException"/> class.
/// </summary>
/// <param name="message">A message that describes the error.</param>
/// <param name="innerException">
/// The exception that is the cause of the current exception. If the innerException parameter is not a null reference,
/// the current exception is raised in a catch block that handles the inner exception.
/// </param>
public UserAuthException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | mit |
DrPandemic/aigar.io | game/src/test/scala/io/aigar/game/AIStateSpec.scala | 3899 | import io.aigar.game._
import scala.math._
import org.scalatest._
import com.github.jpbetz.subspace._
class AIStateSpec extends FlatSpec with Matchers {
"NullState" should "return the same instance as the cell's target" in {
val player = new Player(0, Vector2(0f, 0f))
val cell = player.cells.head
cell.target = Vector2(10f, 10f)
cell.aiState = new NullState(cell)
val target = cell.aiState.update(1f, new Grid(0, 0))
target should be theSameInstanceAs(cell.target)
}
it should "switch to a wandering state after inactivity for too long" in {
val player = new Player(0, Vector2(0f, 0f))
player.active = true
val cell = player.cells.head
cell.aiState = new NullState(cell)
cell.aiState.update(NullState.MaxInactivitySeconds + 1e-2f, new Grid(0, 0))
cell.aiState shouldBe a [WanderingState]
}
it should "not switch to a wandering state after activity" in {
val player = new Player(0, Vector2(0f, 0f))
val cell = player.cells.head
cell.aiState = new NullState(cell)
cell.aiState.update(NullState.MaxInactivitySeconds - 1e-2f, new Grid(0, 0))
cell.aiState.onPlayerActivity
cell.aiState.update(NullState.MaxInactivitySeconds - 1e-2f, new Grid(0, 0))
cell.aiState shouldBe a [NullState]
}
"SeekingState" should "keep the current cell's target on creation" in {
val player = new Player(0, Vector2(0f, 0f))
val cell = player.cells.head
cell.target = Vector2(100f, 100f)
cell.aiState = new SeekingState(cell)
val target = cell.aiState.update(1f, new Grid(0, 0))
target should be theSameInstanceAs(cell.target)
}
it should "change state to SleepingState when it reaches its target" in {
val player = new Player(0, Vector2(10f, 10f))
val cell = player.cells.head
cell.target = Vector2(10f, 10f)
cell.aiState = new SeekingState(cell)
cell.aiState.update(1f, new Grid(0, 0))
cell.aiState shouldBe a [SleepingState]
}
it should "change state to SleepingState after a certain delay" in {
val player = new Player(0, Vector2(0f, 0f))
val cell = player.cells.head
val targetFar = Vector2(100000f, 100000f)
cell.target = targetFar
cell.aiState = new SeekingState(cell)
val target = cell.aiState.update(WanderingState.NewTargetDelay + 1e-2f, new Grid(0, 0))
cell.position.distanceTo(targetFar) should be > 100f // make sure that we really changed because of time (not position)
cell.aiState shouldBe a [SleepingState]
}
it should "change to null state on player activity" in {
val player = new Player(0, Vector2(5f, 5f))
player.active = false
val cell = player.cells.head
cell.aiState = new SeekingState(cell)
cell.aiState.onPlayerActivity
cell.aiState shouldBe a [NullState]
}
"SleepingBehavior" should "returns the cells's position as the new target" in {
val player = new Player(0, Vector2(0f, 0f))
val cell = player.cells.head
cell.target = Vector2(100f, 100f)
cell.aiState = new SleepingState(cell)
val target = cell.aiState.update(1f, new Grid(0, 0))
target should be theSameInstanceAs(cell.position)
}
it should "change cell's state to SeekingState after a certain delay" in {
val player = new Player(0, Vector2(0f, 0f))
val cell = player.cells.head
cell.target = Vector2(100f, 100f)
cell.aiState = new SleepingState(cell)
cell.aiState.update(WanderingState.SleepingDelay + 1e-2f, new Grid(0, 0))
cell.aiState shouldBe a [SeekingState]
}
it should "change the cell's target after a certain delay" in {
val player = new Player(0, Vector2(0f, 0f))
val cell = player.cells.head
cell.target = Vector2(100f, 100f)
cell.aiState = new SleepingState(cell)
val target = cell.aiState.update(WanderingState.SleepingDelay + 1e-2f, new Grid(0, 0))
target shouldNot be theSameInstanceAs(cell.target)
}
}
| mit |
nico01f/z-pec | ZimbraSoap/src/java/com/zimbra/soap/admin/message/ReloadMemcachedClientConfigRequest.java | 1111 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2011 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.soap.admin.message;
import javax.xml.bind.annotation.XmlRootElement;
import com.zimbra.common.soap.AdminConstants;
/**
* @zm-api-command-auth-required true
* @zm-api-command-admin-auth-required true
* @zm-api-command-description Reloads the memcached client configuration on this server. Memcached client layer
* is reinitialized accordingly. Call this command after updating the memcached server list, for example.
*/
@XmlRootElement(name=AdminConstants.E_RELOAD_MEMCACHED_CLIENT_CONFIG_REQUEST)
public class ReloadMemcachedClientConfigRequest {
}
| mit |
manland/draw-my-project | template_src/src/chartView/legendView/LegendViewCtrl.js | 302 | angular.module('app').controller('LegendViewCtrl', [
'$scope', 'LegendViewService', 'ConstantsService',
function($scope, legendViewService, constantsService) {
$scope.isAngularjsType = constantsService.getType() === 'angularjs';
$scope.isJavaType = constantsService.getType() === 'java';
}
]); | mit |
telemark/api.t-fk.no | test/testRecruitments.js | 858 | 'use strict';
var request = require('supertest');
var server = require('../server');
var config = require('../config');
request = request('http://localhost:' + config.SERVER_PORT);
describe('Server recruitments', function() {
before(function() {
server.start();
});
after(function() {
server.stop();
});
describe('GET /recruitments', function() {
it('respond with json', function(done) {
request
.get('/recruitments')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
});
});
describe('GET /recruitment/2402', function() {
it('respond with json', function(done) {
request
.get('/recruitment/2402')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
});
});
});
| mit |
fjogeleit/dynamic-form-bundle | Tests/Unit/Admin/Services/FormField/TemplateGuesserTest.php | 1726 | <?php
namespace DynamicFormBundle\Tests\Unit\Admin\Services\FormField;
use DynamicFormBundle\Admin\Services\FormField\TemplateGuesser;
use DynamicFormBundle\Entity\DynamicForm\FormField;
use DynamicFormBundle\Tests\Utility\TemplateGuesserTestCase;
/**
* @package DynamicFormBundle\Tests\Unit\Admin\Services\FormField
*/
class TemplateGuesserTest extends TemplateGuesserTestCase
{
public function testRenderFallbackTemplateIfNoSpecificTemplateExist()
{
$formField = new FormField();
$engine = $this->getTwigEnvironmentMock(
'@DynamicForm/sonata-admin/form/form_field.html.twig',
['formField' => $formField],
false
);
$templateGuesser = new TemplateGuesser($engine);
$templateGuesser->render($formField);
}
public function testRenderSpecificTemplateeIfExist()
{
$formField = new FormField();
$formField->setFormType('text');
$engine = $this->getTwigEnvironmentMock(
'@DynamicForm/sonata-admin/form/form_field/text.html.twig',
['formField' => $formField],
true
);
$templateGuesser = new TemplateGuesser($engine);
$templateGuesser->render($formField);
}
public function testRenderAdditionalParams()
{
$formField = new FormField();
$formField->setFormType('text');
$engine = $this->getTwigEnvironmentMock(
'@DynamicForm/sonata-admin/form/form_field/text.html.twig',
['formField' => $formField, 'param' => 'render'],
true
);
$templateGuesser = new TemplateGuesser($engine);
$templateGuesser->render($formField, ['param' => 'render']);
}
}
| mit |
kimpiljae/driving_zone_admin | ckeditor/plugins/youtubebootstrap/dialogs/youtubebootstrap.js | 1614 | /**
* @license Edit and use as you want
*
* Creato da TurboLab.it - 01/01/2014 (buon anno!)
* Modified by Eric van Eldik
*/
CKEDITOR.dialog.add( 'youtubebootstrapDialog', function( editor ) {
return {
title: 'Insert YouTube',
minWidth: 400,
minHeight: 75,
contents: [
{
id: 'tab-basic',
label: 'Basic Settings',
elements: [
{
type: 'text',
id: 'youtubeURL',
label: 'Paste the URL to include the youtube video'
}
]
}
],
onOk: function() {
var dialog = this;
var url=dialog.getValueOf( 'tab-basic', 'youtubeURL').trim();
var regExURL=/v=([^&$]+)/i;
var id_video=url.match(regExURL);
if(id_video==null || id_video=='' || id_video[0]=='' || id_video[1]=='')
{
alert("Given URL is not valid, it most look like this: a\n\n\t http://www.youtube.com/watch?v=abcdef \n\n");
return false;
}
var oTag = editor.document.createElement( 'iframe' );
var oP = editor.document.createElement( 'p' );
oP.setAttribute( 'class', 'embed-responsive embed-responsive-16by9');
oP.setHtml( '<iframe src="//www.youtube.com/embed/' + id_video[1] + '?rel=0" style="min-width:600px;min-height:400px"></iframe>' )
editor.insertElement( oP );
}
};
}); | mit |
kugao222/geneticAlgorithmInLua | ref/src/Chapter10/Brainy Aliens/CAlien.cpp | 9513 | #include "CAlien.h"
//the vertices making up its shape
const int NumAlienVerts = 19;
const SPoint Alien[NumAlienVerts] = { SPoint(1,3),
SPoint(4,1),
SPoint(4,-1),
SPoint(2,-4),
SPoint(1,-1),
SPoint(0,-2),
SPoint(-1,-1),
SPoint(-2,-4),
SPoint(-4,-1),
SPoint(-4,1),
SPoint(-1,3),
SPoint(-2,1),
SPoint(-1.5,0.5),
SPoint(-2,0),
SPoint(-2.5,1),
SPoint(2,1),
SPoint(1.5,0.5),
SPoint(2,0),
SPoint(2.5,1)};
//--------------------------------- ctor ---------------------------------
//
//------------------------------------------------------------------------
CAlien::CAlien(): m_dScale(CParams::dAlienScale),
m_vVelocity(SVector2D(0, 0)),
m_dMass(CParams::dAlienMass),
m_iAge(0),
m_bWarning(false)
{
//set its position
m_vPos = SVector2D(RandInt(0, CParams::WindowWidth), CParams::WindowHeight);
//create the vertex buffer
for (int i=0; i<NumAlienVerts; ++i)
{
m_vecAlienVB.push_back(Alien[i]);
}
//setup its bounding box
m_AlienBBox.left = m_vPos.x - (4*CParams::dAlienScale);
m_AlienBBox.right = m_vPos.x + (4*CParams::dAlienScale);
m_AlienBBox.top = m_vPos.y + (3*CParams::dAlienScale);
m_AlienBBox.bottom= m_vPos.y - (4*CParams::dAlienScale);
}
//------------------------------ Render ----------------------------------
void CAlien::Render(HDC &surface, HPEN &GreenPen, HPEN &RedPen)
{
//transform the vertices
WorldTransform();
//select in green pen
HPEN OldPen = (HPEN)SelectObject(surface, GreenPen);
//draw body
MoveToEx(surface, m_vecAlienVBTrans[0].x, m_vecAlienVBTrans[0].y, NULL);
for (int vtx=0; vtx<11; ++vtx)
{
LineTo(surface, m_vecAlienVBTrans[vtx].x, m_vecAlienVBTrans[vtx].y);
}
LineTo(surface, m_vecAlienVBTrans[0].x, m_vecAlienVBTrans[0].y);
//select in red pen
SelectObject(surface, RedPen);
//left eye
MoveToEx(surface, m_vecAlienVBTrans[11].x, m_vecAlienVBTrans[11].y, NULL);
for (vtx=12; vtx<15; ++vtx)
{
LineTo(surface, m_vecAlienVBTrans[vtx].x, m_vecAlienVBTrans[vtx].y);
}
//right eye
MoveToEx(surface, m_vecAlienVBTrans[15].x, m_vecAlienVBTrans[15].y, NULL);
for (vtx=16; vtx<19; ++vtx)
{
LineTo(surface, m_vecAlienVBTrans[vtx].x, m_vecAlienVBTrans[vtx].y);
}
//replace the old pen
SelectObject(surface, OldPen);
//display warning if a problem with the network
if (m_bWarning)
{
string s = "Wrong amount of inputs!";
TextOut(surface, 110, 200, s.c_str(), s.size());
}
}
//---------------------WorldTransform--------------------------------
//
// sets up the translation matrices for the ship and applies the
// world transform to the ships vertex buffer
//-------------------------------------------------------------------
void CAlien::WorldTransform()
{
//copy the original vertices into the buffer about to be transformed
m_vecAlienVBTrans = m_vecAlienVB;
//create a transformation matrix
C2DMatrix matTransform;
//scale
matTransform.Scale(m_dScale, m_dScale);
//and translate
matTransform.Translate(m_vPos.x, m_vPos.y);
//now transform the ships vertices
matTransform.TransformSPoints(m_vecAlienVBTrans);
}
//----------------------------- GetActionFromNetwork ---------------------
//
// this function updates the neural net and returns the action the
// network selects as its output
//------------------------------------------------------------------------
action_type CAlien::GetActionFromNetwork(const vector<CBullet> &bullets,
const SVector2D &GunPos)
{
//the inputs into the net
vector<double> NetInputs;
//This will hold the outputs from the neural net
static vector<double> outputs(0,3);
//add in the vector to the gun turret
int XComponentToTurret = GunPos.x - m_vPos.x;
int YComponentToTurret = GunPos.y - m_vPos.y;
NetInputs.push_back(XComponentToTurret);
NetInputs.push_back(YComponentToTurret);
//now any bullets
for (int blt=0; blt<bullets.size(); ++blt)
{
if (bullets[blt].Active())
{
double xComponent = bullets[blt].Pos().x - m_vPos.x;
double yComponent = bullets[blt].Pos().y - m_vPos.y;
NetInputs.push_back(xComponent);
NetInputs.push_back(yComponent);
}
else
{
//if a bullet is innactive just input the vector to
//the gun turret
NetInputs.push_back(XComponentToTurret);
NetInputs.push_back(YComponentToTurret);
}
}
//feed the inputs into the net and get the outputs
outputs = m_ItsBrain.Update(NetInputs);
//this is set if there is a problem with the update
if (outputs.size() == 0)
{
m_bWarning = true;
}
//determine which action is valid this frame. The highest valued
//output over 0.9. If none are over 0.9 then just drift with
//gravity
double BiggestSoFar = 0;
action_type action = drift;
for (int i=0; i<outputs.size(); ++i)
{
if( (outputs[i] > BiggestSoFar) && (outputs[i] > 0.9))
{
action = (action_type)i;
BiggestSoFar = outputs[i];
}
}
return action;
}
//----------------------------- Update -----------------------------------
//
// Checks for user keypresses and updates the aliens parameters accordingly
//------------------------------------------------------------------------
bool CAlien::Update(vector<CBullet> &bullets,const SVector2D &GunPos)
{
//update age
++m_iAge;
//get the next action from the neural network
int action = GetActionFromNetwork(bullets, GunPos);
//switch on the action
switch(action)
{
case thrust_left:
{
m_vVelocity.x -= CParams::dMaxThrustLateral/m_dMass;
}
break;
case thrust_right:
{
m_vVelocity.x += CParams::dMaxThrustLateral/m_dMass;
}
break;
case thrust_up:
{
m_vVelocity.y += CParams::dMaxThrustVertical/m_dMass;
}
break;
default:break;
}
//add in gravity
SVector2D gravity(0, CParams::dGravityPerTick);
m_vVelocity += gravity;
//clamp the velocity of the alien
Clamp(m_vVelocity.x, -CParams::dMaxVelocity, CParams::dMaxVelocity);
Clamp(m_vVelocity.y, -CParams::dMaxVelocity, CParams::dMaxVelocity);
//update the alien's position
m_vPos += m_vVelocity;
//wrap around window width
if (m_vPos.x < 0)
{
m_vPos.x = CParams::WindowWidth;
}
if (m_vPos.x > CParams::WindowWidth)
{
m_vPos.x = 0;
}
//update the bounding box
m_AlienBBox.left = m_vPos.x - (4*CParams::dAlienScale);
m_AlienBBox.right = m_vPos.x + (4*CParams::dAlienScale);
m_AlienBBox.top = m_vPos.y + (3*CParams::dAlienScale);
m_AlienBBox.bottom= m_vPos.y - (4*CParams::dAlienScale);
//an alien dies if it drops below the gun, flys too high
//or is hit by a bullet
if ( (m_vPos.y > (CParams::WindowHeight + 5)) ||
(m_vPos.y < 15) ||
CheckForCollision(bullets))
{
return false;
}
return true;
}
//------------------------- CheckForCollision ---------------------------
//
// tests the aliens bounding box against each bullet's bounding box.
// returns true if a collision is detected
//-----------------------------------------------------------------------
bool CAlien::CheckForCollision(vector<CBullet> &bullets)const
{
//for each bullet
for (int blt=0; blt<bullets.size(); ++blt)
{
//if bullet is not active goto next bullet
if (!bullets[blt].Active())
{
continue;
}
RECT blts = bullets[blt].BBox();
//test for intersection between bounding boxes
if (!((blts.bottom > m_AlienBBox.top) ||
(blts.top < m_AlienBBox.bottom) ||
(blts.left > m_AlienBBox.right) ||
(blts.right < m_AlienBBox.left)))
{
bullets[blt].SwitchOff();
return true;
}
}
return false;
}
//--------------------------------- Reset --------------------------------
//
//------------------------------------------------------------------------
void CAlien::Reset()
{
m_iAge = 0;
m_vVelocity = SVector2D(0, 0);
m_vPos = SVector2D(RandInt(0, CParams::WindowWidth), CParams::WindowHeight);
}
//------------------------------ mutate ----------------------------------
//
// mutates the connection weights in the alien's neural network.
//------------------------------------------------------------------------
void CAlien::Mutate()
{
//grab the weights for the neural net
vector<double> weights = m_ItsBrain.GetWeights();
//mutate them
for (int w=0; w<weights.size(); ++w)
{
//do we perturb this weight?
if (RandFloat() < CParams::dMutationRate)
{
//add a small value to the weight
weights[w] += (RandomClamped() * CParams::dMaxPerturbation);
}
}
//put 'em back!
m_ItsBrain.PutWeights(weights);
}
| mit |
YABhq/Quazar | fixture/Services/TeamService.php | 5149 | <?php
namespace App\Services;
use DB;
use Illuminate\Support\Str;
use App\Services\UserService;
use App\Models\User;
use App\Models\Team;
use Illuminate\Support\Facades\Schema;
class TeamService
{
/**
* Team Model
* @var Team
*/
public $model;
/**
* UserService
* @var UserService
*/
protected $userService;
public function __construct(
Team $model,
UserService $userService
) {
$this->model = $model;
$this->userService = $userService;
}
/**
* All teams
* @return \Illuminate\Support\Collection|null|static|Team
*/
public function all($userId)
{
return $this->model->where('user_id', $userId)->orderBy('created_at', 'desc')->get();
}
/**
* All teams paginated
* @return \Illuminate\Support\Collection|null|static|Team
*/
public function paginated($userId)
{
return $this->model->where('user_id', $userId)->orderBy('created_at', 'desc')->paginate(env('paginate', 25));
}
/**
* Search the teams
* @param integer $userId
* @param string $input
* @return \Illuminate\Support\Collection|null|static|Team
*/
public function search($userId, $input)
{
$query = $this->model->orderBy('created_at', 'desc');
$columns = Schema::getColumnListing('teams');
$query->where('id', 'LIKE', '%'.$input.'%');
foreach ($columns as $attribute) {
$query->orWhere($attribute, 'LIKE', '%'.$input.'%')->where('user_id', $userId);
};
return $query->paginate(env('paginate', 25));
}
/**
* Create a team
* @param integer $userId
* @param array $input
* @return \Illuminate\Support\Collection|null|static|Team
*/
public function create($userId, $input)
{
try {
$team = DB::transaction(function () use ($userId, $input) {
$input['user_id'] = $userId;
$team = $this->model->create($input);
$this->userService->joinTeam($team->id, $userId);
return $team;
});
return $team;
} catch (Exception $e) {
throw new Exception("Failed to create team", 1);
}
}
/**
* Find a team
* @param integer $id
* @return \Illuminate\Support\Collection|null|static|Team
*/
public function find($id)
{
return $this->model->find($id);
}
/**
* Find a team by name
* @param string $name
* @return \Illuminate\Support\Collection|null|static|Team
*/
public function findByName($name)
{
return $this->model->where('name', $name)->firstOrFail();
}
/**
* Update a team
* @param integer $id
* @param array $input
* @return Team
*/
public function update($id, $input)
{
$team = $this->model->find($id);
$team->update($input);
return $team;
}
/**
* Delete a team
* @param User $user
* @param integer $id
* @return boolean
*/
public function destroy($user, $id)
{
if ($user->isTeamAdmin($id)) {
$team = $this->model->find($id);
foreach ($team->members as $member) {
$this->userService->leaveTeam($id, $member->id);
}
return $this->model->find($id)->delete();
}
return false;
}
/**
* Invite a team member
* @param User $admin
* @param integer $id
* @param string $email
* @return boolean
*/
public function invite($admin, $id, $email)
{
try {
if ($admin->isTeamAdmin($id)) {
$user = $this->userService->findByEmail($email);
if (! $user) {
$password = Str::random(10);
$user = User::create([
'name' => $email,
'email' => $email,
'password' => bcrypt($password),
]);
$this->userService->create($user, $password);
}
if ($user->isTeamMember($id)) {
return false;
}
$this->userService->joinTeam($id, $user->id);
return true;
}
return false;
} catch (Exception $e) {
throw new Exception("Failed to invite member", 1);
}
}
/**
* Remove a team member
* @param User $admin
* @param integer $id
* @param integer $userId
* @return boolean
*/
public function remove($admin, $id, $userId)
{
try {
if ($admin->isTeamAdmin($id)) {
$user = $this->userService->find($userId);
if ($admin->isTeamAdmin($id)) {
$this->userService->leaveTeam($id, $user->id);
return true;
}
}
return false;
} catch (Exception $e) {
throw new Exception("Failed to remove member", 1);
}
}
}
| mit |
ng-seed/universal | tools/test/style-processor.js | 224 | const babelJest = require('babel-jest');
module.exports = {
process: function(src, filename) {
if (filename.match(/\.(css|less|scss|styl|sss)$/))
return '';
return babelJest.process(src, filename);
},
};
| mit |
faidi/JourEtMenu | src/JourEtMenu/JourEtMenuBundle/Controller/ReservationsController.php | 3007 | <?php
namespace JourEtMenu\JourEtMenuBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use JourEtMenu\JourEtMenuBundle\Entity\Reservations;
use JourEtMenu\JourEtMenuBundle\Entity\Menus;
use JourEtMenu\JourEtMenuBundle\Form\ReservationsType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JourEtMenu\JourEtMenuBundle\Entity\platDuJour;
/**
* platDuJour controller.
*
* @Route("/reservation")
*
*/
class ReservationsController extends Controller
{
/**
* Lists all platDuJour entities.
*
* @Route("/{menu}", name="reserver")
*
*
*/
public function reservermenuAction(Menus $menu )
{
$em = $this->getDoctrine ()->getManager ();
$utilisateur = $this->container->get ( 'security.context' )->getToken ()->getUser();
$entities = $em->getRepository('JourEtMenuBundle:statusReservation')->find('3');
$entity=new Reservations();
$entity->setClient($utilisateur);
$form = $this->createForm ( new ReservationsType(), $entity );
$request = $this->get ( 'request' );
$form->add ( 'submit', 'submit', array (
'label' => 'Je Reserve',
'attr'=> array('class'=>'btn btn-success')) );
if ($request->getMethod () == 'POST') {
$form->bind ( $request );
if ($form->isValid ()) {
$entity->setStatus($entities);
$entity->setMenu($menu);
$entity->setRestaurant($menu->getRestaurant());
$em->persist($entity);
$em->flush();
return $this->render ( 'JourEtMenuBundle:Client:resa/succesreservation.html.twig'
);
}
}
return $this->render('JourEtMenuBundle:Client:resa/index.html.twig', array('form' => $form->createView (),'menu' =>$menu ));
}
/**
* Lists all platDuJour entities.
*
* @Route("/plat/{platDuJour}", name="reserver_platdujour")
*
*
*/
public function reserverPlatDuJourAction(platDuJour $platDuJour )
{
$em = $this->getDoctrine ()->getManager ();
$utilisateur = $this->container->get ( 'security.context' )->getToken ()->getUser();
$entities = $em->getRepository('JourEtMenuBundle:statusReservation')->find('3');
$entity=new Reservations();
$entity->setClient($utilisateur);
$form = $this->createForm ( new ReservationsType(), $entity );
$request = $this->get ( 'request' );
$form->add ( 'submit', 'submit', array (
'label' => 'Reserver'
) );
if ($request->getMethod () == 'POST') {
$form->bind ( $request );
if ($form->isValid ()) {
$entity->setStatus($entities);
$entity->setPlatDuJour($platDuJour);
$entity->setRestaurant($platDuJour->getRestaurant());
$em->persist($entity);
$em->flush();
return $this->render ( 'JourEtMenuBundle:Client:resa/succesreservation.html.twig'
);
}
}
return $this->render('JourEtMenuBundle:Client:resa/index.html.twig', array('form' => $form->createView (),'menu' =>$platDuJour ));
}
}
| mit |
crod93/googlePlacesEx-react-native | node_modules/react-native-code-push/windows/CodePushNativeModule.cs | 11672 | using Newtonsoft.Json.Linq;
using ReactNative;
using ReactNative.Bridge;
using ReactNative.Modules.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Windows.Web.Http;
namespace CodePush.ReactNative
{
internal class CodePushNativeModule : ReactContextNativeModuleBase
{
private CodePushReactPackage _codePush;
private MinimumBackgroundListener _minimumBackgroundListener;
private ReactContext _reactContext;
public CodePushNativeModule(ReactContext reactContext, CodePushReactPackage codePush) : base(reactContext)
{
_reactContext = reactContext;
_codePush = codePush;
}
public override string Name
{
get
{
return "CodePush";
}
}
public override IReadOnlyDictionary<string, object> Constants
{
get
{
return new Dictionary<string, object>
{
{ "codePushInstallModeImmediate", InstallMode.Immediate },
{ "codePushInstallModeOnNextResume", InstallMode.OnNextResume },
{ "codePushInstallModeOnNextRestart", InstallMode.OnNextRestart },
{ "codePushUpdateStateRunning", UpdateState.Running },
{ "codePushUpdateStatePending", UpdateState.Pending },
{ "codePushUpdateStateLatest", UpdateState.Lastest },
};
}
}
public override void Initialize()
{
_codePush.InitializeUpdateAfterRestart();
}
[ReactMethod]
public void downloadUpdate(JObject updatePackage, bool notifyProgress, IPromise promise)
{
Action downloadAction = async () =>
{
try
{
updatePackage[CodePushConstants.BinaryModifiedTimeKey] = "" + await _codePush.GetBinaryResourcesModifiedTime();
await _codePush.UpdateManager.DownloadPackage(
updatePackage,
_codePush.AssetsBundleFileName,
new Progress<HttpProgress>(
(HttpProgress progress) =>
{
if (!notifyProgress)
{
return;
}
var downloadProgress = new JObject()
{
{ "totalBytes", progress.TotalBytesToReceive },
{ "receivedBytes", progress.BytesReceived }
};
_reactContext
.GetJavaScriptModule<RCTDeviceEventEmitter>()
.emit(CodePushConstants.DownloadProgressEventName, downloadProgress);
}
)
);
JObject newPackage = await _codePush.UpdateManager.GetPackage((string)updatePackage[CodePushConstants.PackageHashKey]);
promise.Resolve(newPackage);
}
catch (InvalidDataException e)
{
CodePushUtils.Log(e.ToString());
SettingsManager.SaveFailedUpdate(updatePackage);
promise.Reject(e);
}
catch (Exception e)
{
CodePushUtils.Log(e.ToString());
promise.Reject(e);
}
};
Context.RunOnNativeModulesQueueThread(downloadAction);
}
[ReactMethod]
public void getConfiguration(IPromise promise)
{
var config = new JObject
{
{ "appVersion", _codePush.AppVersion },
{ "clientUniqueId", CodePushUtils.GetDeviceId() },
{ "deploymentKey", _codePush.DeploymentKey },
{ "serverUrl", CodePushConstants.CodePushServerUrl }
};
// TODO generate binary hash
// string binaryHash = CodePushUpdateUtils.getHashForBinaryContents(mainActivity, isDebugMode);
/*if (binaryHash != null)
{
configMap.putString(PACKAGE_HASH_KEY, binaryHash);
}*/
promise.Resolve(config);
}
[ReactMethod]
public void getUpdateMetadata(UpdateState updateState, IPromise promise)
{
Action getCurrentPackageAction = async () =>
{
JObject currentPackage = await _codePush.UpdateManager.GetCurrentPackage();
if (currentPackage == null)
{
promise.Resolve("");
return;
}
var currentUpdateIsPending = false;
if (currentPackage[CodePushConstants.PackageHashKey] != null)
{
var currentHash = (string)currentPackage[CodePushConstants.PackageHashKey];
currentUpdateIsPending = SettingsManager.IsPendingUpdate(currentHash);
}
if (updateState == UpdateState.Pending && !currentUpdateIsPending)
{
// The caller wanted a pending update
// but there isn't currently one.
promise.Resolve("");
}
else if (updateState == UpdateState.Running && currentUpdateIsPending)
{
// The caller wants the running update, but the current
// one is pending, so we need to grab the previous.
promise.Resolve(await _codePush.UpdateManager.GetPreviousPackage());
}
else
{
// The current package satisfies the request:
// 1) Caller wanted a pending, and there is a pending update
// 2) Caller wanted the running update, and there isn't a pending
// 3) Caller wants the latest update, regardless if it's pending or not
if (_codePush.IsRunningBinaryVersion)
{
// This only matters in Debug builds. Since we do not clear "outdated" updates,
// we need to indicate to the JS side that somehow we have a current update on
// disk that is not actually running.
currentPackage["_isDebugOnly"] = true;
}
// Enable differentiating pending vs. non-pending updates
currentPackage["isPending"] = currentUpdateIsPending;
promise.Resolve(currentPackage);
}
};
Context.RunOnNativeModulesQueueThread(getCurrentPackageAction);
}
[ReactMethod]
public void getNewStatusReport(IPromise promise)
{
// TODO implement this
promise.Resolve("");
}
[ReactMethod]
public void installUpdate(JObject updatePackage, InstallMode installMode, int minimumBackgroundDuration, IPromise promise)
{
Action installUpdateAction = async () =>
{
await _codePush.UpdateManager.InstallPackage(updatePackage, SettingsManager.IsPendingUpdate(null));
var pendingHash = (string)updatePackage[CodePushConstants.PackageHashKey];
SettingsManager.SavePendingUpdate(pendingHash, /* isLoading */false);
if (installMode == InstallMode.OnNextResume)
{
if (_minimumBackgroundListener == null)
{
// Ensure we do not add the listener twice.
Action loadBundleAction = () =>
{
Context.RunOnNativeModulesQueueThread(async () =>
{
await LoadBundle();
});
};
_minimumBackgroundListener = new MinimumBackgroundListener(loadBundleAction, minimumBackgroundDuration);
_reactContext.AddLifecycleEventListener(_minimumBackgroundListener);
}
else
{
_minimumBackgroundListener.MinimumBackgroundDuration = minimumBackgroundDuration;
}
}
promise.Resolve("");
};
Context.RunOnNativeModulesQueueThread(installUpdateAction);
}
[ReactMethod]
public void isFailedUpdate(string packageHash, IPromise promise)
{
promise.Resolve(SettingsManager.IsFailedHash(packageHash));
}
[ReactMethod]
public void isFirstRun(string packageHash, IPromise promise)
{
Action isFirstRunAction = async () =>
{
bool isFirstRun = _codePush.DidUpdate
&& packageHash != null
&& packageHash.Length > 0
&& packageHash.Equals(await _codePush.UpdateManager.GetCurrentPackageHash());
promise.Resolve(isFirstRun);
};
Context.RunOnNativeModulesQueueThread(isFirstRunAction);
}
[ReactMethod]
public void notifyApplicationReady(IPromise promise)
{
SettingsManager.RemovePendingUpdate();
promise.Resolve("");
}
[ReactMethod]
public void restartApp(bool onlyIfUpdateIsPending)
{
Action restartAppAction = async () =>
{
// If this is an unconditional restart request, or there
// is current pending update, then reload the app.
if (!onlyIfUpdateIsPending || SettingsManager.IsPendingUpdate(null))
{
await LoadBundle();
}
};
Context.RunOnNativeModulesQueueThread(restartAppAction);
}
internal async Task LoadBundle()
{
// #1) Get the private ReactInstanceManager, which is what includes
// the logic to reload the current React context.
FieldInfo info = typeof(ReactPage)
.GetField("_reactInstanceManager", BindingFlags.NonPublic | BindingFlags.Instance);
var reactInstanceManager = (ReactInstanceManager)typeof(ReactPage)
.GetField("_reactInstanceManager", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(_codePush.MainPage);
// #2) Update the locally stored JS bundle file path
Type reactInstanceManagerType = typeof(ReactInstanceManager);
string latestJSBundleFile = await _codePush.GetJavaScriptBundleFileAsync(_codePush.AssetsBundleFileName);
reactInstanceManagerType
.GetField("_jsBundleFile", BindingFlags.NonPublic | BindingFlags.Instance)
.SetValue(reactInstanceManager, latestJSBundleFile);
// #3) Get the context creation method and fire it on the UI thread (which RN enforces)
Context.RunOnDispatcherQueueThread(reactInstanceManager.RecreateReactContextInBackground);
}
}
} | mit |
Luatix/OpenEx | openex-platform/openex-api/src/Kernel.php | 2086 | <?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
use function dirname;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
private const CONFIG_EXTS = '.{php,xml,yaml,yml}';
public function registerBundles(): iterable
{
date_default_timezone_set("UTC");
$contents = require $this->getProjectDir() . '/config/bundles.php';
foreach ($contents as $class => $envs) {
if ($envs[$this->environment] ?? $envs['all'] ?? false) {
yield new $class();
}
}
}
public function getProjectDir(): string
{
return dirname(__DIR__);
}
protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void
{
$container->addResource(new FileResource($this->getProjectDir() . '/config/bundles.php'));
$container->setParameter('container.dumper.inline_class_loader', true);
$confDir = $this->getProjectDir() . '/config';
$loader->load($confDir . '/{packages}/*' . self::CONFIG_EXTS, 'glob');
$loader->load($confDir . '/{packages}/' . $this->environment . '/**/*' . self::CONFIG_EXTS, 'glob');
$loader->load($confDir . '/{services}' . self::CONFIG_EXTS, 'glob');
$loader->load($confDir . '/{services}_' . $this->environment . self::CONFIG_EXTS, 'glob');
}
protected function configureRoutes(RouteCollectionBuilder $routes): void
{
$confDir = $this->getProjectDir() . '/config';
$routes->import($confDir . '/{routes}/' . $this->environment . '/**/*' . self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir . '/{routes}/*' . self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir . '/{routes}' . self::CONFIG_EXTS, '/', 'glob');
}
}
| mit |
stoeffel/react-motion-drawer | lib/styles.js | 1537 | export default function(val, props) {
const {
zIndex,
left,
right,
height,
handleWidth,
overlayColor,
fadeOut,
offset
} = props;
let clientWidth = 1000;
let width = props.width;
if (typeof document !== "undefined") {
clientWidth = document.body.clientWidth;
if (/\D/.test(width))
width = document.body.clientWidth * (width.match(/\d*/) / 100);
}
const opacity = (val - offset) / width;
if (right) val = width - val;
else val = val - width;
const drawer = {
display: "block",
width: width,
height: height,
overflow: "auto"
};
const transform = {
boxSizing: "content-box",
pointer: "cursor",
position: "fixed",
display: "block",
zIndex: zIndex,
width: width,
[right ? "paddingLeft" : "paddingRight"]: handleWidth,
maxWidth: width,
height: height,
top: 0,
[right ? "right" : "left"]: 0,
margin: 0,
transform: `translate3d(${val}px, 0, 0)`,
WebkitTransform: `translate3d(${val}px, 0, 0)`,
opacity: fadeOut ? opacity : 1
};
const overlayTransform = right ? -width : width;
const overlay = {
zIndex: -2,
pointer: "cursor",
position: "fixed",
width: clientWidth,
height: "100%",
background: overlayColor,
opacity: opacity,
top: 0,
[right ? "right" : "left"]: 0,
margin: 0,
transform: `translate3d(${overlayTransform}px, 0, 0)`,
WebkitTransform: `translate3d(${overlayTransform}px, 0, 0)`
};
return { drawer, transform, overlay };
}
| mit |
jakewendt/rails_extension | generators/rails_extension/rails_extension_generator.rb | 2577 | class RailsExtensionGenerator < Rails::Generator::Base
def manifest
# See Rails::Generator::Commands::Create
# rails-2.3.10/lib/rails_generator/commands.rb
# for code methods for record (Manifest)
record do |m|
File.open('.autotest','a'){|f|
f.puts <<-EOF
# From `script/generate simply_testable` ...
Dir["\#{File.dirname(__FILE__)}/config/autotest/**/*rb"].sort.each { |ext| load ext }
EOF
}
# %w( create_pages ).each do |migration|
# m.migration_template "migrations/#{migration}.rb",
# 'db/migrate', :migration_file_name => migration
# end
#
# m.directory('public/javascripts')
# Dir["#{File.dirname(__FILE__)}/templates/javascripts/*js"].each{|file|
# f = file.split('/').slice(-2,2).join('/')
# m.file(f, "public/javascripts/#{File.basename(file)}")
# }
# m.directory('public/stylesheets')
# Dir["#{File.dirname(__FILE__)}/templates/stylesheets/*css"].each{|file|
# f = file.split('/').slice(-2,2).join('/')
# m.file(f, "public/stylesheets/#{File.basename(file)}")
# }
# m.directory('test/functional/pages')
# Dir["#{File.dirname(__FILE__)}/templates/functional/*rb"].each{|file|
# f = file.split('/').slice(-2,2).join('/')
# m.file(f, "test/functional/pages/#{File.basename(file)}")
# }
# m.directory('test/unit/pages')
# Dir["#{File.dirname(__FILE__)}/templates/unit/*rb"].each{|file|
# f = file.split('/').slice(-2,2).join('/')
# m.file(f, "test/unit/pages/#{File.basename(file)}")
# }
end
end
end
module Rails::Generator::Commands
class Create
def migration_template(relative_source,
relative_destination, template_options = {})
migration_directory relative_destination
migration_file_name = template_options[
:migration_file_name] || file_name
if migration_exists?(migration_file_name)
puts "Another migration is already named #{migration_file_name}: #{existing_migrations(migration_file_name).first}: Skipping"
else
template(relative_source, "#{relative_destination}/#{next_migration_string}_#{migration_file_name}.rb", template_options)
end
end
end # Create
class Base
protected
# the loop through migrations happens so fast
# that they all have the same timestamp which
# won't work when you actually try to migrate.
# All the timestamps MUST be unique.
def next_migration_string(padding = 3)
@s = (!@s.nil?)? @s.to_i + 1 : if ActiveRecord::Base.timestamped_migrations
Time.now.utc.strftime("%Y%m%d%H%M%S")
else
"%.#{padding}d" % next_migration_number
end
end
end # Base
end
| mit |
apo-j/Projects_Working | EC/espace-client-dot-net/EspaceClient.BackOffice.Services.Implementations/ServiceTraductionCategorieClient.Generated.cs | 3461 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This code was auto-generated by AFNOR StoredProcedureSystem, version 1.0
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Activation;
using AutoMapper;
using EspaceClient.BackOffice.Infrastructure.Context;
using EspaceClient.BackOffice.Services.Contracts;
using EspaceClient.BackOffice.Services.Implementations.Helpers;
using EspaceClient.FrontOffice.Business.Depots;
using EspaceClient.FrontOffice.Domaine;
using Castle.Core.Logging;
namespace EspaceClient.BackOffice.Services.Implementations
{
/// <summary>
/// Service des utilisateurs.
/// </summary>
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public partial class ServiceTraductionCategorieClient : IServiceTraductionCategorieClient
{
private readonly IDepotTraductionCategorieClient _traductioncategorieclients;
private readonly IDepotLangue _langues;
private ILogger _logger = NullLogger.Instance;
/// <summary>
/// Initialise une nouvelle instance du service des traductioncategorieclients.
/// </summary>
/// <param name="traductioncategorieclients">Dépôt des traductioncategorieclients.</param>
public ServiceTraductionCategorieClient(IDepotTraductionCategorieClient traductioncategorieclients,IDepotLangue langues )
{
_traductioncategorieclients = traductioncategorieclients;
_langues = langues ;
}
/// <summary>
/// Instance du logger.
/// </summary>
public ILogger Logger
{
get { return _logger; }
set { _logger = value; }
}
public IEnumerable<TraductionCategorieClientDto> GetAll(WebContext context)
{
try
{
var cache = Memoizer.Memoize<WebContext, IEnumerable<TraductionCategorieClientDto>>(CacheTraductionCategorieClients);
return cache(context);
}
catch (Exception e)
{
LoggerHelper.Fatal(Logger, e, "SERVICE_CRITICAL_FAILED");
}
return null;
}
private IEnumerable<TraductionCategorieClientDto> CacheTraductionCategorieClients(WebContext context)
{
try
{
var traductioncategorieclients = _traductioncategorieclients.GetAll(context.LangueID);
List<TraductionCategorieClientDto> traductioncategorieclientsDto = new List<TraductionCategorieClientDto>();
foreach (var ob in traductioncategorieclients.ToList())
{
var dto = Mapper.Map<TraductionCategorieClient, TraductionCategorieClientDto>(ob);
traductioncategorieclientsDto.Add(dto);
}
return traductioncategorieclientsDto;
}
catch (Exception e)
{
LoggerHelper.Fatal(Logger, e, "SERVICE_CRITICAL_FAILED");
}
return null;
}
}
}
| mit |
ARCANESOFT/Blog | src/Models/Post.php | 9321 | <?php namespace Arcanesoft\Blog\Models;
use Arcanedev\LaravelSeo\Traits\Seoable;
use Arcanesoft\Blog\Blog;
use Arcanesoft\Blog\Events\Posts as PostEvents;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Class Post
*
* @package Arcanesoft\Blog\Models
* @author ARCANEDEV <arcanedev.maroc@gmail.com>
*
* @property int id
* @property int author_id
* @property int category_id
* @property string locale
* @property string title
* @property string slug
* @property string excerpt
* @property string|null thumbnail
* @property string content_raw
* @property string content_html
* @property bool is_draft
* @property \Carbon\Carbon published_at
* @property \Carbon\Carbon created_at
* @property \Carbon\Carbon updated_at
* @property \Carbon\Carbon deleted_at
*
* @property \Arcanesoft\Contracts\Auth\Models\User author
* @property \Arcanesoft\Blog\Models\Category category
* @property \Illuminate\Database\Eloquent\Collection tags
*
* @method static \Illuminate\Database\Eloquent\Builder published()
* @method static \Illuminate\Database\Eloquent\Builder publishedAt(int $year)
* @method static \Illuminate\Database\Eloquent\Builder localized(string|null $locale)
*/
class Post extends AbstractModel
{
/* -----------------------------------------------------------------
| Traits
| -----------------------------------------------------------------
*/
use Presenters\PostPresenter,
Seoable,
SoftDeletes;
/* -----------------------------------------------------------------
| Properties
| -----------------------------------------------------------------
*/
/**
* The database table used by the model
*
* @var string
*/
protected $table = 'posts';
/**
* The attributes that are mass assignable
*
* @var array
*/
protected $fillable = [
'author_id',
'category_id',
'locale',
'title',
'slug',
'excerpt',
'thumbnail',
'content',
'published_at',
'status',
];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['published_at', 'deleted_at'];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'author_id' => 'integer',
'category_id' => 'integer',
'is_draft' => 'boolean',
];
/**
* The event map for the model.
*
* @var array
*/
protected $dispatchesEvents = [
'creating' => PostEvents\PostCreating::class,
'created' => PostEvents\PostCreated::class,
'updating' => PostEvents\PostUpdating::class,
'updated' => PostEvents\PostUpdated::class,
'saving' => PostEvents\PostSaving::class,
'saved' => PostEvents\PostSaved::class,
'deleting' => PostEvents\PostDeleting::class,
'deleted' => PostEvents\PostDeleted::class,
'restoring' => PostEvents\PostRestoring::class,
'restored' => PostEvents\PostRestored::class,
];
/* -----------------------------------------------------------------
| Scopes
| -----------------------------------------------------------------
*/
/**
* Scope only published posts.
*
* @param \Illuminate\Database\Eloquent\Builder $query
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePublished(Builder $query)
{
return $query->where('is_draft', false)
->where('published_at', '<=', now());
}
/**
* Scope only published posts.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $year
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePublishedAt(Builder $query, $year)
{
return $this->scopePublished($query)
->where(DB::raw('YEAR(published_at)'), $year);
}
/**
* Scope by post's locale.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string|null $locale
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeLocalized(Builder $query, $locale = null)
{
return $query->where('locale', $locale ?: config('app.locale'));
}
/* -----------------------------------------------------------------
| Relationships
| -----------------------------------------------------------------
*/
/**
* Author relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function author()
{
return $this->belongsTo(
config('auth.providers.users.model', 'App\\Models\\User'),
'author_id'
);
}
/**
* Category relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function category()
{
return $this->belongsTo(Category::class);
}
/**
* Tags relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags()
{
return $this->belongsToMany(Tag::class, "{$this->prefix}post_tag");
}
/* -----------------------------------------------------------------
| Getters & Setters
| -----------------------------------------------------------------
*/
/**
* Set the title attribute.
*
* @param string $title
*/
public function setTitleAttribute($title)
{
$this->attributes['title'] = $title;
}
/**
* Get the slug attribute.
*
* @param string $slug
*/
public function setSlugAttribute($slug)
{
$this->attributes['slug'] = Str::slug($slug);
}
/**
* Set the content attribute.
*
* @param string $content
*/
public function setContentAttribute($content)
{
$this->attributes['content_raw'] = $content;
$this->attributes['content_html'] = markdown($content);
}
/* -----------------------------------------------------------------
| Main Functions
| -----------------------------------------------------------------
*/
/**
* Create a post.
*
* @param array $attributes
*
* @return self
*/
public static function createOne(array $attributes)
{
return tap(new self($attributes), function (self $post) use ($attributes) {
$post->save();
$post->tags()->sync($attributes['tags']);
if (Blog::isSeoable()) {
$post->createSeo(
static::extractSeoAttributes($attributes)
);
}
});
}
/**
* Create a post.
*
* @param array $attributes
*
* @return bool|int
*/
public function updateOne(array $attributes)
{
$updated = $this->update(Arr::except($attributes, ['author_id']));
$this->tags()->sync($attributes['tags']);
if (Blog::isSeoable()) {
$seo = static::extractSeoAttributes($attributes);
$this->hasSeo()
? $this->updateSeo($seo)
: $this->createSeo($seo);
}
return $updated;
}
/* -----------------------------------------------------------------
| Check Functions
| -----------------------------------------------------------------
*/
/**
* Check if the post is deletable.
*
* @return bool
*/
public function isDeletable()
{
return true;
}
/**
* Check if the post's status is "draft".
*
* @return bool
*/
public function isDraft()
{
return is_null($this->is_draft)
? true
: $this->is_draft;
}
/**
* Check if the post's status is "published".
*
* @return bool
*/
public function isPublished()
{
return ! $this->isDraft();
}
/**
* Check if the post has thumbnail.
*
* @return bool
*/
public function hasThumbnail()
{
return ! is_null($this->thumbnail);
}
/* -----------------------------------------------------------------
| Other Methods
| -----------------------------------------------------------------
*/
/**
* Extract the seo attributes.
*
* @param array $inputs
*
* @return array
*/
protected static function extractSeoAttributes(array $inputs)
{
return [
'title' => Arr::get($inputs, 'seo_title'),
'description' => Arr::get($inputs, 'seo_description'),
'keywords' => Arr::get($inputs, 'seo_keywords'),
'metas' => Arr::get($inputs, 'seo_metas', []),
];
}
}
| mit |
EkalayaProject/Sebar | codes/shortcodes/custom/custom.shortcode.php | 5706 | <?php
/**
* Prevent the file accessed directly
*/
if ( ! defined( 'ABSPATH' ) ) die( 'Cheating, uh?' );
class VcsShortcodeCustom {
private $viral;
private $options;
private $extensionOptions;
private $randSlider;
private $notAvailableImage;
public function __construct( &$viral, &$options, &$extensionOptions, $randSlider, $notAvailableImage ) {
$this->viral = $viral;
$this->options = $options;
$this->extensionOptions = $extensionOptions;
$this->randSlider = $randSlider;
$this->notAvailableImage = $notAvailableImage;
}
public function generate() {
$customShortcodeContent = '';
$type = 'custom';
$categoryIds = explode( ',', str_replace( array( '{', '}' ), '', $this->viral->categories ) );
$tagIds = explode( ',', str_replace( array( '{', '}' ), '', $this->viral->tags ) );
$authorIds = explode( ',', str_replace( array( '{', '}' ), '', $this->viral->authors ) );
$orderSort = strtoupper( $this->options->display_sort );
$arrayCustomParams = array(
'posts_per_page' => $this->viral->display
);
$taxCatParams = array();
if ( !empty( $categoryIds[0] ) ) {
$taxCatParams[] = array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $categoryIds,
'include_children' => true
);
}
$taxTagParams = array();
if ( !empty( $tagIds[0] ) ) {
$taxTagParams[] = array(
'taxonomy' => 'post_tag',
'field' => 'term_id',
'terms' => $tagIds
);
}
$mergeTaxParam = array_merge( $taxCatParams, $taxTagParams );
$taxQuery = array(
'relation' => 'OR',
$mergeTaxParam
);
if ( !empty( $authorIds[0] ) ) {
$arrayCustomParams['author__in'] = $authorIds;
}
if ( $this->options->display_type == 'bytitle' ) {
$arrayCustomParams['orderby'] = 'title';
$arrayCustomParams['order'] = $orderSort;
}
if ( $this->options->display_type == 'bydatepublished' ) {
$arrayCustomParams['orderby'] = 'date';
$arrayCustomParams['order'] = $orderSort;
}
if ( $this->options->display_type == 'random' ) {
$arrayCustomParams['orderby'] = 'rand';
}
if ( $this->options->display_type == 'bycommented' ) {
$arrayCustomParams['orderby'] = 'comment_count';
$arrayCustomParams['order'] = $orderSort;
}
if ( $this->options->display_type == 'bydefault' ) {
$arrayCustomParams['orderby'] = 'none';
}
if ( !empty( $mergeTaxParam ) ) {
$arrayCustomParams['tax_query'] = $taxQuery;
}
//echo '<pre>'; print_r( $arrayCustomParams ); echo '</pre>';
$posts = get_posts( $arrayCustomParams );
if ( !empty( $posts ) ) {
$customShortcodeContent .= <<<SLIDER
<div class="viralcontentslider_slider_main_{$type}_{$this->viral->id}_{$this->randSlider}">
<ul id="viralcontentslider_{$type}_{$this->viral->id}_{$this->randSlider}" class="viralcontentslider_slider_ul_{$type}_{$this->viral->id}_{$this->randSlider}">
SLIDER;
foreach ( $posts as $post ) {
$idFeaturedImage = get_post_thumbnail_id( $post->ID );
if ( !empty( $idFeaturedImage ) ) {
$customImageUrl = wp_get_attachment_url( $idFeaturedImage );
} else {
$customImageUrl = $this->notAvailableImage;
}
$customPermalink = get_permalink( $post->ID );
$openInNewTab = '';
/**
* Check if extension plugin is activated and option is yes
*/
if ( class_exists( 'VcsExtension' ) ) {
if ( $this->extensionOptions->open_in_landing_page == 'yes' ) {
$customPermalink = site_url() . '/?vcs_landing=' . VIRALCONTENTSLIDER_PLUGIN_SLUG . '&permalink=' . base64_encode( get_permalink( $post->ID ) ) . '&type=custom&te=' . base64_encode( $this->viral->id ) . '&obj=' . base64_encode( $post->ID ) . '&back=' . base64_encode( $_SERVER['REQUEST_URI'] );
}
if ( $this->extensionOptions->open_in_new_tab == 'yes' ) {
$openInNewTab = 'target="_blank"';
}
}
$customTitle = $post->post_title;
$customDescription = strip_shortcodes( strip_tags( str_replace( array( '"', "'" ), '', $post->post_content ) ) );
$trimmedCustomTitle = wp_trim_words( $customTitle, $this->options->title_limit_words );
$trimmedCustomDescription = wp_trim_words( $customDescription, $this->options->description_limit_words );
$customPublished = date( 'j M y, h:ia', strtotime( $post->post_date ) );
$customPublishedHTML = '<em style="font-size:10px !important;" title="Published at ' . $customPublished . '">' . $customPublished . '</em>';
$customThumbnail = wp_nonce_url( site_url() . '/?viralthumbnail=true&url=' . base64_encode( $customImageUrl ) . '', 'viralthumbnail', 'viralthumbnail_nonce' );
if ( empty( $idFeaturedImage ) ) {
$customImage = '<img class="vcs_image" src="' . $customImageUrl . '"/>';
} else {
$customImage = '<img class="vcs_image" src="' . $customThumbnail . '"/>';
}
$customShortcodeContent .= <<<HTML
<li>
<div class="vcs_content">
<div class="vcs_media_inline">
<a href="{$customPermalink}" {$openInNewTab} title="{$customTitle}">{$customImage}</a>
</div>
<div class="vcs_content_inline">
<a href="{$customPermalink}" {$openInNewTab} title="{$customTitle}"><h3 class="vcs_headline">{$trimmedCustomTitle}</h3></a>
<div class="vcs_description" title="{$customDescription}">
{$trimmedCustomDescription}
</div>
<div class="vcs_readmore">
<a href="{$customPermalink}" {$openInNewTab} title="{$customTitle}" class="vcs_readmore_text">{$this->options->readmore_text}</a>
<span style="margin-right:10px;float:right;">{$customPublishedHTML}</span>
</div>
</div>
</div>
</li>
HTML;
}
$customShortcodeContent .= <<<SLIDER
</ul>
</div>
SLIDER;
}
return $customShortcodeContent;
}
}
| mit |
vault/bugit | common/redis_client.py | 293 |
import redis
#redis_pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
class CommandQueue:
queue = 'bugit_processing_queue'
users = 'bugit_processing_users'
processing = 'bugit_in_progress'
def redis_db():
return redis.Redis(host='localhost', port=6379, db=0)
| mit |
jordanco/drafter-frontend | src/app/components/email_suggestion/index.js | 2954 | import React, { Component } from 'react';
export default () => {
return (
<div className="suggestions" data-ix="hide-initial-off-600-left">
<div className="title-background-white">
<div className="suggestions-title">Suggestions</div>
</div>
<div className="template" data-ix="template-ux-animation">
<div className="template-titles">Sent to James G 3 months ago:</div>
<div className="template-header">17 uses, <span style={{ fontWeight: 300 }}>Resp. rate = <strong>72%</strong></span>, Av. resp. speed = <strong> 2hr</strong>
</div>
<div className="template-content">Great to hear back from you.
<br/>
<br/>Do you have time for a quick 15m call next week to check whether we might be a good fit for each other?
<br/>
<br/>I can tell you more about our services and if it makes sense, schedule a full demo of the product.
<br/>
<br/> I could do 9am PT Wednesday if that works for you? I'm also free Thursday morning if that's better.
<br/>
<br/> Otherwise if it is more convenient, you can also select a time that works for you from my calendar here: [link to calendar tool].</div>
</div>
<div className="template" data-ix="template-ux-animation">
<div className="template-titles">You sent this to Freya M 2 months ago:</div>
<div className="template-header">28 uses, <span style={{ fontWeight: 300 }}>Resp. rate = <strong>67%</strong></span>, Av. resp. speed = <strong>12hr</strong>
</div>
<div className="template-content">I would love to tell you more about that. Do you have time for a quick 15m call next week to check whether we might be a good fit for each other? I can tell you more about our services and if it makes sense, schedule a full demo of the product.
<br/>
<br/>{ '{ Scheduling Suggestions }' }</div>
</div>
<div className="template" data-ix="template-ux-animation">
<div className="template-titles">You sent this to Lillie D 2 weeks ago:</div>
<div className="template-header">72 uses, <span style={{ fontWeight: 300 }}>Resp. rate = <strong>42%</strong></span>, Av. resp. speed = <strong>73hr</strong>
</div>
<div className="template-content">Great to hear back from you.
<br/>
<br/> Yes we do. Do you have time for a quick 15m call next week to check whether we might be a good fit for each other? I can tell you more about our services and if it makes sense, schedule a full demo of the product.
<br/>
<br/>{ '{ Scheduling Suggestions }' }</div>
</div>
<div className="spacer-50"></div>
</div>
);
}; | mit |
mathieumack/MvvX.Plugins.HockeyApp | MvvX.Plugins.HockeyApp.MoqUnitTest/MoqHockeyAppException.cs | 439 | using System;
using System.Collections.Generic;
using System.Text;
namespace MvvX.Plugins.HockeyApp.MoqUnitTest
{
public class MoqHockeyAppException
{
/// <summary>
/// Current exception
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Custom properties
/// </summary>
public IDictionary<string, string> Properties { get; set; }
}
}
| mit |
stoplightio/gitlabhq | db/migrate/20180113220114_rework_redirect_routes_indexes.rb | 2964 | # See http://doc.gitlab.com/ce/development/migration_style_guide.html
# for more information on how to write migrations for GitLab.
class ReworkRedirectRoutesIndexes < ActiveRecord::Migration[4.2]
include Gitlab::Database::MigrationHelpers
# Set this constant to true if this migration requires downtime.
DOWNTIME = false
disable_ddl_transaction!
INDEX_NAME_UNIQUE = "index_redirect_routes_on_path_unique_text_pattern_ops"
INDEX_NAME_PERM = "index_redirect_routes_on_path_text_pattern_ops_where_permanent"
INDEX_NAME_TEMP = "index_redirect_routes_on_path_text_pattern_ops_where_temporary"
OLD_INDEX_NAME_PATH_TPOPS = "index_redirect_routes_on_path_text_pattern_ops"
OLD_INDEX_NAME_PATH_LOWER = "index_on_redirect_routes_lower_path"
def up
disable_statement_timeout do
# this is a plain btree on a single boolean column. It'll never be
# selective enough to be valuable.
if index_exists?(:redirect_routes, :permanent)
remove_concurrent_index(:redirect_routes, :permanent)
end
# If we're on MySQL then the existing index on path is ok. But on
# Postgres we need to clean things up:
break unless Gitlab::Database.postgresql?
if_not_exists = Gitlab::Database.version.to_f >= 9.5 ? "IF NOT EXISTS" : ""
# Unique index on lower(path) across both types of redirect_routes:
execute("CREATE UNIQUE INDEX CONCURRENTLY #{if_not_exists} #{INDEX_NAME_UNIQUE} ON redirect_routes (lower(path) varchar_pattern_ops);")
# Make two indexes on path -- one for permanent and one for temporary routes:
execute("CREATE INDEX CONCURRENTLY #{if_not_exists} #{INDEX_NAME_PERM} ON redirect_routes (lower(path) varchar_pattern_ops) where (permanent);")
execute("CREATE INDEX CONCURRENTLY #{if_not_exists} #{INDEX_NAME_TEMP} ON redirect_routes (lower(path) varchar_pattern_ops) where (not permanent or permanent is null) ;")
# Remove the old indexes:
# This one needed to be on lower(path) but wasn't so it's replaced with the two above
execute "DROP INDEX CONCURRENTLY IF EXISTS #{OLD_INDEX_NAME_PATH_TPOPS};"
# This one isn't needed because we only ever do = and LIKE on this
# column so the varchar_pattern_ops index is sufficient
execute "DROP INDEX CONCURRENTLY IF EXISTS #{OLD_INDEX_NAME_PATH_LOWER};"
end
end
def down
disable_statement_timeout do
add_concurrent_index(:redirect_routes, :permanent)
break unless Gitlab::Database.postgresql?
execute("CREATE INDEX CONCURRENTLY #{OLD_INDEX_NAME_PATH_TPOPS} ON redirect_routes (path varchar_pattern_ops);")
execute("CREATE INDEX CONCURRENTLY #{OLD_INDEX_NAME_PATH_LOWER} ON redirect_routes (LOWER(path));")
execute("DROP INDEX CONCURRENTLY IF EXISTS #{INDEX_NAME_UNIQUE};")
execute("DROP INDEX CONCURRENTLY IF EXISTS #{INDEX_NAME_PERM};")
execute("DROP INDEX CONCURRENTLY IF EXISTS #{INDEX_NAME_TEMP};")
end
end
end
| mit |
hansl/devkit | tests/@angular_devkit/build_optimizer/webpack/aio-app/src/app/navigation/navigation.model.ts | 1549 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Pulled all interfaces out of `navigation.service.ts` because of this:
// https://github.com/angular/angular-cli/issues/2034
// Then re-export them from `navigation.service.ts`
export interface NavigationNode {
url?: string;
title?: string;
tooltip?: string;
hidden?: string;
children?: NavigationNode[];
}
export type NavigationResponse = {__versionInfo: VersionInfo } & { [name: string]: NavigationNode[]|VersionInfo };
export interface NavigationViews {
[name: string]: NavigationNode[];
}
/**
* Navigation information about a node at specific URL
* url: the current URL
* view: 'SideNav' | 'TopBar' | 'Footer' | etc
* nodes: the current node and its ancestor nodes within that view
*/
export interface CurrentNode {
url: string;
view: string;
nodes: NavigationNode[];
}
/**
* A map of current nodes by view.
* This is needed because some urls map to nodes in more than one view.
* If a view does not contain a node that matches the current url then the value will be undefined.
*/
export interface CurrentNodes {
[view: string]: CurrentNode;
}
export interface VersionInfo {
raw: string;
major: number;
minor: number;
patch: number;
prerelease: string[];
build: string;
version: string;
codeName: string;
isSnapshot: boolean;
full: string;
branch: string;
commitSHA: string;
}
| mit |
WHCIBoys/nitpik-web | src/reducers/profile.js | 581 | import * as I from 'immutable';
import * as C from '../constants';
import * as ReduxActions from 'redux-actions';
const INITIAL_STATE = I.fromJS({
nits: [],
friendships: [],
});
export default ReduxActions.handleActions({
[C.PROFILE_ACTIONS.LOAD_USER_NITS_SUCCESS]: (state, { payload }) => {
const { nits } = payload;
return state.set('nits', I.fromJS(nits));
},
[C.PROFILE_ACTIONS.LOAD_USER_FRIENDSHIPS_SUCCESS]: (state, { payload }) => {
const { friendships } = payload;
return state.set('friendships', I.fromJS(friendships));
},
}, INITIAL_STATE);
| mit |