repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
ErikSchierboom/xcsharp | exercises/resistor-color/ResistorColorTest.cs | 730 | // This file was auto-generated based on version 1.0.0 of the canonical data.
using Xunit;
public class ResistorColorTest
{
[Fact]
public void Black()
{
Assert.Equal(0, ResistorColor.ColorCode("black"));
}
[Fact(Skip = "Remove to run test")]
public void White()
{
Assert.Equal(9, ResistorColor.ColorCode("white"));
}
[Fact(Skip = "Remove to run test")]
public void Orange()
{
Assert.Equal(3, ResistorColor.ColorCode("orange"));
}
[Fact(Skip = "Remove to run test")]
public void Colors()
{
Assert.Equal(new[] { "black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white" }, ResistorColor.Colors());
}
} | mit |
canfeit/canfei | canfei.js | 1478 | /**
* Creates an array with all falsey values removed. The values undefined,null,0,+0,-0,NaN,'',"",false are falsey.
* <br>compact([1, 0, '', 8])//[1, 8]
*/
const compact = function (arr) {
return arr.filter(v => v)
};
/**
* 判断对象类型
* <br>complexType(1)//'Number'
* <br>complexType(new Date())//'Date'
*/
const complexType = function (o) {
return Object.prototype.toString.call(o).slice(8, -1)
};
/**
* 判断对象或数组非空
* <br>isFilled({K: 1})//true
* <br>isFilled({})//false
* <br>isFilled([0,1,2])//3
*/
const isFilled = function (o) {
if (Array.isArray(o))
{return o.length;}
for (let k in o) {
return true
}
return false
};
/**
* 判断变量未赋值<br>
* 假值:undefined,null,0,+0,-0,NaN,'',"",false<br>
* 空对象:{}<br>
* 空数组:[]
* <br>isFree({})//true
* <br>isFree([])//true
* <br>isFree(0)//true
*/
const isFree = function (o) {
return !o || // 假值
(typeof o === 'object' && (((complexType(o) === 'Array' || complexType(o) === 'Object') && !isFilled(o)) || // 空对象(或数组)
(complexType(o) === 'String' && o.toString() === '') ||
(complexType(o) === 'Number' && o.toString() === '0') ||
(complexType(o) === 'Boolean' && o.toString() === 'false')))
};
if (typeof exports === 'object' &&
typeof module !== 'undefined' &&
module.exports) {
module.exports = {
complexType,
isFilled,
isFree,
compact
}
}
| mit |
maciejkaiser/InvoiceApp | application/controllers/Firm.php | 2806 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* User class
*/
class Firm extends CI_Controller
{
public function index(){
if(($this->session->userdata('user_name'))){
$this->load->model('firmmodel');
$title = "Firms";
$data = array('title' => $title);
$data['firms'] = $this->firmmodel->all();
$data['content'] = $this->load->view('firm/index', $data, true);
$this->load->view('layout', $data);
}else{
redirect('user', 'refresh');
}
}
public function add(){
if(($this->session->userdata('user_name'))){
$this->load->model('firmmodel');
$title = "Firms";
$data = array('title' => $title);
$data['firms'] = $this->firmmodel->all();
$data['content'] = $this->load->view('firm/add', $data, true);
$this->load->view('layout', $data);
}else{
redirect('user', 'refresh');
}
}
public function addFirm()
{
$this->load->model('firmmodel');
$firm_name = $this->input->post('firm_name');
$data = array('firm_name' => $firm_name );
$result = $this->firmmodel->add($data);
if($result)
{
redirect('/firm/', 'refresh');
}
else
{
redirect('/firm/', 'refresh');
}
}
public function edit($firm_id = 0){
if($this->session->userdata('user_name')){
if($firm_id){
$this->load->model('firmmodel');
$title = "Edit firm";
$data = array('title' => $title);
$firm = $this->firmmodel->getFirm($firm_id);
foreach ($firm as $key => $value) {
$data['firm_name'] = $value->firm_name;
}
$data['firm_id'] = $firm_id;
$data['content'] = $this->load->view('firm/edit', $data, true);
$this->load->view('layout', $data);
}
}else{
redirect('user', 'refresh');
}
}
public function editFirm(){
if(($this->session->userdata('user_name'))){
$this->load->model('firmmodel');
$firm_id = $this->input->post('firm_id');
$firm_name = $this->input->post('firm_name');
$result = $this->firmmodel->editFirm($firm_id, $firm_name);
if($result)
{
redirect('/firm/', 'refresh');
}
else
{
redirect('/firm/', 'refresh');
}
}
}
public function delete($firm_id){
if(($this->session->userdata('user_name'))){
$title = "Delete firm";
$data = array('title' => $title, 'content' => "Are you sure to delete this invoice?", 'firm_id' => $firm_id);
$data['content'] = $this->load->view('firm/delete', $data, true);
$this->load->view('layout', $data);
}else{
redirect('firm', 'refresh');
}
}
public function deleteConfirm($firm_id = 0){
if(($this->session->userdata('user_name')) && $firm_id != 0){
$this->load->model('firmmodel');
$this->firmmodel->delete($firm_id);
redirect('firm', 'refresh');
}else{
redirect('firm', 'refresh');
}
}
}
?> | mit |
jocoonopa/lubri | app/Http/Controllers/Report/RetailSalesController.php | 618 | <?php
namespace App\Http\Controllers\Report;
use App\Events\Report\RetailSales\ReportEvent;
use App\Export\RetailSales\Export;
use App\Http\Controllers\Controller;
use Event;
class RetailSalesController extends Controller
{
public function index()
{
return redirect('/pos/store_goal');
}
public function process(Export $export)
{
set_time_limit(0);
return Event::fire(new ReportEvent($export->handleExport()));
}
public function download(Export $export)
{
set_time_limit(0);
return $export->handleExport()->export();
}
} | mit |
ycabon/presentations | 2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/widgets/smartMapping/SizeSlider/nls/SizeSlider.js | 410 | // All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define({root:{widgetLabel:"Size Slider"},ar:1,bs:1,ca:1,cs:1,da:1,de:1,el:1,es:1,et:1,fi:1,fr:1,he:1,hr:1,hu:1,id:1,it:1,ja:1,ko:1,lv:1,lt:1,nl:1,nb:1,pl:1,"pt-br":1,"pt-pt":1,ro:1,ru:1,sl:1,sr:1,sv:1,th:1,tr:1,uk:1,vi:1,"zh-cn":1,"zh-hk":1,"zh-tw":1}); | mit |
RectorPHP/Rector | vendor/ssch/typo3-rector/stubs/t3lib_cache_Factory.php | 196 | <?php
namespace RectorPrefix20210615;
if (\class_exists('t3lib_cache_Factory')) {
return;
}
class t3lib_cache_Factory
{
}
\class_alias('t3lib_cache_Factory', 't3lib_cache_Factory', \false);
| mit |
kamermans/guzzle4-oauth2-subscriber | src/kamermans/GuzzleOAuth2/GrantType/GrantTypeInterface.php | 373 | <?php namespace kamermans\GuzzleOAuth2\GrantType;
use kamermans\GuzzleOAuth2\TokenData;
use kamermans\GuzzleOAuth2\Signer\ClientCredentials\SignerInterface;
interface GrantTypeInterface
{
/**
* Get the token data returned by the OAuth2 server.
*
* @return TokenData
*/
public function getTokenData(SignerInterface $clientCredentialsSigner);
}
| mit |
kunesv/stuha18-server | src/main/java/net/stuha/messages/formattedText/ReplyTo.java | 1089 | package net.stuha.messages.formattedText;
import net.stuha.messages.MessageReplyTo;
public class ReplyTo extends TextNode {
private String replyToId;
private String iconPath;
private String caption;
ReplyTo() {
this.nodeType = NodeType.REPLY_TO;
}
ReplyTo(String replyToId, String iconPath, String caption) {
this();
this.replyToId = replyToId;
this.iconPath = iconPath;
this.caption = caption;
}
ReplyTo(MessageReplyTo messageReplyTo) {
this(messageReplyTo.getReplyToId(), messageReplyTo.getIconPath(), messageReplyTo.getCaption());
}
public String getReplyToId() {
return replyToId;
}
public void setReplyToId(String replyToId) {
this.replyToId = replyToId;
}
public String getIconPath() {
return iconPath;
}
public void setIconPath(String iconPath) {
this.iconPath = iconPath;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
}
| mit |
the-wr/infineon | Infineon/HelpWindow.cs | 2161 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using mshtml;
namespace Infineon
{
public class HelpWindow
{
private WebBrowser wb;
public HelpWindow( WebBrowser wb )
{
this.wb = wb;
wb.Navigated += delegate { ApplyStyle( Localization.Instance.Styles ); };
int feature = FEATURE_DISABLE_NAVIGATION_SOUNDS;
CoInternetSetFeatureEnabled( feature, SET_FEATURE_ON_PROCESS, true );
}
public void ShowHelp( string key )
{
var help = Localization.Instance.GetHelp( key );
SetHTML( help );
}
private void SetHTML( string html )
{
if ( string.IsNullOrEmpty( html ) )
{
wb.NavigateToString( "<html></html>" );
return;
}
wb.NavigateToString( html );
}
private void ApplyStyle( string style )
{
if ( string.IsNullOrEmpty( style ) )
return;
try
{
if ( wb.Document != null )
{
var currentDocument = (IHTMLDocument2)wb.Document;
int length = currentDocument.styleSheets.length;
IHTMLStyleSheet styleSheet = currentDocument.createStyleSheet( @"", length + 1 );
styleSheet.cssText = style;
}
}
catch ( Exception )
{
}
}
// http://stackoverflow.com/questions/393166/how-to-disable-click-sound-in-webbrowser-control
private const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
private const int SET_FEATURE_ON_PROCESS = 0x00000002;
[DllImport( "urlmon.dll" )]
[PreserveSig]
[return: MarshalAs( UnmanagedType.Error )]
static extern int CoInternetSetFeatureEnabled(
int FeatureEntry,
[MarshalAs( UnmanagedType.U4 )] int dwFlags,
bool fEnable );
}
}
| mit |
stevejc/subscribem | app/controllers/subscribem/accounts_controller.rb | 598 | require_dependency "subscribem/application_controller"
module Subscribem
class AccountsController < ApplicationController
def new
@account = Subscribem::Account.new
@account.build_owner
end
def create
@account = Subscribem::Account.new(params[:account])
if @account.save
flash[:success] = "Your account has been successfully created."
redirect_to subscribem.root_url(:subdomain => @account.subdomain)
else
flash[:error] = "Sorry, your account could not be created."
render :new
end
end
end
end
| mit |
nullstyle/nrepl | lib/nrepl.rb | 184 | require "nrepl/version"
require 'active_support/core_ext/hash'
require 'active_support/core_ext/object'
require 'nrepl/core_ext/hash'
module Nrepl
autoload :Repl, 'nrepl/repl'
end
| mit |
monty5811/cedarserver | media/client/subscriptions.js | 27 | Meteor.subscribe('media');
| mit |
kirnbas/BlogEngineTK | BlogEngineTK.WebUI/Properties/AssemblyInfo.cs | 1372 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BlogEngineTK.WebUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BlogEngineTK.WebUI")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ee1dc460-2162-47d5-90a1-c13602fb2d23")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
CCPorg/BOS-BossCoin-Ver-1-Copy | src/wallet.cpp | 52918 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013 Bosscoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "wallet.h"
#include "walletdb.h"
#include "crypter.h"
#include "ui_interface.h"
#include "base58.h"
using namespace std;
//////////////////////////////////////////////////////////////////////////////
//
// mapWallet
//
struct CompareValueOnly
{
bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
{
return t1.first < t2.first;
}
};
CPubKey CWallet::GenerateNewKey()
{
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey(fCompressed);
// Compressed public keys were introduced in version 0.6.0
if (fCompressed)
SetMinVersion(FEATURE_COMPRPUBKEY);
if (!AddKey(key))
throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
bool CWallet::AddKey(const CKey& key)
{
if (!CCryptoKeyStore::AddKey(key))
return false;
if (!fFileBacked)
return true;
if (!IsCrypted())
return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
return true;
}
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
if (!fFileBacked)
return true;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
else
return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
}
return false;
}
bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
}
bool CWallet::Unlock(const SecureString& strWalletPassphrase)
{
if (!IsLocked())
return false;
CCrypter crypter;
CKeyingMaterial vMasterKey;
{
LOCK(cs_wallet);
BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(vMasterKey))
return true;
}
}
return false;
}
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
{
bool fWasLocked = IsLocked();
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial vMasterKey;
BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(vMasterKey))
{
int64 nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
}
}
}
return false;
}
void CWallet::SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteBestBlock(loc);
}
// This class implements an addrIncoming entry that causes pre-0.4
// clients to crash on startup if reading a private-key-encrypted wallet.
class CCorruptAddress
{
public:
IMPLEMENT_SERIALIZE
(
if (nType & SER_DISK)
READWRITE(nVersion);
)
};
bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
{
if (nWalletVersion >= nVersion)
return true;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
if (fFileBacked)
{
CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
if (nWalletVersion >= 40000)
{
// Versions prior to 0.4.0 did not support the "minversion" record.
// Use a CCorruptAddress to make them crash instead.
CCorruptAddress corruptAddress;
pwalletdb->WriteSetting("addrIncoming", corruptAddress);
}
if (nWalletVersion > 40000)
pwalletdb->WriteMinVersion(nWalletVersion);
if (!pwalletdbIn)
delete pwalletdb;
}
return true;
}
bool CWallet::SetMaxVersion(int nVersion)
{
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial vMasterKey;
RandAddSeedPerfmon();
vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey;
RandAddSeedPerfmon();
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64 nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
if (fFileBacked)
{
pwalletdbEncryption = new CWalletDB(strWalletFile);
if (!pwalletdbEncryption->TxnBegin())
return false;
pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
}
if (!EncryptKeys(vMasterKey))
{
if (fFileBacked)
pwalletdbEncryption->TxnAbort();
exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet.
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
if (fFileBacked)
{
if (!pwalletdbEncryption->TxnCommit())
exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet.
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
}
Lock();
Unlock(strWalletPassphrase);
NewKeyPool();
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
CDB::Rewrite(strWalletFile);
}
NotifyStatusChanged(this);
return true;
}
void CWallet::WalletUpdateSpent(const CTransaction &tx)
{
// Anytime a signature is successfully verified, it's proof the outpoint is spent.
// Update the wallet spent flag if it doesn't know due to wallet.dat being
// restored from backup or the user making copies of wallet.dat.
{
LOCK(cs_wallet);
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
CWalletTx& wtx = (*mi).second;
if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
{
printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
wtx.MarkSpent(txin.prevout.n);
wtx.WriteToDisk();
NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
}
}
}
}
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
item.second.MarkDirty();
}
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn)
{
uint256 hash = wtxIn.GetHash();
{
LOCK(cs_wallet);
// Inserts only if not already there, returns tx inserted or tx found
pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew)
wtx.nTimeReceived = GetAdjustedTime();
bool fUpdated = false;
if (!fInsertedNew)
{
// Merge
if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
{
wtx.vMerkleBranch = wtxIn.vMerkleBranch;
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
}
//// debug print
printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!wtx.WriteToDisk())
return false;
#ifndef QT_GUI
// If default receiving address gets used, replace it with a new one
CScript scriptDefaultKey;
scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (txout.scriptPubKey == scriptDefaultKey)
{
CPubKey newDefaultKey;
if (GetKeyFromPool(newDefaultKey, false))
{
SetDefaultKey(newDefaultKey);
SetAddressBookName(vchDefaultKey.GetID(), "");
}
}
}
#endif
// since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
WalletUpdateSpent(wtx);
// Notify UI of new or updated transaction
NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
}
return true;
}
// Add a transaction to the wallet, or update it.
// pblock is optional, but should be provided if the transaction is known to be in a block.
// If fUpdate is true, existing transactions will be updated.
bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
{
uint256 hash = tx.GetHash();
{
LOCK(cs_wallet);
bool fExisted = mapWallet.count(hash);
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx))
{
CWalletTx wtx(this,tx);
// Get merkle branch if transaction was found in a block
if (pblock)
wtx.SetMerkleBranch(pblock);
return AddToWallet(wtx);
}
else
WalletUpdateSpent(tx);
}
return false;
}
bool CWallet::EraseFromWallet(uint256 hash)
{
if (!fFileBacked)
return false;
{
LOCK(cs_wallet);
if (mapWallet.erase(hash))
CWalletDB(strWalletFile).EraseTx(hash);
}
return true;
}
bool CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]))
return true;
}
}
return false;
}
int64 CWallet::GetDebit(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]))
return prev.vout[txin.prevout.n].nValue;
}
}
return 0;
}
bool CWallet::IsChange(const CTxOut& txout) const
{
CTxDestination address;
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a TX_PUBKEYHASH that is mine but isn't in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a multi-signature-protected address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
{
LOCK(cs_wallet);
if (!mapAddressBook.count(address))
return true;
}
return false;
}
int64 CWalletTx::GetTxTime() const
{
return nTimeReceived;
}
int CWalletTx::GetRequestCount() const
{
// Returns -1 if it wasn't being tracked
int nRequests = -1;
{
LOCK(pwallet->cs_wallet);
if (IsCoinBase())
{
// Generated block
if (hashBlock != 0)
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
}
}
else
{
// Did anyone request this transaction?
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end())
{
nRequests = (*mi).second;
// How about the block it's in?
if (nRequests == 0 && hashBlock != 0)
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
else
nRequests = 1; // If it's in someone else's block it must have got out
}
}
}
}
return nRequests;
}
void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
{
nGeneratedImmature = nGeneratedMature = nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
if (IsCoinBase())
{
if (GetBlocksToMaturity() > 0)
nGeneratedImmature = pwallet->GetCredit(*this);
else
nGeneratedMature = GetCredit();
return;
}
// Compute fee:
int64 nDebit = GetDebit();
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
int64 nValueOut = GetValueOut();
nFee = nDebit - nValueOut;
}
// Sent/received.
BOOST_FOREACH(const CTxOut& txout, vout)
{
CTxDestination address;
vector<unsigned char> vchPubKey;
if (!ExtractDestination(txout.scriptPubKey, address))
{
printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString().c_str());
}
// Don't report 'change' txouts
if (nDebit > 0 && pwallet->IsChange(txout))
continue;
if (nDebit > 0)
listSent.push_back(make_pair(address, txout.nValue));
if (pwallet->IsMine(txout))
listReceived.push_back(make_pair(address, txout.nValue));
}
}
void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
int64& nSent, int64& nFee) const
{
nGenerated = nReceived = nSent = nFee = 0;
int64 allGeneratedImmature, allGeneratedMature, allFee;
allGeneratedImmature = allGeneratedMature = allFee = 0;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
if (strAccount == "")
nGenerated = allGeneratedMature;
if (strAccount == strSentAccount)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
nSent += s.second;
nFee = allFee;
}
{
LOCK(pwallet->cs_wallet);
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
{
if (pwallet->mapAddressBook.count(r.first))
{
map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
nReceived += r.second;
}
else if (strAccount.empty())
{
nReceived += r.second;
}
}
}
}
void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
{
vtxPrev.clear();
const int COPY_DEPTH = 3;
if (SetMerkleBranch() < COPY_DEPTH)
{
vector<uint256> vWorkQueue;
BOOST_FOREACH(const CTxIn& txin, vin)
vWorkQueue.push_back(txin.prevout.hash);
// This critsect is OK because txdb is already open
{
LOCK(pwallet->cs_wallet);
map<uint256, const CMerkleTx*> mapWalletPrev;
set<uint256> setAlreadyDone;
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hash = vWorkQueue[i];
if (setAlreadyDone.count(hash))
continue;
setAlreadyDone.insert(hash);
CMerkleTx tx;
map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
if (mi != pwallet->mapWallet.end())
{
tx = (*mi).second;
BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
}
else if (mapWalletPrev.count(hash))
{
tx = *mapWalletPrev[hash];
}
else if (!fClient && txdb.ReadDiskTx(hash, tx))
{
;
}
else
{
printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
continue;
}
int nDepth = tx.SetMerkleBranch();
vtxPrev.push_back(tx);
if (nDepth < COPY_DEPTH)
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
vWorkQueue.push_back(txin.prevout.hash);
}
}
}
}
reverse(vtxPrev.begin(), vtxPrev.end());
}
bool CWalletTx::WriteToDisk()
{
return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
}
// Scan the block chain (starting in pindexStart) for transactions
// from or to us. If fUpdate is true, found transactions that already
// exist in the wallet will be updated.
int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
{
int ret = 0;
CBlockIndex* pindex = pindexStart;
{
LOCK(cs_wallet);
while (pindex)
{
CBlock block;
block.ReadFromDisk(pindex, true);
BOOST_FOREACH(CTransaction& tx, block.vtx)
{
if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
ret++;
}
pindex = pindex->pnext;
}
}
return ret;
}
int CWallet::ScanForWalletTransaction(const uint256& hashTx)
{
CTransaction tx;
tx.ReadFromDisk(COutPoint(hashTx, 0));
if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
return 1;
return 0;
}
void CWallet::ReacceptWalletTransactions()
{
CTxDB txdb("r");
bool fRepeat = true;
while (fRepeat)
{
LOCK(cs_wallet);
fRepeat = false;
vector<CDiskTxPos> vMissingTx;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
if (wtx.IsCoinBase() && wtx.IsSpent(0))
continue;
CTxIndex txindex;
bool fUpdated = false;
if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
{
// Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
if (txindex.vSpent.size() != wtx.vout.size())
{
printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
continue;
}
for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
{
if (wtx.IsSpent(i))
continue;
if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
{
wtx.MarkSpent(i);
fUpdated = true;
vMissingTx.push_back(txindex.vSpent[i]);
}
}
if (fUpdated)
{
printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
wtx.MarkDirty();
wtx.WriteToDisk();
}
}
else
{
// Reaccept any txes of ours that aren't already in a block
if (!wtx.IsCoinBase())
wtx.AcceptWalletTransaction(txdb, false);
}
}
if (!vMissingTx.empty())
{
// TODO: optimize this to scan just part of the block chain?
if (ScanForWalletTransactions(pindexGenesisBlock))
fRepeat = true; // Found missing transactions: re-do Reaccept.
}
}
}
void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
{
BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
{
if (!tx.IsCoinBase())
{
uint256 hash = tx.GetHash();
if (!txdb.ContainsTx(hash))
RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
}
}
if (!IsCoinBase())
{
uint256 hash = GetHash();
if (!txdb.ContainsTx(hash))
{
printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
}
}
}
void CWalletTx::RelayWalletTransaction()
{
CTxDB txdb("r");
RelayWalletTransaction(txdb);
}
void CWallet::ResendWalletTransactions()
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
static int64 nNextTime;
if (GetTime() < nNextTime)
return;
bool fFirst = (nNextTime == 0);
nNextTime = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
static int64 nLastTime;
if (nTimeBestReceived < nLastTime)
return;
nLastTime = GetTime();
// Rebroadcast any of our txes that aren't in a block yet
printf("ResendWalletTransactions()\n");
CTxDB txdb("r");
{
LOCK(cs_wallet);
// Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast until it's had plenty of time that
// it should have gotten in already by now.
if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
}
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{
CWalletTx& wtx = *item.second;
wtx.RelayWalletTransaction(txdb);
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Actions
//
int64 CWallet::GetBalance() const
{
int64 nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsFinal() && pcoin->IsConfirmed())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
int64 CWallet::GetUnconfirmedBalance() const
{
int64 nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
int64 CWallet::GetImmatureBalance() const
{
int64 nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx& pcoin = (*it).second;
if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.GetDepthInMainChain() >= 2)
nTotal += GetCredit(pcoin);
}
}
return nTotal;
}
// populate vCoins with vector of spendable COutputs
void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
{
vCoins.clear();
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsFinal())
continue;
if (fOnlyConfirmed && !pcoin->IsConfirmed())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
// If output is less than minimum value, then don't include transaction.
// This is to help deal with dust spam clogging up create transactions.
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
}
}
}
static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
vector<char>& vfBest, int64& nBest, int iterations = 1000)
{
vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
int64 nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < vValue.size(); i++)
{
if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
{
nTotal += vValue[i].first;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].first;
vfIncluded[i] = false;
}
}
}
}
}
}
bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
coinLowestLarger.first = std::numeric_limits<int64>::max();
coinLowestLarger.second.first = NULL;
vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
int64 nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
BOOST_FOREACH(COutput output, vCoins)
{
const CWalletTx *pcoin = output.tx;
if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
continue;
int i = output.i;
int64 n = pcoin->vout[i].nValue;
pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
if (n == nTargetValue)
{
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
return true;
}
else if (n < nTargetValue + CENT)
{
vValue.push_back(coin);
nTotalLower += n;
}
else if (n < coinLowestLarger.first)
{
coinLowestLarger = coin;
}
}
if (nTotalLower == nTargetValue)
{
for (unsigned int i = 0; i < vValue.size(); ++i)
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
return true;
}
if (nTotalLower < nTargetValue)
{
if (coinLowestLarger.second.first == NULL)
return false;
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
return true;
}
// Solve subset sum by stochastic approximation
sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
vector<char> vfBest;
int64 nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger.second.first &&
((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
{
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
}
else {
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
//// debug print
printf("SelectCoins() best subset: ");
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
printf("%s ", FormatMoney(vValue[i].first).c_str());
printf("total %s\n", FormatMoney(nBest).c_str());
}
return true;
}
bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
{
vector<COutput> vCoins;
AvailableCoins(vCoins);
return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet));
}
bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment)
{
int64 nValue = 0;
BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
{
if (nValue < 0)
return false;
nValue += s.second;
}
if (vecSend.empty() || nValue < 0)
return false;
wtxNew.BindWallet(this);
// transaction comment
wtxNew.strTxComment = strTxComment;
if (wtxNew.strTxComment.length() > MAX_TX_COMMENT_LEN_V2)
wtxNew.strTxComment.resize(MAX_TX_COMMENT_LEN_V2);
{
LOCK2(cs_main, cs_wallet);
// txdb must be opened before the mapWallet lock
CTxDB txdb("r");
{
nFeeRet = nTransactionFee;
loop
{
wtxNew.vin.clear();
wtxNew.vout.clear();
wtxNew.fFromMe = true;
int64 nTotalValue = nValue + nFeeRet;
double dPriority = 0;
// vouts to the payees
BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
wtxNew.vout.push_back(CTxOut(s.second, s.first));
// Choose coins to use
set<pair<const CWalletTx*,unsigned int> > setCoins;
int64 nValueIn = 0;
if (!SelectCoins(nTotalValue, setCoins, nValueIn))
return false;
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
{
int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
}
int64 nChange = nValueIn - nValue - nFeeRet;
// if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
// or until nChange becomes zero
// NOTE: this depends on the exact behaviour of GetMinFee
if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
{
int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
nChange -= nMoveToFee;
nFeeRet += nMoveToFee;
}
if (nChange > 0)
{
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
CPubKey vchPubKey = reservekey.GetReservedKey();
// assert(mapKeys.count(vchPubKey));
// Fill a vout to ourself
// TODO: pass in scriptChange instead of reservekey so
// change transaction isn't always pay-to-bitcoin-address
CScript scriptChange;
scriptChange.SetDestination(vchPubKey.GetID());
// Insert change txn at random position:
vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
}
else
reservekey.ReturnKey();
// Fill vin
BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
// Sign
int nIn = 0;
BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
return false;
// Limit size
unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
return false;
dPriority /= nBytes;
// Check that enough fee is included
int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
bool fAllowFree = CTransaction::AllowFree(dPriority);
int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
if (nFeeRet < max(nPayFee, nMinFee))
{
nFeeRet = max(nPayFee, nMinFee);
continue;
}
// Fill vtxPrev by copying from previous transactions vtxPrev
wtxNew.AddSupportingTransactions(txdb);
wtxNew.fTimeReceivedIsTxTime = true;
break;
}
}
}
return true;
}
bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment)
{
vector< pair<CScript, int64> > vecSend;
vecSend.push_back(make_pair(scriptPubKey, nValue));
return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strTxComment);
}
// Call after CreateTransaction unless you want to abort
bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
{
{
LOCK2(cs_main, cs_wallet);
printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
{
// This is only to keep the database open to defeat the auto-flush for the
// duration of this scope. This is the only place where this optimization
// maybe makes sense; please don't do it anywhere else.
CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
// Take key pair from key pool so it won't be used again
reservekey.KeepKey();
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew);
// Mark old coins as spent
set<CWalletTx*> setCoins;
BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
{
CWalletTx &coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
coin.MarkSpent(txin.prevout.n);
coin.WriteToDisk();
NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
}
if (fFileBacked)
delete pwalletdb;
}
// Track how many getdata requests our transaction gets
mapRequestCount[wtxNew.GetHash()] = 0;
// Broadcast
if (!wtxNew.AcceptToMemoryPool())
{
// This must not fail. The transaction has already been signed and recorded.
printf("CommitTransaction() : Error: Transaction not valid");
return false;
}
wtxNew.RelayWalletTransaction();
}
return true;
}
string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment)
{
CReserveKey reservekey(this);
int64 nFeeRequired;
if (IsLocked())
{
string strError = _("Error: Wallet locked, unable to create transaction ");
printf("SendMoney() : %s", strError.c_str());
return strError;
}
if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strTxComment))
{
string strError;
if (nValue + nFeeRequired > GetBalance())
strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
else
strError = _("Error: Transaction creation failed ");
printf("SendMoney() : %s", strError.c_str());
return strError;
}
if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
return "ABORTED";
if (!CommitTransaction(wtxNew, reservekey))
return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
return "";
}
string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment)
{
// Check amount
if (nValue <= 0)
return _("Invalid amount");
if (nValue + nTransactionFee > GetBalance())
return _("Insufficient funds");
// Parse Bitcoin address
CScript scriptPubKey;
scriptPubKey.SetDestination(address);
return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee, strTxComment);
}
int CWallet::LoadWallet(bool& fFirstRunRet)
{
if (!fFileBacked)
return false;
fFirstRunRet = false;
int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE)
{
if (CDB::Rewrite(strWalletFile, "\x04pool"))
{
setKeyPool.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// the requires a new key.
}
nLoadWalletRet = DB_NEED_REWRITE;
}
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
fFirstRunRet = !vchDefaultKey.IsValid();
CreateThread(ThreadFlushWalletDB, &strWalletFile);
return DB_LOAD_OK;
}
bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
{
std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
mapAddressBook[address] = strName;
NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
if (!fFileBacked)
return false;
return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
}
bool CWallet::DelAddressBookName(const CTxDestination& address)
{
mapAddressBook.erase(address);
NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
if (!fFileBacked)
return false;
return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
}
void CWallet::PrintWallet(const CBlock& block)
{
{
LOCK(cs_wallet);
if (mapWallet.count(block.vtx[0].GetHash()))
{
CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
}
}
printf("\n");
}
bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end())
{
wtx = (*mi).second;
return true;
}
}
return false;
}
bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
{
if (fFileBacked)
{
if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
return false;
}
vchDefaultKey = vchPubKey;
return true;
}
bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
{
if (!pwallet->fFileBacked)
return false;
strWalletFileOut = pwallet->strWalletFile;
return true;
}
//
// Mark old keypool keys as used,
// and generate all new keys
//
bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
CWalletDB walletdb(strWalletFile);
BOOST_FOREACH(int64 nIndex, setKeyPool)
walletdb.ErasePool(nIndex);
setKeyPool.clear();
if (IsLocked())
return false;
int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
for (int i = 0; i < nKeys; i++)
{
int64 nIndex = i+1;
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
setKeyPool.insert(nIndex);
}
printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
}
return true;
}
bool CWallet::TopUpKeyPool()
{
{
LOCK(cs_wallet);
if (IsLocked())
return false;
CWalletDB walletdb(strWalletFile);
// Top up key pool
unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
while (setKeyPool.size() < (nTargetSize + 1))
{
int64 nEnd = 1;
if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1;
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error("TopUpKeyPool() : writing generated key failed");
setKeyPool.insert(nEnd);
printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
}
}
return true;
}
void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
{
nIndex = -1;
keypool.vchPubKey = CPubKey();
{
LOCK(cs_wallet);
if (!IsLocked())
TopUpKeyPool();
// Get the oldest key
if(setKeyPool.empty())
return;
CWalletDB walletdb(strWalletFile);
nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error("ReserveKeyFromKeyPool() : read failed");
if (!HaveKey(keypool.vchPubKey.GetID()))
throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
assert(keypool.vchPubKey.IsValid());
printf("keypool reserve %"PRI64d"\n", nIndex);
}
}
int64 CWallet::AddReserveKey(const CKeyPool& keypool)
{
{
LOCK2(cs_main, cs_wallet);
CWalletDB walletdb(strWalletFile);
int64 nIndex = 1 + *(--setKeyPool.end());
if (!walletdb.WritePool(nIndex, keypool))
throw runtime_error("AddReserveKey() : writing added key failed");
setKeyPool.insert(nIndex);
return nIndex;
}
return -1;
}
void CWallet::KeepKey(int64 nIndex)
{
// Remove from key pool
if (fFileBacked)
{
CWalletDB walletdb(strWalletFile);
walletdb.ErasePool(nIndex);
}
printf("keypool keep %"PRI64d"\n", nIndex);
}
void CWallet::ReturnKey(int64 nIndex)
{
// Return to key pool
{
LOCK(cs_wallet);
setKeyPool.insert(nIndex);
}
printf("keypool return %"PRI64d"\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
{
int64 nIndex = 0;
CKeyPool keypool;
{
LOCK(cs_wallet);
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1)
{
if (fAllowReuse && vchDefaultKey.IsValid())
{
result = vchDefaultKey;
return true;
}
if (IsLocked()) return false;
result = GenerateNewKey();
return true;
}
KeepKey(nIndex);
result = keypool.vchPubKey;
}
return true;
}
int64 CWallet::GetOldestKeyPoolTime()
{
int64 nIndex = 0;
CKeyPool keypool;
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1)
return GetTime();
ReturnKey(nIndex);
return keypool.nTime;
}
CPubKey CReserveKey::GetReservedKey()
{
if (nIndex == -1)
{
CKeyPool keypool;
pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex != -1)
vchPubKey = keypool.vchPubKey;
else
{
printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
vchPubKey = pwallet->vchDefaultKey;
}
}
assert(vchPubKey.IsValid());
return vchPubKey;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1)
pwallet->ReturnKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress)
{
setAddress.clear();
CWalletDB walletdb(strWalletFile);
LOCK2(cs_main, cs_wallet);
BOOST_FOREACH(const int64& id, setKeyPool)
{
CKeyPool keypool;
if (!walletdb.ReadPool(id, keypool))
throw runtime_error("GetAllReserveKeyHashes() : read failed");
assert(keypool.vchPubKey.IsValid());
CKeyID keyID = keypool.vchPubKey.GetID();
if (!HaveKey(keyID))
throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
setAddress.insert(keyID);
}
}
void CWallet::UpdatedTransaction(const uint256 &hashTx)
{
{
LOCK(cs_wallet);
// Only notify UI if this transaction is in this wallet
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end())
NotifyTransactionChanged(this, hashTx, CT_UPDATED);
}
}
| mit |
abbr/ShowPreper | src/components/overview/handouts.js | 1851 | import React from 'react'
import './handouts.less'
import _ from 'lodash'
import { langs } from 'i18n/lang'
var DisplayableComponent = require('components/widgets/displayableComponent')
module.exports = class extends React.Component {
updateNotes = (index, markUndoDesc, e) => {
this.props.onSelectedWidgetUpdated(
{
container: this.props.deck,
index: index
},
{ notes: e.target.value },
markUndoDesc
)
}
render() {
let deckView = this.props.deck.components.map((e, index) => {
let component = _.cloneDeep(e)
if (e.type === 'Slide') {
let bb = this.props.deck.getSlideBoundingBox(e)
// don't transform slides
delete component.x
delete component.y
delete component.z
delete component.scale
delete component.rotate
delete component.skew
component.width = bb.right - bb.left
component.height = bb.bottom - bb.top
}
return (
<div key={index} className="row">
<DisplayableComponent
ownClassName="slide col-xs-1"
component={component}
componentStyle={
component.style || this.props.deck.defaultSlideStyle || {}
}
container={this.props.deck}
idx={index}
ref={index}
combinedTransform={true}
/>
<div className="col-xs-1">
{langs[this.props.language].notes}:
<textarea
value={component.notes}
onBlur={this.updateNotes.bind(null, index, 'notes')}
onChange={this.updateNotes.bind(null, index, null)}
/>
</div>
</div>
)
})
return (
<div className="sp-handouts sp-overview container-fluid">
{deckView}
</div>
)
}
}
| mit |
hrist0stoichev/Telerik-Exams | DataBasesExam2014/Solution/CarsStore/CarsStore/CarsStore.Models/Properties/AssemblyInfo.cs | 1408 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CarsStore.Models")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CarsStore.Models")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7a838c15-9378-4c72-b46c-b81cbda89f6d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
JoeFu/mseproject | Website/demo/backend/ServiceTest.php | 10500 | <!-- This is Test file to test the backend services. -->
<?php
/** APIs is for new DashBoard, Simple Query and Report System **/
session_start();
/** AService is supporting APIs **/
// Load Activity Numbers function
class testService
{
function testLoadActivityNumber()
{
include_once('one_connection.php');
$sql = "SELECT count(*) FROM studentdata.event;";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
$res = $result[0];
if ($res <1000)
{
return $res;
}
elseif($res>1000 && $res < 1000000)
{
return (round($res/1000)) ." K";
}
else{
return (round($res/1000000)) ." M";
}
mysql_close($link);
}
// Load Students Numbers function
function testLoadStudentsNumber()
{
include_once('one_connection.php');
$sql = "select count(*) from event where FKUserId";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
return $result[0];
mysql_close($link);
}
//Load Load Courses Numbers function
function testLoadCoursesNumber()
{
include_once('one_connection.php');
$sql = "select count(DISTINCT CourseName) from event";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
return $result[0];
mysql_close($link);
}
function testLoadCoursesDetail()
{
//Load course name for the first drop down box
include_once('one_connection.php');
$sql = "SELECT distinct `CourseName` from event
where CourseName is not NULL";
$query = mysql_query($sql);
while($row=mysql_fetch_array($query)){
$arr[] = array(
'CourseName'=> $row['CourseName'],
);}
mysql_close($link);
return json_encode($arr);
}
function testpostName()
{
$username="";
if($_SESSION['username']!= NULL)
{
$html = '<i class="fa fa-user fa-fw"></i> ';
$username = $_SESSION['username'];
$str = $html .$username;
return $str;
}
else
{
$html = '<i class="fa fa-user fa-fw"></i> ';
$username ='<a href="../../login">Please Login</a>';
$str = $html .$username;
return $str;
}
}
function testName()
{
$username="";
if($_SESSION['username']!= NULL)
{
$username = $_SESSION['username'];
return $username;
}
else
{
$username ='<a href="../../login/">Please Login</a>';
return $username;
}
}
function testSearchTable($SelectCourseId="",$SelectYearId="",$SelectSemesterId="",$SelectAssignmentNameId="")
{
include('one_connection.php');
$sql = "SELECT FKUserId,CourseName,SchoolYear, Semester, AssignmentName, Name, Grade, Prefix
FROM event
where CourseName='{$SelectCourseId}' and SchoolYear= '{$SelectYearId}' and Semester='{$SelectSemesterId}'and AssignmentName='{$SelectAssignmentNameId}' and DataSourceType ='1'";
$query = mysql_query($sql);
while($row=mysql_fetch_array($query)){
$arr[] = array(
'FKUserId'=> $row['FKUserId'],
'CourseName'=> $row['CourseName'],
'SchoolYear'=> $row['SchoolYear'],
'Semester'=> $row['Semester'],
'AssignmentName'=> $row['AssignmentName'],
'Event Name'=> $row['Name'],
'Grade'=> $row['Grade'],
'Component'=> $row['Prefix'],
);
}
mysql_close();
return json_encode($arr);
}
function testSelectYear()
{
include('one_connection.php');
$sql = "SELECT distinct `SchoolYear` from event where SchoolYear is not NULL";
$query = mysql_query($sql);
while($row=mysql_fetch_array($query)){
$arr[] = array(
'SchoolYear'=> $row['SchoolYear'],
);}
mysql_close();
return json_encode($arr);
}
function testIndexCharts()
{
include('one_connection.php');
$sql = "SELECT SchoolYear, count(Name) from event group by SchoolYear ";
$query =mysql_query($sql);
while($row=mysql_fetch_array($query))
{
$arr[]= array(
'SchoolYear'=> $row['SchoolYear'],
'count'=>$row['count(Name)'],
);
}
mysql_close();
return json_encode($arr);
}
}// End-TestClass
//test Starts Here
function testLoadActivityNumber()
{
require_once('Service.php');
//require_once('APIs.php');
include_once('one_connection.php');
$test_service = new testService;
$service = new APIService;
$test = $test_service->testLoadActivityNumber();
echo "<br>";
echo "-----------------------------";
echo "<br>";
if ($test == $service->LoadActivityNumber())
{
echo "PASS!";
}
else
{
echo "Fail!";
}
}
function testLoadStudentsNumber()
{
require_once('Service.php');
//require_once('APIs.php');
include_once('one_connection.php');
$test_service = new testService;
$service = new APIService;
$test = $test_service->testLoadStudentsNumber();
echo "<br>";
echo "-----------------------------";
echo "<br>";
if ($test == $service->LoadStudentsNumber())
{
echo "PASS!";
}
else
{
echo "Fail!";
}
}
function testLoadCoursesNumber()
{
require_once('Service.php');
//require_once('APIs.php');
include_once('one_connection.php');
$test_service = new testService;
$service = new APIService;
$test = $test_service->testLoadCoursesNumber();
echo "<br>";
echo "-----------------------------";
echo "<br>";
if ($test == $service->LoadCoursesNumber())
{
echo "PASS!";
}
else
{
echo "Fail!";
}
}
function testLoadCoursesDetail()
{
require_once('Service.php');
//require_once('APIs.php');
$test_service = new testService;
$service = new APIService;
$test = $test_service->testLoadCoursesDetail();
echo "<br>";
echo "-----------------------------";
echo "<br>";
if ($test == $service->LoadCoursesDetail())
{
echo "PASS!";
}
else
{
echo "Fail!";
}
}
function testpostName()
{
require_once('Service.php');
//require_once('APIs.php');
$test_service = new testService;
$service = new APIService;
$test = $test_service->testpostName();
echo "<br>";
echo "-----------------------------";
echo "<br>";
if ($test == $service->postName())
{
echo "PASS!";
}
else
{
echo "Fail!";
}
}
function testName()
{
require_once('Service.php');
//require_once('APIs.php');
$test_service = new testService;
$service = new APIService;
$test = $test_service->testName();
echo "<br>";
echo "-----------------------------";
echo "<br>";
if ($test == $service->Name())
{
echo "PASS!";
}
else
{
echo "Fail!";
}
}
function testSelectYear()
{
require_once('Service.php');
//require_once('APIs.php');
$test_service = new testService;
$service = new APIService;
$test = $test_service->testSelectYear();
echo "<br>";
echo "-----------------------------";
echo "<br>";
if ($test == $service->SelectYear())
{
echo "PASS!";
}
else
{
echo "Fail!";
}
}
function testSearchTable()
{
require_once('Service.php');
//require_once('APIs.php');
$test_service = new testService;
$service = new APIService;
$res = $service->SearchTable($SelectCourseId="MSE",$SelectYearId="2012",$SelectSemesterId="Semester 1",$SelectAssignmentId="Assignment 1");
$notexpect = null;
echo "<br>";
echo "-----------------------------";
echo "<br>";
if ($res !=$notexpect)
{
echo "PASS!";
}
else
{
echo "Fail!";
}
}
function testIndexCharts()
{
require_once('Service.php');
//require_once('APIs.php');
include_once('one_connection.php');
$test_service = new testService;
$service = new APIService;
$test = $test_service->testIndexCharts();
echo "<br>";
echo "-----------------------------";
echo "<br>";
if ($test == $service-> IndexCharts())
{
echo "PASS!";
}
else
{
echo "Fail!";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="Student activity analysis" content="behaviour">
<meta name="author" content="">
<title>Service Test Report</title>
</head>
<body>
<h1>This is Website backend php function test report</h1>
<p>/***** Test Enviroment ****/</p>
<p>System: Ubuntu 17.10 </p>
<p>DataBase: Mysql 5.7.20 </p>
<p>DataBase Schema : <a href ="https://github.com/JoeFu/mseproject/blob/master/Database/studentdata_%23207.sql"></a> studentdata_#207.sql</p>
<li>DataBase Connection Status</li>
<p>
<?php
include('one_connection.php');
$sql = "select version();";
$query =mysql_query($sql);
$row=mysql_fetch_array($query);
if ($row[0]!=null)
{
echo "<p style=\"color: green\"> Database connection normal </p>";
}
else
{
echo "<p style=\"color: red\"> Please check your database setup and connection !</p>";
}
?>
</p>
<li>
<?php
echo "LoadActivityNumber Test";
testLoadActivityNumber();
?>
</li>
<li>
<?php
echo "LoadStudentsNumber Test";
testLoadStudentsNumber();
?>
</li>
<li>
<?php
echo "LoadCoursesNumber Test";
testLoadCoursesNumber();
?>
</li>
<li>
<?php
echo "LoadCoursesDetail Test";
testLoadCoursesDetail();
?>
</li>
<li>
<?php
echo "postName Test";
testpostName();
?>
</li>
<li>
<?php
echo "Name Test";
testName();
?>
</li>
<li>
<?php
echo "SelectYear Test";
testSelectYear();
?>
</li>
<li>
<?php
echo "SearchTable Test";
testSearchTable();
?>
</li>
<li>
<?php
echo "IndexCharts Test";
testIndexCharts();
?>
</li>
</body> | mit |
JCube001/socketcan-demo | src/socketcan-raw-demo.cpp | 8308 | /*
The MIT License (MIT)
Copyright (c) 2015, 2016 Jacob McGladdery
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.
-------------------------------------------------------------------------------
Raw Interface Demo
This service demonstrates how to read CAN traffic using the SocketCAN Raw
interface. Specifically, this service shows how to read CAN FD frame, filter by
message ID, perform a blocking read, and process some hypothetical CAN
messages. The exact format of the CAN messages which this service will
recognize is given in the README file.
TODO: Specify the message formats in the README file.
*/
#include <linux/can.h>
#include <linux/can/raw.h>
#include <endian.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <thread>
#include <cerrno>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstring>
#define PROGNAME "socketcan-raw-demo"
#define VERSION "2.0.0"
namespace {
struct EngineFrame {
std::uint16_t rpm;
// TODO: Some more hypothetical data
};
struct VehicleFrame {
// TODO: Some hypothetical vehicle status measurements
};
struct BodyControllerFrame {
// TODO: Some hypothetical vehicle settings flags
};
std::sig_atomic_t signalValue;
void onSignal(int value) {
signalValue = static_cast<decltype(signalValue)>(value);
}
void usage() {
std::cout << "Usage: " PROGNAME " [-h] [-V] [-f] interface" << std::endl
<< "Options:" << std::endl
<< " -h Display this information" << std::endl
<< " -V Display version information" << std::endl
<< " -f Run in the foreground" << std::endl
<< std::endl;
}
void version() {
std::cout << PROGNAME " version " VERSION << std::endl
<< "Compiled on " __DATE__ ", " __TIME__ << std::endl
<< std::endl;
}
void processFrame(const struct canfd_frame& frame) {
switch (frame.can_id) {
case 0x0A0:
{
EngineFrame engine;
engine.rpm = be16toh(*(std::uint16_t *)(frame.data + 0));
std::cout << "RPM: " << engine.rpm << std::endl;
}
break;
case 0x110:
{
// TODO: Work!
// VehicleFrame vehicle;
std::cout << "Got 0x110" << std::endl; // XXX
}
break;
case 0x320:
{
// TODO: Work!
// BodyControllerFrame bodyController;
std::cout << "Got 0x320" << std::endl; // XXX
}
break;
default:
// Should never get here if the receive filters were set up correctly
std::cerr << "Unexpected CAN ID: 0x"
<< std::hex << std::uppercase
<< std::setw(3) << std::setfill('0')
<< frame.can_id << std::endl;
std::cerr.copyfmt(std::ios(nullptr));
break;
}
}
} // namespace
int main(int argc, char** argv) {
using namespace std::chrono_literals;
// Options
const char* interface;
bool foreground = false;
// Service variables
struct sigaction sa;
int rc;
// CAN connection variables
struct sockaddr_can addr;
struct ifreq ifr;
int sockfd;
// Parse command line arguments
{
int opt;
// Parse option flags
while ((opt = ::getopt(argc, argv, "Vfh")) != -1) {
switch (opt) {
case 'V':
version();
return EXIT_SUCCESS;
case 'f':
foreground = true;
break;
case 'h':
usage();
return EXIT_SUCCESS;
default:
usage();
return EXIT_FAILURE;
}
}
// Check for the one positional argument
if (optind != (argc - 1)) {
std::cerr << "Missing network interface option!" << std::endl;
usage();
return EXIT_FAILURE;
}
// Set the network interface to use
interface = argv[optind];
}
// Check if the service should be run as a daemon
if (!foreground) {
if (::daemon(0, 1) == -1) {
std::perror("daemon");
return EXIT_FAILURE;
}
}
// Register signal handlers
sa.sa_handler = onSignal;
::sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
::sigaction(SIGINT, &sa, nullptr);
::sigaction(SIGTERM, &sa, nullptr);
::sigaction(SIGQUIT, &sa, nullptr);
::sigaction(SIGHUP, &sa, nullptr);
// Initialize the signal value to zero
signalValue = 0;
// Open the CAN network interface
sockfd = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (-1 == sockfd) {
std::perror("socket");
goto errSocket;
}
// Set a receive filter so we only receive select CAN IDs
{
struct can_filter filter[3];
filter[0].can_id = 0x0A0;
filter[0].can_mask = CAN_SFF_MASK;
filter[1].can_id = 0x110;
filter[1].can_mask = CAN_SFF_MASK;
filter[2].can_id = 0x320;
filter[2].can_mask = CAN_SFF_MASK;
rc = ::setsockopt(
sockfd,
SOL_CAN_RAW,
CAN_RAW_FILTER,
&filter,
sizeof(filter)
);
if (-1 == rc) {
std::perror("setsockopt filter");
goto errSetup;
}
}
// Enable reception of CAN FD frames
{
int enable = 1;
rc = ::setsockopt(
sockfd,
SOL_CAN_RAW,
CAN_RAW_FD_FRAMES,
&enable,
sizeof(enable)
);
if (-1 == rc) {
std::perror("setsockopt CAN FD");
goto errSetup;
}
}
// Get the index of the network interface
std::strncpy(ifr.ifr_name, interface, IFNAMSIZ);
if (::ioctl(sockfd, SIOCGIFINDEX, &ifr) == -1) {
std::perror("ioctl");
goto errSetup;
}
// Bind the socket to the network interface
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
rc = ::bind(
sockfd,
reinterpret_cast<struct sockaddr*>(&addr),
sizeof(addr)
);
if (-1 == rc) {
std::perror("bind");
goto errSetup;
}
// Log that the service is up and running
std::cout << "Started" << std::endl;
// Main loop
while (0 == signalValue) {
struct canfd_frame frame;
// Read in a CAN frame
auto numBytes = ::read(sockfd, &frame, CANFD_MTU);
switch (numBytes) {
case CAN_MTU:
processFrame(frame);
break;
case CANFD_MTU:
// TODO: Should make an example for CAN FD
break;
case -1:
// Check the signal value on interrupt
if (EINTR == errno)
continue;
// Delay before continuing
std::perror("read");
std::this_thread::sleep_for(100ms);
default:
continue;
}
}
// Cleanup
if (::close(sockfd) == -1) {
std::perror("close");
return errno;
}
std::cout << std::endl << "Bye!" << std::endl;
return EXIT_SUCCESS;
// Error handling (reverse order cleanup)
errSetup:
::close(sockfd);
errSocket:
return errno;
}
| mit |
dangerozov/linqor | Linqor.Tests/SelectManyTests.cs | 2771 | using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using static Linqor.Tests.Helpers;
namespace Linqor.Tests
{
[TestFixture]
public class SelectManyTests
{
[TestCaseSource(nameof(GetTestCases))]
public string[] SelectMany(string[] source, string[][] selectorResult)
{
return Extensions
.SelectMany(
source.AsOrderedBy(NumberInString),
new string[] { }.AsOrderedBy(NumberInString),
(item, index) => selectorResult[index].AsOrderedBy(NumberInString))
.ToArray();
}
private static IEnumerable<TestCaseData> GetTestCases()
{
var testCases = new[]
{
(new string[] { }, Repeat(new string[] { }, 1), new string[] { }),
(new [] { "L0", "L1", "L2" }, Repeat(new string[] { }, 3), new string[] { }),
(new string[] { }, Repeat(new [] { "R0", "R1", "R2" }, 1), new string[] { }),
(new [] { "L0", "L1" }, new[] { new[] { "R0", "R2" }, new[] { "R1", "R3" } }, new[] { "R0", "R1", "R2", "R3" })
};
var linqTestCases = testCases
.Select(c => (c.Item1, c.Item2, Enumerable
.SelectMany(c.Item1, (item, index) => c.Item2[index])
.OrderBy(NumberInString)
.ToArray()));
return testCases.Concat(linqTestCases)
.Select((c, index) => new TestCaseData(c.Item1, c.Item2)
.Returns(c.Item3)
.SetName($"SelectMany {Helpers.Get2DID(index, testCases.Length)}"));
}
[TestCaseSource(nameof(GetErrorCases))]
public void SelectManyError(string[] source, string[][] selectorResult)
{
var result = Extensions
.SelectMany(
source.AsOrderedBy(NumberInString),
new string[] { }.AsOrderedBy(NumberInString),
(item, index) => selectorResult[index].AsOrderedBy(NumberInString));
Assert.That(() => result.ToArray(), Throws.TypeOf<UnorderedElementDetectedException>());
}
private static IEnumerable<TestCaseData> GetErrorCases()
{
var exceptionTestCases = new[]
{
(new[] { "L0", "L1" }, new[] { new[] { "R1", "R0" }, new[] { "R1", "R2" } }),
(new[] { "L0", "L1" }, new[] { new[] { "R0", "R1" }, new[] { "R2", "R1" } }),
(new[] { "L1", "L0" }, new[] { new[] { "R0", "R1" }, new[] { "R1", "R2" } }),
};
return exceptionTestCases
.Select(c => new TestCaseData(c.Item1, c.Item2));
}
}
} | mit |
roshankulkarni/springbaseline | src/main/java/com/mindstix/sample/controller/SampleController.java | 940 | /**
* Released under the Creative Commons License.
*/
package com.mindstix.sample.controller;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
/**
* Sample MVC controller.
*
* @author: Roshan Kulkarni
*/
@Controller
@RequestMapping("/user")
public class SampleController {
// Get log4j handler
private static final Logger logger = Logger.getLogger(SampleController.class);
// Controller Action
@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
// Some business logic here
logger.error("Testing Log Message");
// Render a view
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
}
| mit |
AlexMAS/GostCryptography | Source/GostCryptography/Native/ISafeHandleProvider.cs | 962 | using System.Runtime.InteropServices;
using System.Security;
namespace GostCryptography.Native
{
/// <summary>
/// Провайдер дескрипторов криптографического объекта.
/// </summary>
/// <typeparam name="T">Тип безопасного дескриптора.</typeparam>
public interface ISafeHandleProvider<out T> where T : SafeHandle
{
/// <summary>
/// Возвращает дескриптор объекта.
/// </summary>
T SafeHandle { [SecurityCritical] get; }
}
/// <summary>
/// Методы расширения для <see cref="ISafeHandleProvider{T}"/>.
/// </summary>
public static class SafeHandleProviderExtensions
{
/// <summary>
/// Возвращает дескриптор объекта.
/// </summary>
[SecurityCritical]
public static T GetSafeHandle<T>(this ISafeHandleProvider<T> provider) where T : SafeHandle
{
return provider.SafeHandle;
}
}
} | mit |
ustream/yolo | src/test/java/tv/ustream/yolo/config/ConfigPatternTest.java | 4247 | package tv.ustream.yolo.config;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* @author bandesz
*/
public class ConfigPatternTest
{
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void replacePatternsShouldReplacePatternStringsWithObjects() throws ConfigException
{
Map<String, Object> data = new HashMap<String, Object>();
data.put("key1", "simple string");
data.put("key2", 5);
data.put("key3", "string with #param#");
data.put("key4", Arrays.<Object>asList("s1", "s1 #param#"));
ConfigPattern.replacePatterns(data, null);
Assert.assertEquals("simple string", data.get("key1"));
Assert.assertEquals(5, data.get("key2"));
Assert.assertEquals(new ConfigPattern("string with #param#"), data.get("key3"));
Assert.assertEquals(Arrays.<Object>asList("s1", new ConfigPattern("s1 #param#")), data.get("key4"));
}
@Test
public void replacePatternsShouldAllowValidKey() throws ConfigException
{
Map<String, Object> data = new HashMap<String, Object>();
data.put("key1", "string with #param#");
ConfigPattern.replacePatterns(data, Arrays.<String>asList("param"));
Assert.assertEquals(new ConfigPattern("string with #param#"), data.get("key1"));
}
@Test
public void replacePatternsShouldAllowGlobalKey() throws ConfigException
{
Map<String, Object> data = new HashMap<String, Object>();
data.put("key1", "string with #GLOBAL_PARAM#");
ConfigPattern.addGlobalParameter("GLOBAL_PARAM", "value");
ConfigPattern.replacePatterns(data, Arrays.<String>asList("param"));
Assert.assertEquals(new ConfigPattern("string with #GLOBAL_PARAM#"), data.get("key1"));
}
@Test
public void replacePatternsShouldThrowExceptionWhenKeyIsInvalid() throws ConfigException
{
thrown.expect(ConfigException.class);
Map<String, Object> data = new HashMap<String, Object>();
data.put("key1", "simple string");
data.put("key2", 5);
data.put("key3", "string with #param#");
data.put("key4", Arrays.<Object>asList("s1", "s1 #param#"));
ConfigPattern.replacePatterns(data, Arrays.<String>asList("paramOther"));
Assert.assertEquals("simple string", data.get("key1"));
Assert.assertEquals(5, data.get("key2"));
Assert.assertEquals(new ConfigPattern("string with #param#"), data.get("key3"));
Assert.assertEquals(Arrays.<Object>asList("s1", new ConfigPattern("s1 #param#")), data.get("key4"));
}
@Test
public void applyValuesShouldReplaceParameters()
{
ConfigPattern pattern = new ConfigPattern("text #p1# text #p2# text");
Map<String, Object> params = new HashMap<String, Object>();
params.put("p1", "v1");
params.put("p2", "v2");
String actual = pattern.applyValues(params);
Assert.assertEquals("text v1 text v2 text", actual);
}
@Test
public void applyValuesShouldReturnNullWhenParamsMissing()
{
ConfigPattern pattern = new ConfigPattern("text #p1# text #p2# text #p3# text");
Map<String, Object> params = new HashMap<String, Object>();
params.put("p1", "v1");
params.put("p2", "v2");
String actual = pattern.applyValues(params);
Assert.assertNull(actual);
}
@Test
public void applyValuesShouldReturnValueForSimplePattern()
{
ConfigPattern pattern = new ConfigPattern("#p1#");
Map<String, Object> params = new HashMap<String, Object>();
params.put("p1", "v1");
String actual = pattern.applyValues(params);
Assert.assertEquals("v1", actual);
}
@Test
public void applyValuesShouldReturnNullForSimplePatternWhenValueMissing()
{
ConfigPattern pattern = new ConfigPattern("#p1#");
Map<String, Object> params = new HashMap<String, Object>();
params.put("p2", "v1");
String actual = pattern.applyValues(params);
Assert.assertNull(actual);
}
}
| mit |
mrjoseph/react-redux-todo-app | src/todo-app/actions.js | 635 | const uid = () => Math.random().toString(34).slice(2);
export function addTodo(text) {
return {
type: 'ADD_TODO',
payload: {
id: uid(),
isDone: false,
text: text,
editable:false
}
};
}
export function toggleTodo(id) {
return {
type: 'TOGGLE_TODO',
payload: id
};
}
export function removeTodo(id){
return {
type : 'REMOVE_TODO',
payload : id
}
}
export function editTodo(id){
return {
type : 'EDIT_TODO',
payload : id
}
}
export function finishEditTodo(id,text){
return {
type : 'FINISH_EDIT_TODO',
payload : {
id : id,
text : text
}
}
}
| mit |
thesolarnomad/lora-serialization | test/helpers.cpp | 297 | void printByteArrayToHex(byte *arr) {
for(int i = 0; i < sizeof(arr); i++) {
printf("%02x", arr[i]);
}
printf("\n");
}
void compare_array(byte *arr1, byte *arr2, int start, int len) {
for(int i = start; i < start + len; i++) {
REQUIRE(arr1[i] == arr2[i]);
}
}
| mit |
ClifG/daily-fantasy-football | models/user.js | 493 | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
facebookId: String,
facebookToken: String,
// TODO: Make a publicProfile so we don't expose email address or anything else
// that may be sensitive to other users.
profile: {
name: String,
picture: String,
email: { type: String, lowercase: true }
},
isAdmin: Boolean
});
var User = mongoose.model('User', userSchema);
module.exports = User; | mit |
Alberdi/ancientest | src/country.py | 3817 | from element import Element
class Country():
def __init__(self):
self.area = None
self.element = None
def add_area(self, list_of_points):
if not self._check_inline(list_of_points):
self.area = Area(list_of_points, self)
def is_adjacent(self, other):
return self._intersects(other, False)
def is_enemy(self, other):
return self._intersects(other, True)
def _intersects(self, other, include_borders):
if not self.area or not other.area:
return False
for point in self.area.points:
if other.area.point_inside(point):
return True
for point in other.area.points:
if self.area.point_inside(point):
return True
return self.area.intersects(other.area, include_borders)
def _check_inline(self, list_of_points):
if len(list_of_points) > 2:
before_point = None
before_incline = None
for point in list_of_points:
if before_point:
x = (before_point[0] - point[0])
incline = (before_point[1] - point[1])/x if x else 999999999999999999
if before_incline == None:
before_incline = incline
elif before_incline != incline:
return False
before_point = point
return True
def strength(self):
strength = 0
for resident in self.area.residents:
strength += resident.get_strength_to(self.element)
return strength
def change_element(self, new_element):
self.element = Element.getId(new_element)
def fight(self, enemy):
if self.is_enemy(enemy):
enemy_strength = enemy.strength()
for resident in self.area.residents:
(was_dead, new_strength) = resident.fight(enemy_strength, self.element)
if was_dead:
enemy_strength = new_strength
else:
return self
return self
else:
return None
class Area():
def __init__(self, points, country):
self.points = points
self.country = country
self.residents = []
def add_resident(self, resident):
for r in self.residents:
if r.element == resident.element:
return
self.residents.append(resident)
resident.add_residence(self)
def remove_resident(self, resident):
self.residents.remove(resident)
resident.remove_residence(self)
def intersects(self, other, include_borders):
p1 = self.points
p2 = other.points
for i in xrange(len(p1)):
for j in xrange(len(p2)):
if include_borders and p1[i-1] in [p2[j-1], p2[j]] or p1[i] in [p2[j-1], p2[j]]:
continue
if self._segment_intersect((p1[i-1], p1[i]), (p2[j-1], p2[j])):
return True
return False
def population(self):
return len(self.residents)
def point_inside(self, point):
intersections = 0
prev_vertex = self.points[len(self.points)-1]
for vertex in self.points:
if vertex[0] == point[0] and vertex[1] == point[1]:
return False
if prev_vertex[1] == vertex[1] and prev_vertex[1] == point[1] and point[0] > min(prev_vertex[0], vertex[0]) and point[0] < max(prev_vertex[0], vertex[0]): #On a horizontal line
return False
if point[1] > min(prev_vertex[1], vertex[1]) and point[1] <= max(prev_vertex[1], vertex[1]) and point[0] < max(prev_vertex[0], vertex[0]) and prev_vertex[1] != vertex[1]:
xinters = (point[1] - prev_vertex[1]) * (vertex[0] - prev_vertex[0]) / (vertex[1] - prev_vertex[1]) + prev_vertex[0];
if xinters == point[0]: #On a line
return False
if prev_vertex[0] == vertex[0] or point[0] <= xinters:
intersections += 1
prev_vertex = vertex
if intersections % 2 != 0:
return True
return False
def _segment_intersect(self, s1, s2):
# ccw = counter clock wise, aka magic
# Check http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/
ccw = lambda p1, p2, p3: cmp((p3[1]-p1[1])*(p2[0]-p1[0]) - (p2[1]-p1[1])*(p3[0]-p1[0]), 0)
return ccw(s1[0], s1[1], s2[0]) != ccw(s1[0], s1[1], s2[1]) and \
ccw(s2[0], s2[1], s1[0]) != ccw(s2[0], s2[1], s1[1])
| mit |
cadyyan/levels | src/main/java/com/cadyyan/levels/Levels.java | 1876 | package com.cadyyan.levels;
import com.cadyyan.levels.commands.CommandLevel;
import com.cadyyan.levels.handlers.ConfigurationHandler;
import com.cadyyan.levels.proxies.IProxy;
import com.cadyyan.levels.registries.RecipeModificationRegistry;
import com.cadyyan.levels.utils.SerializationHelper;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
@SuppressWarnings("unused")
@Mod(modid = Levels.MOD_ID, name = Levels.NAME, version = Levels.VERSION, acceptedMinecraftVersions = "[1.8.9]")
public class Levels
{
public static final String MOD_ID = "levels";
public static final String NAME = "Levels";
public static final String VERSION = "@MOD_VERSION@";
@Instance(Levels.MOD_ID)
public static Levels instance;
@SidedProxy(
clientSide = "com.cadyyan.levels.proxies.CommonProxy",
serverSide = "com.cadyyan.levels.proxies.CommonProxy")
public static IProxy proxy;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
ConfigurationHandler.init(event.getSuggestedConfigurationFile());
}
@EventHandler
public void init(FMLInitializationEvent event)
{
proxy.registerEventHandlers();
proxy.registerSkills();
RecipeModificationRegistry.init();
}
@EventHandler
public void postInit(FMLPostInitializationEvent event)
{
proxy.dumpRecipes();
}
@EventHandler
public void onServerStarting(FMLServerStartingEvent event)
{
SerializationHelper.init();
event.registerServerCommand(new CommandLevel());
}
}
| mit |
hazzik/Maybe | src/Maybe/Maybe.Nullable.cs | 517 | namespace Hazzik.Maybe
{
using System;
using JetBrains.Annotations;
public partial class Maybe
{
[CanBeNull, ContractAnnotation("self:null=>null")]
public static TResult With<T, TResult>([CanBeNull] this T? self, [NotNull] Func<T, TResult> func)
where T : struct
{
if (func == null) throw new ArgumentNullException("func");
if (!self.HasValue) return default(TResult);
return func(self.GetValueOrDefault());
}
}
} | mit |
AlanBell/robopi | scratra.py | 6776 | # scratra ~ 0.3
# greatdane ~ easy python implementation with scratch
# inspired by sinatra(sinatrarb.com) ~ code snippets from scratch.py(bit.ly/scratchpy)
import socket
from errno import *
from array import array
import threading
# Errors from scratch.py
class ScratchConnectionError(Exception): pass
class ScratchNotConnected(ScratchConnectionError): pass
class ScratchConnectionRefused(ScratchConnectionError): pass
class ScratchConnectionEstablished(ScratchConnectionError): pass
class ScratchInvalidValue(Exception): pass
broadcast_map = {}
update_map = {}
start_list = []
end_list = []
scratchSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
runtime_quit = 0
scratchInterface = None
# Implementation for Scratch variables
class RemoteSensors:
sensor_values = {}
def __setitem__(self, sensor_name, value):
if isinstance(value, str):
v = Scratch.toScratchMessage('sensor-update "' + sensor_name +'" "'+value+'"')
self.sensor_valueues[sensor_name] = value
scratchSocket.send(v)
elif isinstance(value, int) or isinstance(value, float):
v = Scratch.toScratchMessage('sensor-update "' + sensor_name +'" ' + str(value))
self.sensor_valueues[sensor_name] = value
scratchSocket.send(v)
else:
raise ScratchInvalidValue(sensor_name + ': Incorrect attempted value')
def __getitem__(self, sensor_name):
return self.sensor_values[sensor_name]
# For general convenience, scratch interface
class Scratch:
# Variables interface
sensor = RemoteSensors()
var_values = {}
# Broadcast interface
def broadcast(self, *broadcasts):
for broadcast_name in broadcasts:
scratchSocket.send(self.toScratchMessage('broadcast "' + broadcast_name + '"'))
# Variable interface
def var(self, var_name):
return self.var_values[var_name]
@staticmethod
def toScratchMessage(cmd):
# Taken from chalkmarrow
n = len(cmd)
a = array('c')
a.append(chr((n >> 24) & 0xFF))
a.append(chr((n >> 16) & 0xFF))
a.append(chr((n >> 8) & 0xFF))
a.append(chr(n & 0xFF))
return a.tostring() + cmd
@staticmethod
def atom(msg):
try:
return int(msg)
except:
try:
return float(msg)
except:
return msg.strip('"')
def run(host='localhost', poll=True, msg="Scratra -> Connected\n-> 'stop' to quit", console=True):
runClass(host, poll, msg, console).start()
# actual threading process
class runClass(threading.Thread):
def __init__(self, host, poll, msg, console):
self.host = host
self.poll = poll
self.msg = msg
self.console = console
threading.Thread.__init__(self)
def run(self):
host = self.host
poll = self.poll
port = 42001
console = self.console
while 1:
try: scratchSocket.connect((host, port))
# Except series from scratch.py
except socket.error as error:
(err, msge) = error
if err == EISCONN:
raise ScratchConnectionEstablished('Already connected to Scratch')
elif poll == True:
continue
elif err == ECONNREFUSED:
raise ScratchConnectionRefused('Connection refused, try enabling remote sensor connections')
else:
raise ScratchConnectionError(msge)
scratchInterface = Scratch()
break
if console:
run_console(self.msg).start()
for func in start_list:
func(scratchInterface)
while not runtime_quit:
scratchSocket.settimeout(3)
try:
msg = scratchSocket.recv(1024)
except socket.timeout:
msg = ''#timeouts just mean we listen again, if we never timeout then we can hang whilst shutting down
except socket.error as (errno, message):
raise ScratchConnectionError(errno, message)
if msg:
# If the message is not a sensor-update, but a broadcast
if msg.find('sensor-update')==-1 and 'broadcast' in msg:
msg = msg[15:-1]
if msg in broadcast_map:
for func in broadcast_map[msg]:
func(scratchInterface)
# Otherwise, it must be a sensor-update
else:
msg = msg[4:]
if 'sensor-update' in msg:
msg = msg.split()[1:]
i = 0
while i < len(msg)-1:
if scratchInterface.atom(msg[i]) in update_map:
scratchInterface.var_values[scratchInterface.atom(msg[i])] = scratchInterface.atom(msg[i+1])
for func in update_map[scratchInterface.atom(msg[i])]:
func(scratchInterface, scratchInterface.atom(msg[i+1]))
i+=2
class run_console(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run(self):
global runtime_quit
print self.msg
while not runtime_quit:
cmd = raw_input('-> ')
if cmd == 'stop':
runtime_quit = 1
print '-> Quitting'
for func in end_list:
func(scratchInterface)
# For user convenience, decorator methods
# When Scratch broadcasts this...
# @broadcast('scratch_broadcast')
# def func(scratch): ....
class broadcast:
def __init__(self, broadcast):
self.b = broadcast
def __call__(self, func):
if self.b in broadcast_map:
broadcast_map[self.b].append(func)
else:
broadcast_map[self.b] = [func]
# When this variable is updated...
# @update('variable')
# def func(scratch, value): ...
class update:
def __init__(self, update):
self.u = update
def __call__(self, func):
if self.u in update_map:
update_map[self.u].append(func)
else:
update_map[self.u] = [func]
# When we start listening...
# @start
# def func(scratch): ...
def start(func):
if func not in start_list:
start_list.append(func)
# When we stop listening
# @end
# def func(scratch): ...
def end(func):
if func not in end_list:
end_list.append(func)
| mit |
Innmind/TimeContinuum | tests/Earth/Timezone/Asia/BruneiTest.php | 376 | <?php
declare(strict_types = 1);
namespace Tests\Innmind\TimeContinuum\Earth\Timezone\Asia;
use Innmind\TimeContinuum\{
Earth\Timezone\Asia\Brunei,
Timezone,
};
use PHPUnit\Framework\TestCase;
class BruneiTest extends TestCase
{
public function testInterface()
{
$zone = new Brunei;
$this->assertInstanceOf(Timezone::class, $zone);
}
}
| mit |
DBooots/ReCoupler | ReCoupler/AbstractJointTracker.cs | 2023 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReCoupler
{
public abstract class AbstractJointTracker
{
public List<Part> parts;
public List<AttachNode> nodes;
protected bool[] structNodeMan = new bool[2] { false, false };
public AbstractJointTracker(AttachNode parentNode, AttachNode childNode)
{
this.nodes = new List<AttachNode> { parentNode, childNode };
this.parts = new List<Part> { nodes[0].owner, nodes[1].owner };
}
public virtual void SetNodes()
{
nodes[0].attachedPart = parts[1];
nodes[1].attachedPart = parts[0];
}
public virtual void Destroy()
{
if (nodes[0] != null)
nodes[0].attachedPart = null;
if (nodes[1] != null)
nodes[1].attachedPart = null;
}
protected static bool SetModuleStructuralNode(AttachNode node)
{
bool structNodeMan = false;
ModuleStructuralNode structuralNode = node.owner.FindModulesImplementing<ModuleStructuralNode>().FirstOrDefault(msn => msn.attachNodeNames.Equals(node.id));
if (structuralNode != null)
{
structNodeMan = structuralNode.spawnManually;
structuralNode.spawnManually = true;
structuralNode.SpawnStructure();
}
return structNodeMan;
}
protected static void UnsetModuleStructuralNode(AttachNode node, bool structNodeMan)
{
if (node == null)
return;
ModuleStructuralNode structuralNode = node.owner.FindModulesImplementing<ModuleStructuralNode>().FirstOrDefault(msn => msn.attachNodeNames.Equals(node.id));
if (structuralNode != null)
{
structuralNode.DespawnStructure();
structuralNode.spawnManually = structNodeMan;
}
}
}
}
| mit |
codeflo/cubehack | source/CubeHack.Core/Util/GameDuration.cs | 2567 | // Copyright (c) the CubeHack authors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt in the project root.
using ProtoBuf;
namespace CubeHack.Util
{
/// <summary>
/// Represents a duration (or time span) between two <see cref="GameTime"/> instances.
/// </summary>
[ProtoContract]
public struct GameDuration
{
public static readonly GameDuration Zero = default(GameDuration);
public GameDuration(double seconds)
{
Seconds = seconds;
}
[ProtoMember(1)]
public double Seconds { get; set; }
public static GameDuration operator +(GameDuration a, GameDuration b)
{
return new GameDuration(a.Seconds + b.Seconds);
}
public static GameDuration operator -(GameDuration a, GameDuration b)
{
return new GameDuration(a.Seconds - b.Seconds);
}
public static GameDuration operator *(GameDuration a, double f)
{
return new GameDuration(a.Seconds * f);
}
public static GameDuration operator *(double f, GameDuration a)
{
return new GameDuration(f * a.Seconds);
}
public static GameDuration operator /(GameDuration a, double f)
{
return new GameDuration(a.Seconds / f);
}
public static bool operator ==(GameDuration a, GameDuration b)
{
return a.Seconds == b.Seconds;
}
public static bool operator !=(GameDuration a, GameDuration b)
{
return a.Seconds != b.Seconds;
}
public static bool operator >(GameDuration a, GameDuration b)
{
return a.Seconds > b.Seconds;
}
public static bool operator >=(GameDuration a, GameDuration b)
{
return a.Seconds >= b.Seconds;
}
public static bool operator <(GameDuration a, GameDuration b)
{
return a.Seconds < b.Seconds;
}
public static bool operator <=(GameDuration a, GameDuration b)
{
return a.Seconds <= b.Seconds;
}
public static GameDuration FromSeconds(double seconds)
{
return new GameDuration(seconds);
}
public override bool Equals(object obj)
{
return obj is GameDuration && (Seconds == ((GameDuration)obj).Seconds);
}
public override int GetHashCode()
{
return HashCalculator.Value[Seconds];
}
}
}
| mit |
MarkKremer/laravel-elixir-image | lib/compiler.js | 3570 | var gutil = require('gulp-util'),
through = require('through2'),
path = require('path'),
spawn = require('child_process').spawn,
config = require('./../config'),
util = require('./util');
/**
* Check if the file should be skipped because it is empty or because of incompatibility.
*
* @param file
* @param cb
* @returns {*}
*/
function skipCheck(file, cb) {
if (file.isNull()) {
return cb(null, file);
}
if (file.isStream()) {
return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
}
if (path.basename(file.path).indexOf('_') === 0) {
return cb();
}
if (!file.contents.length) {
return cb(null, file);
}
// Don't skip it.
return null;
}
/**
* A helper function for the compiler to loop through all destination paths while preserving the async nature of
* through2 and not using all the computer's memory when converting large images by keeping everything sequential.
*
* @param _this
* @param file
* @param enc
* @param cb
* @param destPaths
* @param i
*/
function compilerHelper(_this, file, enc, cb, destPaths, i) {
if(i < destPaths.length) {
// Spawn a ImageMagic convert process to convert the image for us.
var sourceExt = util.getFileExtension(file.path),
destExt = util.getFileExtension(destPaths[i]),
outputFile;
// When the input and output extensions are the same and the configuration option for always converting the
// file is disabled, just clone it instead of compiling it.
if(!config.convertSameType && sourceExt === destExt) {
outputFile = file.clone();
outputFile.base = process.cwd();
outputFile.path = destPaths[i];
// Add the file to the pipeline.
_this.push(outputFile);
// Compile the next image if any.
compilerHelper(_this, file, enc, cb, destPaths, i+1);
} else {
// TODO: Multiplatform support.
var proc = spawn(config.executables.convert, [sourceExt + ':-', destExt + ':-']);
// Pipe the incoming file to the process ...
proc.stdin.encoding = enc;
file.pipe(proc.stdin);
// ... and pipe the output to a new vinyl file.
outputFile = new gutil.File({
path: destPaths[i],
contents: proc.stdout
});
// Add the file to the pipeline.
_this.push(outputFile);
proc.on('exit', function () {
// Compile the next image if any when ImageMagick is done converting.
compilerHelper(_this, file, enc, cb, destPaths, i+1);
});
}
} else {
// When every format is converted, call the through2 callback to signal it that we are done.
cb();
}
}
/**
* Compiles the images to the formats and location specified in the options.
*
* @param options
*/
function compiler(options) {
return through.obj(function(file, enc, cb) {
// Do some standard checks before proceeding.
var result = skipCheck(file, cb);
if(result !== null) {
return result;
}
// Get the paths the images should be converted to.
var destPaths = util.getDestinationPaths(file, options);
// Convert the image to all formats.
compilerHelper(this, file, enc, cb, destPaths, 0);
});
}
module.exports = {
compiler: compiler,
skipCheck: skipCheck
}; | mit |
chcaru/csquared | Interpreter/Program.cs | 848 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CSquared;
namespace Interpreter
{
class Interpreter
{
static void Main(string[] args)
{
if (args.Length <= 0)
{
throw new Exception("Program name required as command line arguement!");
}
var parser = new Parser(args[0]);
var evaluator = new Evaluator();
try
{
var program = parser.Parse();
evaluator.Evaluate(program);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
| mit |
rawlep/MetaAnalyticFramework | Program.cs | 7137 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace paperTestsCode
{
class Program
{
static void Main(string[] args)
{
/// example from the article
List<double[]> articleData = new List<double[]>();
articleData.Add(new double[] { 3.199, 3.241, 3.33, 3.383, 3.439, 3.518, 3.56, 3.601, 3.708, 3.705, 3.786 });
articleData.Add(new double[] { 3.223, 3.246, 3.321, 3.406, 3.451, 3.514, 3.555, 3.639, 3.725, 3.781, 3.857 });
articleData.Add(new double[] { 3.204, 3.236, 3.291, 3.387, 3.474, 3.53, 3.602, 3.682, 3.752, 3.834, 3.875 });
articleData.Add(new double[] { 3.167, 3.247, 3.346, 3.444, 3.525, 3.568, 3.652, 3.747, 3.789, 3.838, 3.943 });
articleData.Add(new double[] { 3.196, 4.279, 3.931, 2.711, 6.156, 3.605, 2.547, 3.747, 3.838, 3.912, 4.008 });
articleData.Add(new double[] { 7.231, 5.297, 5.303, 2.409, 1.823, 1.855, 1.841, 1.869, 3.895, 1.931, 1.931 });
articleData.Add(new double[] { 5.24, 5.302, 5.323, 5.372, 1.801, 1.809, 1.831, 4.85, 1.864, 1.857, 1.942 });
articleData.Add(new double[] { 5.267, 5.291, 5.364, 5.418, 1.795, 1.839, 1.838, 1.862, 1.937, 1.881, 1.923 });
articleData.Add(new double[] { 5.263, 5.263, 5.344, 5.418, 1.788, 1.79, 1.871, 1.906, 1.868, 1.911, 1.949 });
articleData.Add(new double[] { 5.263, 5.316, 5.354, 5.42, 1.793, 1.801, 1.858, 0.787, 1.876, 1.907, 1.94 });
articleData.Add(new double[] { 5.221, 5.323, 5.393, 5.401, 1.828, 1.816, 1.87, 1.856, 1.887, 1.904, 1.924 });
articleData.Add(new double[] { 5.26, 5.306, 5.315, 5.4, 1.826, 1.799, 1.84, 1.888, 1.887, 1.908, 1.929 });
articleData.Add(new double[] { 3.269, 5.32, 7.313, 5.391, 1.783, 1.826, 1.803, 1.864, 1.869, 1.895, 1.922 });
articleData.Add(new double[] { 5.249, 5.304, 5.356, 5.397, 1.829, 1.81, 1.845, 1.849, 1.883, 1.907, 1.915 });
articleData.Add(new double[] { 5.262, 7.133, 4.336, 5.393, 1.824, 1.786, 1.878, 1.886, 1.881, 1.896, 1.926 });
articleData.Add(new double[] { 5.235, 5.315, 5.349, 6.388, 1.801, 1.845, 1.872, 1.854, 1.896, 1.902, 1.933 });
articleData.Add(new double[] { 5.268, 3.128, 5.343, 5.385, 2.775, 1.053, 1.836, 1.899, 2.313, 1.896, 0.947 });
articleData.Add(new double[] { 5.207, 5.295, 4.369, 5.403, 1.82, 1.789, 1.849, 0.897, 1.903, 1.905, 1.912 });
Groups gp = new Groups();
/// the Pearson correlation delegate for testing
Func<double[], double[], double> relation = (x, y) => pearsons(x, y);
var optimised_result = gp.metaAnalyticProcedure(relation, Groups.Comprison.LessOrEqual, articleData, 0.8,10);
var meta_result = optimised_result.Item1;
var original_recombinations = optimised_result.Item2;
// print the groups generated from the procedure for evaluations
Console.WriteLine(" ------------- META-ANALYTIC RESULTS ------------- \n");
for (int i = 0; i < meta_result.Count; i++)
{
var trp = meta_result.ElementAt(i);
Console.WriteLine(" ------- Group configuration: {0}. No. of members: {1} ------------------ ", i.ToString(), trp.Count.ToString());
List<string> cuts = trp.Select(x => printSequence(x.Select(y => printSequence(y))) + "\n \n ").ToList();
Console.WriteLine(String.Concat(cuts));
// Console.WriteLine("There are {0} elements in this group\n", trp.Count.ToString());
}
Console.WriteLine(" -------------------------------------------------------- ");
Console.WriteLine("That's it... There are {0} possibilities, instead of {1}. Awesome!", meta_result.Count.ToString(), original_recombinations.ToString());
Console.WriteLine("Now press any key to exit.");
// we can now apply an analytic procedure/metric to determine which group configuration is optimum.
// Let's call our procedure mml as was the case in the article (of course we will not just return the
// first element of the list!).
Func<List<List<List<double[]>>>, List<List<double[]>>> mml = groups => (groups != null && groups.Count > 0)? groups.ElementAt(0) : new List<List<double[]>>();
// We can now apply the metric like
var metric_applied_to_selected_founder_sets = mml(meta_result);
// ... and, subsequently, analyse a smaller number of possibilities amongst which is likely to be the solution
Console.ReadKey();
}
/// <summary>
/// Pretty printing elements in an Enumerable
/// </summary>
static string printSequence<T>(IEnumerable<T> ls)
{
string temp = "";
if (ls != null)
{
int len = ls.Count();
temp += "[";
for (int i = 0; i < len; i++)
{
if (i == len - 1)
temp += ls.ElementAt(i).ToString() + "]";
else
temp += ls.ElementAt(i).ToString() + ",";
}
}
return temp;
}
///<summary>
/// Pearson correlation coefficient for testing
/// </summary>
static double pearsons(IEnumerable<double> xs, IEnumerable<double> ys)
{
int n = Math.Min(xs.Count(), ys.Count());
if (n > 1)
{
var new_xs = n == xs.Count() ? xs : xs.TakeWhile((x, i) => i < n);
var new_ys = n == ys.Count() ? ys : ys.TakeWhile((x, i) => i < n);
var xs_mu = new_xs.Average();
var ys_mu = new_ys.Average();
var sx = standard_dev(new_xs);
var sy = standard_dev(new_ys);
var sumxy = new_xs.Select((x, i) => x * new_ys.ElementAt(i)).Sum();
double rxy = (sumxy - n * xs_mu * ys_mu) / ((n - 1) * sx * sy);
return rxy;
}
else
throw new Exception("Insufficient data for estimating Pearson correlation coefficient");
}
/// <summary>
/// Calculate the Standard deviation
/// </summary>
private static double standard_dev(IEnumerable<double> values)
{
double mu = values.Average();
return standard_dev_aux(values, mu);
}
private static double standard_dev_aux(IEnumerable<double> values, double mu)
{
double sumOfSquaresOfDifferences = values.Select(val => Math.Pow(val - mu, 2)).Sum();
double n1 = values.Count() - 1;
if (n1 != 0)
return Math.Sqrt(sumOfSquaresOfDifferences / n1);
else
throw new Exception("Cannot calculate standard deviation of a sequence with less than 2 elements");
}
}
}
| mit |
travelpaq/Connect-SDK-PHP | src/Models/Exceptions/PackagesAPIException.php | 1331 | <?php
/**
* TravelPAQ Connect Api
*
* @package TravelPAQ
*
* @author TravelPAQ <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace TravelPAQ\PackagesAPI\Models\Exceptions;
abstract class PackagesAPIException extends \Exception implements IException
{
protected $message = 'Unknown exception'; // Exception message
private $string; // Unknown
protected $code = 0; // User-defined exception code
protected $file; // Source filename of exception
protected $line; // Source line of exception
private $trace; // Unknown
public function __construct($message = null, $code = 0)
{
if (!$message) {
throw new $this('Unknown '. get_class($this));
}
parent::__construct($message, $code, null);
}
public function __toString()
{
return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
. "{$this->getTraceAsString()}";
}
}
?> | mit |
guidance-guarantee-programme/pension_guidance | app/lib/bsl/mapper.rb | 1132 | module Bsl
class Mapper
def initialize(booking_request)
@booking_request = booking_request
end
def call # rubocop:disable MethodLength, AbcSize
{
first_name: booking_request.first_name,
last_name: booking_request.last_name,
email: booking_request.email,
phone: booking_request.phone,
memorable_word: booking_request.memorable_word,
date_of_birth: booking_request.date_of_birth,
defined_contribution_pot_confirmed: booking_request.defined_contribution_pot_confirmed,
accessibility_needs: booking_request.accessibility_needs,
additional_info: booking_request.additional_info,
where_you_heard: booking_request.where_you_heard,
gdpr_consent: booking_request.gdpr_consent.to_s,
support: booking_request.supported,
support_name: booking_request.support_name,
support_relationship: booking_request.support_relationship,
support_email: booking_request.support_email,
support_phone: booking_request.support_phone
}
end
private
attr_reader :booking_request
end
end
| mit |
Womak/MVC-Froggy | src/CFroggy/CFroggy.php | 3934 | <?php
/**
* Main class for Froggy, holds everything.
*
* @package FroggyCore
* -- Based on MOS creation Lydia MVC --
*/
class CFroggy implements ISingleton
{
private static $instance = null;
/**
* Constructor
*/
protected function __construct()
{
// include the site specific config.php and create a ref to $ly to be used by config.php
$fr = &$this;
require(FROGGY_SITE_PATH.'/config.php');
}
/**
* Frontcontroller, check url and route to controllers.
*/
public function FrontControllerRoute()
{
// Take current url and divide it in controller, method and parameters
$this->request = new CRequest();
$this->request->Init($this->config['base_url']);
$controller = $this->request->controller;
$method = $this->request->method;
$arguments = $this->request->arguments;
// Is the controller enabled in config.php?
$controllerExists = isset($this->config['controllers'][$controller]);
$controllerEnabled = false;
$className = false;
$classExists = false;
if($controllerExists)
{
$controllerEnabled = ($this->config['controllers'][$controller]['enabled'] == true);
$className = $this->config['controllers'][$controller]['class'];
$classExists = class_exists($className);
}
// Check if controller has a callable method in the controller class, if then call it
if($controllerExists && $controllerEnabled && $classExists)
{
$rc = new ReflectionClass($className);
if($rc->implementsInterface('IController'))
{
if($rc->hasMethod($method))
{
$controllerObj = $rc->newInstance();
$methodObj = $rc->getMethod($method);
$methodObj->invokeArgs($controllerObj, $arguments);
}
else
{
die("404. " . get_class() . ' error: Controller does not contain method.');
}
}
else
{
die('404. ' . get_class() . ' error: Controller does not implement interface IController.');
}
}
else
{
die('404. Page is not found.');
}
}
/**
* Singleton pattern. Get the instance of the latest created object or create a new one.
* @return CFroggy The instance of this class.
*/
public static function Instance()
{
if(self::$instance == null)
{
self::$instance = new CFroggy();
}
return self::$instance;
}
/**
* ThemeEngineRender, renders the reply of the request.
*/
public function ThemeEngineRender()
{
// Get the paths and settings for the theme
$themeName = $this->config['theme']['name'];
$themePath = FROGGY_INSTALL_PATH . "/themes/{$themeName}";
$themeUrl = $this->request->base_url . "themes/{$themeName}";
// Add stylesheet path to the $fr->data array
$this->data['stylesheet'] = "{$themeUrl}/style.css";
//$this->data['stylesheet'] = "{$themeUrl}/css/main.css";
// Include the global functions.php and the functions.php that are part of the theme
$fr = &$this;
$functionsPath = "{$themePath}/functions.php";
if(is_file($functionsPath))
{
include $functionsPath;
}
// Extract $fr->data to own variables and handover to the template file
extract($this->data);
include("{$themePath}/default.tpl.php");
}
}
?> | mit |
pmrozek/highcharts | Highsoft.Web.Mvc/src/Highsoft.Web.Mvc/Charts/PlotOptionsLineMarkerStatesSelect.cs | 3156 | // Type: Highsoft.Web.Mvc.Charts.PlotOptionsLineMarkerStatesSelect
using System.Collections;
using Newtonsoft.Json;
namespace Highsoft.Web.Mvc.Charts
{
public class PlotOptionsLineMarkerStatesSelect : BaseObject
{
public PlotOptionsLineMarkerStatesSelect()
{
bool? nullable1 = new bool?(true);
this.Enabled_DefaultValue = nullable1;
this.Enabled = nullable1;
this.FillColor = this.FillColor_DefaultValue = (object) null;
this.LineColor = this.LineColor_DefaultValue = "#000000";
double? nullable2 = new double?(0.0);
this.LineWidth_DefaultValue = nullable2;
this.LineWidth = nullable2;
double? nullable3 = new double?();
this.Radius_DefaultValue = nullable3;
this.Radius = nullable3;
}
public bool? Enabled { get; set; }
private bool? Enabled_DefaultValue { get; set; }
public object FillColor { get; set; }
private object FillColor_DefaultValue { get; set; }
public string LineColor { get; set; }
private string LineColor_DefaultValue { get; set; }
public double? LineWidth { get; set; }
private double? LineWidth_DefaultValue { get; set; }
public double? Radius { get; set; }
private double? Radius_DefaultValue { get; set; }
internal override Hashtable ToHashtable()
{
Hashtable hashtable = new Hashtable();
bool? enabled = this.Enabled;
bool? enabledDefaultValue = this.Enabled_DefaultValue;
if (enabled.GetValueOrDefault() != enabledDefaultValue.GetValueOrDefault() ||
enabled.HasValue != enabledDefaultValue.HasValue)
hashtable.Add((object) "enabled", (object) this.Enabled);
if (this.FillColor != this.FillColor_DefaultValue)
hashtable.Add((object) "fillColor", this.FillColor);
if (this.LineColor != this.LineColor_DefaultValue)
hashtable.Add((object) "lineColor", (object) this.LineColor);
double? nullable1 = this.LineWidth;
double? nullable2 = this.LineWidth_DefaultValue;
if (nullable1.GetValueOrDefault() != nullable2.GetValueOrDefault() ||
nullable1.HasValue != nullable2.HasValue)
hashtable.Add((object) "lineWidth", (object) this.LineWidth);
nullable2 = this.Radius;
nullable1 = this.Radius_DefaultValue;
if (nullable2.GetValueOrDefault() != nullable1.GetValueOrDefault() ||
nullable2.HasValue != nullable1.HasValue)
hashtable.Add((object) "radius", (object) this.Radius);
return hashtable;
}
internal override string ToJSON()
{
Hashtable hashtable = this.ToHashtable();
if (hashtable.Count > 0)
return JsonConvert.SerializeObject((object) this.ToHashtable());
return "";
}
internal override bool IsDirty()
{
return this.ToHashtable().Count > 0;
}
}
} | mit |
ricsv/react-leonardo-ui | src/tab/tab-aside.js | 136 | import React from 'react';
const TabAside = props => <div className="lui-tab__aside">{props.children}</div>;
export default TabAside;
| mit |
UNOPS/UiMetadataFramework | clients/ionic 3/src/core/handlers/index.ts | 173 | export * from "./MessageResponseHandler";
export * from "./RedirectResponseHandler";
export * from "./ReloadResponseHandler";
export * from "./FormComponentResponseHandler"; | mit |
nippled/majesticcoin | src/qt/optionsdialog.cpp | 8248 | #include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
#include <QRegExp>
#include <QRegExpValidator>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
ui->tabWindow->setVisible(false);
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("BTC") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->reserveBalance, OptionsModel::ReserveBalance);
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
mapper->addMapping(ui->detachDatabases, OptionsModel::DetachDatabases);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting majesticcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting majesticcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}
| mit |
nbushak/postgraphql | src/interface/type/Type.ts | 1339 | /**
* A type in our type system.
*
* Every type will have a `TValue` which represents the internal value of this
* type.
*
* All of the types in our interface represent *data access patterns*. They do
* not perscript how the data should be stored or fetched, but rather just how
* to expose that data. So for example, we could have a string type that was
* really an object. Or an object type that was actually an integer. The type
* system should not be perscriptive.
*
* Data producers can keep data however it is most performant, while data
* consumers will retrieve that data in a given shape.
*/
interface Type<TValue> {
/**
* Every type will have a constant `kind` string. This will tell our system
* how the type should be interacted with. This is mostly useful in the
* `switchType` function.
*/
readonly kind: string
/**
* Tests if a given value is of this type.
*/
// TODO: Remove this.
isTypeOf (value: mixed): value is TValue
}
export default Type
/**
* This user-defined type guard will check to see if the value being passed in
* is a type. We do this by checking the value is an object and has a string
* `kind` field.
*/
export function isType (value: mixed): value is Type<mixed> {
return value != null && typeof value === 'object' && typeof value['kind'] === 'string'
}
| mit |
saxx/Erbsenzaehler-2014 | Erbsenzaehler/Migrations/201405181229284_RefundDate.cs | 530 | namespace Erbsenzaehler.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class RefundDate : DbMigration
{
public override void Up()
{
AddColumn("dbo.Lines", "RefundDate", c => c.DateTime());
DropColumn("dbo.Lines", "Refund");
}
public override void Down()
{
AddColumn("dbo.Lines", "Refund", c => c.Boolean(nullable: false));
DropColumn("dbo.Lines", "RefundDate");
}
}
}
| mit |
llafuente/esprima-ast-utils | test/test-manipulation.js | 5206 | var tap = require("tap"),
test = tap.test,
utils = require("../index.js"),
object = require("object-enhancements");
test("renameVariable", function(t) {
var tree = utils.parseFile(__dirname + "/fixture-manipulation-01.js");
var tokens = object.clone(tree.tokens);
utils.renameVariable(tree, {"A": "B"});
var i,
offset = 0;
t.equal(tree.tokens.length, tokens.length, "same token amount");
for (i = 0; i < tree.tokens.length; ++i) {
t.deepEquals(tree.tokens[i].range, tokens[i].range, "range is ok");
}
utils.renameVariable(tree, {"B": "BBB"});
t.equal(tree.tokens.length, tokens.length, "same token amount");
for (i = 0; i < tree.tokens.length; ++i) {
if (tokens[i].value === "A") {
t.deepEquals(tree.tokens[i].range[0], tokens[i].range[0] + offset, "range is ok");
offset += 2;
t.deepEquals(tree.tokens[i].range[1], tokens[i].range[1] + offset, "range is ok");
} else {
t.deepEquals(tree.tokens[i].range[0], tokens[i].range[0] + offset, "range is ok");
t.deepEquals(tree.tokens[i].range[1], tokens[i].range[1] + offset, "range is ok");
}
}
t.equal(tree.$code.indexOf("A"), -1, "there is A in the final code");
//console.log(require("util").inspect(tree, {depth: null, colors: true}));
console.log(tree.$code);
t.end();
});
test("renameProperty", function(t) {
var tree = utils.parseFile(__dirname + "/fixture-manipulation-02.js");
var tokens = object.clone(tree.tokens);
utils.renameProperty(tree, {"A": "B"});
var i,
offset = 0;
t.equal(tree.tokens.length, tokens.length, "same token amount");
for (i = 0; i < tree.tokens.length; ++i) {
t.deepEquals(tree.tokens[i].range, tokens[i].range, "range is ok");
}
utils.renameProperty(tree, {"B": "BBB"});
t.equal(tree.tokens.length, tokens.length, "same token amount");
for (i = 0; i < tree.tokens.length; ++i) {
if (tokens[i].value === "A") {
t.deepEquals(tree.tokens[i].range[0], tokens[i].range[0] + offset, "range is ok");
offset += 2;
t.deepEquals(tree.tokens[i].range[1], tokens[i].range[1] + offset, "range is ok");
} else {
t.deepEquals(tree.tokens[i].range[0], tokens[i].range[0] + offset, "range is ok");
t.deepEquals(tree.tokens[i].range[1], tokens[i].range[1] + offset, "range is ok");
}
}
t.equal(tree.$code.indexOf("A"), -1, "there is A in the final code");
//console.log(require("util").inspect(tree, {depth: null, colors: true}));
console.log(tree.$code);
t.end();
});
test("renameFunction", function(t) {
var tree = utils.parseFile(__dirname + "/fixture-manipulation-03.js");
var tokens = object.clone(tree.tokens);
utils.renameFunction(tree, {"A": "B"});
var i,
offset = 0,
odd = 0;
t.equal(tree.tokens.length, tokens.length, "same token amount");
for (i = 0; i < tree.tokens.length; ++i) {
t.deepEquals(tree.tokens[i].range, tokens[i].range, "range is ok");
}
utils.renameFunction(tree, {"B": "BBB"});
t.equal(tree.tokens.length, tokens.length, "same token amount");
for (i = 0; i < tree.tokens.length; ++i) {
if (tokens[i].value === "A") {
t.deepEquals(tree.tokens[i].range[0], tokens[i].range[0] + offset, "range is ok");
if ((odd % 2) == 0) {
offset += 2;
}
++odd;
t.deepEquals(tree.tokens[i].range[1], tokens[i].range[1] + offset, "range is ok");
} else {
t.deepEquals(tree.tokens[i].range[0], tokens[i].range[0] + offset, "range is ok");
t.deepEquals(tree.tokens[i].range[1], tokens[i].range[1] + offset, "range is ok");
}
}
t.equal(tree.$code.match(/A/g).length, 2, "there are two A in the final code");
t.equal(utils.isFunctionDeclared(tree, "A"), false, "Function A is not defined");
t.equal(utils.isFunctionDeclared(tree, "BBB"), true, "Function BBB is defined");
console.log(tree.$code);
t.end();
});
test("wrap", function(t) {
var tree = utils.parseFile(__dirname + "/fixture-manipulation-04.js");
var node = tree.body[0];
var text = utils.detach(node);
utils.attach(tree, "body", -1, "(function test() {'use strict';}())");
var block = utils.getFunctionBlock(tree, "test");
utils.attach(block, "body", -1, text);
t.equal(tree.$code, '(function test() {\'use strict\';var WRAP_ME;}())', "valid code");
t.end();
});
test("replaceComment", function(t) {
var tree = utils.parseFile(__dirname + "/fixture-manipulation-05.js");
//utils.debug_tree(tree);
//console.log(require("util").inspect(tree, {depth: null, colors: true}));
var text = utils.replaceComment(tree, "this is a comment", "var XXX;");
//console.log(require("util").inspect(tree, {depth: null, colors: true}));
//console.log(require("util").inspect(tree.$code, {depth: null, colors: true}));
t.equal(tree.$code, '\'use strict\';\n\n(function test() {var XXX;\n \n}())\n', "valid code");
t.end();
});
| mit |
damhau/logify | resources/views/probes/show_fields.blade.php | 760 | <!-- Id Field -->
<div class="form-group">
{!! Form::label('id', 'Id:') !!}
<p>{!! $probe->id !!}</p>
</div>
<!-- Name Field -->
<div class="form-group">
{!! Form::label('Name', 'Name:') !!}
<p>{!! $probe->Name !!}</p>
</div>
<!-- Ip Field -->
<div class="form-group">
{!! Form::label('Ip', 'Ip:') !!}
<p>{!! $probe->Ip !!}</p>
</div>
<!-- Input Field -->
<div class="form-group">
{!! Form::label('Input', 'Input:') !!}
<p>{!! $probe->Input !!}</p>
</div>
<!-- Filter Field -->
<div class="form-group">
{!! Form::label('FIlter', 'Filter:') !!}
<p>{!! $probe->FIlter !!}</p>
</div>
<!-- Output Field -->
<div class="form-group">
{!! Form::label('Output', 'Output:') !!}
<p>{!! $probe->Output !!}</p>
</div>
| mit |
alexkolar/home-assistant | homeassistant/components/device_tracker/__init__.py | 12969 | """
homeassistant.components.device_tracker
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to keep track of devices.
device_tracker:
platform: netgear
# Optional
# How many seconds to wait after not seeing device to consider it not home
consider_home: 180
# Seconds between each scan
interval_seconds: 12
# New found devices auto found
track_new_devices: yes
"""
import csv
from datetime import timedelta
import logging
import os
import threading
from homeassistant.bootstrap import prepare_setup_platform
from homeassistant.components import discovery, group
from homeassistant.config import load_yaml_config_file
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_per_platform
from homeassistant.helpers.entity import Entity
import homeassistant.util as util
import homeassistant.util.dt as dt_util
from homeassistant.helpers.event import track_utc_time_change
from homeassistant.const import (
ATTR_ENTITY_PICTURE, DEVICE_DEFAULT_NAME, STATE_HOME, STATE_NOT_HOME)
DOMAIN = "device_tracker"
DEPENDENCIES = []
GROUP_NAME_ALL_DEVICES = 'all devices'
ENTITY_ID_ALL_DEVICES = group.ENTITY_ID_FORMAT.format('all_devices')
ENTITY_ID_FORMAT = DOMAIN + '.{}'
CSV_DEVICES = "known_devices.csv"
YAML_DEVICES = 'known_devices.yaml'
CONF_TRACK_NEW = "track_new_devices"
DEFAULT_CONF_TRACK_NEW = True
CONF_CONSIDER_HOME = 'consider_home'
DEFAULT_CONF_CONSIDER_HOME = 180 # seconds
CONF_SCAN_INTERVAL = "interval_seconds"
DEFAULT_SCAN_INTERVAL = 12
CONF_AWAY_HIDE = 'hide_if_away'
DEFAULT_AWAY_HIDE = False
SERVICE_SEE = 'see'
ATTR_LATITUDE = 'latitude'
ATTR_LONGITUDE = 'longitude'
ATTR_MAC = 'mac'
ATTR_DEV_ID = 'dev_id'
ATTR_HOST_NAME = 'host_name'
ATTR_LOCATION_NAME = 'location_name'
ATTR_GPS = 'gps'
DISCOVERY_PLATFORMS = {
discovery.SERVICE_NETGEAR: 'netgear',
}
_LOGGER = logging.getLogger(__name__)
# pylint: disable=too-many-arguments
def is_on(hass, entity_id=None):
""" Returns if any or specified device is home. """
entity = entity_id or ENTITY_ID_ALL_DEVICES
return hass.states.is_state(entity, STATE_HOME)
def see(hass, mac=None, dev_id=None, host_name=None, location_name=None,
gps=None):
""" Call service to notify you see device. """
data = {key: value for key, value in
((ATTR_MAC, mac),
(ATTR_DEV_ID, dev_id),
(ATTR_HOST_NAME, host_name),
(ATTR_LOCATION_NAME, location_name),
(ATTR_GPS, gps)) if value is not None}
hass.services.call(DOMAIN, SERVICE_SEE, data)
def setup(hass, config):
""" Setup device tracker """
yaml_path = hass.config.path(YAML_DEVICES)
csv_path = hass.config.path(CSV_DEVICES)
if os.path.isfile(csv_path) and not os.path.isfile(yaml_path) and \
convert_csv_config(csv_path, yaml_path):
os.remove(csv_path)
conf = config.get(DOMAIN, {})
consider_home = util.convert(conf.get(CONF_CONSIDER_HOME), int,
DEFAULT_CONF_CONSIDER_HOME)
track_new = util.convert(conf.get(CONF_TRACK_NEW), bool,
DEFAULT_CONF_TRACK_NEW)
devices = load_config(yaml_path, hass, timedelta(seconds=consider_home))
tracker = DeviceTracker(hass, consider_home, track_new, devices)
def setup_platform(p_type, p_config, disc_info=None):
""" Setup a device tracker platform. """
platform = prepare_setup_platform(hass, config, DOMAIN, p_type)
if platform is None:
return
try:
if hasattr(platform, 'get_scanner'):
scanner = platform.get_scanner(hass, {DOMAIN: p_config})
if scanner is None:
_LOGGER.error('Error setting up platform %s', p_type)
return
setup_scanner_platform(hass, p_config, scanner, tracker.see)
return
if not platform.setup_scanner(hass, p_config, tracker.see):
_LOGGER.error('Error setting up platform %s', p_type)
except Exception: # pylint: disable=broad-except
_LOGGER.exception('Error setting up platform %s', p_type)
for p_type, p_config in \
config_per_platform(config, DOMAIN, _LOGGER):
setup_platform(p_type, p_config)
def device_tracker_discovered(service, info):
""" Called when a device tracker platform is discovered. """
setup_platform(DISCOVERY_PLATFORMS[service], {}, info)
discovery.listen(hass, DISCOVERY_PLATFORMS.keys(),
device_tracker_discovered)
def update_stale(now):
""" Clean up stale devices. """
tracker.update_stale(now)
track_utc_time_change(hass, update_stale, second=range(0, 60, 5))
tracker.setup_group()
def see_service(call):
""" Service to see a device. """
args = {key: value for key, value in call.data.items() if key in
(ATTR_MAC, ATTR_DEV_ID, ATTR_HOST_NAME, ATTR_LOCATION_NAME,
ATTR_GPS)}
tracker.see(**args)
hass.services.register(DOMAIN, SERVICE_SEE, see_service)
return True
class DeviceTracker(object):
""" Track devices """
def __init__(self, hass, consider_home, track_new, devices):
self.hass = hass
self.devices = {dev.dev_id: dev for dev in devices}
self.mac_to_dev = {dev.mac: dev for dev in devices if dev.mac}
self.consider_home = timedelta(seconds=consider_home)
self.track_new = track_new
self.lock = threading.Lock()
for device in devices:
if device.track:
device.update_ha_state()
self.group = None
def see(self, mac=None, dev_id=None, host_name=None, location_name=None,
gps=None):
""" Notify device tracker that you see a device. """
with self.lock:
if mac is None and dev_id is None:
raise HomeAssistantError('Neither mac or device id passed in')
elif mac is not None:
mac = mac.upper()
device = self.mac_to_dev.get(mac)
if not device:
dev_id = util.slugify(host_name or '') or util.slugify(mac)
else:
dev_id = str(dev_id).lower()
device = self.devices.get(dev_id)
if device:
device.seen(host_name, location_name, gps)
if device.track:
device.update_ha_state()
return
# If no device can be found, create it
device = Device(
self.hass, self.consider_home, self.track_new, dev_id, mac,
(host_name or dev_id).replace('_', ' '))
self.devices[dev_id] = device
if mac is not None:
self.mac_to_dev[mac] = device
device.seen(host_name, location_name, gps)
if device.track:
device.update_ha_state()
# During init, we ignore the group
if self.group is not None:
self.group.update_tracked_entity_ids(
list(self.group.tracking) + [device.entity_id])
update_config(self.hass.config.path(YAML_DEVICES), dev_id, device)
def setup_group(self):
""" Initializes group for all tracked devices. """
entity_ids = (dev.entity_id for dev in self.devices.values()
if dev.track)
self.group = group.setup_group(
self.hass, GROUP_NAME_ALL_DEVICES, entity_ids, False)
def update_stale(self, now):
""" Update stale devices. """
with self.lock:
for device in self.devices.values():
if (device.track and device.last_update_home and
device.stale(now)):
device.update_ha_state(True)
class Device(Entity):
""" Tracked device. """
# pylint: disable=too-many-instance-attributes, too-many-arguments
host_name = None
location_name = None
gps = None
last_seen = None
# Track if the last update of this device was HOME
last_update_home = False
_state = STATE_NOT_HOME
def __init__(self, hass, consider_home, track, dev_id, mac, name=None,
picture=None, away_hide=False):
self.hass = hass
self.entity_id = ENTITY_ID_FORMAT.format(dev_id)
# Timedelta object how long we consider a device home if it is not
# detected anymore.
self.consider_home = consider_home
# Device ID
self.dev_id = dev_id
self.mac = mac
# If we should track this device
self.track = track
# Configured name
self.config_name = name
# Configured picture
self.config_picture = picture
self.away_hide = away_hide
@property
def name(self):
""" Returns the name of the entity. """
return self.config_name or self.host_name or DEVICE_DEFAULT_NAME
@property
def state(self):
""" State of the device. """
return self._state
@property
def state_attributes(self):
""" Device state attributes. """
attr = {}
if self.config_picture:
attr[ATTR_ENTITY_PICTURE] = self.config_picture
if self.gps:
attr[ATTR_LATITUDE] = self.gps[0],
attr[ATTR_LONGITUDE] = self.gps[1],
return attr
@property
def hidden(self):
""" If device should be hidden. """
return self.away_hide and self.state != STATE_HOME
def seen(self, host_name=None, location_name=None, gps=None):
""" Mark the device as seen. """
self.last_seen = dt_util.utcnow()
self.host_name = host_name
self.location_name = location_name
self.gps = gps
self.update()
def stale(self, now=None):
""" Return if device state is stale. """
return self.last_seen and \
(now or dt_util.utcnow()) - self.last_seen > self.consider_home
def update(self):
""" Update state of entity. """
if not self.last_seen:
return
elif self.location_name:
self._state = self.location_name
elif self.stale():
self._state = STATE_NOT_HOME
self.last_update_home = False
else:
self._state = STATE_HOME
self.last_update_home = True
def convert_csv_config(csv_path, yaml_path):
""" Convert CSV config file format to YAML. """
used_ids = set()
with open(csv_path) as inp:
for row in csv.DictReader(inp):
dev_id = util.ensure_unique_string(
(util.slugify(row['name']) or DEVICE_DEFAULT_NAME).lower(),
used_ids)
used_ids.add(dev_id)
device = Device(None, None, row['track'] == '1', dev_id,
row['device'], row['name'], row['picture'])
update_config(yaml_path, dev_id, device)
return True
def load_config(path, hass, consider_home):
""" Load devices from YAML config file. """
if not os.path.isfile(path):
return []
return [
Device(hass, consider_home, device.get('track', False),
str(dev_id).lower(), str(device.get('mac')).upper(),
device.get('name'), device.get('picture'),
device.get(CONF_AWAY_HIDE, DEFAULT_AWAY_HIDE))
for dev_id, device in load_yaml_config_file(path).items()]
def setup_scanner_platform(hass, config, scanner, see_device):
""" Helper method to connect scanner-based platform to device tracker. """
interval = util.convert(config.get(CONF_SCAN_INTERVAL), int,
DEFAULT_SCAN_INTERVAL)
# Initial scan of each mac we also tell about host name for config
seen = set()
def device_tracker_scan(now):
""" Called when interval matches. """
for mac in scanner.scan_devices():
if mac in seen:
host_name = None
else:
host_name = scanner.get_device_name(mac)
seen.add(mac)
see_device(mac=mac, host_name=host_name)
track_utc_time_change(hass, device_tracker_scan, second=range(0, 60,
interval))
device_tracker_scan(None)
def update_config(path, dev_id, device):
""" Add device to YAML config file. """
with open(path, 'a') as out:
out.write('\n')
out.write('{}:\n'.format(device.dev_id))
for key, value in (('name', device.name), ('mac', device.mac),
('picture', device.config_picture),
('track', 'yes' if device.track else 'no'),
(CONF_AWAY_HIDE,
'yes' if device.away_hide else 'no')):
out.write(' {}: {}\n'.format(key, '' if value is None else value))
| mit |
okular/markryansatt | src/app/views/PortfolioPageView.js | 344 | import $ from 'jquery';
import _ from 'lodash';
import Marionette from 'backbone.marionette';
import template from '../templates/portfolioTemplate.hbs';
export default class PortfolioPageView extends Marionette.ItemView{
get template() { return template; }
serializeData() {
return {
model: this.model.toJSON()
};
}
};
| mit |
robhor/tcbvrp | src/supplySwapHeuristic.cpp | 412 | // Copyright 2014 Robert Horvath, Johannes Vogel
#include <iostream>
#include <string>
#include "supplySwapHeuristic.h"
#include "./supplySwapper.h"
bool supplySwap(Solution* solution) {
int current_length = solution->length;
SupplySwapper ss(solution);
while (ss.next() != nullptr) {
if (solution->length < current_length) {
return true;
}
}
return false;
}
| mit |
coingecko/cryptoexchange | lib/cryptoexchange/exchanges/idex/services/order_book.rb | 1545 | module Cryptoexchange::Exchanges
module Idex
module Services
class OrderBook < Cryptoexchange::Services::Market
class << self
def supports_individual_ticker_query?
true
end
end
def fetch(market_pair)
params = {}
params['market'] = "#{market_pair.target}_#{market_pair.base}"
params['count'] = 100
output = fetch_using_post(ticker_url, params)
adapt(output, market_pair)
end
def ticker_url
"#{Cryptoexchange::Exchanges::Idex::Market::API_URL}/returnOrderBook"
end
def adapt(output, market_pair)
order_book = Cryptoexchange::Models::OrderBook.new
timestamp = Time.now.to_i
order_book.base = market_pair.base
order_book.target = market_pair.target
order_book.market = Idex::Market::NAME
order_book.asks = adapt_orders output['asks']
order_book.bids = adapt_orders output['bids']
order_book.timestamp = timestamp
order_book.payload = output
order_book
end
def adapt_orders(orders)
orders.collect do |order_entry|
price = order_entry['price']
amount = order_entry['amount']
Cryptoexchange::Models::Order.new(price: price,
amount: amount,
timestamp: nil)
end
end
end
end
end
end
| mit |
sydes/framework | src/L10n/Locales/EtLocale.php | 285 | <?php
namespace Sydes\L10n\Locales;
use Sydes\L10n\Locale;
use Sydes\L10n\Plural\Rule1;
class EtLocale extends Locale
{
use Rule1;
protected $isoCode = 'et';
protected $englishName = 'Estonian';
protected $nativeName = 'Eesti keel';
protected $isRtl = false;
}
| mit |
alexeybob/epc | src/EPC/AdminBundle/Controller/TestController.php | 155 | <?php
namespace EPC\AdminBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
class TestController extends Controller
{
}
| mit |
runandrew/memoriae | app/utils/userDialog.js | 350 | // Required libraries
const remote = require('electron').remote;
const dialog = remote.dialog;
// Required files
const { settings } = require('./userSettings');
const getDbPathUserInput = () => {
let resultArr = dialog.showOpenDialog({
properties: ['openDirectory']
});
return resultArr[0];
};
module.exports = {
getDbPathUserInput
};
| mit |
MatthewGreen/ToolsManagerAppExternalAPI | server.js | 4606 | // server.js
// Base Setup
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// instantiate packages
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
// setup bodyParser()
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // setup port 8080
// Setup JADE
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
// Connect to local MongoDB
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/tools'); // connect to our database
var Tools = require('./app/models/tools');
// Define Routes Below Which Use Middleware & A Router
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
var router = express.Router(); // Create Express Router Object
// Middleware Router For All Requests
router.use(function(req, res, next) {
// Write To Console
console.log('Request Received, Rerouting...');
next(); // Pass Request To Valid Route
});
// Base route '/' to ensure API is active
router.get('/', function(req, res) {
res.json({ message: 'Server Is Active Sir!' });
});
// ========================================= SERVING WEB PAGES ============================================
// GET hello world page
router.get('/helloworld', function(req, res) {
console.log('Hello World Page Has Been Served.');
res.render('helloworld', { title: 'Hello World!' });
});
// ========================================= END SERVING WEB PAGES =========================================
// Define Additional Routes Here
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
router.route('/tools')
// Create a Tool (POST - localhost:8080/api/tools)
.post(function(req, res) {
console.log('Single Object POST Request Received...');
var tool = new Tools(); // New tool object
// Variables from The Model Are Below
tool.name = req.body.name;
tool.tooltype = req.body.tooltype;
tool.weight = req.body.weight;
tool.damagedflag = req.body.damagedflag;
tool.serialnumber = req.body.serialnumber;
// Save the tool and check for errors
tool.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Tool Has Been Added!' });
});
})
// Get all the tools (GET)
.get(function(req, res) {
console.log('All Objects GET Request Received...');
Tools.find(function(err, tools){
if (err)
res.send(err);
res.json(tools);
});
});
router.route('/tools/:tools_id')
// Single Get (GET)
.get(function(req, res) {
console.log('Single ID GET Request Received...');
Tools.findById(req.params.tools_id, function(err, tools) {
if (err)
res.send(err);
res.json(tools);
});
}) // End GET (Single ID)
// Single UPDATE of a tool (PUT)
.put(function(req, res) {
console.log('Single ID PUT Request Received. Updating Entry With ID: ' + req.params.tools_id);
Tools.findById(req.params.tools_id, function(err, tools) {
if (err)
res.send(err);
// Change Name Variable
if (req.body.name)
tools.name = req.body.name;
//else
//res.json({ message: 'No Name Given Or Name Was Blank...Hopefully' });
// Change Tool Type Variable
if (req.body.tooltype)
tools.tooltype = req.body.tooltype;
// Change Weight Variable
if (req.body.weight)
tools.weight = req.body.weight;
// Change DamagedFlag Variable
if (req.body.damagedflag)
tools.damagedflag = req.body.damagedflag;
// Change Serial Number Variable
if (req.body.damagedflag)
tools.serialnumber = req.body.serialnumber;
// Save the tool
tools.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Tool Updated!' });
});
});
}) // End PUT
// Single DELETE of a tool (DELETE)
.delete(function(req, res) {
Tools.remove({
_id: req.params.tools_id
}, function(err, tools) {
if (err)
res.send(err);
res.json({ message: 'Tool has been removed from the catalog. Tool ID: ' + req.params.tools_id})
})
}); // End DELETE
// Register Defined Routes
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
app.use('/api', router);
app.use('/', router);
// Start The Server
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
app.listen(port);
console.log('Server Started Running On Port ' + port); | mit |
Satyam/RoxyMusic | client/store/config/reducer.js | 764 | import update from 'react-addons-update';
import {
REPLY_RECEIVED,
} from '_store/requests/actions';
import {
GET_CONFIG,
GET_ALL_CONFIG,
SET_CONFIG,
} from './actions';
const SUB_STORE = 'config';
export const configSelectors = {
all: state => state[SUB_STORE],
get: (state, name) => state[SUB_STORE][name],
loaded: state => !!Object.keys(state[SUB_STORE]).length,
};
export default (
state = {},
action
) => {
const payload = action.payload;
if (action.stage && action.stage !== REPLY_RECEIVED) return state;
switch (action.type) {
case GET_ALL_CONFIG:
return payload;
case GET_CONFIG:
case SET_CONFIG:
return update(state, { [payload.key]: { $set: payload.value } });
default:
return state;
}
};
| mit |
RooseveltJavier/Proyecto | resources/js/modules/stecnico.js | 6142 | var progressbar = '<div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 45%"> <span class="sr-only">45% Complete</span> </div> </div>';
function searchMarca(){
$('#marcasearchid').typeahead({
template:['<div class="media br-bottom">',
'<div class="media-body"><h4 class="media-heading">{{value}}</h4>',
'<p>{{descripcion}}<p></div></div>'
].join(''),
engine: Hogan,
remote: main_path+'/modules/comunes/controlador/marcaA.php?q=%QUERY',
minLength: 2
})
// .on('typeahead:selected', function(event, datum) {
// $('#marca_id').val(datum.id);
// });
/*al momento de buscar ingresos realizados*/
$('#marcasearchid2').typeahead({
template:['<div class="media br-bottom">',
'<div class="media-body"><h4 class="media-heading">{{value}}</h4>',
'<p>{{descripcion}}<p></div></div>'
].join(''),
engine: Hogan,
remote: main_path+'/modules/comunes/controlador/marcaA.php?q=%QUERY',
minLength: 2
})
.on('typeahead:selected', function(event, datum) {
$('#marca_id2').val(datum.id);
});
}
function selectTecnico(){
$(document).on("change", "#tecnicoencargado", function(e) {
var tecniconame = $('#tecnicoencargado :selected').text();
$('#tecnico_name').val(tecniconame);
return false;
});
}
/*quitar un producto de la lista*/
function delProduct(){
$(document).on("click", "#delproductbtn", function(e) {
bloquearPantalla()
var form = $(this).parents('form');
// $(form).bt_validate();
$(form).ajaxForm({dataType: 'json', success: getRespDelProduct});
});
}
function getRespDelProduct(data, statusText, xhr, $form){
if($.trim(data.ok) == '1'){
var formElement = $form;
formElement.parents('tr').remove();
alertaExito('El producto ha sido removido de la lista', 'Remover Producto');
}else{
alertaExito('No se ha podido remover el producto de la lista', 'Remover Producto');
}
}
function editPrefact(elem){
$(document).on("keyup", elem, function(e) {
var objThis = $(this), prefactid = objThis.attr('prefactid');
var parametros = {
"inputval" : objThis.val(),
"prefactid" : prefactid,
"action" : objThis.attr('action')
};
if($.trim(objThis.val()) != '0' && $.trim(objThis.val()) != 'undefined' && $.trim(objThis.val()) != ''){
$.ajax({
data: parametros,
url: objThis.attr('data-url'),
type: 'post',
beforeSend: function () {
// $("#ajaxproccessview").html("Procesando, espere por favor...");
$("#ajaxproccessview").html(progressbar);
},
success: function (response) {
$("#ajaxproccessview").html(response);
var cantprodfact = getNumericVal('.cantprodfact'+prefactid,'int'),
preciounit = getNumericVal('.preciounit'+prefactid, 'float'),
totxprod = cantprodfact * preciounit,
ivaxunit = totxprod + ((totxprod * ivaporcent) / 100);
$('#totxprod'+prefactid).html(totxprod.toFixed(numdecimales));
$('input[name=totxprod'+prefactid+']').val(totxprod.toFixed(numdecimales));
$('#ivaxunit'+prefactid).html(ivaxunit.toFixed(numdecimales));
var subtotnewcompra = 0, ivafact = 0, totfact = 0;
$("input#totxprod").each(function(e) {
var total = parseFloat($(this).val());
// alert(total)
subtotnewcompra += total;
});
$('#subtotview').html(subtotnewcompra.toFixed(numdecimales)); $('#subtotfact').val(subtotnewcompra);
ivafact = (subtotnewcompra * ivaporcent) / 100;
$('#ivafactview').html(ivafact.toFixed(numdecimales)); $('#ivafact').val(ivafact);
totfact = subtotnewcompra + ivafact;
$('#totfactview').html(totfact.toFixed(numdecimales)); $('#totfact').val(totfact);
}
});
}else{
alertaError("No se puede establecer un valor nulo","");
}
});
}
function historialReparacion(){
$(document).on('click', '#openhistreparacion', function(e){
var stequipo_id = $.trim($(this).attr('stequipo_id')),
clientemail = $.trim($(this).attr('clientemail')),
clientcelular = $.trim($(this).attr('clientcelular')),
client = $.trim($(this).attr('client'));
$( '.container-fluid' ).jsPanel({
size: { width: 660, height: 460 },
// theme: 'info',
title: 'Historial Reparacion Equipo',
overflow: 'auto',
position: { top: 0, left: 15},
// theme: 'info',
theme: 'success',
controls: { iconfont: 'bootstrap' },
// controls: { buttons: 'closeonly', iconfont: 'font-awesome' },
ajax: {
url: main_path+'/modules/stecnico/view/histreparacion.php?stequipo_id='+stequipo_id+'&clientemail='+clientemail+'&clientcelular='+clientcelular+'&client='+client
}
});
// return false;
});
}
function stecnico(){
historialReparacion();
editPrefact("#preciounit");
editPrefact("#cantprodfact");
// alert('hi..')
// $(".pick-a-color").pickAColor();
delProduct();
searchMarca();
selectTecnico();
} | mit |
flybayer/next.js | packages/next/compiled/webpack/amd-define.js | 1800 | module.exports =
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 441:
/***/ (function(module) {
module.exports = function() {
throw new Error("define cannot be used indirect");
};
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __nccwpck_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(__webpack_module_cache__[moduleId]) {
/******/ return __webpack_module_cache__[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ var threw = true;
/******/ try {
/******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__);
/******/ threw = false;
/******/ } finally {
/******/ if(threw) delete __webpack_module_cache__[moduleId];
/******/ }
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat */
/******/
/******/ __nccwpck_require__.ab = __dirname + "/";/************************************************************************/
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // Load entry module and return exports
/******/ return __nccwpck_require__(441);
/******/ })()
; | mit |
acq4/acq4 | acq4/devices/MicroManagerCamera/mmcamera.py | 17155 | # -*- coding: utf-8 -*-
from __future__ import division, with_statement, print_function
import time
from collections import OrderedDict
import numpy as np
import six
from pyqtgraph.debug import Profiler
from six.moves import range
import acq4.util.ptime as ptime
from acq4.devices.Camera import Camera
from acq4.util import micromanager
from acq4.util.Mutex import Mutex
try:
from functools import lru_cache
except ImportError:
from backports.functools_lru_cache import lru_cache
# Micromanager does not standardize trigger modes across cameras,
# so we use this dict to translate the modes of various cameras back
# to the standard ACQ4 modes:
# Normal: Camera starts by software and acquires frames on its own clock
# TriggerStart: Camera starts by trigger and acquires frames on its own clock
# Strobe: Camera acquires one frame of a predefined exposure time for every trigger pulse
# Bulb: Camera exposes one frame for the duration of each trigger pulse
triggerModes = {
'TriggerType': {'Freerun': 'Normal'}, # QImaging
'Trigger': {'NORMAL': 'Normal', 'START': 'TriggerStart'}, # Hamamatsu
}
class MicroManagerCamera(Camera):
"""Camera device that uses MicroManager to provide imaging.
Configuration keys:
* mmAdapterName
* mmDeviceName
"""
def __init__(self, manager, config, name):
self.camName = str(name) # we will use this name as the handle to the MM camera
mmpath = config.get('path')
self.mmc = micromanager.getMMCorePy(mmpath)
self._triggerProp = None # the name of the property for setting trigger mode
self._triggerModes = ({}, {}) # forward and reverse mappings for the names of trigger modes
self._binningMode = None # 'x' or 'xy' for binning strings like '1' and '1x1', respectively
self.camLock = Mutex(Mutex.Recursive) ## Lock to protect access to camera
self._config = config
Camera.__init__(self, manager, config, name) ## superclass will call setupCamera when it is ready.
self.acqBuffer = None
self.frameId = 0
self.lastFrameTime = None
def setupCamera(self):
# sanity check for MM adapter and device name
adapterName = self._config['mmAdapterName']
allAdapters = self.mmc.getDeviceAdapterNames()
if adapterName not in allAdapters:
raise ValueError("Adapter name '%s' is not valid. Options are: %s" % (adapterName, allAdapters))
deviceName = self._config['mmDeviceName']
allDevices = self.mmc.getAvailableDevices(adapterName)
if deviceName not in allDevices:
raise ValueError("Device name '%s' is not valid for adapter '%s'. Options are: %s" % (
deviceName, adapterName, allDevices))
self.mmc.loadDevice(self.camName, adapterName, deviceName)
self.mmc.initializeDevice(self.camName)
self._readAllParams()
def startCamera(self):
with self.camLock:
self.mmc.startContinuousSequenceAcquisition(0)
def stopCamera(self):
with self.camLock:
self.mmc.stopSequenceAcquisition()
self.acqBuffer = None
def isRunning(self):
# This is needed to allow calling setParam inside startCamera before the acquisition has actually begun
# (but after the acquisition thread has started)
return self.mmc.isSequenceRunning()
def _acquireFrames(self, n=1):
if self.isRunning():
self.stop()
self.mmc.setCameraDevice(self.camName)
self.mmc.startSequenceAcquisition(n, 0, True)
frames = []
for i in range(n):
start = time.time()
while self.mmc.getRemainingImageCount() == 0:
time.sleep(0.005)
if time.time() - start > 10.0:
raise Exception("Timed out waiting for camera frame.")
frames.append(self.mmc.popNextImage().T[np.newaxis, ...])
self.mmc.stopSequenceAcquisition()
return np.concatenate(frames, axis=0)
def newFrames(self):
"""Return a list of all frames acquired since the last call to newFrames."""
with self.camLock:
nFrames = self.mmc.getRemainingImageCount()
if nFrames == 0:
return []
now = ptime.time()
if self.lastFrameTime is None:
self.lastFrameTime = now
dt = (now - self.lastFrameTime) / nFrames
frames = []
with self.camLock:
for i in range(nFrames):
frame = {}
frame['time'] = self.lastFrameTime + (dt * (i + 1))
frame['id'] = self.frameId
frame['data'] = self.mmc.popNextImage().T
frames.append(frame)
self.frameId += 1
self.lastFrame = frame
self.lastFrameTime = now
return frames
def quit(self):
self.mmc.stopSequenceAcquisition()
self.mmc.unloadDevice(self.camName)
def _readAllParams(self):
# these are parameters expected for all cameras
defaultParams = ['exposure', 'binningX', 'binningY', 'regionX', 'regionY', 'regionW', 'regionH', 'triggerMode']
with self.camLock:
params = OrderedDict([(n, None) for n in defaultParams])
properties = self.mmc.getDevicePropertyNames(self.camName)
for prop in properties:
vals = self.mmc.getAllowedPropertyValues(self.camName, prop)
if vals == ():
if self.mmc.hasPropertyLimits(self.camName, prop):
vals = (
self.mmc.getPropertyLowerLimit(self.camName, prop),
self.mmc.getPropertyUpperLimit(self.camName, prop),
)
else:
# just guess..
vals = (1e-6, 1e3)
else:
vals = list(vals)
readonly = self.mmc.isPropertyReadOnly(self.camName, prop)
# translate standard properties to the names / formats that we expect
if prop == 'Exposure':
prop = 'exposure'
# convert ms to s
vals = tuple([v * 1e-3 for v in vals])
elif prop == 'Binning':
for i in range(len(vals)):
if 'x' in vals[i]:
vals[i] = vals[i].split('x')
self._binningMode = 'xy'
else:
vals[i] = [vals[i], vals[i]]
self._binningMode = 'x'
params['binningX'] = ([int(v[0]) for v in vals], not readonly, True, [])
params['binningY'] = ([int(v[1]) for v in vals], not readonly, True, [])
continue
elif prop in triggerModes:
self._triggerProp = prop
modes = triggerModes[prop]
self._triggerModes = (modes, {v: k for k, v in modes.items()})
prop = 'triggerMode'
vals = [modes[v] for v in vals]
# translation from PixelType to bitDepth is not exact; this will take more work.
# for now we just expose PixelType directly.
# elif prop == 'PixelType':
# prop = 'bitDepth'
# vals = [int(bd.rstrip('bit')) for bd in vals]
params[prop] = (vals, not readonly, True, [])
# Reset ROI to full frame so we know the native resolution
self.mmc.setCameraDevice(self.camName)
bin = '1' if self._binningMode == 'x' else '1x1'
self.mmc.setProperty(self.camName, 'Binning', bin)
self.mmc.clearROI()
rgn = self.getROI()
self._sensorSize = rgn[2:]
params.update({
'regionX': [(0, rgn[2] - 1, 1), True, True, []],
'regionY': [(0, rgn[3] - 1, 1), True, True, []],
'regionW': [(1, rgn[2], 1), True, True, []],
'regionH': [(1, rgn[3], 1), True, True, []],
})
if params['triggerMode'] is None:
params['triggerMode'] = (['Normal'], False, True, [])
if params['binningX'] is None:
params['binningX'] = [[1], False, True, []]
params['binningY'] = [[1], False, True, []]
self._allParams = params
def getROI(self):
camRegion = self.mmc.getROI(self.camName)
if self._useBinnedPixelsForROI:
xAdjustment = self.getParam("binningX")
yAdjustment = self.getParam("binningY")
else:
xAdjustment = 1
yAdjustment = 1
return [
camRegion[0] * xAdjustment,
camRegion[1] * yAdjustment,
camRegion[2] * xAdjustment,
camRegion[3] * yAdjustment,
]
def setROI(self, rgn):
if self._useBinnedPixelsForROI:
rgn[0] = int(rgn[0] / self.getParam('binningX'))
rgn[1] = int(rgn[1] / self.getParam('binningY'))
rgn[2] = int(rgn[2] / self.getParam('binningX'))
rgn[3] = int(rgn[3] / self.getParam('binningY'))
self.mmc.setROI(*rgn)
@lru_cache(maxsize=None)
def _useBinnedPixelsForROI(self):
# Adjusting ROI to be in binned-pixel units is necessary in all versions of
# MMCore 7.0.2 and above.
version = self.mmc.getVersionInfo() # e.g. "MMCore version 7.0.2"
ver_num = version.split(" ")[-1].split(".")
ver_tup = tuple([int(d) for d in ver_num])
return ver_tup >= (7, 0, 2)
def listParams(self, params=None):
"""List properties of specified parameters, or of all parameters if None"""
if params is None:
return self._allParams.copy()
if isinstance(params, six.string_types):
return self._allParams[params]
return dict([(p, self._allParams[p]) for p in params])
def setParams(self, params, autoRestart=True, autoCorrect=True):
p = Profiler(disabled=True, delayed=False)
# umanager will refuse to set params while camera is running,
# so autoRestart doesn't make sense in this context
if self.isRunning():
restart = autoRestart
self.stop()
p('stop')
else:
restart = False
# Join region params into one request (_setParam can be very slow)
regionKeys = ['regionX', 'regionY', 'regionW', 'regionH']
nRegionKeys = len([k for k in regionKeys if k in params])
if nRegionKeys > 1:
rgn = list(self.getROI())
for k in regionKeys:
if k not in params:
continue
i = {'X': 0, 'Y': 1, 'W': 2, 'H': 3}[k[-1]]
rgn[i] = params[k]
del params[k]
params['region'] = rgn
newVals = {}
for k, v in params.items():
self._setParam(k, v, autoCorrect=autoCorrect)
p('setParam %r' % k)
if k == 'binning':
newVals['binningX'], newVals['binningY'] = self.getParam(k)
elif k == 'region':
newVals['regionX'], newVals['regionY'], newVals['regionW'], newVals['regionH'] = self.getParam(k)
else:
newVals[k] = self.getParam(k)
p('reget param')
self.sigParamsChanged.emit(newVals)
p('emit')
if restart:
self.start()
p('start')
needRestart = False
return newVals, needRestart
def setParam(self, param, value, autoCorrect=True, autoRestart=True):
return self.setParams({param: value}, autoCorrect=autoCorrect, autoRestart=autoRestart)
def _setParam(self, param, value, autoCorrect=True):
if param.startswith('region'):
if param == 'region':
rgn = [value[0], value[1], value[2], value[3]]
else:
rgn = list(self.getROI())
if param[-1] == 'X':
rgn[0] = value
elif param[-1] == 'Y':
rgn[1] = value
elif param[-1] == 'W':
rgn[2] = value
elif param[-1] == 'H':
rgn[3] = value
self.mmc.setCameraDevice(self.camName)
self.setROI(rgn)
return
# translate requested parameter into a list of sub-parameters to set
setParams = []
if param.startswith('binning'):
if self._binningMode is None:
# camera does not support binning; only allow values of 1
if value in [1, (1, 1)]:
return
else:
raise ValueError('Invalid binning value %s=%s' % (param, value))
if param == 'binningX':
y = self.getParam('binningY')
value = (value, y)
elif param == 'binningY':
x = self.getParam('binningX')
value = (x, value)
if self._binningMode == 'x':
value = '%d' % value[0]
else:
value = '%dx%d' % value
setParams.append(('Binning', value))
elif param == 'exposure':
# s to ms
setParams.append(('Exposure', value * 1e3))
elif param == 'triggerMode':
if self._triggerProp is None:
# camera does not support triggering; only allow 'Normal' mode
if value != 'Normal':
raise ValueError("Invalid trigger mode '%s'" % value)
return
# translate trigger mode name
setParams.append((self._triggerProp, self._triggerModes[1][value]))
# Hamamatsu cameras require setting a trigger source as well
if self._config['mmAdapterName'] == 'HamamatsuHam':
if value == 'Normal':
source = 'INTERNAL'
elif value == 'TriggerStart':
source = 'EXTERNAL'
else:
raise ValueError("Invalid trigger mode '%s'" % value)
# On Orca 4 we actually have to toggle the source property
# back and forth, otherwise it is sometimes ignored.
setParams.append(('TRIGGER SOURCE', 'INTERNAL'))
setParams.append(('TRIGGER SOURCE', source))
else:
setParams.append((param, value))
# elif param == 'bitDepth':
# param = 'PixelType'
# value = '%dbit' % value
with self.camLock:
for param, value in setParams:
self.mmc.setProperty(self.camName, str(param), str(value))
def getParams(self, params=None):
if params is None:
params = list(self.listParams().keys())
return dict([(p, self.getParam(p)) for p in params])
def getParam(self, param):
if param == 'sensorSize':
return self._sensorSize
elif param.startswith('region'):
rgn = self.getROI()
if param == 'region':
return rgn
i = ['regionX', 'regionY', 'regionW', 'regionH'].index(param)
return rgn[i]
elif param.startswith('binning') and self._binningMode is None:
# camera does not support binning; fake it here
if param == 'binning':
return 1, 1
elif param in ('binningX', 'binningY'):
return 1
elif param == 'triggerMode' and self._triggerProp is None:
# camera does not support triggering; fake it here
return 'Normal'
paramTrans = {
'exposure': 'Exposure',
'binning': 'Binning',
'binningX': 'Binning',
'binningY': 'Binning',
'triggerMode': self._triggerProp,
'bitDepth': 'PixelType',
}.get(param, param)
with self.camLock:
val = self.mmc.getProperty(self.camName, str(paramTrans))
# coerce to int or float if possible
try:
val = int(val)
except ValueError:
try:
val = float(val)
except ValueError:
pass
if param in ('binning', 'binningX', 'binningY'):
if self._binningMode == 'x':
val = (int(val),) * 2
else:
val = tuple([int(b) for b in val.split('x')])
if param == 'binningY':
return val[1]
elif param == 'binningX':
return val[0]
elif param == 'binning':
return val
elif param == 'exposure':
# ms to s
val = val * 1e-3
# elif param == 'bitDepth':
# val = int(val.rstrip('bit'))
elif param == 'triggerMode':
val = self._triggerModes[0][val]
return val
| mit |
wadeanthony0100/api | app/Http/Controllers/MentorController.php | 1417 | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class MentorController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param Request $request
* @param int $id
* @return Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}
}
| mit |
encse/sicp | Sicp/app/sicp/Env.ts | 2398 | module Sicp.Lang {
export class StackFrame {
constructor(private _sv: Sicp.Lang.Sv, private _env: Sicp.Lang.Env) {}
public sv(): Sicp.Lang.Sv { return this._sv; }
public env(): Sicp.Lang.Env { return this._env; }
public parent(): StackFrame { return this._env.getParentStackFrame(); }
}
export class Env {
private obj: {[id: string] : Sv} = {};
private envParent: Env = null;
private svSymbolProcedure: SvSymbol;
private parentStackFrame: StackFrame;
constructor(envParent: Env, svSymbolProcedure: SvSymbol = null, parentStackFrame: StackFrame = null) {
this.envParent = envParent;
this.svSymbolProcedure = svSymbolProcedure;
this.parentStackFrame = parentStackFrame;
}
public getNames(): string[] {
const res: string[] = [];
for (let key in this.obj) {
if (this.obj.hasOwnProperty(key))
res.push(key);
}
return res;
}
public getEnvParent(): Env {
return this.envParent;
}
public getSvSymbolProcedure(): SvSymbol{
return this.svSymbolProcedure;
}
public getParentStackFrame(): StackFrame {
if (this.parentStackFrame)
return this.parentStackFrame;
if (this.envParent)
return this.envParent.getParentStackFrame();
return null;
}
public get(name: string):Sv {
if (name in this.obj)
return this.obj[name];
if (this.envParent == null)
throw "no binding for " + name;
return this.envParent.get(name);
}
public set(name: string, rv: Sv) {
if (name in this.obj)
this.obj[name] = rv;
else if (this.envParent == null)
throw name + " is not declared";
else
this.envParent.set(name, rv);
}
public define(name: string, value: Sv) {
if (name in this.obj)
throw name + ' is already defined';
this.obj[name] = value;
}
setOrDefine(name: string, value: Sv) {
this.obj[name] = value;
}
}
} | mit |
stoeffel/react-motion-drawer | example/webpack.config.js | 667 | var path = require("path");
var webpack = require("webpack");
module.exports = {
devtool: "eval",
entry: [
'./example/src/index.js',
],
output: {
path: path.join(__dirname, "static"),
filename: "bundle.js",
publicPath: "/static/",
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
],
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
"babel-loader",
],
},
],
},
devServer: {
contentBase: __dirname,
compress: true,
hot: true,
port: 8888
}
};
| mit |
plumer/codana | tomcat_files/6.0.43/MapELResolver.java | 3910 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.el;
import java.beans.FeatureDescriptor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class MapELResolver extends ELResolver {
private final static Class UNMODIFIABLE = Collections.unmodifiableMap(
new HashMap()).getClass();
private final boolean readOnly;
public MapELResolver() {
this.readOnly = false;
}
public MapELResolver(boolean readOnly) {
this.readOnly = readOnly;
}
public Object getValue(ELContext context, Object base, Object property)
throws NullPointerException, PropertyNotFoundException, ELException {
if (context == null) {
throw new NullPointerException();
}
if (base instanceof Map) {
context.setPropertyResolved(true);
return ((Map) base).get(property);
}
return null;
}
public Class<?> getType(ELContext context, Object base, Object property)
throws NullPointerException, PropertyNotFoundException, ELException {
if (context == null) {
throw new NullPointerException();
}
if (base instanceof Map) {
context.setPropertyResolved(true);
return Object.class;
}
return null;
}
public void setValue(ELContext context, Object base, Object property,
Object value) throws NullPointerException,
PropertyNotFoundException, PropertyNotWritableException,
ELException {
if (context == null) {
throw new NullPointerException();
}
if (base instanceof Map) {
context.setPropertyResolved(true);
if (this.readOnly) {
throw new PropertyNotWritableException(message(context,
"resolverNotWriteable", new Object[] { base.getClass()
.getName() }));
}
try {
((Map) base).put(property, value);
} catch (UnsupportedOperationException e) {
throw new PropertyNotWritableException(e);
}
}
}
public boolean isReadOnly(ELContext context, Object base, Object property)
throws NullPointerException, PropertyNotFoundException, ELException {
if (context == null) {
throw new NullPointerException();
}
if (base instanceof Map) {
context.setPropertyResolved(true);
return this.readOnly || UNMODIFIABLE.equals(base.getClass());
}
return this.readOnly;
}
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
if (base instanceof Map) {
Iterator itr = ((Map) base).keySet().iterator();
List<FeatureDescriptor> feats = new ArrayList<FeatureDescriptor>();
Object key;
FeatureDescriptor desc;
while (itr.hasNext()) {
key = itr.next();
desc = new FeatureDescriptor();
desc.setDisplayName(key.toString());
desc.setExpert(false);
desc.setHidden(false);
desc.setName(key.toString());
desc.setPreferred(true);
desc.setValue(RESOLVABLE_AT_DESIGN_TIME, Boolean.FALSE);
desc.setValue(TYPE, key.getClass());
feats.add(desc);
}
return feats.iterator();
}
return null;
}
public Class<?> getCommonPropertyType(ELContext context, Object base) {
if (base instanceof Map) {
return Object.class;
}
return null;
}
}
| mit |
monque/PHP-Migration | src/Utils/Packager.php | 4393 | <?php
namespace PhpMigration\Utils;
class Packager
{
const NAME = 'phpmig.phar';
protected $filelist = [
'LICENSE',
'README.md',
'README_ZH.md',
'bin/phpmig',
'composer.json',
'composer.lock',
'doc/Migrating from PHP 5.2.x to PHP 5.3.x.md',
'doc/Migrating from PHP 5.3.x to PHP 5.4.x.md',
'doc/Migrating from PHP 5.4.x to PHP 5.5.x.md',
'doc/Migrating from PHP 5.5.x to PHP 5.6.x.md',
'doc/migration70.yml',
'src/App.php',
'src/Changes/AbstractChange.php',
'src/Changes/AbstractIntroduced.php',
'src/Changes/AbstractKeywordReserved.php',
'src/Changes/AbstractRemoved.php',
'src/Changes/ClassTree.php',
'src/Changes/RemoveTableItemTrait.php',
'src/Changes/v5dot3/Deprecated.php',
'src/Changes/v5dot3/IncompByReference.php',
'src/Changes/v5dot3/IncompCallFromGlobal.php',
'src/Changes/v5dot3/IncompMagic.php',
'src/Changes/v5dot3/IncompMagicInvoked.php',
'src/Changes/v5dot3/IncompMisc.php',
'src/Changes/v5dot3/IncompReserved.php',
'src/Changes/v5dot3/Introduced.php',
'src/Changes/v5dot3/Removed.php',
'src/Changes/v5dot4/Deprecated.php',
'src/Changes/v5dot4/IncompBreakContinue.php',
'src/Changes/v5dot4/IncompByReference.php',
'src/Changes/v5dot4/IncompHashAlgo.php',
'src/Changes/v5dot4/IncompMisc.php',
'src/Changes/v5dot4/IncompParamName.php',
'src/Changes/v5dot4/IncompRegister.php',
'src/Changes/v5dot4/IncompReserved.php',
'src/Changes/v5dot4/Introduced.php',
'src/Changes/v5dot4/Removed.php',
'src/Changes/v5dot5/Deprecated.php',
'src/Changes/v5dot5/IncompCaseInsensitive.php',
'src/Changes/v5dot5/IncompPack.php',
'src/Changes/v5dot5/Introduced.php',
'src/Changes/v5dot5/Removed.php',
'src/Changes/v5dot6/Deprecated.php',
'src/Changes/v5dot6/IncompMisc.php',
'src/Changes/v5dot6/IncompPropertyArray.php',
'src/Changes/v5dot6/Introduced.php',
'src/Changes/v5dot6/Removed.php',
'src/Changes/v7dot0/Deprecated.php',
'src/Changes/v7dot0/ExceptionHandle.php',
'src/Changes/v7dot0/ForeachLoop.php',
'src/Changes/v7dot0/FuncList.php',
'src/Changes/v7dot0/FuncParameters.php',
'src/Changes/v7dot0/IntegerOperation.php',
'src/Changes/v7dot0/Introduced.php',
'src/Changes/v7dot0/KeywordReserved.php',
'src/Changes/v7dot0/ParseDifference.php',
'src/Changes/v7dot0/Removed.php',
'src/Changes/v7dot0/StringOperation.php',
'src/Changes/v7dot0/SwitchMultipleDefaults.php',
'src/CheckVisitor.php',
'src/Logger.php',
'src/ReduceVisitor.php',
'src/Sets/classtree.json',
'src/Sets/to53.json',
'src/Sets/to54.json',
'src/Sets/to55.json',
'src/Sets/to56.json',
'src/Sets/to70.json',
'src/Sets/v53.json',
'src/Sets/v54.json',
'src/Sets/v55.json',
'src/Sets/v56.json',
'src/Sets/v70.json',
'src/SymbolTable.php',
'src/Utils/FunctionListExporter.php',
'src/Utils/Logging.php',
'src/Utils/Packager.php',
'src/Utils/ParserHelper.php',
];
public function pack()
{
if (file_exists(self::NAME)) {
\Phar::unlinkArchive(self::NAME);
}
$phar = new \Phar(self::NAME);
// Stub
$code = <<<'EOC'
#! /usr/bin/env php
<?php
Phar::mapPhar('phpmig.phar');
define('PHPMIG_PHAR', true);
require 'phar://phpmig.phar/vendor/autoload.php';
$app = new PhpMigration\App();
$app->run();
__HALT_COMPILER();
EOC;
$phar->setStub($code);
// File
foreach ($this->filelist as $file) {
$phar->addFile($file);
}
// Vendor
chdir(__DIR__.'/../../');
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator('vendor'),
0,
\RecursiveIteratorIterator::CATCH_GET_CHILD
);
foreach ($iterator as $file) {
if (!preg_match('/\/(\.|test\/)/i', $file)) {
$phar->addFile($file);
}
}
// Add execute permission
chmod(self::NAME, 0755);
}
}
| mit |
wistityhq/strapi | packages/strapi-plugin-content-manager/admin/src/utils/formatFiltersFromQuery.js | 1267 | // List of all the possible filters
const VALID_REST_OPERATORS = [
'eq',
'ne',
'in',
'nin',
'contains',
'ncontains',
'containss',
'ncontainss',
'lt',
'lte',
'gt',
'gte',
'null',
];
// from strapi-utils/convert-rest-query-params
const findAppliedFilter = whereClause => {
// Useful to remove the mainField of relation fields.
const formattedWhereClause = whereClause.split('.')[0];
const separatorIndex = whereClause.lastIndexOf('_');
if (separatorIndex === -1) {
return { operator: '=', field: formattedWhereClause };
}
const fieldName = formattedWhereClause.substring(0, separatorIndex);
const operator = whereClause.slice(separatorIndex + 1);
// the field as underscores
if (!VALID_REST_OPERATORS.includes(operator)) {
return { operator: '=', field: formattedWhereClause };
}
return { operator: `_${operator}`, field: fieldName };
};
const formatFiltersFromQuery = ({ _where }) => {
if (!_where) {
return [];
}
return _where.map(obj => {
const [key] = Object.keys(obj);
const { field, operator } = findAppliedFilter(key);
const value = obj[key];
return { name: field, filter: operator, value };
});
};
export default formatFiltersFromQuery;
export { findAppliedFilter };
| mit |
oRastor/jira-client | src/Resource/FluentIssueDelete.php | 691 | <?php
namespace JiraClient\Resource;
use JiraClient\JiraClient,
JiraClient\Resource\Issue,
JiraClient\Exception\JiraException;
/**
* Description of FluentIssueCreate
*
* @author rastor
*/
class FluentIssueDelete
{
/**
*
* @var JiraClient
*/
private $issue;
public function __construct(Issue $issue)
{
$this->issue = $issue;
}
public function execute()
{
$data = array();
try {
$this->issue->getClient()->callDelete('/issue/' . $this->issue->getKey(), $data)->getData();
} catch (\Exception $e) {
throw new JiraException("Failed to delete issue", $e);
}
}
}
| mit |
BStalewski/dontWasteTime | webapp/crawler_app/crawling/urls.py | 527 | from django.conf.urls import patterns, url
import crawling.views as crv
urlpatterns = patterns(
'',
url(r'^results$', crv.CrawlerResultList.as_view()),
url(r'^new$', crv.CrawlerNewList.as_view()),
url(r'^accepted$', crv.CrawlerAcceptedList.as_view()),
url(r'^ignored$', crv.CrawlerIgnoredList.as_view()),
url(r'^crawl/$', crv.crawl_all_sources),
url(r'^crawl/(?P<source>\w+)/$', crv.crawl_source),
url(r'^accept/(?P<id>\d+)/$', crv.accept),
url(r'^ignore/(?P<id>\d+)/$', crv.ignore),
)
| mit |
tomekwszelaki/WeddingPlanner | backend/utils/rabbittest.js | 562 | /**
* Created by tomasj on 26/03/14.
*/
var amqpClient = require('./amqp');
var config = require('../../config');
var receiverOptions = {
url: config.rabbitmq.receiverURL,
implOptions: config.rabbitmq.implOptions,
qname: config.rabbitmq.uploadQueue
};
amqpClient.init(receiverOptions, function(err) {
if (err) {
console.error("There was an error: " + err);
}
else {
amqpClient.subscribe(receiverOptions.qname, function(msg) {
console.log("got a message: ", JSON.stringify(msg));
});
}
});
| mit |
aescobarr/natusfera | spec/lib/acts_as_spammable/active_record_spec.rb | 4152 | require "spec_helper"
describe "ActsAsSpammable", "ActiveRecord" do
before(:all) do
@user = User.make!
Rakismet.disabled = false
end
after(:all) do
Rakismet.disabled = true
end
it "recognizes spam" do
Rakismet.should_receive(:akismet_call).and_return("true")
o = Observation.make!(user: @user)
o.spam?.should == true
end
it "recognizes non-spam" do
Rakismet.should_receive(:akismet_call).and_return("false")
o = Observation.make!(user: @user)
o.spam?.should == false
end
it "knows when it has been flagged as spam" do
Rakismet.should_receive(:akismet_call).and_return("false")
o = Observation.make!(user: @user)
o.flagged_as_spam?.should == false
Flag.make!(flaggable: o, flag: Flag::SPAM)
o.flagged_as_spam?.should == true
end
it "resolved flags are not spam" do
Rakismet.should_receive(:akismet_call).and_return("false")
o = Observation.make!(user: @user)
o.flagged_as_spam?.should == false
f = Flag.make!(flaggable: o, flag: Flag::SPAM)
o.flagged_as_spam?.should == true
Flag.last.update_attributes(resolved: true, resolver: @user)
o.flagged_as_spam?.should == false
end
it "does not check for spam unless a spammable field is modified" do
Rakismet.should_receive(:akismet_call).and_return("true")
o = Observation.make!(user: @user)
o.flagged_as_spam?.should == false
# we now set the user, which would normally cause an item to be flagged
# as spam by akismet. But since user isn't one of the text fields which
# we send to akismet, and none of those fields were changed, the spam
# check isn't triggered yet
o.positional_accuracy = 1234
o.save
o.flagged_as_spam?.should == false
o.reload
# and now we set one of the configured fields and the spam check is
# triggered. Since we set the spammy user above the check will fail
# and create a spam flag
o.description = "anything"
o.save
o.flagged_as_spam?.should == true
end
it "does not check for spam all fields are blank" do
o = Observation.make!(user: @user)
o.description = ""
o.should_not_receive(:spam?)
o.save
o.flagged_as_spam?.should == false
end
it "creates a spam flag when the akismet check fails" do
Rakismet.should_receive(:akismet_call).once.ordered.and_return("true")
o = Observation.make!(user: @user)
o.flagged_as_spam?.should == false
o.description = "spam"
o.save
o.flagged_as_spam?.should == true
end
it "ultimately updates the users spam count" do
starting_spam_count = @user.spam_count
Rakismet.should_receive(:akismet_call).once.ordered.and_return("true")
o = Observation.make!(user: @user, description: "something")
@user.reload
@user.spam_count.should == starting_spam_count + 1
end
it "knows which models are spammable" do
Observation.spammable?.should == true
Post.spammable?.should == true
User.spammable?.should == false
Taxon.spammable?.should == false
end
it "identifies flagged content as known_spam?" do
o = Observation.make!(user: @user)
o.known_spam?.should == false
Flag.make!(flaggable: o, flag: Flag::SPAM, user: @user)
o.reload
o.known_spam?.should == true
end
it "identifies spammer-owned content as owned_by_spammer?" do
Rakismet.should_receive(:akismet_call).and_return("false")
u = User.make!
o = Observation.make!(user: u)
o.owned_by_spammer?.should == false
u.update_column(:spammer, true)
o.reload
o.owned_by_spammer?.should == true
end
it "users are spam if they are spammers" do
Rakismet.should_receive(:akismet_call).and_return("false")
u = User.make!
u.owned_by_spammer?.should == false
u.update_column(:spammer, true)
u.reload
u.owned_by_spammer?.should == true
end
it "all models respond to known_spam?" do
Role.make!.known_spam?.should == false
Taxon.make!.known_spam?.should == false
end
it "all models respond to spam_or_owned_by_spammer?" do
Role.make!.owned_by_spammer?.should == false
Taxon.make!.owned_by_spammer?.should == false
end
end
| mit |
evanhughes3/tutorials | webpack/tutorial/node_modules/css-loader/lib/parseSource.js | 9143 | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var loaderUtils = require("loader-utils");
var Parser = require("fastparse");
function errorMatch(message, newParserMode) {
return function(match) {
var index = arguments[arguments.length - 1];
var nextLine = this.source.indexOf("\n", index);
var splittedSource = this.source.substr(0, index).split("\n");
var line = splittedSource.length;
var lineBeforeError = splittedSource.pop();
var lineAfterError = this.source.substr(index, nextLine);
this.errors.push("Unexpected '" + match + "' in line " + (line + 1) + ", " + message + "\n" +
lineBeforeError + lineAfterError + "\n" + lineBeforeError.replace(/[^\\s]/g, " ") + "^");
return newParserMode;
};
}
function urlMatch(match, textBeforeUrl, replacedText, url, index) {
this.urls.push({
url: url,
raw: replacedText,
start: index + textBeforeUrl.length,
length: replacedText.length
});
}
function importMatch(match, url, mediaQuery, index) {
this.imports.push({
url: url,
mediaQuery: mediaQuery,
start: index,
length: match.length
});
}
function rulesStartMatch() {
this.mode = null;
return "firstRule";
}
function rulesEndMatch() {
this.activeSelectors = [];
return "source";
}
function nextSelectorMatch() {
this.mode = null;
}
function enableLocal(match, whitespace, index) {
this.remove.push({
start: index + whitespace.length,
length: match.length - whitespace.length
});
this.mode = "local";
}
function enableGlobal(match, whitespace, index) {
this.remove.push({
start: index + whitespace.length,
length: match.length - whitespace.length
});
this.mode = "global";
}
function localStart(match, whitespace, index) {
this.remove.push({
start: index + whitespace.length,
length: match.length - whitespace.length
});
this.bracketStatus = 0;
return "local";
}
function globalStart(match, whitespace, index) {
this.remove.push({
start: index + whitespace.length,
length: match.length - whitespace.length
});
this.bracketStatus = 0;
return "global";
}
function withMode(mode, fn) {
return function() {
var oldMode = this.mode;
this.mode = mode;
var newParserMode = fn.apply(this, arguments);
this.mode = oldMode;
return newParserMode;
};
}
function jump(newParserMode, fn) {
return function() {
fn.apply(this, arguments);
return newParserMode;
};
}
function innerBracketIn() {
this.bracketStatus++;
}
function innerBracketOut(match, index) {
if(this.bracketStatus-- === 0) {
this.remove.push({
start: index,
length: match.length
});
return "source";
}
}
function selectorMatch(match, prefix, name, index) {
var selector = {
name: name,
prefix: prefix,
start: index,
length: match.length,
mode: this.mode
};
this.selectors.push(selector);
this.activeSelectors.push(selector);
}
function extendsStartMatch(match, index) {
this.remove.push({
start: index,
length: 0
});
this.activeExtends = [];
return "extends";
}
function extendsEndMatch(match, index) {
var lastRemove = this.remove[this.remove.length - 1];
lastRemove.length = index + match.length - lastRemove.start;
if(this.activeExtends.length === 0) {
errorMatch("expected class names")(match, index);
return "rule";
}
return "firstRule";
}
function extendsClassNameMatch(match, name, index) {
this.activeSelectors.forEach(function(selector) {
if(!selector.extends)
selector.extends = [];
var extend = {
name: name,
start: index,
length: match.length,
from: null,
fromType: null
};
selector.extends.push(extend);
this.activeExtends.push(extend);
}, this);
}
function extendsFromUrlMatch(match, request) {
this.activeExtends.forEach(function(extend) {
extend.from = request;
extend.fromType = "url";
});
}
function extendsFromMatch(match, request) {
this.activeExtends.forEach(function(extend) {
extend.from = loaderUtils.parseString(request);
extend.fromType = "module";
});
}
var parser = new Parser({
// shared stuff
comments: {
"/\\*.*?\\*/": true
},
strings: {
'"([^\\\\"]|\\\\.)*"': true,
"'([^\\\\']|\\\\.)*'": true
},
urls: {
'(url\\s*\\()(\\s*"([^"]*)"\\s*)\\)': urlMatch,
"(url\\s*\\()(\\s*'([^']*)'\\s*)\\)": urlMatch,
"(url\\s*\\()(\\s*([^)]*)\\s*)\\)": urlMatch
},
scopedRules: {
"(?:-[a-z]+-)?animation(?:-name)?:": "ruleScoped"
},
// states
source: [
"comments",
"strings",
"urls",
{
// imports
'@\\s*import\\s+"([^"]*)"\\s*([^;\\n]*);': importMatch,
"@\\s*import\\s+'([^'']*)'\\s*([^;\\n]*);": importMatch,
'@\\s*import\\s+url\\s*\\(\\s*"([^"]*)"\\s*\\)\\s*([^;\\n]*);': importMatch,
"@\\s*import\\s+url\\s*\\(\\s*'([^']*)'\\s*\\)\\s*([^;\\n]*);": importMatch,
"@\\s*import\\s+url\\s*\\(\\s*([^)]*)\\s*\\)\\s*([^;\\n]*);": importMatch,
// charset
"@charset": true,
// namespace
"@(?:-[a-z]+-)?namespace": true,
// atrule
"@(?:-[a-z]+-)?keyframes": "atruleScoped",
"@": "atrule"
},
{
// local
"(\\s*):local\\(": localStart,
"():local": enableLocal,
"(\\s+):local\\s+": enableLocal,
// global
"(\\s*):global\\(": globalStart,
"():global": enableGlobal,
"(\\s+):global\\s+": enableGlobal,
// class
"(\\.)([A-Za-z_\\-0-9]+)": selectorMatch,
// id
"(#)([A-Za-z_\\-0-9]+)": selectorMatch,
// inside
"\\{": rulesStartMatch,
",": nextSelectorMatch
}
],
atruleScoped: [
"comments",
"strings",
{
// identifier
":local\\(\\s*()([A-Za-z_\\-0-9]+)\\s*\\)": withMode("local", selectorMatch),
":global\\(\\s*()([A-Za-z_\\-0-9]+)\\s*\\)": withMode("global", selectorMatch),
"()([A-Za-z_\\-0-9]+)": selectorMatch,
// local
"():local": enableLocal,
"(\\s+):local\\s+": enableLocal,
// global
"():global": enableGlobal,
"(\\s+):global\\s+": enableGlobal,
// back to normal source
"\\{": "source"
}
],
atrule: [
"comments",
"strings",
{
// back to normal source
"\\{": "source"
}
],
ruleScoped: [
"comments",
{
// identifier
":local\\(\\s*()([A-Za-z_\\-0-9]+)\\s*\\)": jump("ruleScopedInactive", withMode("local", selectorMatch)),
":global\\(\\s*()([A-Za-z_\\-0-9]+)\\s*\\)": jump("ruleScopedInactive", withMode("global", selectorMatch)),
"()([A-Za-z_\\-0-9]+)": jump("ruleScopedInactive", selectorMatch),
// local
"():local": enableLocal,
"(\\s+):local\\s+": enableLocal,
// global
"():global": enableGlobal,
"(\\s+):global\\s+": enableGlobal,
// back to normal rule
";": "rule",
// back to normal source
"\\}": rulesEndMatch
}
],
ruleScopedInactive: [
"comments",
{
// reactivate
",": "ruleScoped",
// back to normal rule
";": "rule",
// back to normal source
"\\}": rulesEndMatch
}
],
rule: [
"comments",
"strings",
"urls",
"scopedRules",
{
// back to normal source
"\\}": rulesEndMatch
}
],
firstRule: [
"rule",
{
"extends\\s*:": extendsStartMatch,
// whitespace
"\\s+": true,
// url
".": "rule"
}
],
extends: [
"comments",
{
";\\s*": extendsEndMatch,
// whitespace
"\\s+": true,
// from
"from": "extendsFrom",
// class name
"([A-Za-z_\\-0-9]+)": extendsClassNameMatch,
".+[;}]": errorMatch("expected class names or 'from'", "rule"),
".": errorMatch("expected class names or 'from'", "rule")
}
],
extendsFrom: [
"comments",
{
";\\s*": extendsEndMatch,
// whitespace
"\\s+": true,
// module
'url\\s*\\(\\s*"([^"]*)"\\s*\\)': extendsFromUrlMatch,
"url\\s*\\(\\s*'([^']*)'\\s*\\)": extendsFromUrlMatch,
"url\\s*\\(\\s*([^)]*)\\s*\\)": extendsFromUrlMatch,
'("(?:[^\\\\"]|\\\\.)*")': extendsFromMatch,
"('(?:[^\\\\']|\\\\.)*')": extendsFromMatch,
".+[;}]": errorMatch("expected module identifier (a string or 'url(...)'')", "rule"),
".": errorMatch("expected module identifier (a string or 'url(...)'')", "rule")
}
],
local: [
"comments",
"strings",
{
// class
"(\\.)([A-Za-z_\\-0-9]+)": withMode("local", selectorMatch),
// id
"(#)([A-Za-z_\\-0-9]+)": withMode("local", selectorMatch),
// brackets
"\\(": innerBracketIn,
"\\)": innerBracketOut
}
],
global: [
"comments",
"strings",
{
// class
"(\\.)([A-Za-z_\\-0-9]+)": withMode("global", selectorMatch),
// id
"(#)([A-Za-z_\\-0-9]+)": withMode("global", selectorMatch),
// brackets
"\\(": innerBracketIn,
"\\)": innerBracketOut
}
]
});
module.exports = function parseSource(source) {
var context = {
source: source,
imports: [],
urls: [],
selectors: [],
remove: [],
errors: [],
activeSelectors: [],
bracketStatus: 0,
mode: null
};
return parser.parse("source", source, context);
};
| mit |
civol/HDLRuby | lib/HDLRuby/high_samples/with_fsm.rb | 991 | require 'HDLRuby'
configure_high
require 'HDLRuby/std/fsm'
include HDLRuby::High::Std
# Implementation of a fsm.
system :my_fsm do
input :clk,:rst
[7..0].input :a, :b
[7..0].output :z
# fsm :fsmI
# fsmI.for_event { clk.posedge }
# # Shortcut: fsmI.for_event(clk)
# fsmI.for_reset { rst }
# # Shortcut: fsmI.for_reset(rst)
# fsmI do
# state { z <= 0 }
# state(:there) { z <= a+b }
# state do
# hif (a>0) { z <= a-b }
# helse { goto(:there) }
# end
# end
# Other alternative:
fsm(clk.posedge,rst) do
reset { z <= 0 }
state { z <= a+b }
state(:there) do
hif (z!=0) { z <= a-b }
goto(z==0,:end,:there)
end
state(:end) { goto(:end) }
end
end
# Instantiate it for checking.
my_fsm :my_fsmI
# Generate the low level representation.
low = my_fsmI.systemT.to_low
# Displays it
puts low.to_yaml
| mit |
DDReaper/XNAGameStudio | Samples/PerformanceMeasuringSample_4_0/PerformanceMeasuring/PerformanceMeasuring/Program.cs | 729 | #region File Description
//-----------------------------------------------------------------------------
// Program.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
using System;
namespace PerformanceMeasuring
{
#if WINDOWS || XBOX
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
using (PerformanceMeasuringGame game = new PerformanceMeasuringGame())
{
game.Run();
}
}
}
#endif
}
| mit |
Skrittles/SPMinistocks | src/nitezh/ministock/utils/UrlDataTools.java | 2680 | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
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 nitezh.ministock.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class UrlDataTools {
private UrlDataTools() {
}
private static String inputStreamToString(InputStream stream) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
builder.append(line).append("\n");
}
return builder.toString();
}
private static String getUrlData(String url) {
// Ensure we always request some data
if (!url.contains("INDU")) {
url = url.replace("&s=", "&s=INDU+");
}
try {
URLConnection connection = new URL(url).openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(60000);
return inputStreamToString(connection.getInputStream());
} catch (IOException ignored) {
}
return null;
}
public static String getCachedUrlData(String url, Cache cache, Integer ttl) {
String data;
if (ttl != null && (data = cache.get(url)) != null) {
return data;
}
data = getUrlData(url);
if (data != null) {
cache.put(url, data, ttl);
return data;
}
return "";
}
}
| mit |
hkupty/dotfiles | .config/nvim/lua/tasks.lua | 3761 | local errands = require("errands")
local tasks = require("errands.tasks")
local impromptu = require("impromptu")
local pop = {
description = "Return to previous screen"
}
local with_pop = function(fn)
return function(session, option)
if option.index == 'pop' then
session:pop()
return false
else
return fn(session, option)
end
end
end
local _new_task = function()
return impromptu.new.form{
title = "New task",
options = {
title = {
description = "Title"
},
descr = {
description = "Task Description"
}
},
handler = function(_, answers)
errands.task(answers)
return true
end
}
end
local _new_note = function()
return impromptu.new.form{
title = "New note",
options = {
title = {
description = "Note"
}
},
handler = function(_, answers)
errands.task(answers)
return true
end
}
end
local _show = function(errand)
return impromptu.new.showcase{
title = "Show Errand",
options = errand,
actions = { pop = pop },
handler = with_pop(function(session, opt)
return true
end)
}
end
local _list = function()
local err_list = {}
local title_from_item = function(item)
return "[" .. tasks.status(item) .. "] " .. item.title
end
errands.tasks(function(errands)
for k, v in pairs(errands) do
err_list[k] = title_from_item(v)
end
end)
return impromptu.new.showcase{
title = "List errands",
options = err_list,
actions = { pop = pop },
handler = with_pop(function(session, opt)
return true
end)
}
end
local _manage_errand = function(errand)
return impromptu.new.ask{
title = "Managing [" .. errand.title .. "]",
options = {
pop = pop,
close = {
description = "Complete errand"
},
show = {
description = "Show errand"
}
},
handler = with_pop(function(session, opt)
if opt.index == 'close' then
errands.upsert(tasks.complete(errand))
return true
elseif opt.index == 'show' then
session:stack(_show(errand))
return false
end
end)
}
end
local _all_errands = function()
local opt_from_item = function(item)
return {
description = "[" .. tasks.status(item) .. "] " .. item.title,
errand = item
}
end
local opts = {
title = "Manage Errands",
handler = with_pop(function(session, opt)
if opt.index == 'completed' then
for _, k in errands.tasks(errands.filters.completed) do
session.lines[k.id] = opt_from_item(k)
end
else
session:stack(_manage_errand(opt.errand))
end
return false
end),
options = {
pop = pop,
completed = {
description = "Show completed errands"
}
}
}
for _, k in errands.tasks(errands.filters.open) do
opts.options[k.id] = opt_from_item(k)
end
return impromptu.new.ask(opts)
end
local _errands = function()
return impromptu.new.ask{
title = "Errands",
options = {
task = {
description = "Create new errand"
},
note = {
description = "Write new note"
},
list = {
description = "List errands"
},
manage = {
description = "Manage existing errands"
}
},
handler = function(session, opt)
errands.read()
if opt.index == 'task' then
session:stack(_new_task())
elseif opt.index == 'note' then
session:stack(_new_note())
elseif opt.index == 'list' then
session:stack(_list())
elseif opt.index == 'manage' then
session:stack(_all_errands())
end
return false
end
}
end
_G.tasks = function()
impromptu.session():stack(_errands()):render()
end
vim.api.nvim_command[[map <C-q> <Cmd>lua tasks()<Cr>]]
| mit |
posita/stone | stone/frontend/lexer.py | 13729 | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
import ply.lex as lex
_MYPY = False
if _MYPY:
import typing # noqa: F401 # pylint: disable=import-error,unused-import,useless-suppression
class MultiToken(object):
"""Object used to monkeypatch ply.lex so that we can return multiple
tokens from one lex operation."""
def __init__(self, tokens):
self.type = tokens[0].type
self.tokens = tokens
# Represents a null value. We want to differentiate between the Python "None"
# and null in several places.
NullToken = object()
class Lexer(object):
"""
Lexer. Tokenizes stone files.
"""
states = (
('WSIGNORE', 'inclusive'),
)
def __init__(self):
self.lex = None
self.tokens_queue = None
# The current indentation "level" rather than a count of spaces.
self.cur_indent = None
self._logger = logging.getLogger('stone.stone.lexer')
self.last_token = None
# [(character, line number), ...]
self.errors = []
def input(self, file_data, **kwargs):
"""
Required by ply.yacc for this to quack (duck typing) like a ply lexer.
:param str file_data: Contents of the file to lex.
"""
self.lex = lex.lex(module=self, **kwargs)
self.tokens_queue = []
self.cur_indent = 0
# Hack to avoid tokenization bugs caused by files that do not end in a
# new line.
self.lex.input(file_data + '\n')
def token(self):
"""
Returns the next LexToken. Returns None when all tokens have been
exhausted.
"""
if self.tokens_queue:
self.last_token = self.tokens_queue.pop(0)
else:
r = self.lex.token()
if isinstance(r, MultiToken):
self.tokens_queue.extend(r.tokens)
self.last_token = self.tokens_queue.pop(0)
else:
if r is None and self.cur_indent > 0:
if (self.last_token and
self.last_token.type not in ('NEWLINE', 'LINE')):
newline_token = _create_token(
'NEWLINE', '\n', self.lex.lineno, self.lex.lexpos)
self.tokens_queue.append(newline_token)
dedent_count = self.cur_indent
dedent_token = _create_token(
'DEDENT', '\t', self.lex.lineno, self.lex.lexpos)
self.tokens_queue.extend([dedent_token] * dedent_count)
self.cur_indent = 0
self.last_token = self.tokens_queue.pop(0)
else:
self.last_token = r
return self.last_token
def test(self, data):
"""Logs all tokens for human inspection. Useful for debugging."""
self.input(data)
while True:
token = self.token()
if not token:
break
self._logger.debug('Token %r', token)
# List of token names
tokens = (
'ID',
'KEYWORD',
'PATH',
'DOT',
) # type: typing.Tuple[typing.Text, ...]
# Whitespace tokens
tokens += (
'DEDENT',
'INDENT',
'NEWLINE',
)
# Attribute lists, aliases
tokens += (
'COMMA',
'EQ',
'LPAR',
'RPAR',
)
# Primitive types
tokens += (
'BOOLEAN',
'FLOAT',
'INTEGER',
'NULL',
'STRING',
)
# List notation
tokens += (
'LBRACKET',
'RBRACKET',
)
# Map notation
tokens += (
'LBRACE',
'RBRACE',
'COLON',
)
tokens += (
'Q',
)
# Annotation notation
tokens += (
'AT',
)
# Regular expression rules for simple tokens
t_DOT = r'\.'
t_LBRACKET = r'\['
t_RBRACKET = r'\]'
t_EQ = r'='
t_COMMA = r','
t_Q = r'\?'
t_LBRACE = r'\{'
t_RBRACE = r'\}'
t_COLON = r'\:'
t_AT = r'@'
# TODO(kelkabany): Use scoped/conditional lexing to restrict where keywords
# are identified as such.
KEYWORDS = [
'alias',
'annotation',
'attrs',
'by',
'deprecated',
'doc',
'example',
'error',
'extends',
'import',
'namespace',
'patch',
'route',
'struct',
'union',
'union_closed',
]
RESERVED = {
'annotation': 'ANNOTATION',
'attrs': 'ATTRS',
'deprecated': 'DEPRECATED',
'by': 'BY',
'extends': 'EXTENDS',
'import': 'IMPORT',
'patch': 'PATCH',
'route': 'ROUTE',
'struct': 'STRUCT',
'union': 'UNION',
'union_closed': 'UNION_CLOSED',
}
tokens += tuple(RESERVED.values())
def t_LPAR(self, token):
r'\('
token.lexer.push_state('WSIGNORE')
return token
def t_RPAR(self, token):
r'\)'
token.lexer.pop_state()
return token
def t_ANY_BOOLEAN(self, token):
r'\btrue\b|\bfalse\b'
token.value = (token.value == 'true')
return token
def t_ANY_NULL(self, token):
r'\bnull\b'
token.value = NullToken
return token
# No leading digits
def t_ANY_ID(self, token):
r'[a-zA-Z_][a-zA-Z0-9_-]*'
if token.value in self.KEYWORDS:
token.type = self.RESERVED.get(token.value, 'KEYWORD')
return token
else:
return token
def t_ANY_PATH(self, token):
r'\/[/a-zA-Z0-9_-]*'
return token
def t_ANY_FLOAT(self, token):
r'-?\d+(\.\d*(e-?\d+)?|e-?\d+)'
token.value = float(token.value)
return token
def t_ANY_INTEGER(self, token):
r'-?\d+'
token.value = int(token.value)
return token
# Read in a string while respecting the following escape sequences:
# \", \\, \n, and \t.
def t_ANY_STRING(self, t):
r'\"([^\\"]|(\\.))*\"'
escaped = 0
t.lexer.lineno += t.value.count('\n')
s = t.value[1:-1]
new_str = ""
for i in range(0, len(s)):
c = s[i]
if escaped:
if c == 'n':
c = '\n'
elif c == 't':
c = '\t'
new_str += c
escaped = 0
else:
if c == '\\':
escaped = 1
else:
new_str += c
# remove current indentation
indentation_str = ' ' * _indent_level_to_spaces_count(self.cur_indent)
lines_without_indentation = [
line.replace(indentation_str, '', 1)
for line in new_str.splitlines()]
t.value = '\n'.join(lines_without_indentation)
return t
# Ignore comments.
# There are two types of comments.
# 1. Comments that take up a full line. These lines are ignored entirely.
# 2. Comments that come after tokens in the same line. These comments
# are ignored, but, we still need to emit a NEWLINE since this rule
# takes all trailing newlines.
# Regardless of comment type, the following line must be checked for a
# DEDENT or INDENT.
def t_INITIAL_comment(self, token):
r'[#][^\n]*\n+'
token.lexer.lineno += token.value.count('\n')
# Scan backwards from the comment hash to figure out which type of
# comment this is. If we find an non-ws character, we know it was a
# partial line. But, if we find a newline before a non-ws character,
# then we know the entire line was a comment.
i = token.lexpos - 1
while i >= 0:
is_full_line_comment = token.lexer.lexdata[i] == '\n'
is_partial_line_comment = (not is_full_line_comment and
token.lexer.lexdata[i] != ' ')
if is_full_line_comment or is_partial_line_comment:
newline_token = _create_token('NEWLINE', '\n',
token.lineno, token.lexpos + len(token.value) - 1)
newline_token.lexer = token.lexer
dent_tokens = self._create_tokens_for_next_line_dent(
newline_token)
if is_full_line_comment:
# Comment takes the full line so ignore entirely.
return dent_tokens
elif is_partial_line_comment:
# Comment is only a partial line. Preserve newline token.
if dent_tokens:
dent_tokens.tokens.insert(0, newline_token)
return dent_tokens
else:
return newline_token
i -= 1
def t_WSIGNORE_comment(self, token):
r'[#][^\n]*\n+'
token.lexer.lineno += token.value.count('\n')
newline_token = _create_token('NEWLINE', '\n',
token.lineno, token.lexpos + len(token.value) - 1)
newline_token.lexer = token.lexer
self._check_for_indent(newline_token)
# Define a rule so we can track line numbers
def t_INITIAL_NEWLINE(self, newline_token):
r'\n+'
newline_token.lexer.lineno += newline_token.value.count('\n')
dent_tokens = self._create_tokens_for_next_line_dent(newline_token)
if dent_tokens:
dent_tokens.tokens.insert(0, newline_token)
return dent_tokens
else:
return newline_token
def t_WSIGNORE_NEWLINE(self, newline_token):
r'\n+'
newline_token.lexer.lineno += newline_token.value.count('\n')
self._check_for_indent(newline_token)
def _create_tokens_for_next_line_dent(self, newline_token):
"""
Starting from a newline token that isn't followed by another newline
token, returns any indent or dedent tokens that immediately follow.
If indentation doesn't change, returns None.
"""
indent_delta = self._get_next_line_indent_delta(newline_token)
if indent_delta is None or indent_delta == 0:
# Next line's indent isn't relevant OR there was no change in
# indentation.
return None
dent_type = 'INDENT' if indent_delta > 0 else 'DEDENT'
dent_token = _create_token(
dent_type, '\t', newline_token.lineno + 1,
newline_token.lexpos + len(newline_token.value))
tokens = [dent_token] * abs(indent_delta)
self.cur_indent += indent_delta
return MultiToken(tokens)
def _check_for_indent(self, newline_token):
"""
Checks that the line following a newline is indented, otherwise a
parsing error is generated.
"""
indent_delta = self._get_next_line_indent_delta(newline_token)
if indent_delta is None or indent_delta == 1:
# Next line's indent isn't relevant (e.g. it's a comment) OR
# next line is correctly indented.
return None
else:
self.errors.append(
('Line continuation must increment indent by 1.',
newline_token.lexer.lineno))
def _get_next_line_indent_delta(self, newline_token):
"""
Returns the change in indentation. The return units are in
indentations rather than spaces/tabs.
If the next line's indent isn't relevant (e.g. it's a comment),
returns None. Since the return value might be 0, the caller should
explicitly check the return type, rather than rely on truthiness.
"""
assert newline_token.type == 'NEWLINE', \
'Can only search for a dent starting from a newline.'
next_line_pos = newline_token.lexpos + len(newline_token.value)
if next_line_pos == len(newline_token.lexer.lexdata):
# Reached end of file
return None
line = newline_token.lexer.lexdata[next_line_pos:].split(os.linesep, 1)[0]
if not line:
return None
lstripped_line = line.lstrip()
lstripped_line_length = len(lstripped_line)
if lstripped_line_length == 0:
# If the next line is composed of only spaces, ignore indentation.
return None
if lstripped_line[0] == '#':
# If it's a comment line, ignore indentation.
return None
indent = len(line) - lstripped_line_length
if indent % 4 > 0:
self.errors.append(
('Indent is not divisible by 4.', newline_token.lexer.lineno))
return None
indent_delta = indent - _indent_level_to_spaces_count(self.cur_indent)
return indent_delta // 4
# A string containing ignored characters (spaces and tabs)
t_ignore = ' \t'
# Error handling rule
def t_ANY_error(self, token):
self._logger.debug('Illegal character %r at line %d',
token.value[0], token.lexer.lineno)
self.errors.append(
('Illegal character %s.' % repr(token.value[0]).lstrip('u'),
token.lexer.lineno))
token.lexer.skip(1)
def _create_token(token_type, value, lineno, lexpos):
"""
Helper for creating ply.lex.LexToken objects. Unfortunately, LexToken
does not have a constructor defined to make settings these values easy.
"""
token = lex.LexToken()
token.type = token_type
token.value = value
token.lineno = lineno
token.lexpos = lexpos
return token
def _indent_level_to_spaces_count(indent):
return indent * 4
| mit |
kairos666/pmp-ui | e2e/app.po.ts | 210 | import { browser, element, by } from 'protractor';
export class PmpUiPage {
navigateTo() {
return browser.get('/');
}
getParagraphText() {
return element(by.css('app-root h1')).getText();
}
}
| mit |
storybooks/storybook | addons/measure/src/preset/addDecorator.tsx | 181 | import { withMeasure } from '../withMeasure';
import { PARAM_KEY } from '../constants';
export const decorators = [withMeasure];
export const globals = {
[PARAM_KEY]: false,
};
| mit |
mathiasquintero/RandomStuff | Java/Numerical Programming/FastMath/Gleitpunktzahl.java | 11162 |
public class Gleitpunktzahl {
/**
* Update by
*
* @author Juergen Braeckle ([email protected])
* @author Sebastian Rettenberger ([email protected])
* @since Oktober 22, 2014
* @version 1.2
*
* Diese Klasse beschreibt eine Form von Gleitpunktarithmetik
*/
/********************/
/* Membervariablen: */
/********************/
/* Vorzeichen, Mantisse und Exponent der Gleitpunktzahl */
public boolean vorzeichen; /* true = "-1" */
public int exponent;
public int mantisse;
/*
* Anzahl der Bits fuer die Mantisse: einmal gesetzt, soll sie nicht mehr
* veraendert werden koennen
*/
private static int sizeMantisse = 32;
private static boolean sizeMantisseFixed = false;
/*
* Anzahl der Bits fuer dem Exponent: einmal gesetzt, soll sie nicht mehr
* veraendert werden koennen. Maximale Groesse: 32
*/
private static int sizeExponent = 8;
private static boolean sizeExponentFixed = false;
/*
* Aus der Anzahl an Bits fuer den Exponenten laesst sich der maximale
* Exponent und der Offset berechnen
*/
private static int maxExponent = (int) Math.pow(2, sizeExponent) - 1;
private static int expOffset = (int) Math.pow(2, sizeExponent - 1) - 1;
/**
* Falls die Anzahl der Bits der Mantisse noch nicht gesperrt ist, so wird
* sie auf abm gesetzt und gesperrt
*/
public static void setSizeMantisse(int abm) {
/*
* Falls sizeMantisse noch nicht gesetzt und abm > 0 dann setze auf
* abm und sperre den Zugriff
*/
if (!sizeMantisseFixed & (abm > 0)) {
sizeMantisse = abm;
sizeMantisseFixed = true;
}
}
/**
* Falls die Anzahl der Bits des Exponenten noch nicht gesperrt ist, so wird
* sie auf abe gesetzt und gesperrt. maxExponent und expOffset werden
* festgelegt
*/
public static void setSizeExponent(int abe) {
if (!sizeExponentFixed & (abe > 0)) {
sizeExponent = abe;
sizeExponentFixed = true;
maxExponent = (int) Math.pow(2, abe) - 1;
expOffset = (int) Math.pow(2, abe - 1) - 1;
}
}
/** Liefert die Anzahl der Bits der Mantisse */
public static int getSizeMantisse() {
return sizeMantisse;
}
/** Liefert die Anzahl der Bits des Exponenten */
public static int getSizeExponent() {
return sizeExponent;
}
/**
* erzeugt eine Gleitpunktzahl ohne Anfangswert. Die Bitfelder fuer Mantisse
* und Exponent werden angelegt. Ist die Anzahl der Bits noch nicht gesetzt,
* wird der Standardwert gesperrt
*/
Gleitpunktzahl() {
sizeMantisseFixed = true;
sizeExponentFixed = true;
}
/** erzeugt eine Kopie der reellen Zahl r */
Gleitpunktzahl(Gleitpunktzahl r) {
/* Vorzeichen kopieren */
this.vorzeichen = r.vorzeichen;
/*
* Kopiert den Inhalt der jeweiligen Felder aus r
*/
this.exponent = r.exponent;
this.mantisse = r.mantisse;
}
/**
* erzeugt eine reelle Zahl mit der Repraesentation des Double-Wertes d. Ist
* die Anzahl der Bits fuer Mantisse und Exponent noch nicht gesetzt, wird
* der Standardwert gesperrt
*/
Gleitpunktzahl(double d) {
this();
this.setDouble(d);
}
/**
* setzt dieses Objekt mit der Repraesentation des Double-Wertes d.
*/
public void setDouble(double d) {
/* Abfangen der Sonderfaelle */
if (d == 0) {
this.setNull();
return;
}
if (Double.isInfinite(d)) {
this.setInfinite(d < 0);
return;
}
if (Double.isNaN(d)) {
this.setNaN();
return;
}
/* Falls d<0 -> Vorzeichen setzten, Vorzeichen von d wechseln */
if (d < 0) {
this.vorzeichen = true;
d = -d;
} else
this.vorzeichen = false;
/*
* Exponent exp von d zur Basis 2 finden d ist danach im Intervall [1,2)
*/
int exp = 0;
while (d >= 2) {
d = d / 2;
exp++;
}
while (d < 1) {
d = 2 * d;
exp--;
} /* d in [1,2) */
this.exponent = exp + expOffset;
/*
* Mantisse finden; fuer Runden eine Stelle mehr als noetig berechnen
*/
double rest = d;
this.mantisse = 0;
for (int i = 0; i <= sizeMantisse; i++) {
this.mantisse <<= 1;
if (rest >= 1) {
rest = rest - 1;
this.mantisse |= 1;
}
rest = 2 * rest;
}
this.exponent -= 1; /* Mantisse ist um eine Stelle groesser! */
/*
* normalisiere uebernimmt die Aufgaben des Rundens
*/
this.normalisiere();
}
/** liefert eine String-Repraesentation des Objekts */
public String toString() {
if (this.isNaN())
return "NaN";
if (this.isNull())
return "0";
StringBuffer s = new StringBuffer();
if (this.vorzeichen)
s.append('-');
if (this.isInfinite())
s.append("Inf");
else {
for (int i = 32 - Integer.numberOfLeadingZeros(this.mantisse) - 1;
i >= 0; i--) {
if (i == sizeMantisse - 2)
s.append(',');
if (((this.mantisse >> i) & 1) == 1)
s.append('1');
else
s.append('0');
}
s.append(" * 2^(");
s.append(this.exponent);
s.append("-");
s.append(expOffset);
s.append(")");
}
return s.toString();
}
/** berechnet den Double-Wert des Objekts */
public double toDouble() {
/*
* Wenn der Exponent maximal ist, nimmt die Gleitpunktzahl einen der
* speziellen Werte an
*/
if (this.exponent == maxExponent) {
/*
* Wenn die Mantisse Null ist, hat die Zahl den Wert Unendlich oder
* -Unendlich
*/
if (this.mantisse == 0) {
if (this.vorzeichen)
return -1.0 / 0.0;
else
return 1.0 / 0.0;
}
/* Ansonsten ist der Wert NaN */
else
return 0.0 / 0.0;
}
double m = this.mantisse;
if (this.vorzeichen)
m *= (-1);
return m
* Math.pow(2, (this.exponent - expOffset)
- (sizeMantisse - 1));
}
/**
* Sonderfaelle abfragen
*/
/** Liefert true, wenn die Gleitpunktzahl die Null repraesentiert */
public boolean isNull() {
return (!this.vorzeichen && this.mantisse == 0 && this.exponent == 0);
}
/**
* Liefert true, wenn die Gleitpunktzahl der NotaNumber Darstellung
* entspricht
*/
public boolean isNaN() {
return (this.mantisse != 0 && this.exponent == maxExponent);
}
/** Liefert true, wenn die Gleitpunktzahl betragsmaessig unendlich gross ist */
public boolean isInfinite() {
return (this.mantisse == 0 && this.exponent == maxExponent);
}
/**
* vergleicht betragsmaessig den Wert des aktuellen Objekts mit der reellen
* Zahl r
*/
public int compareAbsTo(Gleitpunktzahl r) {
/*
* liefert groesser gleich 1, falls |this| > |r|
* 0, falls |this| = |r|
* kleiner gleich -1, falls |this| < |r|
*/
if (this.isNaN() && r.isNaN()) return 0;
/* Exponenten vergleichen */
int expVergleich = this.exponent - r.exponent;
if (expVergleich != 0)
return expVergleich;
/* Bei gleichen Exponenten: Bitweisses Vergleichen der Mantissen */
return this.mantisse - r.mantisse;
}
/**
* normalisiert und rundet das aktuelle Objekt auf die Darstellung r =
* (-1)^vorzeichen * 1,r_t-1 r_t-2 ... r_1 r_0 * 2^exponent. Die 0 wird zu
* (-1)^0 * 0,00...00 * 2^0 normalisiert WICHTIG: Es kann sein, dass die
* Anzahl der Bits nicht mit sizeMantisse uebereinstimmt. Das Ergebnis
* soll aber eine Mantisse mit sizeMantisse Bits haben. Deshalb muss
* evtl. mit Bits aufgefuellt oder Bits abgeschnitten werden. Dabei muss das
* Ergebnis nach Definition gerundet werden.
*
* Beispiel: Bei 3 Mantissenbits wird die Zahl 10.11 * 2^-1 zu 1.10 * 2^0
*/
public void normalisiere() {
if (isNull() || isInfinite()) return;
shrinkMantisse();
expandMantisse();
}
/**
* Will shrink the Mantisse and increase the exponent accordingly.
* if the exponent reaches its maximum the value will
* be set to inf
*/
public void shrinkMantisse() {
int maxMantisse = (int) Math.pow(2, sizeMantisse) - 1;
int counter = 0, tmp = mantisse;
while (mantisse > maxMantisse) {
mantisse >>= 1;
exponent++;
counter++;
}
tmp >>= counter - 1;
mantisse += (tmp & 1);
if (mantisse > maxMantisse)
shrinkMantisse();
if (exponent >= maxExponent)
setInfinite(vorzeichen);
}
/**
* Will expand the Mantisse to fill up the last bit.
* This will also decrease the exponent.
*/
public void expandMantisse() {
int minMantisse = (int) Math.pow(2, sizeMantisse - 1);
while (mantisse != 0 && mantisse < minMantisse) {
mantisse <<= 1;
exponent--;
}
}
/**
* denormalisiert die betragsmaessig goessere Zahl, so dass die Exponenten
* von a und b gleich sind. Die Mantissen beider Zahlen werden entsprechend
* erweitert. Denormalisieren wird fuer add und sub benoetigt.
*/
public static void denormalisiere(Gleitpunktzahl a, Gleitpunktzahl b) {
int compareResult = a.compareAbsTo(b);
Gleitpunktzahl big = compareResult >= 0 ? a : b;
Gleitpunktzahl small = compareResult >= 0 ? b : a;
while (small.exponent < big.exponent) {
big.exponent--;
big.mantisse *= 2;
}
}
/**
* addiert das aktuelle Objekt und die Gleitpunktzahl r. Dabei wird zuerst
* die betragsmaessig groessere Zahl denormalisiert und die Mantissen beider
* zahlen entsprechend vergroessert. Das Ergebnis wird in einem neuen Objekt
* gespeichert, normiert, und dieses wird zurueckgegeben.
*/
public Gleitpunktzahl add(Gleitpunktzahl r) {
if (this.isInfinite() && r.isInfinite() && this.vorzeichen != r.vorzeichen) {
r = new Gleitpunktzahl();
r.setNaN();
return r;
}
if (this.isNull() || r.isInfinite()) return new Gleitpunktzahl(r);
if (r.isNull() || this.isInfinite()) return new Gleitpunktzahl(this);
denormalisiere(this, r);
Gleitpunktzahl result = new Gleitpunktzahl();
result.vorzeichen = this.vorzeichen;
result.exponent = this.exponent;
if (this.vorzeichen == r.vorzeichen) {
result.mantisse = this.mantisse + r.mantisse;
} else {
int res = this.mantisse - r.mantisse;
result.mantisse = Math.abs(res);
if (res < 0) result.vorzeichen = !result.vorzeichen;
}
this.normalisiere();
r.normalisiere();
result.normalisiere();
return result;
}
/**
* subtrahiert vom aktuellen Objekt die Gleitpunktzahl r. Dabei wird zuerst
* die betragsmaessig groessere Zahl denormalisiert und die Mantissen beider
* zahlen entsprechend vergroessert. Das Ergebnis wird in einem neuen Objekt
* gespeichert, normiert, und dieses wird zurueckgegeben.
*/
public Gleitpunktzahl sub(Gleitpunktzahl r) {
Gleitpunktzahl z = new Gleitpunktzahl(r);
z.vorzeichen = !r.vorzeichen;
return add(z);
}
/**
* Setzt die Zahl auf den Sonderfall 0
*/
public void setNull() {
this.vorzeichen = false;
this.exponent = 0;
this.mantisse = 0;
}
/**
* Setzt die Zahl auf den Sonderfall +/- unendlich
*/
public void setInfinite(boolean vorzeichen) {
this.vorzeichen = vorzeichen;
this.exponent = maxExponent;
this.mantisse = 0;
}
/**
* Setzt die Zahl auf den Sonderfall NaN
*/
public void setNaN() {
this.vorzeichen = false;
this.exponent = maxExponent;
this.mantisse = 1;
}
}
| mit |
FezVrasta/brackets-git | src/git/GitCli.js | 31744 | /*jshint maxstatements:false*/
/*
This module is used to communicate with Git through Cli
Output string from Git should always be parsed here
to provide more sensible outputs than just plain strings.
Format of the output should be specified in Git.js
*/
define(function (require, exports) {
// Brackets modules
var _ = brackets.getModule("thirdparty/lodash"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
FileUtils = brackets.getModule("file/FileUtils");
// Local modules
var Promise = require("bluebird"),
Cli = require("src/Cli"),
ErrorHandler = require("src/ErrorHandler"),
Events = require("src/Events"),
EventEmitter = require("src/EventEmitter"),
ExpectedError = require("src/ExpectedError"),
Preferences = require("src/Preferences"),
Utils = require("src/Utils");
// Module variables
var _gitPath = null,
_gitQueue = [],
_gitQueueBusy = false;
var FILE_STATUS = {
STAGED: "STAGED",
UNMODIFIED: "UNMODIFIED",
IGNORED: "IGNORED",
UNTRACKED: "UNTRACKED",
MODIFIED: "MODIFIED",
ADDED: "ADDED",
DELETED: "DELETED",
RENAMED: "RENAMED",
COPIED: "COPIED",
UNMERGED: "UNMERGED"
};
// Implementation
function getGitPath() {
if (_gitPath) { return _gitPath; }
_gitPath = Preferences.get("gitPath");
return _gitPath;
}
function setGitPath(path) {
if (path === true) { path = "git"; }
Preferences.set("gitPath", path);
_gitPath = path;
}
function _processQueue() {
// do nothing if the queue is busy
if (_gitQueueBusy) {
return;
}
// do nothing if the queue is empty
if (_gitQueue.length === 0) {
_gitQueueBusy = false;
return;
}
// get item from queue
var item = _gitQueue.shift(),
defer = item[0],
args = item[1],
opts = item[2];
// execute git command in a queue so no two commands are running at the same time
if (opts.nonblocking !== true) { _gitQueueBusy = true; }
Cli.spawnCommand(getGitPath(), args, opts)
.progressed(function () {
defer.progress.apply(defer, arguments);
})
.then(function (r) {
defer.resolve(r);
})
.catch(function (e) {
var call = "call: git " + args.join(" ");
e.stack = [call, e.stack].join("\n");
defer.reject(e);
})
.finally(function () {
if (opts.nonblocking !== true) { _gitQueueBusy = false; }
_processQueue();
});
}
function git(args, opts) {
var rv = Promise.defer();
_gitQueue.push([rv, args || [], opts || {}]);
_processQueue();
return rv.promise;
}
/*
git branch
-d --delete Delete a branch.
-D Delete a branch irrespective of its merged status.
--no-color Turn off branch colors
-r --remotes List or delete (if used with -d) the remote-tracking branches.
-a --all List both remote-tracking branches and local branches.
--track When creating a new branch, set up branch.<name>.remote and branch.<name>.merge
--set-upstream If specified branch does not exist yet or if --force has been given, acts exactly like --track
*/
function setUpstreamBranch(remoteName, remoteBranch) {
if (!remoteName) { throw new TypeError("remoteName argument is missing!"); }
if (!remoteBranch) { throw new TypeError("remoteBranch argument is missing!"); }
return git(["branch", "--no-color", "-u", remoteName + "/" + remoteBranch]);
}
function branchDelete(branchName) {
return git(["branch", "--no-color", "-d", branchName]);
}
function forceBranchDelete(branchName) {
return git(["branch", "--no-color", "-D", branchName]);
}
function getBranches(moreArgs) {
var args = ["branch", "--no-color"];
if (moreArgs) { args = args.concat(moreArgs); }
return git(args).then(function (stdout) {
if (!stdout) { return []; }
return stdout.split("\n").reduce(function (arr, l) {
var name = l.trim(),
currentBranch = false,
remote = null,
sortPrefix = "";
if (name.indexOf("->") !== -1) {
return arr;
}
if (name.indexOf("* ") === 0) {
name = name.substring(2);
currentBranch = true;
}
if (name.indexOf("remotes/") === 0) {
name = name.substring("remotes/".length);
remote = name.substring(0, name.indexOf("/"));
}
var sortName = name.toLowerCase();
if (remote) {
sortName = sortName.substring(remote.length + 1);
}
if (sortName.indexOf("#") !== -1) {
sortPrefix = sortName.slice(0, sortName.indexOf("#"));
}
arr.push({
name: name,
sortPrefix: sortPrefix,
sortName: sortName,
currentBranch: currentBranch,
remote: remote
});
return arr;
}, []);
});
}
function getAllBranches() {
return getBranches(["-a"]);
}
/*
git fetch
--all Fetch all remotes.
--dry-run Show what would be done, without making any changes.
--multiple Allow several <repository> and <group> arguments to be specified. No <refspec>s may be specified.
--prune After fetching, remove any remote-tracking references that no longer exist on the remote.
--progress This flag forces progress status even if the standard error stream is not directed to a terminal.
*/
function repositoryNotFoundHandler(err) {
var m = ErrorHandler.matches(err, /Repository (.*) not found$/gim);
if (m) {
throw new ExpectedError(m[0]);
}
throw err;
}
function fetchRemote(remote) {
return git(["fetch", "--progress", remote]).catch(repositoryNotFoundHandler);
}
function fetchAllRemotes() {
return git(["fetch", "--progress", "--all"]).catch(repositoryNotFoundHandler);
}
/*
git remote
add Adds a remote named <name> for the repository at <url>.
rename Rename the remote named <old> to <new>.
remove Remove the remote named <name>.
show Gives some information about the remote <name>.
prune Deletes all stale remote-tracking branches under <name>.
*/
function getRemotes() {
return git(["remote", "-v"])
.then(function (stdout) {
return !stdout ? [] : _.uniq(stdout.replace(/\((push|fetch)\)/g, "").split("\n")).map(function (l) {
var s = l.trim().split("\t");
return {
name: s[0],
url: s[1]
};
});
});
}
function createRemote(name, url) {
return git(["remote", "add", name, url])
.then(function () {
// stdout is empty so just return success
return true;
});
}
function deleteRemote(name) {
return git(["remote", "rm", name])
.then(function () {
// stdout is empty so just return success
return true;
});
}
/*
git pull
--no-commit Do not commit result after merge
--ff-only Refuse to merge and exit with a non-zero status
unless the current HEAD is already up-to-date
or the merge can be resolved as a fast-forward.
*/
function mergeRemote(remote, branch, ffOnly, noCommit) {
var args = ["merge"];
if (ffOnly) { args.push("--ff-only"); }
if (noCommit) { args.push("--no-commit", "--no-ff"); }
args.push(remote + "/" + branch);
var readMergeMessage = function () {
return Utils.loadPathContent(Utils.getProjectRoot() + "/.git/MERGE_MSG").then(function (msg) {
return msg;
});
};
return git(args)
.then(function (stdout) {
// return stdout if available - usually not
if (stdout) { return stdout; }
return readMergeMessage().then(function (msg) {
if (msg) { return msg; }
return "Remote branch " + branch + " from " + remote + " was merged to current branch";
});
})
.catch(function (error) {
return readMergeMessage().then(function (msg) {
if (msg) { return msg; }
throw error;
});
});
}
function rebaseRemote(remote, branch) {
return git(["rebase", remote + "/" + branch]);
}
function resetRemote(remote, branch) {
return git(["reset", "--soft", remote + "/" + branch]).then(function (stdout) {
return stdout || "Current branch was resetted to branch " + branch + " from " + remote;
});
}
function mergeBranch(branchName, mergeMessage) {
var args = ["merge", "--no-ff"];
if (mergeMessage && mergeMessage.trim()) { args.push("-m", mergeMessage); }
args.push(branchName);
return git(args);
}
/*
git push
--porcelain Produce machine-readable output.
--delete All listed refs are deleted from the remote repository. This is the same as prefixing all refs with a colon.
--force Usually, the command refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it.
--set-upstream For every branch that is up to date or successfully pushed, add upstream (tracking) reference
--progress This flag forces progress status even if the standard error stream is not directed to a terminal.
*/
/*
returns parsed push response in this format:
{
flag: "="
flagDescription: "Ref was up to date and did not need pushing"
from: "refs/heads/rewrite-remotes"
remoteUrl: "http://github.com/zaggino/brackets-git.git"
status: "Done"
summary: "[up to date]"
to: "refs/heads/rewrite-remotes"
}
*/
function push(remoteName, remoteBranch, additionalArgs) {
if (!remoteName) { throw new TypeError("remoteName argument is missing!"); }
var args = ["push", "--porcelain", "--progress"];
if (Array.isArray(additionalArgs)) {
args = args.concat(additionalArgs);
}
args.push(remoteName);
if (remoteBranch) {
args.push(remoteBranch);
}
return git(args)
.catch(repositoryNotFoundHandler)
.then(function (stdout) {
var retObj = {},
lines = stdout.split("\n"),
lineTwo = lines[1].split("\t");
retObj.remoteUrl = lines[0].trim().split(" ")[1];
retObj.flag = lineTwo[0];
retObj.from = lineTwo[1].split(":")[0];
retObj.to = lineTwo[1].split(":")[1];
retObj.summary = lineTwo[2];
retObj.status = lines[2];
switch (retObj.flag) {
case " ":
retObj.flagDescription = "Successfully pushed fast-forward";
break;
case "+":
retObj.flagDescription = "Successful forced update";
break;
case "-":
retObj.flagDescription = "Successfully deleted ref";
break;
case "*":
retObj.flagDescription = "Successfully pushed new ref";
break;
case "!":
retObj.flagDescription = "Ref was rejected or failed to push";
break;
case "=":
retObj.flagDescription = "Ref was up to date and did not need pushing";
break;
default:
retObj.flagDescription = "Unknown push flag received: " + retObj.flag;
}
return retObj;
});
}
function getCurrentBranchName() {
return git(["branch", "--no-color"]).then(function (stdout) {
var branchName = _.find(stdout.split("\n"), function (l) { return l[0] === "*"; });
if (branchName) {
branchName = branchName.substring(1).trim();
var m = branchName.match(/^\(.*\s(\S+)\)$/); // like (detached from f74acd4)
if (m) { return m[1]; }
return branchName;
}
// no branch situation so we need to create one by doing a commit
if (stdout.match(/^\s*$/)) {
return EventEmitter.emit(Events.GIT_NO_BRANCH_EXISTS);
}
// alternative
return git(["log", "--pretty=format:%H %d", "-1"]).then(function (stdout) {
var m = stdout.trim().match(/^(\S+)\s+\((.*)\)$/);
var hash = m[1].substring(0, 20);
m[2].split(",").forEach(function (info) {
info = info.trim();
if (info === "HEAD") { return; }
var m = info.match(/^tag:(.+)$/);
if (m) {
hash = m[1].trim();
return;
}
hash = info;
});
return hash;
});
});
}
function getCurrentUpstreamBranch() {
return git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
.catch(function () {
return null;
});
}
// Get list of deleted files between two branches
function getDeletedFiles(oldBranch, newBranch) {
return git(["diff", "--no-ext-diff", "--name-status", oldBranch + ".." + newBranch])
.then(function (stdout) {
var regex = /^D/;
return stdout.split("\n").reduce(function (arr, row) {
if (regex.test(row)) {
arr.push(row.substring(1).trim());
}
return arr;
}, []);
});
}
function getConfig(key) {
return git(["config", key.replace(/\s/g, "")]);
}
function setConfig(key, value, allowGlobal) {
key = key.replace(/\s/g, "");
return git(["config", key, value]).catch(function (err) {
if (allowGlobal && ErrorHandler.contains(err, "No such file or directory")) {
return git(["config", "--global", key, value]);
}
throw err;
});
}
function getHistory(branch, skipCommits, file) {
var separator = "_._",
newline = "_.nw._",
format = [
"%h", // abbreviated commit hash
"%H", // commit hash
"%an", // author name
"%ai", // author date, ISO 8601 format
"%ae", // author email
"%s", // subject
"%b" // body
].join(separator) + newline;
var args = ["log", "-100"];
if (skipCommits) { args.push("--skip=" + skipCommits); }
args.push("--format=" + format, branch, "--");
// follow is too buggy - do not use
// if (file) { args.push("--follow"); }
if (file) { args.push(file); }
return git(args).then(function (stdout) {
stdout = stdout.substring(0, stdout.length - newline.length);
return !stdout ? [] : stdout.split(newline).map(function (line) {
var data = line.trim().split(separator),
commit = {};
commit.hashShort = data[0];
commit.hash = data[1];
commit.author = data[2];
commit.date = data[3];
commit.email = data[4];
commit.subject = data[5];
commit.body = data[6];
return commit;
});
});
}
function init() {
return git(["init"]);
}
function clone(remoteGitUrl, destinationFolder) {
return git(["clone", remoteGitUrl, destinationFolder, "--progress"]);
}
function stage(file, updateIndex) {
var args = ["add"];
if (updateIndex) { args.push("-u"); }
args.push("--", file);
return git(args);
}
function stageAll() {
return git(["add", "--all"]);
}
function commit(message, amend) {
var lines = message.split("\n"),
args = ["commit"];
if (amend) {
args.push("--amend", "--reset-author");
}
if (lines.length === 1) {
args.push("-m", message);
return git(args);
} else {
return new Promise(function (resolve, reject) {
// FUTURE: maybe use git commit --file=-
var fileEntry = FileSystem.getFileForPath(Utils.getProjectRoot() + ".bracketsGitTemp");
Promise.cast(FileUtils.writeText(fileEntry, message))
.then(function () {
args.push("-F", ".bracketsGitTemp");
return git(args);
})
.then(function (res) {
fileEntry.unlink(function () {
resolve(res);
});
})
.catch(function (err) {
fileEntry.unlink(function () {
reject(err);
});
});
});
}
}
function reset(type, hash) {
var args = ["reset", type || "--mixed"]; // mixed is the default action
if (hash) { args.push(hash, "--"); }
return git(args);
}
function unstage(file) {
return git(["reset", "--", file]);
}
function checkout(hash) {
return git(["checkout", hash], {
timeout: false // never timeout this
});
}
function createBranch(branchName, originBranch, trackOrigin) {
var args = ["checkout", "-b", branchName];
if (originBranch) {
if (trackOrigin) {
args.push("--track");
}
args.push(originBranch);
}
return git(args);
}
function _isquoted(str) {
return str[0] === "\"" && str[str.length - 1] === "\"";
}
function _unquote(str) {
return str.substring(1, str.length - 1);
}
function _isescaped(str) {
return /\\[0-9]{3}/.test(str);
}
function status(type) {
return git(["status", "-u", "--porcelain"]).then(function (stdout) {
if (!stdout) { return []; }
// files that are modified both in index and working tree should be resetted
var isEscaped = false,
needReset = [],
results = [],
lines = stdout.split("\n");
lines.forEach(function (line) {
var statusStaged = line.substring(0, 1),
statusUnstaged = line.substring(1, 2),
status = [],
file = line.substring(3);
// check if the file is quoted
if (_isquoted(file)) {
file = _unquote(file);
if (_isescaped(file)) {
isEscaped = true;
}
}
if (statusStaged !== " " && statusUnstaged !== " " &&
statusStaged !== "?" && statusUnstaged !== "?") {
needReset.push(file);
return;
}
var statusChar;
if (statusStaged !== " " && statusStaged !== "?") {
status.push(FILE_STATUS.STAGED);
statusChar = statusStaged;
} else {
statusChar = statusUnstaged;
}
switch (statusChar) {
case " ":
status.push(FILE_STATUS.UNMODIFIED);
break;
case "!":
status.push(FILE_STATUS.IGNORED);
break;
case "?":
status.push(FILE_STATUS.UNTRACKED);
break;
case "M":
status.push(FILE_STATUS.MODIFIED);
break;
case "A":
status.push(FILE_STATUS.ADDED);
break;
case "D":
status.push(FILE_STATUS.DELETED);
break;
case "R":
status.push(FILE_STATUS.RENAMED);
break;
case "C":
status.push(FILE_STATUS.COPIED);
break;
case "U":
status.push(FILE_STATUS.UNMERGED);
break;
default:
throw new Error("Unexpected status: " + statusChar);
}
var display = file,
io = file.indexOf("->");
if (io !== -1) {
file = file.substring(io + 2).trim();
}
results.push({
status: status,
display: display,
file: file,
name: file.substring(file.lastIndexOf("/") + 1)
});
});
if (isEscaped) {
return setConfig("core.quotepath", "false").then(function () {
if (type === "SET_QUOTEPATH") {
throw new Error("git status is calling itself in a recursive loop!");
}
return status("SET_QUOTEPATH");
});
}
if (needReset.length > 0) {
return Promise.all(needReset.map(function (fileName) {
if (fileName.indexOf("->") !== -1) {
fileName = fileName.split("->")[1].trim();
}
return unstage(fileName);
})).then(function () {
if (type === "RECURSIVE_CALL") {
throw new Error("git status is calling itself in a recursive loop!");
}
return status("RECURSIVE_CALL");
});
}
return results.sort(function (a, b) {
if (a.file < b.file) {
return -1;
}
if (a.file > b.file) {
return 1;
}
return 0;
});
}).then(function (results) {
EventEmitter.emit(Events.GIT_STATUS_RESULTS, results);
return results;
});
}
function _isFileStaged(file) {
return git(["status", "-u", "--porcelain", "--", file]).then(function (stdout) {
if (!stdout) { return false; }
return _.any(stdout.split("\n"), function (line) {
return line[0] !== " " && line[0] !== "?" && // first character marks staged status
line.lastIndexOf(" " + file) === line.length - file.length - 1; // in case another file appeared here?
});
});
}
function getDiffOfStagedFiles() {
return git(["diff", "--no-ext-diff", "--no-color", "--staged"], {
timeout: false // never timeout this
});
}
function getListOfStagedFiles() {
return git(["diff", "--no-ext-diff", "--no-color", "--staged", "--name-only"], {
timeout: false // never timeout this
});
}
function diffFile(file) {
return _isFileStaged(file).then(function (staged) {
var args = ["diff", "--no-ext-diff", "--no-color"];
if (staged) { args.push("--staged"); }
args.push("-U0", "--", file);
return git(args, {
timeout: false // never timeout this
});
});
}
function diffFileNice(file) {
return _isFileStaged(file).then(function (staged) {
var args = ["diff", "--no-ext-diff", "--no-color"];
if (staged) { args.push("--staged"); }
args.push("--", file);
return git(args, {
timeout: false // never timeout this
});
});
}
function difftool(file) {
return _isFileStaged(file).then(function (staged) {
var args = ["difftool"];
if (staged) {
args.push("--staged");
}
args.push("--", file);
return git(args, {
timeout: false, // never timeout this
nonblocking: true // allow running other commands before this command finishes its work
});
});
}
function clean() {
return git(["clean", "-f", "-d"]);
}
function getFilesFromCommit(hash) {
return git(["diff", "--no-ext-diff", "--name-only", hash + "^!"]).then(function (stdout) {
return !stdout ? [] : stdout.split("\n");
});
}
function getDiffOfFileFromCommit(hash, file) {
return git(["diff", "--no-ext-diff", "--no-color", hash + "^!", "--", file]);
}
function difftoolFromHash(hash, file) {
return git(["difftool", hash + "^!", "--", file], {
timeout: false // never timeout this
});
}
function rebaseInit(branchName) {
return git(["rebase", "--ignore-date", branchName]);
}
function rebase(whatToDo) {
return git(["rebase", "--" + whatToDo]);
}
function getVersion() {
return git(["--version"]).then(function (stdout) {
var m = stdout.match(/[0-9].*/);
return m ? m[0] : stdout.trim();
});
}
function getCommitsAhead() {
return git(["rev-list", "HEAD", "--not", "--remotes"]).then(function (stdout) {
return !stdout ? [] : stdout.split("\n");
});
}
function getLastCommitMessage() {
return git(["log", "-1", "--pretty=%B"]).then(function (stdout) {
return stdout.trim();
});
}
function getBlame(file, from, to) {
var args = ["blame", "-w", "--line-porcelain"];
if (from || to) { args.push("-L" + from + "," + to); }
args.push(file);
return git(args).then(function (stdout) {
if (!stdout) { return []; }
var sep = "-@-BREAK-HERE-@-",
sep2 = "$$#-#$BREAK$$-$#";
stdout = stdout.replace(sep, sep2)
.replace(/^\t(.*)$/gm, function (a, b) { return b + sep; });
return stdout.split(sep).reduce(function (arr, lineInfo) {
lineInfo = lineInfo.replace(sep2, sep).trimLeft();
if (!lineInfo) { return arr; }
var obj = {},
lines = lineInfo.split("\n"),
firstLine = _.first(lines).split(" ");
obj.hash = firstLine[0];
obj.num = firstLine[2];
obj.content = _.last(lines);
// process all but first and last lines
for (var i = 1, l = lines.length - 1; i < l; i++) {
var line = lines[i],
io = line.indexOf(" "),
key = line.substring(0, io),
val = line.substring(io + 1);
obj[key] = val;
}
arr.push(obj);
return arr;
}, []);
}).catch(function (stderr) {
var m = stderr.match(/no such path (\S+)/);
if (m) {
throw new Error("File is not tracked by Git: " + m[1]);
}
throw stderr;
});
}
// Public API
exports._git = git;
exports.setGitPath = setGitPath;
exports.FILE_STATUS = FILE_STATUS;
exports.fetchRemote = fetchRemote;
exports.fetchAllRemotes = fetchAllRemotes;
exports.getRemotes = getRemotes;
exports.createRemote = createRemote;
exports.deleteRemote = deleteRemote;
exports.push = push;
exports.setUpstreamBranch = setUpstreamBranch;
exports.getCurrentBranchName = getCurrentBranchName;
exports.getCurrentUpstreamBranch = getCurrentUpstreamBranch;
exports.getConfig = getConfig;
exports.setConfig = setConfig;
exports.getBranches = getBranches;
exports.getAllBranches = getAllBranches;
exports.branchDelete = branchDelete;
exports.forceBranchDelete = forceBranchDelete;
exports.getDeletedFiles = getDeletedFiles;
exports.getHistory = getHistory;
exports.init = init;
exports.clone = clone;
exports.stage = stage;
exports.unstage = unstage;
exports.stageAll = stageAll;
exports.commit = commit;
exports.reset = reset;
exports.checkout = checkout;
exports.createBranch = createBranch;
exports.status = status;
exports.diffFile = diffFile;
exports.diffFileNice = diffFileNice;
exports.difftool = difftool;
exports.clean = clean;
exports.getFilesFromCommit = getFilesFromCommit;
exports.getDiffOfFileFromCommit = getDiffOfFileFromCommit;
exports.difftoolFromHash = difftoolFromHash;
exports.rebase = rebase;
exports.rebaseInit = rebaseInit;
exports.mergeRemote = mergeRemote;
exports.rebaseRemote = rebaseRemote;
exports.resetRemote = resetRemote;
exports.getVersion = getVersion;
exports.getCommitsAhead = getCommitsAhead;
exports.getLastCommitMessage = getLastCommitMessage;
exports.mergeBranch = mergeBranch;
exports.getDiffOfStagedFiles = getDiffOfStagedFiles;
exports.getListOfStagedFiles = getListOfStagedFiles;
exports.getBlame = getBlame;
});
| mit |
davidchristie/kaenga-housing-calculator | src/components/pages/Privacy/Privacy.test.js | 265 | import React from 'react'
import ReactTestUtils from 'react-dom/test-utils'
import Privacy from './Privacy'
const shallowRenderer = ReactTestUtils.createRenderer()
it('matches snapshot', () => {
expect(shallowRenderer.render(<Privacy />)).toMatchSnapshot()
})
| mit |
dhax/go-base | auth/jwt/token.go | 992 | package jwt
import (
"time"
"github.com/go-pg/pg/orm"
)
// Token holds refresh jwt information.
type Token struct {
ID int `json:"id,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
AccountID int `json:"-"`
Token string `json:"-"`
Expiry time.Time `json:"-"`
Mobile bool `sql:",notnull" json:"mobile"`
Identifier string `json:"identifier,omitempty"`
}
// BeforeInsert hook executed before database insert operation.
func (t *Token) BeforeInsert(db orm.DB) error {
now := time.Now()
if t.CreatedAt.IsZero() {
t.CreatedAt = now
t.UpdatedAt = now
}
return nil
}
// BeforeUpdate hook executed before database update operation.
func (t *Token) BeforeUpdate(db orm.DB) error {
t.UpdatedAt = time.Now()
return nil
}
// Claims returns the token claims to be signed
func (t *Token) Claims() RefreshClaims {
return RefreshClaims{
ID: t.ID,
Token: t.Token,
}
}
| mit |
aldenaik/angular_practice | app/js/services/EventData.js | 828 | eventsApp.factory('eventData',function(){
return{
event: {
name:"Whatever",
date: '1/1/2013',
time: '10:30 am',
location: {
address: 'Google Headquarters',
city: 'Mountain View',
province: 'CA'
},
imageUrl: '/Users/aldenaik/DevMtn/angular_practice/app/img/angularjs.jpg',
sessions: [
{
name: "Class Numero Uno",
creator:"rodney Dude",
duration:"20 mins",
level:"wow",
abstract: "what does this even mean?",
upVoteCount: 0
},
{
name: "Class Numbero Dos",
creator:"Duder Man",
duration:"40 mins",
level:"wowzer",
abstract: "who knows?",
upVoteCount: 0
},
{
name: "Class Number Tres",
creator:"Iam Theman",
duration:"forever",
level:"top notch",
abstract: "thinking?",
upVoteCount: 0
}
]
}
};
}); | mit |
nchkdxlq/Algorithm | Algorithm/LeetCode/39-combinationSum/39-combinationSum.cpp | 5099 | //
// 39-combinationSum.cpp
// LeetCode
//
// Created by Knox on 2019/8/18.
// Copyright © 2019 nchkdxlq. All rights reserved.
//
#include "39-combinationSum.hpp"
#include "STLHelper.hpp"
/*
39. 组合总和
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
链接:https://leetcode-cn.com/problems/combination-sum
*/
namespace combinationSum_39 {
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
// return v1_combinationSum(candidates, target);
// return v2_combinationSum(candidates, target);
return v3_combinationSum(candidates, target);
}
private:
vector<vector<int>> res;
unordered_set<string> usedIndexSet;
/*
执行用时 : 328 ms, 5.00%
内存消耗 : 22.2 MB, 21.02%
*/
vector<vector<int>> v1_combinationSum(vector<int>& candidates, int target) {
if (candidates.empty()) return {};
res.clear();
vector<int> cur;
v1_combinationSum_helper(candidates, target, 0, cur);
return res;
}
void v1_combinationSum_helper(vector<int>& candidates, int target, int sum, vector<int>& cur) {
if (sum == target) {
// 这个地方被坑了很久
vector<int> tmp_c = cur; // cur 不能在这排序,否者在回溯的时候,push、pop的元素不一致,所以需要复制一份数组
sort(tmp_c.begin(), tmp_c.end());
vector<int> tmp;
string key;
for (auto i : tmp_c) {
tmp.push_back(candidates[i]);
key += to_string(i);
}
if (usedIndexSet.find(key) == usedIndexSet.end()) {
res.push_back(tmp);
usedIndexSet.insert(key);
}
return;
} else if (sum > target) {
return;
}
for (int i = 0; i < candidates.size(); i++) {
cur.push_back(i);
v1_combinationSum_helper(candidates, target, sum + candidates[i], cur);
cur.pop_back();
}
}
/*
执行用时 : 20 ms,80.15%
内存消耗 : 9.7 MB, 86.66%
*/
vector<vector<int>> v2_combinationSum(vector<int>& candidates, int target) {
if (candidates.empty()) return {};
vector<int> cur;
v2_combinationSum_helper(candidates, target, 0, cur);
return res;
}
void v2_combinationSum_helper(vector<int>& candidates, int target, int index, vector<int>& cur) {
if (target == 0) {
res.push_back(cur);
return;
} else if (target < 0) {
return;
}
for (int i = index; i < candidates.size(); i++) {
cur.push_back(candidates[i]);
v2_combinationSum_helper(candidates, target - candidates[i], i, cur);
cur.pop_back();
}
}
/*
执行用时 :12 ms, 98.93%
内存消耗 : 9.7 MB, 86.99%
*/
vector<vector<int>> v3_combinationSum(vector<int>& candidates, int target) {
if (candidates.empty()) return {};
vector<int> cur;
// 优化点,先排序,是剪枝的前提条件
sort(candidates.begin(), candidates.end());
v3_combinationSum_helper(candidates, target, 0, cur);
return res;
}
void v3_combinationSum_helper(vector<int>& candidates, int target, int index, vector<int>& cur) {
if (target == 0) {
res.push_back(cur);
return;
}
for (int i = index; i < candidates.size(); i++) {
// 剪枝, 因为candidates是升序的,所以,如果candidates[i] > target, 那么后面的元素都大于target,可提前结束循环
if (candidates[i] > target) break;
cur.push_back(candidates[i]);
v3_combinationSum_helper(candidates, target - candidates[i], i, cur);
cur.pop_back();
}
}
};
}
void __39_entry() {
vector<int> candidates = {2,3,6,7}; int target = 7;
candidates = {2,3,5}; target = 8;
auto res = combinationSum_39::Solution().combinationSum(candidates, target);
cout << "==== 39-combinationSum ====" << endl;
cout << "[" << endl;
for (auto &item : res) {
cout << " ";
print_vector(item);
cout << endl;
}
cout << "]" << endl;
cout << endl;
}
| mit |
skyiea/wix-style-react | stories/EditableSelector/PopoverWithEditableSelector.js | 1853 | import React from 'react';
import {EditableSelector, Tooltip, Button} from 'wix-style-react';
class PopoverWithEditableSelector extends React.Component {
constructor(props) {
super(props);
this.state = {
options: [
{title: 'Marc Banks'},
{title: 'Bernard Park'},
{title: 'Carlos Dunn'},
{title: 'Norman Reeves'},
{title: 'Richard Medina'}
]
};
}
onOptionAdded = ({newTitle}) => {
this.setState({
options: [...this.state.options, {title: newTitle, isSelected: true}]
});
};
onOptionEdit = ({newTitle, index}) => {
this.setState({
options: this.state.options.map((option, i) => index === i ? {title: newTitle} : option)
});
};
onOptionToggle = index => {
this.setState({
options: this.state.options.map((option, i) => {
if (index === i) {
option.isSelected = !option.isSelected;
return option;
} else {
return option;
}
})
});
};
onOptionDelete = ({index}) => {
this.setState({
options: this.state.options.filter((option, i) => index !== i)
});
};
render() {
const content = (
<EditableSelector
onOptionAdded={params => this.onOptionAdded(params)}
onOptionEdit={params => this.onOptionEdit(params)}
onOptionDelete={params => this.onOptionDelete(params)}
onOptionToggle={params => this.onOptionToggle(params)}
options={this.state.options}
/>
);
return (
<div style={{backgroundColor: '#f0f4f7', minHeight: '300px', padding: '20px'}}>
<Tooltip textAlign="start" placement="bottom" content={content} showTrigger="click" hideTrigger="click">
<Button>click me</Button>
</Tooltip>
</div>
);
}
}
export default PopoverWithEditableSelector;
| mit |
harc/ohm-editor | src/searchBar.js | 3721 | /* global CodeMirror */
import ohmEditor from './ohmEditor';
import {$} from './domUtil';
// Returns the first ancestor node of `el` that has class `className`.
function ancestorWithClassName(el, className) {
let node = el;
while ((node = node.parentElement) != null) {
if (node.classList.contains(className)) {
return node;
}
}
}
function installEventHandlers(editor, footer, findCallback) {
const input = footer.querySelector('input[type=search]');
// Install a temporary keymap while the toolbar is open, which makes Cmd-F
// refocus the search bar rather than starting a new search.
const tempKeyMap = {fallthrough: 'default'};
tempKeyMap['Cmd-F'] = tempKeyMap['Ctrl-F'] = function doFind(cm) {
const selection = cm.getSelection();
// If there's no selection or it's the same as the current search, refocus the search bar.
// Otherwise, start a new search.
if (selection.length === 0 || selection === input.value) {
input.select();
} else {
cm.execCommand('findPersistent');
}
};
editor.addKeyMap(tempKeyMap);
// Handles find-related keys when the search bar has focus. `binding` is the result
// of looking up the key in `tempKeyMap`. Returns `true` if the key was handled, and
// `false` otherwise.
const handleKey = function (binding) {
if (typeof binding === 'function') {
binding(editor);
return true;
} else if (typeof binding === 'string' && binding.indexOf('find') === 0) {
editor.execCommand(binding);
return true;
}
return false;
};
const closeFooter = function () {
footer.parentNode.removeChild(footer);
editor.execCommand('clearSearch');
editor.removeKeyMap(tempKeyMap);
editor.focus();
};
// Handler for keydown events in the search bar.
footer.onkeydown = function (e) {
const keyName = CodeMirror.keyName(e);
if (keyName === 'Esc') {
closeFooter();
editor.focus();
} else if (e.target === input && keyName === 'Enter') {
findCallback(input.value, e);
} else if (
CodeMirror.lookupKey(keyName, tempKeyMap, handleKey) === 'handled'
) {
e.preventDefault();
}
};
const closeButton = footer.querySelector('.closeButton');
closeButton.onclick = closeFooter;
}
// An implementation of CodeMirror's `openDialog` API, but specialized for use
// as the search box. As such, it might not be very well suited to other purposes.
CodeMirror.defineExtension('openDialog', function (template, callback, opts) {
const editor = this; // eslint-disable-line no-invalid-this
if (template.indexOf('Search:') !== 0) {
throw new Error('No dialog for template ' + template);
}
// Re-use the existing footer if it's visible, or create a new one.
const container = ancestorWithClassName(
editor.getWrapperElement(),
'flex-fix'
).parentNode;
let footer = container.querySelector('.footer');
if (!footer) {
footer = $('#protos .footer').cloneNode(true);
container.appendChild(footer);
footer.removeAttribute('hidden');
installEventHandlers(editor, footer, callback);
}
const closeButton = footer.querySelector('.closeButton');
const input = footer.querySelector('input[type=search]');
if (opts.value) {
input.value = opts.value;
}
input.select();
return closeButton.onclick;
});
// A keymap which maps Ctrl-F/Cmd-F to 'findPersistent' (rather than 'find').
const editorKeyMap = {};
editorKeyMap['Ctrl-F'] = editorKeyMap['Cmd-F'] = 'findPersistent';
const handleEditorInit = function (cm) {
cm.addKeyMap(editorKeyMap);
};
ohmEditor.addListener('init:inputEditor', handleEditorInit);
ohmEditor.addListener('init:grammarEditor', handleEditorInit);
| mit |
carlosbuenosvinos/php-geckoboard-api | src/CarlosIO/Geckoboard/Tests/Data/PointTest.php | 981 | <?php
namespace CarlosIO\Geckoboard\Tests\Data;
use CarlosIO\Geckoboard\Data\Point;
class PointTest extends \PHPUnit_Framework_TestCase
{
public function testFullMethodsDataEntry()
{
$point = new Point();
$point
->setCityName('Barcelona')
->setColor('ffffff')
->setCssClass('mycss')
->setCountryCode('ES')
->setSize(8)
->setLatitude('1.1')
->setLongitude('2.2')
;
$json = json_encode($point->toArray());
$this->assertEquals('{"city":{"city_name":"Barcelona","country_code":"ES"},"latitude":"1.1","longitude":"2.2","size":8,"color":"ffffff","cssclass":"mycss"}', $json);
}
/**
* @test
* @expectedException \CarlosIO\Geckoboard\Data\Point\SizeOutOfBoundsException
*/
public function whenSettingSizeOverTenAnExceptionShouldBeThrown()
{
$point = new Point();
$point
->setSize(11);
}
}
| mit |
chylex/TweetDuck | resources/Plugins/reply-account/browser.js | 4779 | enabled(){
let configuration = { defaultAccount: "#preferred" };
window.TDPF_loadConfigurationFile(this, "configuration.js", "configuration.default.js", obj => configuration = obj);
this.lastSelectedAccount = null;
this.uiComposeTweetEvent = (e, data) => {
if (!(data.type === "reply" || (data.type === "tweet" && "quotedTweet" in data)) || data.popFromInline || !("element" in data)) {
return;
}
let query;
if (configuration.useAdvancedSelector) {
if (configuration.customSelector) {
let customSelectorDef = configuration.customSelector.toString();
if (customSelectorDef.startsWith("function (column){")) {
$TD.alert("warning", "Plugin reply-account has invalid configuration: customSelector needs to be updated due to TweetDeck changes, please read the default configuration file for the updated guide");
return;
}
else if (customSelectorDef.startsWith("function (type,")) {
$TD.alert("warning", "Plugin reply-account has invalid configuration: the type parameter is no longer present due to TweetDeck changes, please read the default configuration file for the updated guide");
return;
}
let section = data.element.closest("section.js-column");
let column = TD.controller.columnManager.get(section.attr("data-column"));
let feeds = column.getFeeds();
let accountText = "";
if (feeds.length === 1) {
let metadata = feeds[0].getMetadata();
let id = metadata.ownerId || metadata.id;
if (id) {
accountText = TD.cache.names.getScreenName(id);
}
else {
let account = TD.storage.accountController.get(feeds[0].getAccountKey());
if (account) {
accountText = "@" + account.getUsername();
}
}
}
let header = $(".column-header-title", section);
let title = header.children(".column-heading");
let titleText = title.length ? title.text() : header.children(".column-title-edit-box").val();
try {
query = configuration.customSelector(titleText, accountText, column, section.hasClass("column-temp"));
} catch (e) {
$TD.alert("warning", "Plugin reply-account has invalid configuration: customSelector threw an error: " + e.message);
return;
}
}
else {
$TD.alert("warning", "Plugin reply-account has invalid configuration: useAdvancedSelector is true, but customSelector function is missing");
return;
}
}
else {
query = configuration.defaultAccount;
if (query === "") {
query = "#preferred";
}
else if (typeof query !== "string") {
query = "#default";
}
}
if (typeof query === "undefined") {
query = "#preferred";
}
if (typeof query !== "string") {
return;
}
else if (query.length === 0) {
$TD.alert("warning", "Plugin reply-account has invalid configuration: the requested account is empty");
return;
}
else if (query[0] !== "@" && query[0] !== "#") {
$TD.alert("warning", "Plugin reply-account has invalid configuration: the requested account does not begin with @ or #: " + query);
return;
}
let identifier = null;
switch (query) {
case "#preferred":
identifier = TD.storage.clientController.client.getDefaultAccount();
break;
case "#last":
if (this.lastSelectedAccount === null) {
return;
}
identifier = this.lastSelectedAccount;
break;
case "#default":
return;
default:
if (query[0] === "@") {
let obj = TD.storage.accountController.getAccountFromUsername(query.substring(1));
if (obj.length === 0) {
$TD.alert("warning", "Plugin reply-account has invalid configuration: requested account not found: " + query);
return;
}
else {
identifier = obj[0].privateState.key;
}
}
else {
$TD.alert("warning", "Plugin reply-account has invalid configuration: unknown requested account query: " + query);
return;
}
}
data.singleFrom = data.from = [ identifier ];
};
this.onSelectedAccountChanged = () => {
let selected = $(".js-account-item.is-selected", ".js-account-list");
this.lastSelectedAccount = selected.length === 1 ? selected.attr("data-account-key") : null;
};
}
ready(){
for (let event of [ "uiInlineComposeTweet", "uiDockedComposeTweet" ]) {
$(document).on(event, this.uiComposeTweetEvent);
window.TDPF_prioritizeNewestEvent(document, event);
}
$(document).on("click", ".js-account-list .js-account-item", this.onSelectedAccountChanged);
}
disabled(){
$(document).off("uiInlineComposeTweet", this.uiComposeTweetEvent);
$(document).off("uiDockedComposeTweet", this.uiComposeTweetEvent);
$(document).off("click", ".js-account-list .js-account-item", this.onSelectedAccountChanged);
}
| mit |
oscar-barlow/apiify | lib/apiify/scaffolder.rb | 1674 | class Apiify::Scaffolder
def generate(csv_path, index_col)
run_scaffold(csv_path, index_col)
confirm(csv_path, index_col)
end
def get_file_name(csv_path)
if is_a_csv?(csv_path)
get_file(csv_path).first
else
raise "Error: wrong file type. Please supply a .csv file"
end
end
def find_class(path)
table = CSV.table(path)
headers = table.headers
result = {}
headers.each do |header|
table.each do |row|
if row[header].class != Float
result[header] = row[header].class
else
result[header] = row[header].class
break
end
end
end
result
end
def hash_to_string(hash, index_col)
output_str = ""
hash.each do |key, value|
if !index_col.nil? && key.to_s == index_col
output_str += "#{key}:#{value.to_s.downcase}:index "
else
output_str += "#{key}:#{value.to_s.downcase} "
end
end
output_str.strip
end
def create_scaffold(csv_path, index_col)
model_name = get_file_name(csv_path).capitalize
hash_result = find_class(csv_path)
"bin/rails g scaffold #{model_name} #{hash_to_string(hash_result, index_col)}"
end
def run_scaffold(csv_path, index_col)
system(create_scaffold(csv_path, index_col))
end
def confirm(csv_path, index_col)
puts "Created #{get_file_name(csv_path).capitalize} model with properties #{hash_to_string(find_class(csv_path),index_col)}"
puts "Please run `bin/rake db:migrate`"
end
private
def is_a_csv?(csv_path)
get_file(csv_path).last == "csv"
end
def get_file(csv_path)
csv_path.split("/").last.split(".")
end
end
| mit |
spiral/spiral | src/Boot/src/Exception/FatalException.php | 242 | <?php
/**
* Spiral Framework.
*
* @license MIT
* @author Anton Titov (Wolfy-J)
*/
declare(strict_types=1);
namespace Spiral\Boot\Exception;
/**
* Raised on fatal exceptions.
*/
class FatalException extends \ErrorException
{
}
| mit |
kbase/ui-common | src/widgets/social/kbaseWSObjRefUsers.js | 10120 | define (
[
'kbwidget',
'bootstrap',
'jquery'
], function(
KBWidget,
bootstrap,
$
) {
return KBWidget({
name: "KBaseWSObjRefUsers",
parent : kbaseAuthenticatedWidget,
version: "1.0.0",
//wsUrl: "http://dev04.berkeley.kbase.us:7058",
wsUrl:"https://kbase.us/services/ws",
userNameFetchUrl:"https://kbase.us/services/genome_comparison/users?usernames=",
options: {
wsNameOrId: null,
objNameOrId: null,
objVer: null,
kbCache:{},
width:350
},
wsName:"",
objName:"",
kbws:null, //this is the ws client
userList:{},
loggedIn: false,
init: function(options) {
this._super(options);
var self = this;
self.userList={};
if (options.wsUrl) {
self.wsUrl = options.wsUrl;
}
if (self.options.kbCache.ws_url) {
self.wsUrl = self.options.kbCache.ws_url;
}
if (self.options.kbCache.token) {
self.kbws = new Workspace(self.wsUrl, {token: self.options.kbCache.token});
self.loggedIn = true;
} else {
self.kbws = new Workspace(self.wsUrl);
}
self.$elem.append('<div id="loading-mssg"><p class="muted loader-table"><center><img src="assets/img/ajax-loader.gif"><br><br>finding all data that references this object...</center></p></div>');
self.$elem.append($('<div id="mainview">').css("overflow","auto"));
//self.$elem.append(JSON.stringify(options)+"<br>");
if ( (/^\d+$/.exec(options.wsNameOrId)) || ( /^\d+$/.exec(options.objNameOrId)) ){
// it is an ID, so we need to get the object name
// (this one is gonna be blocking on getting everything else...)
var objectIdentity = self.getObjectIdentity(options.wsNameOrId, options.objNameOrId, options.objVer);
var getInfoJob = [
self.kbws.get_object_info([objectIdentity],0,
function(data) {
self.objName = data[0][1];
self.wsName = data[0][7];
},
function(err) {
self.$elem.find('#loading-mssg').remove();
self.$elem.append("<br><b>Error: Could not access data for this object.</b><br>");
self.$elem.append("<i>Error was:</i><br>"+err['error']['message']+"<br>");
console.error("Error in finding referencing objects! (note: v0.1.6 throws this error if no referencing objects were found)");
console.error(err);
})
];
$.when.apply($, getInfoJob).done(function() {
self.getTheRefsAndRender();
});
}
else {
// it is a name already, so we can get right to the fun
wsName = options.wsNameOrId;
self.objName = options.objNameOrId;
self.wsName = options.wsNameOrId;
self.getTheRefsAndRender();
}
return this;
},
getTheRefsAndRender : function () {
var self = this;
var objectIdentity = self.getObjectIdentity(self.options.wsNameOrId, self.options.objNameOrId, self.options.objVer);
// get the refs
self.kbws.list_referencing_objects([objectIdentity], function(data) {
for(var i = 0; i < data[0].length; i++) {
//var savedate = new Date(objInfo[3]); // todo: add last save date
var refName = data[0][i][1] + " ("+data[0][i][6]+"/"+data[0][i][0]+"/"+data[0][i][4]+")";
if (data[0][i][5] in self.userList) {
self.userList[data[0][i][5]]['refCount']++;
self.userList[data[0][i][5]]['refs'].push(refName);
} else {
self.userList[data[0][i][5]] = {refCount:1, name:"[Login to view name]", narCount:0, refs:[refName], nars:{}};
}
}
self.renderTable(true);
}, function(err) {
self.$elem.find('#loading-mssg').remove();
self.$elem.append("<br><b>Error: Could not access data for this object.</b><br>");
self.$elem.append("<i>Error was:</i><br>"+err['error']['message']+"<br>");
console.error("Error in finding referencing objects! (note: v0.1.6 throws this error if no referencing objects were found)");
console.error(err);
});
// We also need to check if there are narrative references
var narrrativeTypeName = "KBaseNarrative.Narrative"; var dependentDataPath ="/metadata/data_dependencies";
var listObjParams = { includeMetadata:0, type:narrrativeTypeName};
if (/^\d+$/.exec(self.options.wsNameOrId))
listObjParams['ids'] = [ self.options.wsNameOrId ];
else
listObjParams['workspaces'] = [ self.options.wsNameOrId ];
self.kbws.list_objects( listObjParams, function(data) {
if (data.length>0) {
var narList = [];
for(var i = 0; i < data.length; i++) {
//0:obj_id, 1:obj_name, 2:type ,3:timestamp, 4:version, 5:username saved_by, 6:ws_id, 7:ws_name, 8 chsum, 9 size, 10:usermeta
narList.push({ref:data[i][6]+"/"+data[i][0]+"/"+data[i][4],included:[dependentDataPath]});
}
// then we get subdata containing the data dependencies
if (narList.length>0) {
self.kbws.get_object_subset(narList, function(data) {
for(var i = 0; i < data.length; i++) {
var depList = data[i]['data']['metadata']['data_dependencies'];
for(var k=0; k<depList.length; k++) {
var name = depList[k].trim().split(/\s+/)[1];
if (name) {
if (name == self.objName) {
var narName = data[i]['info'][1] + " ("+data[i]['info'][6]+"/"+data[i]['info'][0]+"/"+data[i]['info'][4]+")";
if (data[i]['info'][5] in self.userList) {
self.userList[data[i]['info'][5]]['narCount']++;
self.userList[data[i]['info'][5]]['nars'][narName]=1;
} else {
self.userList[data[i]['info'][5]] = {refCount:0, name:"[Login to view name]", narCount:0, refs:[], nars:{}};
self.userList[data[i]['info'][5]]['narCount']++;
self.userList[data[i]['info'][5]]['nars'][narName]=1;
}
}
}
}
}
// finally, render the table
self.renderTable(true);
},
function(err) {
// we couldn't get the subdata, so do nothing
});
}
}
},
function(err) {
// do nothing, this isn't critical to this widget
});
return this;
},
renderTable : function(getNiceNames) {
var self = this;
var tblData = [];
for (var ud in self.userList) {
// do a little prettifying
var limit = 10; var count = 0;
var narToolTip = "Narratives:\n";
for(var narName in self.userList[ud]['nars']){
if (count==limit) {
narToolTip += "...";
break;
}
narToolTip += narName+"\n";
count++;
}
var refToolTip = "Data objects (includes all versions):\n";
for(var r=0; r<self.userList[ud]['refs'].length; r++) {
if (r==limit) {
refToolTip += "...";
break;
}
refToolTip += self.userList[ud]['refs'][r]+"\n";
count++;
}
var mentionStr = "";
if (self.userList[ud]['narCount']>0) {
mentionStr += '<span style="cursor:help;" title="'+narToolTip+'">'+self.userList[ud]['narCount']+' in narratives</span>';
}
if (self.userList[ud]['refCount'] > 0) {
if (mentionStr.length>0) { mentionStr += ",<br>"}
mentionStr += '<span style="cursor:help;" title="'+refToolTip+'">'+self.userList[ud]['refCount']+" in data objects</span>";
}
tblData.push({name:self.userList[ud]['name'],user_id:ud,mentions:mentionStr});
}
if (tblData.length>0) {
var $maindiv = self.$elem.find('#mainview');
$maindiv.html(""); // clear it all out in case we are reloading
$maindiv.append('<table cellpadding="0" cellspacing="0" border="0" id="ref-table" \
class="table table-bordered table-striped" style="width: 100%; margin-left: 0px; margin-right: 0px;"/>');
var sDom = 't<fip>'
if (tblData.length<=10) { sDom = 'ti'; }
var tblSettings = {
//"sPaginationType": "full_numbers",
"iDisplayLength": 10,
"sDom": sDom,
"aoColumns": [
{sTitle: "Name", mData: "name", sWidth:"30%"},
{sTitle: "User Id", mData: "user_id"},
{sTitle: "Mentions", mData: "mentions"}
],
"aaData": tblData
};
var refTable = self.$elem.find('#ref-table').dataTable(tblSettings);
self.$elem.find('#loading-mssg').remove();
if(getNiceNames) { self.getNiceUserNames(); }
} else {
var $maindiv = self.$elem.find('#mainview');
self.$elem.find('#loading-mssg').remove();
$maindiv.append("<br><b>There are no other users that have referenced or used this object.</b>");
}
},
getNiceUserNames: function() {
var self = this;
// todo : use globus to populate user names, but we use a hack because of globus CORS headers
if (self.loggedIn) {
var userNames = ""
var firstOne = true;
for(var u in self.userList) {
if (firstOne) { firstOne = false; }
else { userNames +=',' }
userNames+=u;
}
$.ajax({
type: "GET",
url: self.userNameFetchUrl + userNames + "&token="+self.options.kbCache.token,
dataType:"json",
crossDomain : true,
success: function(data,res,jqXHR) {
for(var u in self.userList) {
if (u in data['data'] && data['data'][u]['fullName']) {
self.userList[u]['name'] = data['data'][u]['fullName'];
} else {
self.userList[u]['name'] = "Full name not set or found.";
}
}
self.renderTable(false);
},
error: function(jqXHR, textStatus, errorThrown) {
//do nothing
}
})
}
},
getData: function() {
return {title:"People using this data object.",id:this.options.objNameOrId, workspace:this.options.wsNameOrId};
},
/* Construct an ObjectIdentity that can be used to query the WS*/
getObjectIdentity: function(wsNameOrId, objNameOrId, objVer) {
if (objVer) { return {ref:wsNameOrId+"/"+objNameOrId+"/"+objVer}; }
return {ref:wsNameOrId+"/"+objNameOrId } ;
},
monthLookup : ["Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct", "Nov", "Dec"]
});
});
| mit |
changke/grunt-plovr-modules | test/fixtures/entry.js | 410 | goog.provide('entry');
goog.require('pm.application');
pm.start = function() {
try {
var app = pm.application.getInstance();
app.registerModule('core');
app.registerModule('moduleone');
app.registerModule('moduletwo');
app.registerModule('modulethree');
app.start();
} catch (e) {
console.error('Somerhing went wrong: ' + e);
}
};
goog.exportSymbol('pm.start', pm.start);
| mit |
izzyaxel/ArcaneArtificing | src/main/java/izzyaxel/arcaneartificing/divination/divinationEffects/EffectMobs.java | 5391 | package izzyaxel.arcaneartificing.divination.divinationEffects;
import izzyaxel.arcaneartificing.main.AAUtils;
import izzyaxel.arcaneartificing.mana.Mana;
import net.minecraft.entity.monster.EntityIronGolem;
import net.minecraft.entity.monster.EntitySnowman;
import net.minecraft.entity.passive.*;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import java.util.Random;
public class EffectMobs extends DivinationEffect
{
Mana.ManaType color = Mana.ManaType.B;
boolean disabled = false;
private static EffectMobs INSTANCE = new EffectMobs();
Random rand = new Random();
public static EffectMobs getEffectMobs()
{
return INSTANCE;
}
@Override
public Mana.ManaType getColor()
{
return this.color;
}
@Override
public boolean isDisabled()
{
return this.disabled;
}
@Override
public void doEffect(EntityPlayer player)
{
if(!player.worldObj.isRemote)
{
AAUtils.AALog.divination("Mobs", player);
World world = player.worldObj;
for(int i = 0; i < rand.nextInt(16) + 16; i++)
{
double x = player.posX + (rand.nextInt(11) - 5), y = player.posY + 1, z = player.posZ + (rand.nextInt(11) - 5);
switch(rand.nextInt(12))
{
case (0):
EntityChicken chicken = new EntityChicken(world);
chicken.setPosition(x, y, z);
world.spawnEntityInWorld(chicken);
break;
case (1):
EntityCow cow = new EntityCow(world);
cow.setPosition(x, y, z);
world.spawnEntityInWorld(cow);
break;
case (2):
EntityWolf wolf = new EntityWolf(world);
wolf.setPosition(x, y, z);
world.spawnEntityInWorld(wolf);
break;
case (3):
EntityPig pig = new EntityPig(world);
pig.setPosition(x, y, z);
world.spawnEntityInWorld(pig);
break;
case (4):
EntitySheep sheep = new EntitySheep(world);
sheep.setPosition(x, y, z);
world.spawnEntityInWorld(sheep);
break;
case (5):
EntityMooshroom shroom = new EntityMooshroom(world);
shroom.setPosition(x, y, z);
world.spawnEntityInWorld(shroom);
break;
case (6):
EntityBat bat = new EntityBat(world);
bat.setPosition(x, y, z);
world.spawnEntityInWorld(bat);
break;
case (7):
EntityVillager villager = new EntityVillager(world);
villager.setPosition(x, y, z);
world.spawnEntityInWorld(villager);
break;
case (8):
EntityOcelot ocelot = new EntityOcelot(world);
ocelot.setPosition(x, y, z);
world.spawnEntityInWorld(ocelot);
break;
case (9):
EntityHorse horse = new EntityHorse(world);
horse.setPosition(x, y, z);
world.spawnEntityInWorld(horse);
break;
case (10):
EntitySquid squid = new EntitySquid(world);
squid.setPosition(x, y, z);
world.spawnEntityInWorld(squid);
break;
case (11):
EntityIronGolem ironGolem = new EntityIronGolem(world);
ironGolem.setPosition(x, y, z);
world.spawnEntityInWorld(ironGolem);
break;
case (12):
EntitySnowman snowman = new EntitySnowman(world);
snowman.setPosition(x, y, z);
world.spawnEntityInWorld(snowman);
break;
default:
break;
}
}
/*//hostile
else
{
for(int i = 0; i < 30; i++)
{
double x = player.posX + (rand.nextInt(11) - 5), y = player.posY + 1, z = player.posZ + (rand.nextInt(11) - 5);
switch(rand.nextInt(11))
{
case (0):
EntitySkeleton skeleton = new EntitySkeleton(world);
skeleton.setPosition(x, y, z);
world.spawnEntityInWorld(skeleton);
break;
case (1):
EntitySpider spider = new EntitySpider(world);
spider.setPosition(x, y, z);
world.spawnEntityInWorld(spider);
break;
case (2):
EntityZombie zombie = new EntityZombie(world);
zombie.setPosition(x, y, z);
world.spawnEntityInWorld(zombie);
break;
case (3):
EntitySlime slime = new EntitySlime(world);
slime.setPosition(x, y, z);
world.spawnEntityInWorld(slime);
break;
case (4):
EntityEnderman enderman = new EntityEnderman(world);
enderman.setPosition(x, y, z);
world.spawnEntityInWorld(enderman);
break;
case (5):
EntityPigZombie pigZombie = new EntityPigZombie(world);
pigZombie.setPosition(x, y, z);
world.spawnEntityInWorld(pigZombie);
break;
case (6):
EntityCaveSpider caveSpider = new EntityCaveSpider(world);
caveSpider.setPosition(x, y, z);
world.spawnEntityInWorld(caveSpider);
break;
case (7):
EntitySilverfish silverfish = new EntitySilverfish(world);
silverfish.setPosition(x, y, z);
world.spawnEntityInWorld(silverfish);
break;
case (8):
EntityWitch witch = new EntityWitch(world);
witch.setPosition(x, y, z);
world.spawnEntityInWorld(witch);
break;
case (9):
EntityBlaze blaze = new EntityBlaze(world);
blaze.setPosition(x, y, z);
world.spawnEntityInWorld(blaze);
break;
case (10):
EntityMagmaCube magmaCube = new EntityMagmaCube(world);
magmaCube.setPosition(x, y, z);
world.spawnEntityInWorld(magmaCube);
break;
default:
break;
}
}
}*/
}
}
}
| mit |
concordiadiscors/chili_pepper | app/models/chili_pepper/menu.rb | 2794 | # == Schema Information
#
# Table name: chili_pepper_menus
#
# id :integer not null, primary key
# name :string(255)
# position :integer
# description :string(255)
# created_at :datetime
# updated_at :datetime
# slug :string(255)
# menu_type :integer
# availability :string(255)
# price :decimal(5, 2)
# published :boolean
# downloadable_pdf_file_name :string(255)
# downloadable_pdf_content_type :string(255)
# downloadable_pdf_file_size :integer
# downloadable_pdf_updated_at :datetime
# image_file_name :string(255)
# image_content_type :string(255)
# image_file_size :integer
# image_updated_at :datetime
#
module ChiliPepper
class Menu < ActiveRecord::Base
validates_presence_of :name
enum menu_type: [:food, :drinks]
acts_as_list
has_many :sections, class_name: 'ChiliPepper::Section', dependent: :destroy
extend FriendlyId
friendly_id :name, use: :slugged
has_many :annotations, dependent: :destroy
accepts_nested_attributes_for :annotations, allow_destroy: true
has_attached_file :image,
styles: {
medium: ChiliPepper.menu_medium_image,
thumb: '100x100>'
},
default_url: '/images/:style/missing.png'
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
has_attached_file :downloadable_pdf
validates_attachment_content_type :downloadable_pdf,
content_type: ['application/pdf']
def self.published
where published: true
end
def self.food_menus
where menu_type: menu_types[:food]
end
def self.drinks_menus
where menu_type: menu_types[:drinks]
end
def self.same_type_menus(menu_type)
where(menu_type: menu_types[menu_type])
.select('id, name, slug, position, menu_type, published')
.order('position')
end
def food_menu?
menu_type == 'food'
end
def duplicate
new_menu = Menu.create!(name: "#{name} copy", menu_type: menu_type)
sections.each do |original_section|
new_section = original_section.dup
new_section.menu_id = new_menu.id
new_section.save
original_section.items.each do |item|
Item.create!(
section_id: new_section.id,
dish_id: item.dish_id,
column: item.column,
position: item.position
)
end
end
end
end
end
| mit |
NormanMarlier/blcf | src/main.cpp | 6228 |
//
// Disclamer:
// ----------
//
// This code will work only if you selected window, graphics and audio.
//
// Note that the "Run Script" build phase will copy the required frameworks
// or dylibs to your application bundle so you can execute it on any OS X
// computer.
//
// Your resource files (images, sounds, fonts, ...) are also copied to your
// application bundle. To get the path to these resource, use the helper
// method resourcePath() from ResourcePath.hpp
//
// Standard dependencies
#include <thread>
#include <iostream>
// SFML dependencies
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include "ResourcePath.hpp"
// tmxlite dependencies
#include <tmxlite/Map.hpp>
#include <SFMLOrthogonalLayer.hpp>
// Main project
#include "EvolutivePerso.hpp"
#include "Classes.h"
#include "MapLevel.hpp"
#include "ServeurClient.hpp"
#include "CombatInteface.hpp"
#include "DecisionMaker.hpp"
// Constants
#include "Constants.h"
int main(int argc, char const** argv)
{
tmx::Map map;
map.load(resourcePath() + "map_neige1.tmx");
MapLevel mapLevel(resourcePath() + "map_neige1.tmx");
MapLayer layerZero(map, 0);
MapLayer layerOne(map, 1);
MapLayer layerTwo(map, 2);
MapLayer layerThree(map, 4);
MapLayer layerFour(map, 5);
sf::RenderWindow window(sf::VideoMode(1024, 512), "The Best Game Ever");
//framerate control => synchronize the vertical framerate.
window.setVerticalSyncEnabled(true);
sf::Texture textureCharac;
if (!textureCharac.loadFromFile(resourcePath() + "charac.png")) std::cerr << " Erreur " << std::endl;
sf::Texture textureCentaure;
if (!textureCentaure.loadFromFile(resourcePath() + "centaures.png")) std::cerr << " Erreur " << std::endl;
AnimeObject Centaure("Centaure", sf::IntRect(240,60,48,66), true, textureCentaure, sf::IntRect(472,0,48,66));
Warrior Blerims("Blerims");
Wizzard Dralkcib("Dralkcib");
RPGperso No(Dralkcib, textureCharac);
RPGperso Alex(Dralkcib, textureCharac);
//Alex.setStatePerso(FIGHT);
//No.setStatePerso(FIGHT);
while (window.isOpen())
{
// Check the state of the main character
if (No.getStatePerso() == MOVABLE)
{
// Event
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyPressed)
{
// Escape pressed: exit
if (event.key.code == sf::Keyboard::Escape)
{
window.close();
}
// Basic move
if (event.key.code == sf::Keyboard::Q )
{
// la touche "flèche gauche" est enfoncée : on bouge le personnage
No.movePosition(mapLevel, -PERSO_SPEED, 0);
}
if (event.key.code == sf::Keyboard::A )
{
// la touche "flèche gauche" est enfoncée : on bouge le personnage
No.movePosition(mapLevel, -PERSO_SPEED/2, -PERSO_SPEED/2);
}
if (event.key.code == sf::Keyboard::E )
{
// la touche "flèche gauche" est enfoncée : on bouge le personnage
No.movePosition(mapLevel, PERSO_SPEED/2, -PERSO_SPEED/2);
}
if (event.key.code == sf::Keyboard::W )
{
// la touche "flèche gauche" est enfoncée : on bouge le personnage
No.movePosition(mapLevel, -PERSO_SPEED/2, PERSO_SPEED/2);
}
if (event.key.code == sf::Keyboard::C )
{
// la touche "flèche gauche" est enfoncée : on bouge le personnage
No.movePosition(mapLevel, PERSO_SPEED/2, PERSO_SPEED/2);
}
if (event.key.code == sf::Keyboard::D)
{
// la touche "flèche droite" est enfoncée : on bouge le personnage
No.movePosition(mapLevel, PERSO_SPEED, 0);
}
if (event.key.code == sf::Keyboard::Z)
{
// la touche "flèche du haut" est enfoncée : on bouge le personnage
No.movePosition(mapLevel, 0, -PERSO_SPEED);
}
if (event.key.code == sf::Keyboard::S)
{
// la touche "flèche du bas" est enfoncée : on bouge le personnage
No.movePosition(mapLevel, 0, PERSO_SPEED);
}
}
}
window.clear(sf::Color::Black);
// Set view
window.setView(No.getView());
window.draw(layerZero);
window.draw(layerOne);
window.draw(layerTwo);
window.draw(Centaure.getSprite());
window.draw(No.getSprite());
window.draw(layerThree);
window.draw(layerFour);
}
else if (No.getStatePerso() == FIGHT)
{
// Combat interface
}
else
{
// Error... DO NOTHING !
}
window.display();
}
return 0;
}
| mit |
airbrake/gobrake | fiber/fiberbrake.go | 702 | package fiber
import (
"context"
"errors"
"github.com/airbrake/gobrake/v5"
"github.com/gofiber/fiber/v2"
)
// New returns a function that satisfies fiber.Handler interface
func New(notifier *gobrake.Notifier) fiber.Handler {
return func(c *fiber.Ctx) error {
if notifier == nil {
return errors.New("airbrake notifier not defined")
}
// Starts the timer.
_, metric := gobrake.NewRouteMetric(context.TODO(), c.Route().Method, c.Route().Path)
err := c.Next()
// capture the status code and resolved Route
metric.StatusCode = c.Response().StatusCode()
metric.Route = c.Route().Path
// Send to Airbrake
_ = notifier.Routes.Notify(context.TODO(), metric)
return err
}
}
| mit |
hiloteam/generator-hilo | generators/app/templates/src/js/hilo/kissy/hilo/view/CacheMixin.js | 1766 | /**
* Hilo 1.1.10 for kissy
* Copyright 2016 alibaba.com
* Licensed under the MIT License
*/
KISSY.add('hilo/view/CacheMixin', function(S, Drawable, browser){
var _cacheCanvas, _cacheContext;
/**
* @language=en
* @class CacheMixin A mixin that contains cache method.You can mix cache method to the target by use Class.mix(target, CacheMixin).
* @static
* @mixin
* @module hilo/view/CacheMixin
* @requires hilo/view/Drawable
* @requires hilo/util/browser
*/
var CacheMixin = /** @lends CacheMixin# */ {
_cacheDirty:true,
/**
* @language=en
* Cache the view.
* @param {Boolean} forceUpdate is force update cache.
*/
cache: function(forceUpdate){
if(forceUpdate || this._cacheDirty || !this.drawable){
this.updateCache();
}
},
/**
* @language=en
* Update the cache.
*/
updateCache:function(){
if(browser.supportCanvas){
if(!_cacheCanvas){
_cacheCanvas = document.createElement('canvas');
_cacheContext = _cacheCanvas.getContext('2d');
}
//TODO:width, height自动判断
_cacheCanvas.width = this.width;
_cacheCanvas.height = this.height;
this._draw(_cacheContext);
this.drawable = this.drawable||new Drawable();
this.drawable.init({
image:_cacheCanvas.toDataURL()
});
this._cacheDirty = false;
}
},
/**
* @language=en
* set the cache state diry.
* @param {Boolean} dirty is cache dirty
*/
setCacheDirty:function(dirty){
this._cacheDirty = dirty;
}
};
return CacheMixin;
}, {
requires: ['hilo/view/Drawable', 'hilo/util/browser']
}); | mit |
dazzle-php/redis | src/Redis/Command/CommandInterface.php | 421 | <?php
namespace Dazzle\Redis\Command;
interface CommandInterface extends
Api\ApiChannelInterface,
Api\ApiClusterInterface,
Api\ApiConnInterface,
Api\ApiCoreInterface,
Api\ApiGeospatialInterface,
Api\ApiHyperLogInterface,
Api\ApiKeyValInterface,
Api\ApiListInterface,
Api\ApiSetInterface,
Api\ApiSetHashInterface,
Api\ApiSetSortedInterface,
Api\ApiTransactionInterface
{}
| mit |
ivanna-ostrovets/language-and-literature-admin | src/common/components/backButton/backButton.component.ts | 318 | import { Component } from '@angular/core';
import { Location } from '@angular/common';
@Component({
selector: 'llta-back-button',
templateUrl: './backButton.component.html'
})
export class BackButtonComponent {
constructor(
private location: Location
) {
}
goBack() {
this.location.back();
}
}
| mit |
kennisnet/phpEdurepSearch | src/Model/DrilldownNavigator.php | 492 | <?php
namespace Kennisnet\Edurep\Model;
class DrilldownNavigator
{
/**
* @var string
*/
private $name;
/**
* @var DrilldownNavigatorItem[]
*/
private $items;
public function __construct(string $name, array $items)
{
$this->name = $name;
$this->items = $items;
}
public function getName(): string
{
return $this->name;
}
public function getItems(): array
{
return $this->items;
}
} | mit |
afaan5556/phase-0 | week-6/nested_data_solution.rb | 2990 | # RELEASE 2: NESTED STRUCTURE GOLF
# Hole 1
# Target element: "FORE"
array = [[1,2], ["inner", ["eagle", "par", ["FORE", "hook"]]]]
# attempts: 1
# ============================================================
p array[1][1][2][0]
# ============================================================
# Hole 2
# Target element: "congrats!"
hash = {outer: {inner: {"almost" => {3 => "congrats!"}}}}
# attempts: 1
# ============================================================
p hash[:outer][:inner]["almost"][3]
# ============================================================
# Hole 3
# Target element: "finished"
nested_data = {array: ["array", {hash: "finished"}]}
# attempts: 1
# ============================================================
p nested_data[:array][1][:hash]
# ============================================================
# RELEASE 3: ITERATE OVER NESTED STRUCTURES
number_array = [5, [10, 15], [20,25,30], 35]
number_array.map! do |element|
if element.is_a?(Array)
element.map! {|array_element| array_element += 5}
else
element += 5
end
end
p number_array
# Bonus:
startup_names = ["bit", ["find", "fast", ["optimize", "scope"]]]
startup_names.map! do |element|
if element.is_a?(Array)
element.map! do |sub_element|
if sub_element.is_a?(Array)
sub_element.map! {|sub_sub_element| sub_sub_element += "ly"}
else
sub_element += "ly"
end
end
else
element += "ly"
end
end
p startup_names
=begin
NOTE: SOLUTIONS ABOVE ASSUME THAT THE INTENT IS TO MAINTAIN THE DATA STRUCTURE IN THE END
THE FOLLOWING SINGLE LINE OF CODE CAN ITERATE TROUGH ARRAY ELEMENTS, SUB-ELEMENTS, AND SUB-SUB-ELEMENTS
=> startup_name.map! do {|element| puts element}
# What are some general rules you can apply to nested arrays?
=> You can access them with sequential square brackets []
=> For eaxample array[4][0][1] would return the second element, within the first array-element, within the fifth array-element for this example array
=> You can have any kind of data structure in a nested array. An nested array could have hashes in it
# What are some ways you can iterate over nested arrays?
=> The same enumerate methods can e applied to nested arrays as are applied to one-dimensional arrays
=> puts can be used instead of p to iterate over the inner arrays while outputting the result
# Did you find any good new methods to implement or did you re-use one you were already familiar with? What was it and why did you decide that was a good option?
=> If maintaining the data structure is not important, then .flat_map would have been a cool new method to use
=> We played and solidified our understanding of map, map!, and each through this exercise
=> The instructions sometimes specifies whether destructive or non-destructive methods are needed, but other times they do not
=> Also, it was not clear if the original data structure needed to e preserved. We chose to preserve it
=end
| mit |
fea17e86/node-webserver | routes/index.js | 1647 | var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('index', {title: 'Express Server', name: 'Cynthia'});
});
router.get('/variable', function (req, res, next) {
res.render('variable', {
title: 'Basic Variable',
user: {
firstname: 'Manish',
lastname: 'Prakash',
email: '[email protected]'
}
});
});
router.get('/loop', function (req, res, next) {
res.render('loop', {
title: 'Basic If Conditions and Loop',
"employees": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
]
});
});
router.get('/helper', function (req, res, next) {
res.render('helper', {
title: 'Using Helpers',
helpers: {
canDisplayDeal: function (options) {
if (this.is_publish == 1 || this.is_publish == '1') {
return options.fn(this);
} else {
return options.inverse(this);
}
}
},
deals: [
{
"is_publish": "1",
"name": "LG L90 Dual D410 Smartphone at Rs.11599"
},
{
"is_publish": "0",
"name": "Sony MDR-XB250 Headphone"
},
{
"is_publish": "1",
"name": "Philips HTB7150 Blu Ray Bluetooth Soundbar with Subwoofer Rs.27999"
},
{
"is_publish": "0",
"name": "Get 65% off On Over 5000 Books"
},
{
"is_publish": "0",
"name": "HealthKart Health & Beauty Products Rs. 100 off on Rs. 101"
}
]
});
});
module.exports = router;
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.