repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
arkenthera/CryEngineModifications
Code/GameSDK/GameDll/ProceduralCollectibleSystem.cpp
5200
/************************************************************************* Copyright (C) 2015 Alperen Gezer This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ------------------------------------------------------------------------- Description: Procedural Collectible Generation ------------------------------------------------------------------------- History: - 3.12.2015 - Created *************************************************************************/ #include "StdAfx.h" #include "ProceduralCollectibleSystem.h" #include "Game.h" #include "Actor.h" //--------------------------------------------------------------------- #define PROCEDURAL_COLLECTIBLE_SYS_UPDATE_SLOT 0 //--------------------------------------------------------------------- void CProceduralCollectibleSystem::SProperties::InitFromScript(const IEntity& entity) { IScriptTable* pScriptTable = entity.GetScriptTable(); if(pScriptTable != NULL) { SmartScriptTable propertiesTable; if (pScriptTable->GetValue("Properties", propertiesTable)) { propertiesTable->GetValue("bEnabled",m_enabled); propertiesTable->GetValue("bVisualize",m_visualize); SmartScriptTable spawnTable; if(propertiesTable->GetValue("Spawn",spawnTable)) { spawnTable->GetValue("fInterval",m_interval); spawnTable->GetValue("fRadius",m_radius); spawnTable->GetValue("object_Model",m_model); } } } } //--------------------------------------------------------------------- CProceduralCollectibleSystem::CProceduralCollectibleSystem() { } //--------------------------------------------------------------------- CProceduralCollectibleSystem::~CProceduralCollectibleSystem() { } //--------------------------------------------------------------------- void CProceduralCollectibleSystem::SpawnSingleEntity() { } //--------------------------------------------------------------------- void CProceduralCollectibleSystem::SpawnEntities() { } //--------------------------------------------------------------------- void CProceduralCollectibleSystem::RemoveEntites() { } //--------------------------------------------------------------------- bool CProceduralCollectibleSystem::Init( IGameObject * pGameObject ) { SetGameObject(pGameObject); return true; } //--------------------------------------------------------------------- void CProceduralCollectibleSystem::PostInit(IGameObject *pGameObject) { Reset(); /*SpawnSingleEntity();*/ } //-------------------------------------------------------------------- void CProceduralCollectibleSystem::ProcessEvent( SEntityEvent &event) { if (event.event == ENTITY_EVENT_XFORM) { } else if (gEnv->IsEditor() && (event.event == ENTITY_EVENT_RESET)) { const bool leavingGameMode = (event.nParam[0] == 0); if (leavingGameMode) { Reset(); } } } //-------------------------------------------------------------------- void CProceduralCollectibleSystem::Update( SEntityUpdateContext& ctx, int updateSlot ) { } //-------------------------------------------------------------------- bool CProceduralCollectibleSystem::ReloadExtension( IGameObject * pGameObject, const SEntitySpawnParams &params ) { ResetGameObject(); return true; } //-------------------------------------------------------------------- void CProceduralCollectibleSystem::PostReloadExtension( IGameObject * pGameObject, const SEntitySpawnParams &params ) { } //-------------------------------------------------------------------- bool CProceduralCollectibleSystem::GetEntityPoolSignature( TSerialize signature ) { return true; } //-------------------------------------------------------------------- void CProceduralCollectibleSystem::ActivateGeneration(bool activate) { GetEntity()->Activate( activate ); if (activate && (gEnv->IsEditor())) { if (GetGameObject()->GetUpdateSlotEnables( this, PROCEDURAL_COLLECTIBLE_SYS_UPDATE_SLOT) == 0) { GetGameObject()->EnableUpdateSlot( this, PROCEDURAL_COLLECTIBLE_SYS_UPDATE_SLOT ) ; } } else { GetGameObject()->DisableUpdateSlot( this, PROCEDURAL_COLLECTIBLE_SYS_UPDATE_SLOT ); } } //-------------------------------------------------------------------- void CProceduralCollectibleSystem::Reset() { m_ScriptsProps.InitFromScript(*GetEntity()); } //---------------------------------------------------------------------// void CProceduralCollectibleSystem::FullSerialize( TSerialize ser ) { } //---------------------------------------------------------------------// void CProceduralCollectibleSystem::PostSerialize() { } //---------------------------------------------------------------------//
mit
SingularInversions/FaceGenBaseLibrary
source/LibFgWin/FgGuiWinTabs.cpp
8375
// // Coypright (c) 2022 Singular Inversions Inc. (facegen.com) // Use, modification and distribution is subject to the MIT License, // see accompanying file LICENSE.txt or facegen.com/base_library_license.txt // // // Win32 has no way to dynamically change the background color of specific tabs (ie currently selected). // The only way to do this is to override the default WM_ERASEBKGND and WM_PAINT and draw them yourself. // At which point you may as well implement your own tabs. #include "stdafx.h" #include "FgGuiApiTabs.hpp" #include "FgGuiWin.hpp" #include "FgThrowWindows.hpp" #include "FgMatrixC.hpp" #include "FgBounds.hpp" #include "FgMetaFormat.hpp" using namespace std; namespace Fg { struct GuiTabsWin : public GuiBaseImpl { GuiTabs m_api; HWND m_tabHwnd; HWND hwndThis; GuiImplPtrs m_panes; uint m_currPane; Vec2I m_client; RECT m_dispArea; String8 m_store; GuiTabsWin(const GuiTabs & api) : m_api(api) { FGASSERT(m_api.tabs.size()>0); for (size_t ii=0; ii<m_api.tabs.size(); ++ii) m_panes.push_back(api.tabs[ii].win->getInstance()); m_currPane = 0; } ~GuiTabsWin() { if (!m_store.empty()) // Win32 instance was created saveBsaXml(m_store+".xml",m_currPane,false); } virtual void create(HWND parentHwnd,int ident,String8 const & store,DWORD extStyle,bool visible) { //fgout << fgnl << "Tabs::create visible: " << visible << " extStyle: " << extStyle << fgpush; if (m_store.empty()) { // First creation this session so check for saved state uint cp; if (loadBsaXml(store+".xml",cp,false)) if (cp < m_panes.size()) m_currPane = cp; } m_store = store; WinCreateChild cc; cc.extStyle = extStyle; cc.visible = visible; // Without this, tab outline shadowing can disappear: cc.useFillBrush = true; winCreateChild(parentHwnd,ident,this,cc); //fgout << fgpop; } virtual void destroy() { // Automatically destroys children first: DestroyWindow(hwndThis); } virtual Vec2UI getMinSize() const { Vec2UI max(0); for (size_t ii=0; ii<m_panes.size(); ++ii) { const GuiTabDef & tab = m_api.tabs[ii]; Vec2UI pad(tab.padLeft+tab.padRight,tab.padTop+tab.padBottom); max = cMax(max,m_panes[ii]->getMinSize()+pad); } return max + Vec2UI(0,37); } virtual Vec2B wantStretch() const { for (size_t ii=0; ii<m_panes.size(); ++ii) if (m_panes[ii]->wantStretch()[0]) return Vec2B(true,true); return Vec2B(false,true); } virtual void updateIfChanged() { //fgout << fgnl << "Tabs::updateIfChanged" << fgpush; m_panes[m_currPane]->updateIfChanged(); //fgout << fgpop; } virtual void moveWindow(Vec2I lo,Vec2I sz) { //fgout << fgnl << "Tabs::moveWindow " << lo << "," << sz << fgpush; MoveWindow(hwndThis,lo[0],lo[1],sz[0],sz[1],FALSE); //fgout << fgpop; } virtual void showWindow(bool s) { //fgout << fgnl << "Tabs::showWindow: " << s << fgpush; ShowWindow(hwndThis,s ? SW_SHOW : SW_HIDE); //fgout << fgpop; } LRESULT wndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) { if (msg == WM_CREATE) { //fgout << fgnl << "Tabs::WM_CREATE" << fgpush; hwndThis = hwnd; // Creating the panes before the tabs fixes the problem of trackbars not being visible // on first paint (almost ... top/bottom arrows don't appear). No idea why. // Used to create all tab windows here and turn visibility on and off with selection but as of // Windows 10 this approach causes huge latency when moving main window so now we create/destroy // each time tab is changed. Used to be the case that WM_SIZE was not sent non-visible windows, // but either that is not the case any more or MS has managed to do something even stupider ... FGASSERT(m_currPane < m_panes.size()); m_panes[m_currPane]->create(hwnd, int(m_currPane+1), // Child identifiers start at 1 since 0 taken above. Not used anyway. m_store+"_"+toStr(m_currPane), NULL, true); m_tabHwnd = CreateWindowEx(0, WC_TABCONTROL, L"", WS_CHILD | WS_VISIBLE, 0,0,0,0, hwnd, 0, // Identifier 0 s_guiWin.hinst, NULL); TCITEM tc = {0}; tc.mask = TCIF_TEXT; for (size_t ii=0; ii<m_panes.size(); ++ii) { wstring wstr = m_api.tabs[ii].label.as_wstring(); wstr += wchar_t(0); tc.pszText = &wstr[0]; TabCtrl_InsertItem(m_tabHwnd,ii,&tc); } SendMessage(m_tabHwnd,TCM_SETCURSEL,m_currPane,0); //fgout << fgpop; return 0; } else if (msg == WM_SIZE) { m_client = Vec2I(LOWORD(lParam),HIWORD(lParam)); if (m_client[0] * m_client[1] > 0) { //fgout << fgnl << "Tabs::WM_SIZE: " << m_api.tabs[0].label << " : " << m_client << fgpush; resize(hwnd); //fgout << fgpop; } return 0; } else if (msg == WM_NOTIFY) { LPNMHDR lpnmhdr = (LPNMHDR)lParam; if (lpnmhdr->code == TCN_SELCHANGE) { int idx = int(SendMessage(m_tabHwnd,TCM_GETCURSEL,0,0)); // This can apparently be -1 for 'no tab selected': if ((idx >= 0) && (size_t(idx) < m_panes.size())) { //fgout << fgnl << "Tabs::WM_NOTIFY: " << idx << fgpush; if (uint(idx) != m_currPane) { m_panes[m_currPane]->destroy(); m_currPane = uint(idx); String8 subStore = m_store + "_" + toStr(m_currPane); m_panes[m_currPane]->create(hwnd,int(m_currPane)+1,subStore,NULL,true); resizeCurrPane(); // Always required after creation m_panes[m_currPane]->updateIfChanged(); // Required to update win32 state (eg. sliders) InvalidateRect(hwndThis,NULL,TRUE); // Tested to be necessary } //fgout << fgpop; } } return 0; } else if (msg == WM_PAINT) { //fgout << fgnl << "Tabs::WM_PAINT"; } return DefWindowProc(hwnd,msg,wParam,lParam); } void resizeCurrPane() { GuiTabDef const & tab = m_api.tabs[m_currPane]; Vec2I lo (m_dispArea.left + tab.padLeft, m_dispArea.top + tab.padTop), hi (m_dispArea.right - tab.padRight,m_dispArea.bottom - tab.padBottom), sz = hi - lo; m_panes[m_currPane]->moveWindow(lo,sz); } void resize(HWND) { // The repaint TRUE argument is only necessary when going from maximized to normal window size, // for some reason the tabs are repainted anyway in other situations: MoveWindow(m_tabHwnd,0,0,m_client[0],m_client[1],TRUE); m_dispArea.left = 0; m_dispArea.top = 0; m_dispArea.right = m_client[0]; m_dispArea.bottom = m_client[1]; SendMessage(m_tabHwnd, TCM_ADJUSTRECT, NULL, // Give me the display area for this window area: LPARAM(&m_dispArea)); resizeCurrPane(); } }; GuiImplPtr guiGetOsImpl(const GuiTabs & api) {return GuiImplPtr(new GuiTabsWin(api)); } }
mit
jenspapenhagen/miniORM
datamodel/datamanager/GenericEntityManager.php
8835
<?php include_once (dirname(__FILE__)."/../datamodel/ConnectionProvider.php"); include_once (dirname(__FILE__)."/../datamodel/Constants.php"); include_once (dirname(__FILE__)."/../datamodel/Updater.php"); include_once (dirname(__FILE__)."/../datamodel/entity/GenericEntity.php"); include_once (dirname(__FILE__)."/../business/service/CSVHandler.php"); include_once (dirname(__FILE__)."/../business/service/HelperFunctions.php"); include_once (dirname(__FILE__)."/../business/service/Evaluator.php"); class GenericEntityManager{ protected $entityToManage; protected $PDO; protected $Updater; protected $CSVHandler; protected $HelperFunctions; protected $Evaluator; protected $findAll = "select * from "; protected $findById = "select * from "; protected $lastId = "select max(id) form "; protected $countAll = "select count(*) from "; protected $tableColumnsQuery; protected $tableColumns; public function __construct(GenericEntity $entity){ $this->Updater = New Updater(); if($this->Updater->ExistEntry($entity)){ $this->entityToManage = $entity; }else{ echo "entity not found."; die(); } $this->PDO = ConnectionProvider::getConnection(); $this->findAll .= Constants::$databaseName.".".$entity->getTablename(); $this->findById .= Constants::$databaseName.".".$entity->getTablename()." where ".$this->entityToManage->getIdcolumn()." = '"; $this->lastId .= Constants::$databaseName.".".$entity->getTablename(); $this->countAll .= Constants::$databaseName.".".$entity->getTablename(); } public function GenericEntityManager(GenericEntity $entity) { self::__construct($entity); } public function entityexist($entity){ $this->Updater->ExistEntry($entity); } public function findAll() { try { $statement = $this->PDO->prepare($this->findAll); $statement->execute(); $reflect = new ReflectionClass($this->entityToManage); $result = $statement->fetchAll(PDO::FETCH_CLASS,$reflect->getName()); return $result; }catch (PDOException $e) { echo "findAll failed: ".$e->getMessage(); die(); } } public function findById(int $id):int { $this->findById .= $id."';"; $statement = $this->PDO->prepare($this->findById); $statement->execute(); $reflect = new ReflectionClass($this->entityToManage); $result = $statement->fetchAll(PDO::FETCH_CLASS,$reflect->getName()); $this->findById = "select * from "; $this->findById .= Constants::$databaseName.".".$this->entityToManage->getTablename()." where ".$this->entityToManage->getIdcolumn()." = '"; if (!empty($result)) { return $result[0]; } else { return NULL; } } public function lastId(GenericEntity $entity):int { $this->lastId .= $this->entityToManage->getTablename()."';"; $statement = $this->PDO->prepare($this->lastId); $statement->execute(); $reflect = new ReflectionClass($this->entityToManage); $result = $statement->fetchAll(PDO::FETCH_CLASS,$reflect->getName()); if (!empty($result)) { return $result[0]; } else { return NULL; } } public function delete(GenericEntity $entity) { try { $deleteStatement = "delete from ".$entity->getTablename()." where ".$entity->getIdcolumn()." = '".$entity->{("get".ucfirst($entity->getIdcolumn()))}()."'"; $statement = $this->PDO->prepare($deleteStatement); $statement->execute(); }catch (PDOException $e) { echo "delete failed: ".$e->getMessage(); die(); } } public function insertOrUpdate(GenericEntity $entity) { $entityID = $entity->{("get".ucfirst($entity->getIdcolumn()))}(); $preparedStatement= NULL; if ($entityID != NULL){ $updateStatement = "update ".$entity->getTablename()." set ".$this->getEntityValuesAsCommaSeperatedUpdateString($entity)." where ".$entity->getIdcolumn()."='".$entityID."';"; $preparedStatement = $this->PDO->prepare($updateStatement); $preparedStatement->execute(); return 0; } else { $insertStatement = "insert into ".$entity->getTablename()." (".$this->getEntityColumnsAsCommaSeperatedString($entity).") values (".$this->getEntityValuesAsCommaSeperatedString($entity).");"; $preparedStatement = $this->PDO->prepare($insertStatement); $preparedStatement->execute(); return $this->PDO->lastInsertId(); } } public function getEntityValuesAsCommaSeperatedString($entity):string { $reflection = new ReflectionClass($entity); $propertyArray = $reflection->getProperties(ReflectionProperty::IS_PRIVATE); $valuesAsString = ""; foreach ($propertyArray as $property) { if (empty($valuesAsString)) { $valuesAsString .= "'".$entity->{("get".ucfirst($property->getName()))}()."'"; } else { $valuesAsString .= ",'".$entity->{("get".ucfirst($property->getName()))}()."'"; } } return $valuesAsString; } public function getEntityColumnsAsCommaSeperatedString($entity):string { $reflection = new ReflectionClass($entity); $propertyArray = $reflection->getProperties(ReflectionProperty::IS_PRIVATE); $valuesAsString = ""; foreach ($propertyArray as $property) { if (empty($valuesAsString)) { $valuesAsString .= $property->getName(); } else { $valuesAsString .= ",".$property->getName(); } } return $valuesAsString; } public function getEntityColumnsAsArray($entity):array { $reflection = new ReflectionClass($entity); $propertyArray = $reflection->getProperties(ReflectionProperty::IS_PRIVATE); return $propertyArray; } public function getEntityValuesAsCommaSeperatedUpdateString($entity):string { $reflection = new ReflectionClass($entity); $propertyArray = $reflection->getProperties(ReflectionProperty::IS_PRIVATE); $valuesAsString = ""; foreach ($propertyArray as $property) { if (empty($valuesAsString)) { $valuesAsString .= $property->getName()."='".$entity->{("get".ucfirst($property->getName()))}()."'"; } else { $valuesAsString .= ", ".$property->getName()."='".$entity->{("get".ucfirst($property->getName()))}()."'"; } } return $valuesAsString; } public function getAllTablenames():array{ $results_array = array(); $sql = "select table_name from information_schema.tables where table_schema='".Constants::$databaseName."';"; $result = $this->executeGenericStatement($sql); if (empty($result)) { return NULL; } return $results_array; } public function exportTableHeaderToCSV($file){ $tableheader = $this->getAllTablenames(); $filename = $file.".csv"; if (fileExists($filename)){ echo "ExportFile exist"; die(); } $CSVHandler = New CSVHandler($filename); $CSVHandler->writeRow($tableheader); } public function importTableHeaderFromCSV($file){ $filename = $file.".csv"; if (!fileExists($filename) and $this->entityexist($file)){ echo "import can only in a new table"; die(); } $CSVHandler = New CSVHandler($filename); $CSVHandler->countColumns(); $data = $CSVHandler->getHeaders(); $HelperFunctions = New HelperFunctions; $data = $HelperFunctions->array_trim($data); $Evaluator = New Evaluator; $date = array_filter($data,$Evaluator->returnOnlyLettersNumbersUnderscore($data)); $sql = "CREATE TABLE IF NOT EXISTS ` ".$file." ` ("; for($i=0; $i<= $CSVHandler->countColumns();$i++){ if($i==0){ $sql .= "`". $data[$i]."` int(11) NOT NULL auto_increment"; } $sql .= "`". $data[$i]."` varchar(255) NOT NULL default ''"; if($i==0){ $sql .= "PRIMARY KEY (`".$data[$i]."`)"; } } $sql .= ")"; $result = $this->executeGenericStatement($sql); if (empty($result)) { return NULL; } } public function executeGenericSelect($statement) { $preparedStatement = $this->PDO->prepare($statement); $preparedStatement->execute(); $reflection = new ReflectionClass($this->entityToManage); $result = $preparedStatement->fetchAll(PDO::FETCH_CLASS,$reflection->getName()); return $result; } public function executeGenericStatement($statement) { $statement = trim($statement); try { $preparedStatement = $this->PDO->prepare($statement); $preparedStatement->execute(); } catch (PDOException $e) { echo "Execute of this SQL failed: ".$e->getMessage(); die(); } } public function getEntityToManage() { return $this->entityToManage; } }
mit
thaim/ansible
lib/ansible/modules/cloud/google/gcp_bigquery_dataset_info.py
12799
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_bigquery_dataset_info description: - Gather info for GCP Dataset - This module was called C(gcp_bigquery_dataset_facts) before Ansible 2.9. The usage has not changed. short_description: Gather info for GCP Dataset version_added: '2.8' author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: project: description: - The Google Cloud Platform project to use. type: str auth_kind: description: - The type of credential used. type: str required: true choices: - application - machineaccount - serviceaccount service_account_contents: description: - The contents of a Service Account JSON file, either in a dictionary or as a JSON string that represents it. type: jsonarg service_account_file: description: - The path of a Service Account JSON file if serviceaccount is selected as type. type: path service_account_email: description: - An optional service account email address if machineaccount is selected and the user does not wish to use the default email. type: str scopes: description: - Array of scopes to be used type: list env_type: description: - Specifies which Ansible environment you're running this module within. - This should not be set unless you know what you're doing. - This only alters the User Agent string for any API requests. type: str notes: - for authentication, you can set service_account_file using the c(gcp_service_account_file) env variable. - for authentication, you can set service_account_contents using the c(GCP_SERVICE_ACCOUNT_CONTENTS) env variable. - For authentication, you can set service_account_email using the C(GCP_SERVICE_ACCOUNT_EMAIL) env variable. - For authentication, you can set auth_kind using the C(GCP_AUTH_KIND) env variable. - For authentication, you can set scopes using the C(GCP_SCOPES) env variable. - Environment variables values will only be used if the playbook values are not set. - The I(service_account_email) and I(service_account_file) options are mutually exclusive. ''' EXAMPLES = ''' - name: get info on a dataset gcp_bigquery_dataset_info: project: test_project auth_kind: serviceaccount service_account_file: "/tmp/auth.pem" ''' RETURN = ''' resources: description: List of resources returned: always type: complex contains: name: description: - Dataset name. returned: success type: str access: description: - An array of objects that define dataset access for one or more entities. returned: success type: complex contains: domain: description: - A domain to grant access to. Any users signed in with the domain specified will be granted the specified access . returned: success type: str groupByEmail: description: - An email address of a Google Group to grant access to. returned: success type: str role: description: - Describes the rights granted to the user specified by the other member of the access object. Primitive, Predefined and custom roles are supported. Predefined roles that have equivalent primitive roles are swapped by the API to their Primitive counterparts, and will show a diff post-create. See [official docs](U(https://cloud.google.com/bigquery/docs/access-control)). returned: success type: str specialGroup: description: - A special group to grant access to. - 'Possible values include: * `projectOwners`: Owners of the enclosing project.' - "* `projectReaders`: Readers of the enclosing project." - "* `projectWriters`: Writers of the enclosing project." - "* `allAuthenticatedUsers`: All authenticated BigQuery users. ." returned: success type: str userByEmail: description: - 'An email address of a user to grant access to. For example: [email protected] .' returned: success type: str view: description: - A view from a different dataset to grant access to. Queries executed against that view will have read access to tables in this dataset. The role field is not required when this field is set. If that view is updated by any user, access to the view needs to be granted again via an update operation. returned: success type: complex contains: datasetId: description: - The ID of the dataset containing this table. returned: success type: str projectId: description: - The ID of the project containing this table. returned: success type: str tableId: description: - The ID of the table. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores. The maximum length is 1,024 characters. returned: success type: str creationTime: description: - The time when this dataset was created, in milliseconds since the epoch. returned: success type: int datasetReference: description: - A reference that identifies the dataset. returned: success type: complex contains: datasetId: description: - A unique ID for this dataset, without the project name. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores. The maximum length is 1,024 characters. returned: success type: str projectId: description: - The ID of the project containing this dataset. returned: success type: str defaultTableExpirationMs: description: - The default lifetime of all tables in the dataset, in milliseconds. - The minimum value is 3600000 milliseconds (one hour). - Once this property is set, all newly-created tables in the dataset will have an `expirationTime` property set to the creation time plus the value in this property, and changing the value will only affect new tables, not existing ones. When the `expirationTime` for a given table is reached, that table will be deleted automatically. - If a table's `expirationTime` is modified or removed before the table expires, or if you provide an explicit `expirationTime` when creating a table, that value takes precedence over the default expiration time indicated by this property. returned: success type: int defaultPartitionExpirationMs: description: - The default partition expiration for all partitioned tables in the dataset, in milliseconds. - Once this property is set, all newly-created partitioned tables in the dataset will have an `expirationMs` property in the `timePartitioning` settings set to this value, and changing the value will only affect new tables, not existing ones. The storage in a partition will have an expiration time of its partition time plus this value. - 'Setting this property overrides the use of `defaultTableExpirationMs` for partitioned tables: only one of `defaultTableExpirationMs` and `defaultPartitionExpirationMs` will be used for any new partitioned table. If you provide an explicit `timePartitioning.expirationMs` when creating or updating a partitioned table, that value takes precedence over the default partition expiration time indicated by this property.' returned: success type: int description: description: - A user-friendly description of the dataset. returned: success type: str etag: description: - A hash of the resource. returned: success type: str friendlyName: description: - A descriptive name for the dataset. returned: success type: str id: description: - The fully-qualified unique name of the dataset in the format projectId:datasetId. The dataset name without the project name is given in the datasetId field . returned: success type: str labels: description: - The labels associated with this dataset. You can use these to organize and group your datasets . returned: success type: dict lastModifiedTime: description: - The date when this dataset or any of its tables was last modified, in milliseconds since the epoch. returned: success type: int location: description: - The geographic location where the dataset should reside. - See [official docs](U(https://cloud.google.com/bigquery/docs/dataset-locations)). - There are two types of locations, regional or multi-regional. A regional location is a specific geographic place, such as Tokyo, and a multi-regional location is a large geographic area, such as the United States, that contains at least two geographic places. - 'Possible regional values include: `asia-east1`, `asia-northeast1`, `asia-southeast1`, `australia-southeast1`, `europe-north1`, `europe-west2` and `us-east4`.' - 'Possible multi-regional values: `EU` and `US`.' - The default value is multi-regional location `US`. - Changing this forces a new resource to be created. returned: success type: str ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest import json ################################################################################ # Main ################################################################################ def main(): module = GcpModule(argument_spec=dict()) if module._name == 'gcp_bigquery_dataset_facts': module.deprecate("The 'gcp_bigquery_dataset_facts' module has been renamed to 'gcp_bigquery_dataset_info'", version='2.13') if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/bigquery'] return_value = {'resources': fetch_list(module, collection(module))} module.exit_json(**return_value) def collection(module): return "https://www.googleapis.com/bigquery/v2/projects/{project}/datasets".format(**module.params) def fetch_list(module, link): auth = GcpSession(module, 'bigquery') return auth.list(link, return_if_object, array_name='datasets') def return_if_object(module, response): # If not found, return nothing. if response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result if __name__ == "__main__": main()
mit
iporaitech/react-to-mdl
src/dataTable/DataTable.js
697
import React, { PropTypes } from 'react'; import classNames from 'classnames'; const DataTable = (props) => { const { className, selectable, shadow, children, ...otherProps } = props; const classes = classNames('mdl-data-table mdl-js-data-table', { 'mdl-data-table--selectable': selectable, [`mdl-shadow--${shadow}`]: shadow }, className); return ( <table className={classes} {...otherProps}> {children} </table> ) } DataTable.propTypes = { className: PropTypes.string, selectable: PropTypes.bool, shadow: PropTypes.oneOf([ '2dp', '3dp', '4dp', '6dp', '8dp', '16dp' ]) } DataTable.defaultProps = { selectable: false } export default DataTable;
mit
integratedfordevelopers/integrated-channel-bundle
Model/ConfigRepository.php
2429
<?php /* * This file is part of the Integrated package. * * (c) e-Active B.V. <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Integrated\Bundle\ChannelBundle\Model; use Doctrine\ORM\EntityRepository; use Integrated\Common\Channel\ChannelInterface; use Integrated\Common\Channel\Connector\Config\ConfigInterface; use Integrated\Common\Channel\Connector\Config\ConfigManagerInterface; use InvalidArgumentException; /** * @author Jan Sanne Mulder <[email protected]> */ class ConfigRepository extends EntityRepository implements ConfigManagerInterface { /** * {@inheritdoc} */ public function create() { return $this->_class->getReflectionClass()->newInstance(); } /** * {@inheritdoc} */ public function persist(ConfigInterface $object, $flush = true) { if (!$this->_class->getReflectionClass()->isInstance($object)) { throw new InvalidArgumentException( sprintf('The object (%s) is not a instance of %s', get_class($object), $this->getClassName()) ); } $this->_em->persist($object); if ($flush) { $this->_em->flush($object); } } /** * {@inheritdoc} */ public function remove(ConfigInterface $object, $flush = true) { if (!$this->_class->getReflectionClass()->isInstance($object)) { throw new InvalidArgumentException( sprintf('The object (%s) is not a instance of %s', get_class($object), $this->getClassName()) ); } $this->_em->remove($object); if ($flush) { $this->_em->flush($object); } } /** * {@inheritdoc} */ public function findByAdaptor($criteria) { return $this->findBy([ 'adaptor' => $criteria ]); } /** * {@inheritdoc} */ public function findByChannel($criteria) { if ($criteria instanceof ChannelInterface) { $criteria = $criteria->getId(); } $expr = $this->_em->getExpressionBuilder(); return $this->createQueryBuilder('r') ->where($expr->like('r.channels', $expr->literal('%' . json_encode($criteria) . '%'))) ->getQuery() ->getResult(); } }
mit
bryanvu/lnd
lnwire/lnwire_test.go
4347
package lnwire import ( "encoding/hex" "net" "github.com/roasbeef/btcd/btcec" "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" ) // Common variables and functions for the message tests var ( revHash = [32]byte{ 0xb7, 0x94, 0x38, 0x5f, 0x2d, 0x1e, 0xf7, 0xab, 0x4d, 0x92, 0x73, 0xd1, 0x90, 0x63, 0x81, 0xb4, 0x4f, 0x2f, 0x6f, 0x25, 0x88, 0xa3, 0xef, 0xb9, 0x6a, 0x49, 0x18, 0x83, 0x31, 0x98, 0x47, 0x53, } maxUint32 uint32 = (1 << 32) - 1 maxUint24 uint32 = (1 << 24) - 1 maxUint16 uint16 = (1 << 16) - 1 // For debugging, writes to /dev/shm/ // Maybe in the future do it if you do "go test -v" WRITE_FILE = false filename = "/dev/shm/serialized.raw" // preimage: 9a2cbd088763db88dd8ba79e5726daa6aba4aa7e // echo -n | openssl sha256 | openssl ripemd160 | openssl sha256 | openssl ripemd160 revocationHashBytes, _ = hex.DecodeString("4132b6b48371f7b022a16eacb9b2b0ebee134d41") revocationHash [20]byte // preimage: "hello world" redemptionHashBytes, _ = hex.DecodeString("5b315ebabb0d8c0d94281caa2dfee69a1a00436e") redemptionHash [20]byte // preimage: "next hop" nextHopBytes, _ = hex.DecodeString("94a9ded5a30fc5944cb1e2cbcd980f30616a1440") nextHop [20]byte privKeyBytes, _ = hex.DecodeString("9fa1d55217f57019a3c37f49465896b15836f54cb8ef6963870a52926420a2dd") privKey, pubKey = btcec.PrivKeyFromBytes(btcec.S256(), privKeyBytes) address = pubKey // Delivery PkScript // Privkey: f2c00ead9cbcfec63098dc0a5f152c0165aff40a2ab92feb4e24869a284c32a7 // PKhash: n2fkWVphUzw3zSigzPsv9GuDyg9mohzKpz deliveryPkScript, _ = hex.DecodeString("76a914e8048c0fb75bdecc91ebfb99c174f4ece29ffbd488ac") // Change PkScript // Privkey: 5b18f5049efd9d3aff1fb9a06506c0b809fb71562b6ecd02f6c5b3ab298f3b0f // PKhash: miky84cHvLuk6jcT6GsSbgHR8d7eZCu9Qc changePkScript, _ = hex.DecodeString("76a914238ee44bb5c8c1314dd03974a17ec6c406fdcb8388ac") // echo -n | openssl sha256 // This stuff gets reversed!!! shaHash1Bytes, _ = hex.DecodeString("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") shaHash1, _ = chainhash.NewHash(shaHash1Bytes) outpoint1 = wire.NewOutPoint(shaHash1, 0) // echo | openssl sha256 // This stuff gets reversed!!! shaHash2Bytes, _ = hex.DecodeString("01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b") shaHash2, _ = chainhash.NewHash(shaHash2Bytes) outpoint2 = wire.NewOutPoint(shaHash2, 1) // create inputs from outpoint1 and outpoint2 inputs = []*wire.TxIn{wire.NewTxIn(outpoint1, nil, nil), wire.NewTxIn(outpoint2, nil, nil)} // Commitment Signature tx = wire.NewMsgTx(1) emptybytes = new([]byte) sigStr, _ = txscript.RawTxInSignature(tx, 0, *emptybytes, txscript.SigHashAll, privKey) commitSig, _ = btcec.ParseSignature(sigStr, btcec.S256()) // Funding TX Sig 1 sig1privKeyBytes, _ = hex.DecodeString("927f5827d75dd2addeb532c0fa5ac9277565f981dd6d0d037b422be5f60bdbef") sig1privKey, _ = btcec.PrivKeyFromBytes(btcec.S256(), sig1privKeyBytes) sigStr1, _ = txscript.RawTxInSignature(tx, 0, *emptybytes, txscript.SigHashAll, sig1privKey) commitSig1, _ = btcec.ParseSignature(sigStr1, btcec.S256()) // Funding TX Sig 2 sig2privKeyBytes, _ = hex.DecodeString("8a4ad188f6f4000495b765cfb6ffa591133a73019c45428ddd28f53bab551847") sig2privKey, _ = btcec.PrivKeyFromBytes(btcec.S256(), sig2privKeyBytes) sigStr2, _ = txscript.RawTxInSignature(tx, 0, *emptybytes, txscript.SigHashAll, sig2privKey) commitSig2, _ = btcec.ParseSignature(sigStr2, btcec.S256()) // Slice of Funding TX Sigs ptrFundingTXSigs = append(*new([]*btcec.Signature), commitSig1, commitSig2) // TxID txid = new(chainhash.Hash) // Reversed when displayed txidBytes, _ = hex.DecodeString("fd95c6e5c9d5bcf9cfc7231b6a438e46c518c724d0b04b75cc8fddf84a254e3a") _ = copy(txid[:], txidBytes) someAlias, _ = NewAlias("012345678901234567890") someSig, _ = btcec.ParseSignature(sigStr, btcec.S256()) someSigBytes = someSig.Serialize() someAddress = &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8333} someChannelID = ChannelID{ BlockHeight: maxUint24, TxIndex: maxUint24, TxPosition: maxUint16, } someRGB = RGB{ red: 255, green: 255, blue: 255, } )
mit
moonCrawler/ipl-logistik.de
typo3conf/ext/powermail/Classes/Domain/Service/FinisherService.php
7303
<?php namespace In2code\Powermail\Domain\Service; use In2code\Powermail\Domain\Model\Mail; use In2code\Powermail\Finisher\AbstractFinisher; use In2code\Powermail\Utility\StringUtility; use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer; /*************************************************************** * Copyright notice * * (c) 2015 Alex Kellner <[email protected]>, in2code.de * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project is * free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ /** * Load individual single finisher class * * @package powermail * @license http://www.gnu.org/licenses/lgpl.html * GNU Lesser General Public License, version 3 or later */ class FinisherService { /** * @var ContentObjectRenderer */ protected $contentObject; /** * Classname * * @var string */ protected $class = ''; /** * Path that should be required * * @var null|string */ protected $requirePath = null; /** * Finisher Configuration * * @var array */ protected $configuration = []; /** * @var Mail */ protected $mail; /** * @var array */ protected $settings; /** * Was form already submitted * * @var bool */ protected $formSubmitted = false; /** * Controller actionName - usually "createAction" or "confirmationAction" * * @var null */ protected $actionMethodName = null; /** * @var string */ protected $finisherInterface = 'In2code\Powermail\Finisher\FinisherInterface'; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface * @inject */ protected $objectManager = null; /** * @return string */ public function getClass() { return $this->class; } /** * @param string $class * @return FinisherService */ public function setClass($class) { $this->class = $class; return $this; } /** * @return null|string */ public function getRequirePath() { return $this->requirePath; } /** * Set require path and do a require_once * * @param null|string $requirePath * @return FinisherService */ public function setRequirePath($requirePath) { $this->requirePath = $requirePath; if ($this->getRequirePath() && file_exists($this->getRequirePath())) { require_once($this->getRequirePath()); } return $this; } /** * @return array */ public function getConfiguration() { return $this->configuration; } /** * @param array $configuration * @return FinisherService */ public function setConfiguration($configuration) { $this->configuration = $configuration; return $this; } /** * @return Mail */ public function getMail() { return $this->mail; } /** * @param Mail $mail * @return FinisherService */ public function setMail($mail) { $this->mail = $mail; return $this; } /** * @return array */ public function getSettings() { return $this->settings; } /** * @param array $settings * @return FinisherService */ public function setSettings($settings) { $this->settings = $settings; return $this; } /** * @return boolean */ public function isFormSubmitted() { return $this->formSubmitted; } /** * @param boolean $formSubmitted * @return FinisherService */ public function setFormSubmitted($formSubmitted) { $this->formSubmitted = $formSubmitted; return $this; } /** * @return null */ public function getActionMethodName() { return $this->actionMethodName; } /** * @param null $actionMethodName * @return FinisherService */ public function setActionMethodName($actionMethodName) { $this->actionMethodName = $actionMethodName; return $this; } /** * Start implementation * * @throws \Exception * @return void */ public function start() { if (!class_exists($this->getClass())) { throw new \Exception( 'Class ' . $this->getClass() . ' does not exists - check if file was loaded with autoloader' ); } if (is_subclass_of($this->getClass(), $this->finisherInterface)) { /** @var AbstractFinisher $finisher */ $finisher = $this->objectManager->get( $this->getClass(), $this->getMail(), $this->getConfiguration(), $this->getSettings(), $this->isFormSubmitted(), $this->getActionMethodName(), $this->contentObject ); $finisher->initializeFinisher(); $this->callFinisherMethods($finisher); } else { throw new \Exception('Finisher does not implement ' . $this->finisherInterface); } } /** * Call methods in finisher class * * @param AbstractFinisher $finisher * @return void */ protected function callFinisherMethods(AbstractFinisher $finisher) { foreach (get_class_methods($finisher) as $method) { if (!StringUtility::endsWith($method, 'Finisher') || strpos($method, 'initialize') === 0) { continue; } $this->callInitializeFinisherMethod($finisher, $method); $finisher->{$method}(); } } /** * Call initializeFinisherMethods like "initializeSaveFinisher()" * * @param AbstractFinisher $finisher * @param string $finisherMethod * @return void */ protected function callInitializeFinisherMethod(AbstractFinisher $finisher, $finisherMethod) { if (method_exists($finisher, 'initialize' . ucFirst($finisherMethod))) { $finisher->{'initialize' . ucFirst($finisherMethod)}(); } } /** * @param Mail $mail * @param array $settings * @param ContentObjectRenderer $contentObject */ public function __construct(Mail $mail, array $settings, ContentObjectRenderer $contentObject) { $this->setMail($mail); $this->setSettings($settings); $this->contentObject = $contentObject; } }
mit
vindvaki/zonotope.js
src/geom3.js
1686
// // 3 dimensional geometry // var Geom3 = { equals: function(p, q) { return p.x == q.x && p.y == q.y && p.z == q.z; }, norm: function(p) { return Math.sqrt(p.x*p.x + p.y*p.y + p.z*p.z); }, add: function(p, q) { return { x: p.x + q.x, y: p.y + q.y, z: p.z + q.z }; }, sub: function(p, q) { return { x: p.x - q.x, y: p.y - q.y, z: p.z - q.z }; }, scale: function(alpha, p) { return { x: alpha * p.x, y: alpha * p.y, z: alpha * p.z }; }, antipode: function(p) { return this.scale(-1, p); }, crossProduct: function(p, q) { return { x: p.y * q.z - p.z * q.y, y: p.z * q.x - p.x * q.z, z: p.x * q.y - p.y * q.x }; }, dot: function(p ,q) { return p.x*q.x + p.y*q.y + p.z*q.z; }, kernelBasis: function(u) { var b = []; b[0] = {x: 1, y: 0, z: 0}; b[1] = {x: 0, y: 1, z: 0}; b[2] = {x: 0, y: 0, z: 1}; // // pivot // var i; var j = -1; var x = []; for ( i = 0; i < 3; ++i ) { x[i] = Geom3.dot(b[i], u); if ( x[i] !== 0 ) { j = i; } } if ( j == -1 ) { // u is orthogonal to all unit vectors, so u == {x:0, y:0, z:0} return b; } var tmp; tmp = x[2]; x[2] = x[j]; x[j] = tmp; tmp = b[2]; b[2] = b[j]; b[j] = tmp; // x[2] != 0 // // update the basis // for ( i = 0; i < 2; ++i ) { b[i] = Geom3.sub(Geom3.scale(x[2], b[i]), Geom3.scale(x[i], b[2])); // dot( b[i], u ) == 0 } b.pop(); return b; }, str: function(p) { return [p.x, p.y, p.z].join(','); } };
mit
ordinary-developer/book_pragmatic_unit_testing_in_java_8_with_junit_j_langr
my_code/chapter_1_BUILDING_YOUR_FIRST_JUNIT_TEST/ScoreCollection.java
343
import java.util.*; public class ScoreCollection { private List<Scoreable> scores = new ArrayList<>(); public void add(Scoreable scoreable) { scores.add(scoreable); } public int arithmeticMean() { int total = scores.stream().mapToInt(Scoreable::getScore).sum(); return total / scores.size(); } }
mit
ata/kkn
protected/extensions/giix/generators/crud/templates/default/_view.php
804
<?php /** * The following variables are available in this template: * - $this: the CrudCode object */ ?> <div class="view"> <?php echo "\t<b><?php echo CHtml::encode(\$data->getAttributeLabel('{$this->tableSchema->primaryKey}')); ?>:</b>\n"; echo "\t<?php echo CHtml::link(CHtml::encode(\$data->{$this->tableSchema->primaryKey}), array('view', 'id'=>\$data->{$this->tableSchema->primaryKey})); ?>\n\t<br />\n\n"; $count=0; foreach($this->tableSchema->columns as $column) { if($column->isPrimaryKey) continue; if(++$count==7) echo "\t<?php /*\n"; echo "\t<b><?php echo CHtml::encode(\$data->getAttributeLabel('{$column->name}')); ?>:</b>\n"; echo "\t<?php echo CHtml::encode(\$data->{$column->name}); ?>\n\t<br />\n\n"; } if($count>=7) echo "\t*/ ?>\n"; ?> </div>
mit
jcupitt/ruby-vips
lib/vips/operationcomplexget.rb
222
module Vips # The type of complex projection operation to perform on an image. See # {Image#complexget}. # # * ':real' get real part # * ':imag' get imaginary part class OperationComplexget < Symbol end end
mit
IvanGrigorov/OOP
Extensions-Methods-Delegates-Lambda-LINQ/ExtractMarks/Properties/AssemblyInfo.cs
1400
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("ExtractMarks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ExtractMarks")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a570cda4-97ed-41ab-81ee-860e0994fda0")] // 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
nvillemin/MinesweeperWithTwitch
MinesweeperWithTwitch/Assets/Scripts/Global/GlobalManager.cs
1635
using System.Collections.Generic; using UnityEngine; namespace Global { // Static class used to store global variables public static class GlobalManager { // TwitchIRC, must be kept between scenes public static TwitchIRC twitch; // Text colors for the number of mines nearby public static readonly Color[] minesTextColor = { new Color(0, 0.35f, 1), // 1 new Color(0, 0.51f, 0.09f), // 2 new Color(0.78f, 0, 0), // 3 new Color(0, 0, 0.61f), // 4 new Color(0.47f, 0, 0), // 5 new Color(0.29f, 0.55f, 0.55f), // 6 new Color(0.23f, 0.23f, 0.23f), // 7 Color.black // 8 }; // Values for the end of the game public static string endTime; public static int endDeaths; public static List<KeyValuePair<string, int>> gameScores; public static UserScores globalScores; // ======================================================================== // Convert a float to a string with hours, minutes and seconds public static string TimeToString(float time) { int hours = (int)time / 3600; int minutes = (int)(time / 60) % 60; int seconds = (int)time % 60; string timeString = string.Empty; if (hours > 0) { timeString += hours.ToString() + "h "; } if (minutes > 0) { timeString += minutes.ToString() + "m "; } timeString += seconds.ToString() + "s"; return timeString; } } }
mit
gitlapse/gitlapse.rb
gitrepotest/lola/hack2.rb
20
# todo hackor lazez
mit
devicehive/devicehive-.net
src/Device/Examples/BinaryClient/Properties/AssemblyInfo.cs
1424
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("BinaryClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DataArt Apps")] [assembly: AssemblyProduct("DeviceHive")] [assembly: AssemblyCopyright("Copyright © DataArt Apps 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("66cdde43-ba7f-4bb8-9476-1ba342a3f294")] // 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("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
mit
xavmer9/FixMyCH
constants.js
196
angular.module('citizen-engagement') .constant('apiUrl', '@apiUrl@') .constant('mapboxSecret', '@mapboxSecret@') .constant('qimgUrl', '@qimgUrl@') .constant('qimgSecret', '@qimgSecret@') ;
mit
sithcoin-/sithcoin
src/main.cpp
131097
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2013 Sithcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "db.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> using namespace std; using namespace boost; // // Global state // CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; CTxMemPool mempool; unsigned int nTransactionsUpdated = 0; map<uint256, CBlockIndex*> mapBlockIndex; uint256 hashGenesisBlock = hashGenesisBlockOfficial; static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // Sithcoin: starting difficulty is 1 / 2^12 CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; CBigNum bnBestChainWork = 0; CBigNum bnBestInvalidWork = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64 nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; map<uint256, CDataStream*> mapOrphanTransactions; map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = "Sithcoin Signed Message:\n"; double dHashesPerSec; int64 nHPSTimerStart; // Settings int64 nTransactionFee = 0; int64 nMinimumInputValue = CENT; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void static ResendWalletTransactions() { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CDataStream& vMsg) { CTransaction tx; CDataStream(vMsg) >> tx; uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; CDataStream* pvMsg = new CDataStream(vMsg); // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: if (pvMsg->size() > 5000) { printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str()); delete pvMsg; return false; } mapOrphanTransactions[hash] = pvMsg; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg)); printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(), mapOrphanTransactions.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CDataStream* pvMsg = mapOrphanTransactions[hash]; CTransaction tx; CDataStream(*pvMsg) >> tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) { mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) mapOrphanTransactionsByPrev.erase(txin.prevout.hash); } delete pvMsg; mapOrphanTransactions.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } ////////////////////////////////////////////////////////////////////////////// // // CTransaction and CTxIndex // bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(prevout.hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::IsStandard() const { if (nVersion > CTransaction::CURRENT_VERSION) return false; BOOST_FOREACH(const CTxIn& txin, vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; } BOOST_FOREACH(const CTxOut& txout, vout) if (!::IsStandard(txout.scriptPubKey)) return false; return true; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int CTransaction::GetLegacySigOpCount() const { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { if (fClient) { if (hashBlock == 0) return 0; } else { CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); } // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { if (txout.nValue < 0) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative")); if (txout.nValue > MAX_MONEY) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high")); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs) { if (pfMissingInputs) *pfMissingInputs = false; if (!tx.CheckTransaction()) return error("CTxMemPool::accept() : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx")); // To help v0.1.5 clients who would see it as a negative number if ((int64)tx.nLockTime > std::numeric_limits<int>::max()) return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet"); // Rather not work on nonstandard transactions (unless -testnet) if (!fTestNet && !tx.IsStandard()) return error("CTxMemPool::accept() : nonstandard transaction type"); // Do we already have it? uint256 hash = tx.GetHash(); { LOCK(cs); if (mapTx.count(hash)) return false; } if (fCheckInputs) if (txdb.ContainsTx(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = mapNextTx[outpoint].ptx; if (ptxOld->IsFinal()) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } if (fCheckInputs) { MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return false; } // Check for non-standard pay-to-script-hash in inputs if (!tx.AreInputsStandard(mapInputs) && !fTestNet) return error("CTxMemPool::accept() : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block if (nFees < tx.GetMinFee(1000, true, GMF_RELAY)) return error("CTxMemPool::accept() : not enough fees"); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make other's transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEE) { static CCriticalSection cs; static double dFreeCount; static int64 nLastTime; int64 nNow = GetTime(); { LOCK(cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) return error("CTxMemPool::accept() : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory { LOCK(cs); if (ptxOld) { printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); remove(*ptxOld); } addUnchecked(hash, tx); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("CTxMemPool::accept() : accepted %s (poolsz %u)\n", hash.ToString().substr(0,10).c_str(), mapTx.size()); return true; } bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs) { return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs); } bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx) { // Add to memory pool without checking anything. Don't call this directly, // call CTxMemPool::accept to properly check the transaction first. { mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); nTransactionsUpdated++; } return true; } bool CTxMemPool::remove(CTransaction &tx) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); nTransactionsUpdated++; } } return true; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) return 0; return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs) { if (fClient) { if (!IsInMainChain() && !ClientConnectInputs()) return false; return CTransaction::AcceptToMemoryPool(txdb, false); } else { return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs); } } bool CMerkleTx::AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); } bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs) { { LOCK(mempool.cs); // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(txdb, fCheckInputs); } } return AcceptToMemoryPool(txdb, fCheckInputs); } return false; } bool CWalletTx::AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { LOCK(mempool.cs); if (mempool.exists(hash)) { tx = mempool.lookup(hash); return true; } } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } int static generateMTRandom(unsigned int s, int range) { random::mt19937 gen(s); random::uniform_int_distribution<> dist(1, range); return dist(gen); } int64 static GetBlockValue(int nHeight, int64 nFees, uint256 prevHash) { int64 nSubsidy = 500 * COIN; std::string cseed_str = prevHash.ToString().substr(7,7); const char* cseed = cseed_str.c_str(); long seed = hex2long(cseed); int rand = generateMTRandom(seed, 999999); int rand1 = 0; int rand2 = 0; int rand3 = 0; int rand4 = 0; int rand5 = 0; if(nHeight < 100000) { nSubsidy = (1 + rand) * COIN; } else if(nHeight < 200000) { cseed_str = prevHash.ToString().substr(7,7); cseed = cseed_str.c_str(); seed = hex2long(cseed); rand1 = generateMTRandom(seed, 499999); nSubsidy = (1 + rand1) * COIN; } else if(nHeight < 300000) { cseed_str = prevHash.ToString().substr(6,7); cseed = cseed_str.c_str(); seed = hex2long(cseed); rand2 = generateMTRandom(seed, 249999); nSubsidy = (1 + rand2) * COIN; } else if(nHeight < 400000) { cseed_str = prevHash.ToString().substr(7,7); cseed = cseed_str.c_str(); seed = hex2long(cseed); rand3 = generateMTRandom(seed, 124999); nSubsidy = (1 + rand3) * COIN; } else if(nHeight < 500000) { cseed_str = prevHash.ToString().substr(7,7); cseed = cseed_str.c_str(); seed = hex2long(cseed); rand4 = generateMTRandom(seed, 62499); nSubsidy = (1 + rand4) * COIN; } else if(nHeight < 600000) { cseed_str = prevHash.ToString().substr(6,7); cseed = cseed_str.c_str(); seed = hex2long(cseed); rand5 = generateMTRandom(seed, 31249); nSubsidy = (1 + rand5) * COIN; } return nSubsidy + nFees; } static const int64 nTargetTimespan = 1 * 24 * 60 * 60 * 7; // Sithcoin: every week static const int64 nTargetSpacing = 60 * 15; // Sithcoin: 1 minutes static const int64 nInterval = nTargetTimespan / nTargetSpacing; // // minimum amount of work that could possibly be required nTime after // minimum work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) { // Testnet has min-difficulty blocks // after nTargetSpacing*2 time between blocks: if (fTestNet && nTime > nTargetSpacing*2) return bnProofOfWorkLimit.GetCompact(); CBigNum bnResult; bnResult.SetCompact(nBase); while (nTime > 0 && bnResult < bnProofOfWorkLimit) { // Maximum 400% adjustment... bnResult *= 4; // ... in best-case exactly 4-times-normal target time nTime -= nTargetTimespan*4; } if (bnResult > bnProofOfWorkLimit) bnResult = bnProofOfWorkLimit; return bnResult.GetCompact(); } unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock) { unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % nInterval != 0) { // Special difficulty rule for testnet: if (fTestNet) { // If the new block's timestamp is more than 2*nTargetSpacing minutes // then allow mining of a min-difficulty block. if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Sithcoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = nInterval-1; if ((pindexLast->nHeight+1) != nInterval) blockstogoback = nInterval; // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); // Limit adjustment step int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan); if(pindexLast->nHeight+1 > 10000) { if (nActualTimespan < nTargetTimespan/4) nActualTimespan = nTargetTimespan/4; if (nActualTimespan > nTargetTimespan*4) nActualTimespan = nTargetTimespan*4; } else if(pindexLast->nHeight+1 > 5000) { if (nActualTimespan < nTargetTimespan/8) nActualTimespan = nTargetTimespan/8; if (nActualTimespan > nTargetTimespan*4) nActualTimespan = nTargetTimespan*4; } else { if (nActualTimespan < nTargetTimespan/16) nActualTimespan = nTargetTimespan/16; if (nActualTimespan > nTargetTimespan*4) nActualTimespan = nTargetTimespan*4; } // Retarget CBigNum bnNew; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= nTargetTimespan; if (bnNew > bnProofOfWorkLimit) bnNew = bnProofOfWorkLimit; /// debug print printf("GetNextWorkRequired RETARGET\n"); printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan); printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str()); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64 nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 10 && pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->bnChainWork > bnBestInvalidWork) { bnBestInvalidWork = pindexNew->bnChainWork; CTxDB().WriteBestInvalidWork(bnBestInvalidWork); uiInterface.NotifyBlocksChanged(); } printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str()); printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n"); } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); // Updating time can change work required on testnet: if (fTestNet) nBits = GetNextWorkRequired(pindexPrev, this); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory { LOCK(mempool.cs); if (!mempool.exists(prevout.hash)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); txPrev = mempool.lookup(prevout.hash); } if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n's are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64 nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal Sithcoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64 nValueIn = 0; int64 nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase, check that it's matured if (txPrev.IsCoinBase()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0)) { // only during transition phase for P2SH: do not invoke anti-DoS code for // potentially old clients relaying bad P2SH transactions if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0)) return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str()); return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64 nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); nFees += nTxFee; if (!MoneyRange(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } return true; } bool CTransaction::ClientConnectInputs() { if (IsCoinBase()) return false; // Take over previous transactions' spent pointers { LOCK(mempool.cs); int64 nValueIn = 0; for (unsigned int i = 0; i < vin.size(); i++) { // Get prev tx from single transactions in memory COutPoint prevout = vin[i].prevout; if (!mempool.exists(prevout.hash)) return false; CTransaction& txPrev = mempool.lookup(prevout.hash); if (prevout.n >= txPrev.vout.size()) return false; // Verify signature if (!VerifySignature(txPrev, *this, i, true, 0)) return error("ConnectInputs() : VerifySignature failed"); ///// this is redundant with the mempool.mapNextTx stuff, ///// not sure which I want to get rid of ///// this has to go away now that posNext is gone // // Check for conflicts // if (!txPrev.vout[prevout.n].posNext.IsNull()) // return error("ConnectInputs() : prev tx already used"); // // // Flag outpoints as used // txPrev.vout[prevout.n].posNext = posThisTx; nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return error("ClientConnectInputs() : txin values out of range"); } if (GetValueOut() > nValueIn) return false; } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i--) if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Check it again in case a previous version let a bad block in if (!CheckBlock()) return false; // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction id's entirely. // This rule applies to all blocks whose timestamp is after October 1, 2012, 0:00 UTC. int64 nBIP30SwitchTime = 1349049600; bool fEnforceBIP30 = (pindex->nTime > nBIP30SwitchTime); // BIP16 didn't become active until October 1 2012 int64 nBIP16SwitchTime = 1349049600; bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime); //// issue here: it doesn't know the version unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64 nFees = 0; unsigned int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { uint256 hashTx = tx.GetHash(); if (fEnforceBIP30) { CTxIndex txindexOld; if (txdb.ReadTxIndex(hashTx, txindexOld)) { BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } } nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); MapPrevTx mapInputs; if (!tx.IsCoinBase()) { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; if (fStrictPayToScriptHash) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); } nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash)) return false; } mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size()); } // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } uint256 prevHash = 0; if(pindex->pprev) { prevHash = pindex->pprev->GetBlockHash(); } if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees, prevHash)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); // Disconnect shorter branch vector<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); // Queue memory transactions to resurrect BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!tx.IsCoinBase()) vResurrect.push_back(tx); } // Connect longer branch vector<CTransaction> vDelete; for (unsigned int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) tx.AcceptToMemoryPool(txdb, false); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) mempool.remove(tx); printf("REORGANIZE: done\n"); return true; } // Called from inside SetBestChain: attaches a block to the new best chain being built bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew) { uint256 hash = GetHash(); // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return false; } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) mempool.remove(tx); return true; } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); if (!txdb.TxnBegin()) return error("SetBestChain() : TxnBegin failed"); if (pindexGenesisBlock == NULL && hash == hashGenesisBlock) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { if (!SetBestChainInner(txdb, pindexNew)) return error("SetBestChain() : SetBestChainInner failed"); } else { // the first block in the new chain that will cause it to become the new best chain CBlockIndex *pindexIntermediate = pindexNew; // list of blocks that need to be connected afterwards std::vector<CBlockIndex*> vpindexSecondary; // Reorganize is costly in terms of db load, as it works in a single db transaction. // Try to limit how much needs to be done inside while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork) { vpindexSecondary.push_back(pindexIntermediate); pindexIntermediate = pindexIntermediate->pprev; } if (!vpindexSecondary.empty()) printf("Postponing %i reconnects\n", vpindexSecondary.size()); // Switch to new best branch if (!Reorganize(txdb, pindexIntermediate)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } // Connect futher blocks BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary) { CBlock block; if (!block.ReadFromDisk(pindex)) { printf("SetBestChain() : ReadFromDisk failed\n"); break; } if (!txdb.TxnBegin()) { printf("SetBestChain() : TxnBegin 2 failed\n"); break; } // errors now are not fatal, we still did a reorganisation to a new chain in a valid way if (!block.SetBestChainInner(txdb, pindex)) break; } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; nBestHeight = pindexBest->nHeight; bnBestChainWork = pindexNew->bnChainWork; nTimeBestReceived = GetTime(); nTransactionsUpdated++; printf("SetBestChain: new best=%s height=%d work=%s date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); // Check the version of the last 100 blocks to see if we need to upgrade: if (!fIsInitialDownload) { int nUpgraded = 0; const CBlockIndex* pindex = pindexBest; for (int i = 0; i < 100 && pindex != NULL; i++) { if (pindex->nVersion > CBlock::CURRENT_VERSION) ++nUpgraded; pindex = pindex->pprev; } if (nUpgraded > 0) printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION); // if (nUpgraded > 100/2) // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: // strMiscWarning = _("Warning: this version is obsolete, upgrade required"); } std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork(); CTxDB txdb; if (!txdb.TxnBegin()) return false; txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; // New best if (pindexNew->bnChainWork > bnBestChainWork) if (!SetBestChain(txdb, pindexNew)) return false; txdb.Close(); if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = vtx[0].GetHash(); } uiInterface.NotifyBlocksChanged(); return true; } bool CBlock::CheckBlock() const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (!CheckProofOfWork(GetPoWHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; BOOST_FOREACH(const CTransaction& tx, vtx) { uniqueTx.insert(tx.GetHash()); } if (uniqueTx.size() != vtx.size()) return DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkleroot if (hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); return true; } bool CBlock::AcceptBlock() { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; // Check proof of work if (nBits != GetNextWorkRequired(pindexPrev, this)) return DoS(100, error("AcceptBlock() : incorrect proof of work")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetMedianTimePast()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.IsFinal(nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckBlock(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight)); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } return true; } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; if (deltaTime < 0) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with timestamp before last checkpoint"); } CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little proof-of-work"); } } // If don't already have its previous block, shunt it off to holding area until we get it if (!mapBlockIndex.count(pblock->hashPrevBlock)) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); CBlock* pblock2 = new CBlock(*pblock); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); return true; } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { CBlock* pblockOrphan = (*mi).second; if (pblockOrphan->AcceptBlock()) vWorkQueue.push_back(pblockOrphan->GetHash()); mapOrphanBlocks.erase(pblockOrphan->GetHash()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); return true; } bool CheckDiskSpace(uint64 nAdditionalBytes) { uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low"); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage, "Sithcoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); StartShutdown(); return false; } return true; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if ((nFile < 1) || (nFile == (unsigned int) -1)) return NULL; FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; loop { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < 0x7F000000 - MAX_SIZE) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { if (fTestNet) { pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0xc1; pchMessageStart[2] = 0xb7; pchMessageStart[3] = 0xdc; hashGenesisBlock = uint256("0x4d0e7e26d9466caa4013a7c3440c7dc992a92298f63c518dd9e3ce50ff30235a"); } // // Load block index // CTxDB txdb("cr"); if (!txdb.LoadBlockIndex()) return false; txdb.Close(); // // Init with genesis block // if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis Block: // hashGenesisBlock = 9b7bce58999062b63bfb18586813c42491fa32f4591d8d3043cb4fa9e551541b // block.hashMerkleRoot = 6f80efd038566e1e3eab3e1d38131604d06481e77f2462235c6a9a94b1f8abf9 // CBlock(hash=9b7bce58999062b63bfb, PoW=caeb449903dc4f0e0ee2, ver=1, hashPrevBlock=00000000000000000000, // hashMerkleRoot=6f80efd038, nTime=1369199888, nBits=1e0ffff0, nNonce=11288888, vtx=1) // CTransaction(hash=6f80efd038, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, -1), coinbase 04ffff001d01044cd14d61792032322c20323031332c2031323a313620612e6d2e204544543a204a6170616e9273204e696b6b65692053746f636b2041766572616765204a503a4e494b202b312e3737252c20776869636820656e6465642061742074686569722068696768657374206c6576656c20696e206d6f7265207468616e206669766520796561727320696e2065616368206f6620746865206c6173742074687265652074726164696e672073657373696f6e732c20636c696d6265642061206675727468657220312e3225205765646e6573646179) // CTxOut(nValue=88.00000000, scriptPubKey=040184710fa689ad5023690c80f3a4) // vMerkleTree: 6f80efd038 // Genesis block const char* pszTimestamp = "The empire invades the planet of Hoth, to squash the rebel scum."; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 88 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG; CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = 1; block.nTime = 1388680710; block.nBits = 0x1e0ffff0; block.nNonce = 727563; if (fTestNet) { block.nTime = 1388680710; block.nNonce = 0; } //// debug print printf("block.GetHash() = %s\n", block.GetHash().ToString().c_str()); printf("hashGenesisBlock = %s\n", hashGenesisBlock.ToString().c_str()); printf("block.hashMerkleRoot = %s\n", block.hashMerkleRoot.ToString().c_str()); assert(block.hashMerkleRoot == uint256("0xb9c3f5f8ab1a2c8ef49f13f658f848c9c85a1f3a689999fc17e7da0a2a930293")); if (true && block.GetHash() != hashGenesisBlock) { printf("Searching for genesis block...\n"); // This will figure out a valid hash and Nonce if you're // creating a different genesis block: uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); uint256 thash; char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; loop { scrypt_1024_1_1_256_sp(BEGIN(block.nVersion), BEGIN(thash), scratchpad); if (thash <= hashTarget) break; if ((block.nNonce & 0xFFF) == 0) { printf("nonce %08X: hash = %s (target = %s)\n", block.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++block.nNonce; if (block.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++block.nTime; } } printf("block.nTime = %u \n", block.nTime); printf("block.nNonce = %u \n", block.nNonce); printf("block.GetHash = %s\n", block.GetHash().ToString().c_str()); } // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos)) return error("LoadBlockIndex() : genesis block not accepted"); } return true; } void PrintBlockTree() { // precompute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %s tx %d", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().substr(0,20).c_str(), DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(), block.vtx.size()); PrintWallets(block); // put the main timechain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } bool LoadExternalBlockFile(FILE* fileIn) { int nLoaded = 0; { LOCK(cs_main); try { CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION); unsigned int nPos = 0; while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown) { unsigned char pchData[65536]; do { fseek(blkdat, nPos, SEEK_SET); int nRead = fread(pchData, 1, sizeof(pchData), blkdat); if (nRead <= 8) { nPos = (unsigned int)-1; break; } void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart)); if (nFind) { if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0) { nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart); break; } nPos += ((unsigned char*)nFind - pchData) + 1; } else nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1; } while(!fRequestShutdown); if (nPos == (unsigned int)-1) break; fseek(blkdat, nPos, SEEK_SET); unsigned int nSize; blkdat >> nSize; if (nSize > 0 && nSize <= MAX_BLOCK_SIZE) { CBlock block; blkdat >> block; if (ProcessBlock(NULL,&block)) { nLoaded++; nPos += 4 + nSize; } } } } catch (std::exception &e) { printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__); } } printf("Loaded %i blocks from external file\n", nLoaded); return nLoaded > 0; } ////////////////////////////////////////////////////////////////////////////// // // CAlert // map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // Longer invalid proof-of-work chain if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) { nPriority = 2000; strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade."; } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI if it applies to me if(AppliesToMe()) uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; { LOCK(mempool.cs); txInMap = (mempool.exists(inv.hash)); } return txInMap || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ascii, not valid as UTF-8, and produce // a large 4-byte int at any alignment. unsigned char pchMessageStart[4] = { 0xc0, 0xc0, 0xc0, 0xc0 }; bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, CPubKey> mapReuseKey; RandAddSeedPerfmon(); if (fDebug) printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size()); if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64 nTime; CAddress addrMe; CAddress addrFrom; uint64 nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PROTO_VERSION) { // Since February 20, 2012, the protocol is initiated at version 209, // and earlier versions are no longer supported printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; if (pfrom->fInbound && addrMe.IsRoutable()) { pfrom->addrLocal = addrMe; SeenLocal(addrMe); } // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr); if (addr.IsRoutable()) pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && !pfrom->fOneShot && (pfrom->nVersion < NOBLKS_VERSION_START || pfrom->nVersion >= NOBLKS_VERSION_END) && (nAskedForBlocks < 1 || vNodes.size() <= 1)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str()); cPeerBlockCounts.input(pfrom->nStartingHeight); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %d", vAddr.size()); } // Store the new addresses vector<CAddress> vAddrOk; int64 nNow = GetAdjustedTime(); int64 nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint64 hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message inv size() = %d", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } CTxDB txdb("r"); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) pfrom->AskFor(inv); else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. std::vector<CInv> vGetData(1,inv); pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0)); if (fDebug) printf("force request: %s\n", inv.ToString().c_str()); } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message getdata size() = %d", vInv.size()); } if (fDebugNet || (vInv.size() != 1)) printf("received getdata (%d invsz)\n", vInv.size()); BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; if (fDebugNet || (vInv.size() == 1)) printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, hashBestChain)); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) pfrom->PushMessage(inv.GetCommand(), (*mi).second); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str()); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CDataStream vMsg(vRecv); CTxDB txdb("r"); CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); bool fMissingInputs = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); mi != mapOrphanTransactionsByPrev[hashPrev].end(); ++mi) { const CDataStream& vMsg = *((*mi).second); CTransaction tx; CDataStream(vMsg) >> tx; CInv inv(MSG_TX, tx.GetHash()); bool fMissingInputs2 = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); } else if (!fMissingInputs2) { // invalid orphan vEraseQueue.push_back(inv.hash); printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(vMsg); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str()); // block.print(); CInv inv(MSG_BLOCK, block.GetHash()); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) pfrom->PushAddress(addr); } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; /// we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; { LOCK(pfrom->cs_mapRequests); map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64 nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alert.GetHash()); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } bool ProcessMessages(CNode* pfrom) { CDataStream& vRecv = pfrom->vRecv; if (vRecv.empty()) return true; //if (fDebug) // printf("ProcessMessages(%u bytes)\n", vRecv.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // loop { // Don't bother if send buffer is too full to respond anyway if (pfrom->vSend.size() >= SendBufferSize()) break; // Scan for message start CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader()); if (vRecv.end() - pstart < nHeaderSize) { if ((int)vRecv.size() > nHeaderSize) { printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n"); vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); } break; } if (pstart - vRecv.begin() > 0) printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin()); vRecv.erase(vRecv.begin(), pstart); // Read header vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); CMessageHeader hdr; vRecv >> hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; if (nMessageSize > MAX_SIZE) { printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize); continue; } if (nMessageSize > vRecv.size()) { // Rewind and wait for rest of message vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); break; } // Checksum uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Copy message to its own buffer CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion); vRecv.ignore(nMessageSize); // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vMsg); } if (fShutdown) return true; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from underlength message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from overlong size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } vRecv.Compact(); return true; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) { uint64 nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Resend wallet transactions that haven't gotten in a block yet ResendWalletTransactions(); // Address refresh broadcast static int64 nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen) { CAddress addr = GetLocalAddress(&pnode->addr); if (addr.IsRoutable()) pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64 nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { if (fDebugNet) printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } mapAlreadyAskedFor[inv] = nNow; } pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // // ScanHash scans nonces looking for a hash with at least some zero bits. // It operates on big endian data. Caller does the byte reversing. // All input buffers are 16-byte aligned. nNonce is usually preserved // between calls, but periodically or if nNonce is 0xffff0000 or above, // the block is rebuilt and nNonce starts over at zero. // unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone) { unsigned int& nNonce = *(unsigned int*)(pdata + 12); for (;;) { // Crypto++ SHA-256 // Hash pdata using pmidstate as the starting state into // preformatted buffer phash1, then hash phash1 into phash nNonce++; SHA256Transform(phash1, pdata, pmidstate); SHA256Transform(phash, phash1, pSHA256InitState); // Return the nonce if the hash has at least some zero bits, // caller will check if it has enough to reach the target if (((unsigned short*)phash)[14] == 0) return nNonce; // If nothing found after trying for a while, return -1 if ((nNonce & 0xffff) == 0) { nHashesDone = 0xffff+1; return (unsigned int) -1; } } } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; CBlock* CreateNewBlock(CReserveKey& reservekey) { CBlockIndex* pindexPrev = pindexBest; // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); // Collect memory pool transactions into the block int64 nFees = 0; { LOCK2(cs_main, mempool.cs); CTxDB txdb("r"); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; multimap<double, CTransaction*> mapPriority; for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) { // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); continue; } int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; // Read block header int nConf = txindex.GetDepthInMainChain(); dPriority += (double)nValueIn * nConf; if (fDebug && GetBoolArg("-printpriority")) printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority); } // Priority is sum(valuein * age) / txsize dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (porphan) porphan->dPriority = dPriority; else mapPriority.insert(make_pair(-dPriority, &(*mi).second)); if (fDebug && GetBoolArg("-printpriority")) { printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str()); if (porphan) porphan->print(); printf("\n"); } } // Collect transactions into block map<uint256, CTxIndex> mapTestPool; uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; while (!mapPriority.empty()) { // Take highest priority transaction off priority queue double dPriority = -(*mapPriority.begin()).first; CTransaction& tx = *(*mapPriority.begin()).second; mapPriority.erase(mapPriority.begin()); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Transaction fee required depends on block size // Sithcoind: Reduce the exempted free transactions to 500 bytes (from Bitcoin's 3000 bytes) bool fAllowFree = (nBlockSize + nTxSize < 1500 || CTransaction::AllowFree(dPriority)); int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK); // Connecting shouldn't fail due to dependency on other memory pool transactions // because we're already processing them in order of dependency map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); MapPrevTx mapInputs; bool fInvalid; if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid)) continue; int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (nTxFees < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true)) continue; mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size()); swap(mapTestPool, mapTestPoolTmp); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; // Add transactions that depend on this one to the priority queue uint256 hash = tx.GetHash(); if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx)); } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; printf("CreateNewBlock(): total size %lu\n", nBlockSize); } pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees, pindexPrev->GetBlockHash()); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); pblock->UpdateTime(pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get()); pblock->nNonce = 0; return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Prebuild hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hash = pblock->GetPoWHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); if (hash > hashTarget) return false; //// debug print printf("BitcoinMiner:\n"); printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("BitcoinMiner : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[pblock->GetHash()] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("BitcoinMiner : ProcessBlock, block not accepted"); } return true; } void static ThreadBitcoinMiner(void* parg); static bool fGenerateBitcoins = false; static bool fLimitProcessors = false; static int nLimitProcessors = -1; void static BitcoinMiner(CWallet *pwallet) { printf("BitcoinMiner started\n"); SetThreadPriority(THREAD_PRIORITY_LOWEST); // Make this thread recognisable as the mining thread RenameThread("bitcoin-miner"); // Each thread has its own key and counter CReserveKey reservekey(pwallet); unsigned int nExtraNonce = 0; while (fGenerateBitcoins) { if (fShutdown) return; while (vNodes.empty() || IsInitialBlockDownload()) { Sleep(1000); if (fShutdown) return; if (!fGenerateBitcoins) return; } // // Create new block // unsigned int nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlock> pblock(CreateNewBlock(reservekey)); if (!pblock.get()) return; IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size()); // // Prebuild hash buffers // char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf); char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf); char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf); FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1); unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4); unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8); //unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12); // // Search // int64 nStart = GetTime(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); loop { unsigned int nHashesDone = 0; //unsigned int nNonceFound; uint256 thash; char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; loop { scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad); if (thash <= hashTarget) { // Found a solution SetThreadPriority(THREAD_PRIORITY_NORMAL); CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); break; } pblock->nNonce += 1; nHashesDone += 1; if ((pblock->nNonce & 0xFF) == 0) break; } // Meter hashes/sec static int64 nHashCounter; if (nHPSTimerStart == 0) { nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; } else nHashCounter += nHashesDone; if (GetTimeMillis() - nHPSTimerStart > 4000) { static CCriticalSection cs; { LOCK(cs); if (GetTimeMillis() - nHPSTimerStart > 4000) { dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0); static int64 nLogTime; if (GetTime() - nLogTime > 30 * 60) { nLogTime = GetTime(); printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str()); printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0); } } } } // Check for stop or if block needs to be rebuilt if (fShutdown) return; if (!fGenerateBitcoins) return; if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors) return; if (vNodes.empty()) break; if (pblock->nNonce >= 0xffff0000) break; if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != pindexBest) break; // Update nTime every few seconds pblock->UpdateTime(pindexPrev); nBlockTime = ByteReverse(pblock->nTime); if (fTestNet) { // Changing pblock->nTime can change work required on testnet: nBlockBits = ByteReverse(pblock->nBits); hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); } } } } void static ThreadBitcoinMiner(void* parg) { CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_MINER]++; BitcoinMiner(pwallet); vnThreadsRunning[THREAD_MINER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MINER]--; PrintException(&e, "ThreadBitcoinMiner()"); } catch (...) { vnThreadsRunning[THREAD_MINER]--; PrintException(NULL, "ThreadBitcoinMiner()"); } nHPSTimerStart = 0; if (vnThreadsRunning[THREAD_MINER] == 0) dHashesPerSec = 0; printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]); } void GenerateBitcoins(bool fGenerate, CWallet* pwallet) { fGenerateBitcoins = fGenerate; nLimitProcessors = GetArg("-genproclimit", -1); if (nLimitProcessors == 0) fGenerateBitcoins = false; fLimitProcessors = (nLimitProcessors != -1); if (fGenerate) { int nProcessors = boost::thread::hardware_concurrency(); printf("%d processors\n", nProcessors); if (nProcessors < 1) nProcessors = 1; if (fLimitProcessors && nProcessors > nLimitProcessors) nProcessors = nLimitProcessors; int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER]; printf("Starting %d BitcoinMiner threads\n", nAddThreads); for (int i = 0; i < nAddThreads; i++) { if (!CreateThread(ThreadBitcoinMiner, pwallet)) printf("Error: CreateThread(ThreadBitcoinMiner) failed\n"); Sleep(10); } } }
mit
manito17711/system_stat
system_stat/network.cpp
830
#include "network.hpp" #define LOAD_TEST_SERVERS Network::Network() { #ifdef LOAD_TEST_SERVERS // 6 testing servers.. for (int i = 140; i < 146; ++i) { std::string s = "192.168.194." + std::to_string(i); addServer(s, 13651); } std::cout << "6 testing servers imported.\n"; #endif } void Network::addServer(std::__cxx11::string ipAddr, std::size_t port) { // TODO: validate address and port addServer(Node(ipAddr, port)); } void Network::addServer(const Node& n) { for (std::size_t i = 0; i < servers.size(); ++i) { if (n.ipAddr == servers[i].ipAddr) return; } servers.push_back(n); } const Node& Network::getServer(std::size_t idx) const { return servers[idx]; } std::size_t Network::serversCount() const { return servers.size(); }
mit
awakenweb/Iridium-components-eventdispatcher
tests/units/Event/Event.php
2088
<?php namespace Iridium\Components\EventDispatcher\tests\units\Event; require_once __DIR__ . '/../../../vendor/autoload.php'; use atoum , \Iridium\Components\EventDispatcher\Event\Event as IrEvent; /** * Description of Event * * @author Mathieu */ class Event extends atoum { public function testCreate() { $test = new IrEvent( 'test' ); $dispatcher = new \mock\Iridium\Components\EventDispatcher\Dispatcher\Dispatcher(); $this->object( $test ) ->isInstanceOf( '\Iridium\Components\EventDispatcher\Event\Event' ) ->string( $test->getName() ) ->isEqualTo( 'test' ) ->when( $test->setDispatcher( $dispatcher ) ) ->object( $test->getDispatcher() ) ->isInstanceOf( '\mock\Iridium\Components\EventDispatcher\Dispatcher\Dispatcher' ); } public function testSetNameThrowsException() { // name is not a string $this->exception( function () { $test = new IrEvent( 'test' ); $test->setName( null ); } ) ->isInstanceOf( '\InvalidArgumentException' ) ->hasMessage( 'Event name must be a non empty string and must only contain letters, digits, hyphens and dots' ) ->exception( function () { $test = new IrEvent( 'test' ); $test->setName( 'test£' ); } ) ->isInstanceOf( '\InvalidArgumentException' ) ->hasMessage( 'Event name must be a non empty string and must only contain letters, digits, hyphens and dots' ); } public function testAttach() { $test = new IrEvent( 'test' ); $this->array( $test->getAttachments() ) ->isEmpty(); $test = new IrEvent( 'test' , array( new \stdClass() ) ); $this->array( $test->getAttachments() ) ->isNotEmpty() ->object( $test->getIterator() ) ->isInstanceOf( '\ArrayIterator' ); } }
mit
dayler/SimpleJsfSample
src/com/dayler/jsf/sample/started/domain/Card.java
884
/** * */ package com.dayler.jsf.sample.started.domain; import java.util.Random; /** * @author ariel * */ public class Card { private int left; private int right; private int result = 0; public Card() { Random random = new Random(); int i = 0; int j = 0; do { i = random.nextInt(10); } while (i <= 4); do { j = random.nextInt(100); } while (j <= 20); left = i; right = j; } public int getLeft() { return left; } public void setLeft(int left) { this.left = left; } public int getRight() { return right; } public void setRight(int right) { this.right = right; } // Controller public String show() { result = left * right; return "success"; } public String clear() { result = 0; return "clear"; } public int getResult() { return result; } public void setResult(int result) { this.result = result; } }
mit
rvsiqueira/client
app/containers/AcquisitionPage/jsonBuilder.js
1932
export function user(data, name) { const telephone = data.get('telephone').split(')'); const userDetails = JSON.parse(sessionStorage.getItem('userDetails')); return { completeName: name, password: data.get('password'), cpf: (data.get('cpf')).replace(/\D*/g, ''), emailAddress: userDetails.data.userDetails.emailAddress, gender: data.get('gender'), userAddresses: [ { id: userDetails.data.userDetails.userAddresses[0] ? userDetails.data.userDetails.userAddresses[0].id : '', city: data.get('localidade'), complement: data.get('complemento'), country: 'Brazil', district: 'NA', state: data.get('uf'), streetName: data.get('logradouro'), streetNumber: (data.get('Number')).toString(), type: 'permanent', zipcode: data.get('zipNo'), }, ], userPhones: [ { id: userDetails.data.userDetails.userPhones[0] ? userDetails.data.userDetails.userPhones[0].id : '', areaCode: telephone[0].replace(/\D*/g, ''), countryCode: '+55', phoneNumber: telephone[1].replace(/\D*/g, ''), type: 'NA', }, ], }; } export function billing(data, simulation, dream, currentAge) { return { userId: sessionStorage.getItem('userId'), agreement: { fee: parseInt((simulation.get('perMonth')), 10), initialContribution: parseInt(simulation.get('initialDeposit'), 10), monthlyYearly: 'MONTHLY', name: dream.dreamName, tenure: parseInt(simulation.get('age'), 10) - currentAge, dreamId: dream.id, maturityAge: parseInt(simulation.get('age'), 10), maturityValue: parseInt(simulation.get('accumulated'), 10), }, cardDetails: { paymentType: data.get('payment'), cardNumber: data.get('cardNumber'), expiryDate: data.get('cardValidity'), cvv: data.get('cvv'), status: 'active', }, }; }
mit
floooh/oryol-tools
src/oryol-conv3d/AssimpLoader.cc
3386
//------------------------------------------------------------------------------ // AssimpLoader.cc //------------------------------------------------------------------------------ #include "AssimpLoader.h" #include "ExportUtil/Log.h" #include "assimp/scene.h" #include "assimp/postprocess.h" using namespace OryolTools; //------------------------------------------------------------------------------ void AssimpLoader::Load(const std::string& path, IRep& irep) { Log::FailIf(path.empty(), "path to 3D file required!"); this->importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, aiComponent_LIGHTS|aiComponent_CAMERAS); this->importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT|aiPrimitiveType_LINE); this->importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, (1<<16)); const uint32_t procFlags = aiProcess_CalcTangentSpace| aiProcess_JoinIdenticalVertices| aiProcess_Triangulate| aiProcess_GenNormals| // only if mesh doesn't already have normals aiProcess_ImproveCacheLocality| aiProcess_SplitLargeMeshes| aiProcess_RemoveRedundantMaterials| aiProcess_SortByPType| aiProcess_FindDegenerates| aiProcess_FindInvalidData| aiProcess_GenUVCoords| aiProcess_TransformUVCoords| aiProcess_OptimizeMeshes| aiProcess_OptimizeGraph| aiProcess_FlipWindingOrder; this->scene = importer.ReadFile(path, procFlags); Log::FailIf(!this->scene, "Failed to import file '%s' via assimp: %s\n", path.c_str(), importer.GetErrorString()); this->toIRep(irep); } //------------------------------------------------------------------------------ void AssimpLoader::toIRep(IRep& irep) { this->writeVertexComponents(irep); // FIXME } //------------------------------------------------------------------------------ void AssimpLoader::writeVertexComponents(IRep& irep) { std::array<VertexFormat::Code, VertexAttr::Num> comps; comps.fill(VertexFormat::Invalid); for (uint32_t meshIndex = 0; meshIndex < this->scene->mNumMeshes; meshIndex++) { const aiMesh* msh = scene->mMeshes[meshIndex]; if (msh->HasPositions()) { comps[VertexAttr::Position] = VertexFormat::Float3; } if (msh->HasNormals()) { comps[VertexAttr::Normal] = VertexFormat::Float3; } if (msh->HasTangentsAndBitangents()) { comps[VertexAttr::Tangent] = VertexFormat::Float3; comps[VertexAttr::Binormal] = VertexFormat::Float3; } for (uint32_t i = 0; i < 4; i++) { if (msh->HasTextureCoords(i)) { comps[VertexAttr::TexCoord0+i] = VertexFormat::Float2; } } for (uint32_t i = 0; i < 2; i++) { if (msh->HasVertexColors(i)) { comps[VertexAttr::Color0+i] = VertexFormat::Float4; } } if (msh->HasBones()) { comps[VertexAttr::Weights] = VertexFormat::Float4; comps[VertexAttr::Indices] = VertexFormat::Float4; } } for (int i = 0; i < VertexAttr::Num; i++) { if (comps[i] != VertexFormat::Invalid) { IRep::VertexComponent c; c.Attr = (VertexAttr::Code) i; c.Format = comps[i]; irep.VertexComponents.push_back(c); } } }
mit
shafiqabs/bdeducations
src/Setting/Bundle/ContentBundle/Entity/Page.php
8110
<?php namespace Setting\Bundle\ContentBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Validator\Constraints as Assert; /** * Page * * @ORM\Table(name="page") * @ORM\Entity(repositoryClass="Setting\Bundle\ContentBundle\Entity\PageRepository") */ class Page { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\ManyToOne(targetEntity="Page", inversedBy="children", cascade={"detach","merge"}) * @ORM\JoinColumn(name="parent", referencedColumnName="id", onDelete="SET NULL") */ protected $parent; /** * @ORM\OneToMany(targetEntity="Page" , mappedBy="parent") * @ORM\OrderBy({"name" = "ASC"}) **/ private $children; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * @var string * * @ORM\Column(name="menu", type="string", length=255) */ private $menu; /** * @var string * * @ORM\Column(name="menuSlug", type="string", length=255) */ private $menuSlug; /** * @var string * * @ORM\Column(name="content", type="text" , nullable = true) */ private $content; /** * @var boolean * * @ORM\Column(name="status", type="boolean") */ private $status; /** * @var \DateTime * * @ORM\Column(name="created", type="datetime") */ private $created; /** * @ORM\ManyToOne(targetEntity="Setting\Bundle\MediaBundle\Entity\PhotoGallery", inversedBy="pageGalleries") */ protected $photoGallery; /** * @ORM\ManyToOne(targetEntity="Core\UserBundle\Entity\User", inversedBy="pages" ) **/ protected $user; /** * @ORM\OneToOne(targetEntity="Setting\Bundle\AppearanceBundle\Entity\Menu", mappedBy="page" , cascade={"persist", "remove"} ) **/ protected $nav; /** * @var string * * @ORM\Column(name="uniqueCode", type="string", length=255) */ private $uniqueCode; /** * @ORM\Column(type="string", length=255, nullable=true) */ protected $path; /** * @Assert\File(maxSize="") */ protected $file; public function __construct() { if(!$this->getId()){ $this->setCreated(new \DateTime()); $this->setStatus(true); $passcode =substr(str_shuffle(str_repeat('0123456789',5)),0,4); $t = microtime(true); $micro = ($passcode + floor($t)); $this->uniqueCode = $micro; } } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Page */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set menu * * @param string $menu * @return Page */ public function setMenu($menu) { $this->menu = $menu; return $this; } /** * Get menu * * @return string */ public function getMenu() { return $this->menu; } /** * Set menuSlug * * @param string $menuSlug * @return Page */ public function setMenuSlug($menuSlug) { $this->menuSlug = $menuSlug; return $this; } /** * Get menuSlug * * @return string */ public function getMenuSlug() { return $this->menuSlug; } /** * Set content * * @param string $content * @return Page */ public function setContent($content) { $this->content = $content; return $this; } /** * Get content * * @return string */ public function getContent() { return $this->content; } /** * Set status * * @param boolean $status * @return Page */ public function setStatus($status) { $this->status = $status; return $this; } /** * Get status * * @return boolean */ public function getStatus() { return $this->status; } /** * Set created * * @param \DateTime $created * @return Page */ public function setCreated($created) { $this->created = $created; return $this; } /** * Get created * * @return \DateTime */ public function getCreated() { return $this->created; } /** * @param mixed $user */ public function setUser($user) { $this->user = $user; } /** * @return mixed */ public function getUser() { return $this->user; } /** * @param mixed $photoGallery */ public function setPhotoGallery($photoGallery) { $this->photoGallery = $photoGallery; } /** * @return mixed */ public function getPhotoGallery() { return $this->photoGallery; } /** * @param string $uniqueCode */ public function setUniqueCode($uniqueCode) { $this->uniqueCode = $uniqueCode; } /** * @return string */ public function getUniqueCode() { return $this->uniqueCode; } /** * Sets file. * * @param Page $file */ public function setFile(UploadedFile $file = null) { $this->file = $file; } /** * Get file. * * @return Page */ public function getFile() { return $this->file; } public function getAbsolutePath() { return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path; } public function getWebPath() { return null === $this->path ? null : $this->getUploadDir().'/'.$this->path; } protected function getUploadRootDir() { return __DIR__.'/../../../../../web/'.$this->getUploadDir(); } protected function getUploadDir() { return 'uploads/files'; } public function upload() { // the file property can be empty if the field is not required if (null === $this->getFile()) { return; } // use the original file name here but you should // sanitize it at least to avoid any security issues // move takes the target directory and then the // target filename to move to $this->getFile()->move( $this->getUploadRootDir(), $this->getFile()->getClientOriginalName() ); // set the path property to the filename where you've saved the file $this->path = $this->getFile()->getClientOriginalName(); // clean up the file property as you won't need it anymore $this->file = null; } /** * @return mixed */ public function getNav() { return $this->nav; } /** * @param mixed $nav */ public function setNav($nav) { $this->nav = $nav; } /** * @return mixed */ public function getParent() { return $this->parent; } /** * @param mixed $parent */ public function setParent($parent) { $this->parent = $parent; } /** * @return mixed */ public function getSubPages() { return $this->subPages; } /** * @param mixed $subPages */ public function setSubPages($subPages) { $this->subPages = $subPages; } /** * @return mixed */ public function getChildren() { return $this->children; } }
mit
tchatel/JDEV2015-T7A04
js/app-filters.js
52
"use strict"; angular.module('app-filters', []) ;
mit
neontribe/gbptm
src/components/Media.js
330
import { createMedia } from '@artsy/fresnel'; import theme from '../theme'; const { MediaContextProvider, Media } = createMedia({ breakpoints: { sm: 0, md: parseInt(theme.breakpoints[0]), lg: parseInt(theme.breakpoints[1]), xl: parseInt(theme.breakpoints[2]), }, }); export { MediaContextProvider, Media };
mit
xcambar/aura
lib/platform.js
3243
define(function() { // The bind method is used for callbacks. // // * (bind)[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind] // * (You don't need to use $.proxy)[http://www.aaron-powell.com/javascript/you-dont-need-jquery-proxy] if (typeof Function.prototype.bind !== "function") { Function.prototype.bind = function(oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1); var fToBind = this; var FNOP = function() {}; var FBound = function() { return fToBind.apply(this instanceof FNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; FNOP.prototype = this.prototype; FBound.prototype = new FNOP(); return FBound; }; } // Returns true if an object is an array, false if it is not. // // * (isArray)[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray] if (typeof Array.isArray !== "function") { Array.isArray = function(vArg) { return Object.prototype.toString.call(vArg) === "[object Array]"; }; } // Creates a new object with the specified prototype object and properties. // // * (create)[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create] if (!Object.create) { Object.create = function (o) { if (arguments.length > 1) { throw new Error('Object.create implementation only accepts the first parameter.'); } function F() {} F.prototype = o; return new F(); }; } // Returns an array of a given object's own enumerable properties, in the same order as that provided by a for-in loop // (the difference being that a for-in loop enumerates properties in the prototype chain as well). // // (keys)[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys] if (!Object.keys) { Object.keys = (function () { var ownProp = Object.prototype.hasOwnProperty, hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) { throw new TypeError('Object.keys called on non-object'); } var result = []; for (var prop in obj) { if (ownProp.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (var i=0; i < dontEnumsLength; i++) { if (ownProp.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; })(); } });
mit
bkzl/vue-fraction-grid
vue-fraction-grid.js
588
import Container from './components/Container' import Grid from './components/Grid' import GridItem from './components/GridItem' import defaults from './utils/defaults' const VueFractionGrid = { install (Vue, options) { const config = Object.assign(defaults, options) Vue.component(Container.name, { extends: Container, config }) Vue.component(Grid.name, { extends: Grid, config }) Vue.component(GridItem.name, { extends: GridItem, config }) } } if (typeof window !== 'undefined' && window.Vue) { window.Vue.use(VueFractionGrid) } export default VueFractionGrid
mit
thespacedoctor/fundamentals
fundamentals/tests/test_cl_utils.py
1367
from __future__ import print_function from builtins import str import os import unittest import shutil import yaml from fundamentals.utKit import utKit from fundamentals import tools from os.path import expanduser from docopt import docopt from fundamentals import cl_utils doc = cl_utils.__doc__ home = expanduser("~") packageDirectory = utKit("").get_project_root() settingsFile = packageDirectory + "/test_settings.yaml" su = tools( arguments={"settingsFile": settingsFile}, docString=__doc__, logLevel="DEBUG", options_first=False, projectName=None, defaultSettingsFile=False ) arguments, settings, log, dbConn = su.setup() # SETUP PATHS TO COMMON DIRECTORIES FOR TEST DATA moduleDirectory = os.path.dirname(__file__) pathToInputDir = moduleDirectory + "/input/" pathToOutputDir = moduleDirectory + "/output/" try: shutil.rmtree(pathToOutputDir) except: pass # COPY INPUT TO OUTPUT DIR shutil.copytree(pathToInputDir, pathToOutputDir) # Recursively create missing directories if not os.path.exists(pathToOutputDir): os.makedirs(pathToOutputDir) class test_cl_utils(unittest.TestCase): def test_init(self): # TEST CL-OPTIONS # command = "fundamentals init" # args = docopt(doc, command.split(" ")[1:]) # cl_utils.main(args) return # x-class-to-test-named-worker-function
mit
ianharmon/visualizer
js/vizFlyout.js
1483
/******************************************************************************* * bars flying from center */ function VizFlyout(variant) { this.dampen = false; this.hasVariants = true; this.variants = [[2], [3]]; this.vary(variant); this.distances = []; for (var i = 0; i < bandCount; i++) { this.distances.push(0); } } VizFlyout.prototype.vary = function(variant) { this.variant = variant; this.bars = this.variants[variant][0]; } VizFlyout.prototype.resize = function() { this.maxDistance = longestSide * 0.71; this.offset = this.maxDistance / this.bars; } VizFlyout.prototype.draw = function(spectrum) { ctx.save(); ctx.clearRect(0, 0, cv.width, cv.height) ctx.translate(cv.width / 2, cv.height / 2); ctx.rotate(allRotate); for (var i = 0; i < bandCount; i++) { ctx.rotate(rotateAmount); ctx.lineWidth = 1 + (spectrum[i] / 256 * 5); var hue = (360.0 / bandCount * i) / 360.0; var brightness = constrain(spectrum[i] * 1.0 / 150, 0.3, 1); ctx.strokeStyle = HSVtoRGB(hue, 1, brightness); this.distances[i] += (Math.max(50, spectrum[i]) * heightMultiplier / 40); this.distances[i] %= this.offset; for (var j = 0; j < this.bars; j++) { this.arc(this.distances[i] + j * this.offset, rotateAmount * .75); } } allRotate += 0.002; ctx.restore(); } VizFlyout.prototype.arc = function(distance, angle) { ctx.beginPath(); ctx.arc(0, 0, distance, 0, angle); ctx.stroke(); ctx.closePath(); }
mit
Skarabaeus/PhotoYear
app/helpers/photo_style_helper.rb
1694
module PhotoStyleHelper def get_form_fields(style) html = StringIO.new style.instance_variables.each do |var| html << '<fieldset>' html << '<legend>' << style.instance_variable_get(var).selector << '</legend>' html << get_css_fields(style.instance_variable_get(var).selector, style.instance_variable_get(var).style) html << '</fieldset>' end # add requited javascript content_for :additional_javascript do javascript_include_tag 'colorpicker.js', 'jquery.ImageColorPicker.min.js', 'photos_form.js' end # add required css content_for :head do stylesheet_link_tag 'colorpicker.css', 'ImageColorPicker.css' end html.string.html_safe end private def get_css_fields(selector, style) html = StringIO.new style.each do |css_property, value| html << css_property << ': ' case css_property when 'color', 'background-color' html << get_color_picker(selector, css_property, value) when 'border', 'box-shadow' html << text_field_tag(get_field_name(selector, css_property), value) else '' end html << '<br />' end html.string end def get_color_picker(selector, css_property, value) html = StringIO.new html << '<div>' html << '<div class="colorSelector">' html << '<div class="colorpicker-color" style="background-color: ' << value << ';"></div>' html << hidden_field_tag(get_field_name(selector, css_property), value) html << '</div>' html << '<div class="setSelectedColor">Set Selected Color: <span class="selectedColorHex"></span></div>' html << '</div>' html.string end def get_field_name(selector, css_property) 'css_' + selector + '_' + css_property end end
mit
GreatMindsRobotics/DemoGames
Pong/Pong/Pong/Pong/Sprites/Paddle.cs
2021
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FontEffectsLib.SpriteTypes; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace Pong.Sprites { public class Paddle : GameSprite { public Keys UpKey { get; set; } public Keys DownKey { get; set; } public GamePadMapper.GamePadButtons UpButton { get; set; } public GamePadMapper.GamePadButtons DownButton { get; set; } public float Left { get { return _position.X - _origin.X * _scale.X; } } public float Right { get { return _position.X + _origin.X * _scale.X; } } public float Top { get { return _position.Y - _origin.Y * _scale.Y; } } public float Bottom { get { return _position.Y + _origin.Y * _scale.Y; } } public float VectorY { get { return _position.Y; } set { _position.Y = value; } } public float VectorX { get { return _position.X; } set { _position.X = value; } } public Paddle(Texture2D image, Vector2 location, Color tint): base(image, location, tint) { /*UpButton = GamePadMapper.GamePadButtons.LeftTrigger; GamePadMapper mapper = new GamePadMapper(PlayerIndex.One); mapper.IsButtonDown(UpButton);*/ } public override void Update(GameTime gameTime) { //todo: add moving functions base.Update(gameTime); } } }
mit
alecw/picard
src/test/java/picard/sam/SamErrorMetric/ReadBaseStratificationTest.java
36650
package picard.sam.SamErrorMetric; import htsjdk.samtools.*; import htsjdk.samtools.reference.SamLocusAndReferenceIterator.SAMLocusAndReference; import htsjdk.samtools.util.SamLocusIterator; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import picard.sam.AbstractAlignmentMerger; import picard.sam.util.Pair; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * A slew of unit tests for the various stratifiers */ public class ReadBaseStratificationTest { @BeforeClass public void setup() { ReadBaseStratification.setLongHomopolymer(6); } @DataProvider public Object[][] baseStratifierData() { return new Object[][]{ {-1, true, null, ReadBaseStratification.currentReadBaseStratifier}, {0, true, 'C', ReadBaseStratification.currentReadBaseStratifier}, {1, true, 'A', ReadBaseStratification.currentReadBaseStratifier}, {2, true, 'T', ReadBaseStratification.currentReadBaseStratifier}, {3, true, 'G', ReadBaseStratification.currentReadBaseStratifier}, {4, true, 'G', ReadBaseStratification.currentReadBaseStratifier}, {5, true, 'G', ReadBaseStratification.currentReadBaseStratifier}, {6, true, 'G', ReadBaseStratification.currentReadBaseStratifier}, {7, true, 'A', ReadBaseStratification.currentReadBaseStratifier}, {8, true, null, ReadBaseStratification.currentReadBaseStratifier}, {-1, false, null, ReadBaseStratification.currentReadBaseStratifier}, {0, false, 'G', ReadBaseStratification.currentReadBaseStratifier}, {1, false, 'T', ReadBaseStratification.currentReadBaseStratifier}, {2, false, 'A', ReadBaseStratification.currentReadBaseStratifier}, {3, false, 'C', ReadBaseStratification.currentReadBaseStratifier}, {4, false, 'C', ReadBaseStratification.currentReadBaseStratifier}, {5, false, 'C', ReadBaseStratification.currentReadBaseStratifier}, {6, false, 'C', ReadBaseStratification.currentReadBaseStratifier}, {7, false, 'T', ReadBaseStratification.currentReadBaseStratifier}, {8, false, null, ReadBaseStratification.currentReadBaseStratifier}, {0, true, null, ReadBaseStratification.previousReadBaseStratifier}, {1, true, 'C', ReadBaseStratification.previousReadBaseStratifier}, {2, true, 'A', ReadBaseStratification.previousReadBaseStratifier}, {3, true, 'T', ReadBaseStratification.previousReadBaseStratifier}, {4, true, 'G', ReadBaseStratification.previousReadBaseStratifier}, {5, true, 'G', ReadBaseStratification.previousReadBaseStratifier}, {6, true, 'G', ReadBaseStratification.previousReadBaseStratifier}, {7, true, 'G', ReadBaseStratification.previousReadBaseStratifier}, {8, true, 'A', ReadBaseStratification.previousReadBaseStratifier}, {9, true, null, ReadBaseStratification.previousReadBaseStratifier}, {-2, false, null, ReadBaseStratification.previousReadBaseStratifier}, {-1, false, 'G', ReadBaseStratification.previousReadBaseStratifier}, {0, false, 'T', ReadBaseStratification.previousReadBaseStratifier}, {1, false, 'A', ReadBaseStratification.previousReadBaseStratifier}, {2, false, 'C', ReadBaseStratification.previousReadBaseStratifier}, {3, false, 'C', ReadBaseStratification.previousReadBaseStratifier}, {4, false, 'C', ReadBaseStratification.previousReadBaseStratifier}, {5, false, 'C', ReadBaseStratification.previousReadBaseStratifier}, {6, false, 'T', ReadBaseStratification.previousReadBaseStratifier}, {7, false, null, ReadBaseStratification.previousReadBaseStratifier}, {-2, true, null, ReadBaseStratification.nextReadBaseStratifier}, {-1, true, 'C', ReadBaseStratification.nextReadBaseStratifier}, {0, true, 'A', ReadBaseStratification.nextReadBaseStratifier}, {1, true, 'T', ReadBaseStratification.nextReadBaseStratifier}, {2, true, 'G', ReadBaseStratification.nextReadBaseStratifier}, {3, true, 'G', ReadBaseStratification.nextReadBaseStratifier}, {4, true, 'G', ReadBaseStratification.nextReadBaseStratifier}, {5, true, 'G', ReadBaseStratification.nextReadBaseStratifier}, {6, true, 'A', ReadBaseStratification.nextReadBaseStratifier}, {7, true, null, ReadBaseStratification.nextReadBaseStratifier}, {0, false, null, ReadBaseStratification.nextReadBaseStratifier}, {1, false, 'G', ReadBaseStratification.nextReadBaseStratifier}, {2, false, 'T', ReadBaseStratification.nextReadBaseStratifier}, {3, false, 'A', ReadBaseStratification.nextReadBaseStratifier}, {4, false, 'C', ReadBaseStratification.nextReadBaseStratifier}, {5, false, 'C', ReadBaseStratification.nextReadBaseStratifier}, {6, false, 'C', ReadBaseStratification.nextReadBaseStratifier}, {7, false, 'C', ReadBaseStratification.nextReadBaseStratifier}, {8, false, 'T', ReadBaseStratification.nextReadBaseStratifier}, {9, false, null, ReadBaseStratification.nextReadBaseStratifier}, {-1, true, null, ReadBaseStratification.referenceBaseStratifier}, {0, true, 'C', ReadBaseStratification.referenceBaseStratifier}, {1, true, 'A', ReadBaseStratification.referenceBaseStratifier}, {2, true, 'T', ReadBaseStratification.referenceBaseStratifier}, {3, true, 'G', ReadBaseStratification.referenceBaseStratifier}, {4, true, 'G', ReadBaseStratification.referenceBaseStratifier}, {5, true, 'G', ReadBaseStratification.referenceBaseStratifier}, {6, true, 'G', ReadBaseStratification.referenceBaseStratifier}, {7, true, 'A', ReadBaseStratification.referenceBaseStratifier}, {8, true, null, ReadBaseStratification.referenceBaseStratifier}, {-1, false, null, ReadBaseStratification.referenceBaseStratifier}, {0, false, 'G', ReadBaseStratification.referenceBaseStratifier}, {1, false, 'T', ReadBaseStratification.referenceBaseStratifier}, {2, false, 'A', ReadBaseStratification.referenceBaseStratifier}, {3, false, 'C', ReadBaseStratification.referenceBaseStratifier}, {4, false, 'C', ReadBaseStratification.referenceBaseStratifier}, {5, false, 'C', ReadBaseStratification.referenceBaseStratifier}, {6, false, 'C', ReadBaseStratification.referenceBaseStratifier}, {7, false, 'T', ReadBaseStratification.referenceBaseStratifier}, {8, false, null, ReadBaseStratification.referenceBaseStratifier}, {-1, true, null, ReadBaseStratification.postDiNucleotideStratifier}, {0, true, new Pair<>('C', 'A'), ReadBaseStratification.postDiNucleotideStratifier}, {1, true, new Pair<>('A', 'T'), ReadBaseStratification.postDiNucleotideStratifier}, {2, true, new Pair<>('T', 'G'), ReadBaseStratification.postDiNucleotideStratifier}, {3, true, new Pair<>('G', 'G'), ReadBaseStratification.postDiNucleotideStratifier}, {4, true, new Pair<>('G', 'G'), ReadBaseStratification.postDiNucleotideStratifier}, {5, true, new Pair<>('G', 'G'), ReadBaseStratification.postDiNucleotideStratifier}, {6, true, new Pair<>('G', 'A'), ReadBaseStratification.postDiNucleotideStratifier}, {7, true, null, ReadBaseStratification.postDiNucleotideStratifier}, {0, false, null, ReadBaseStratification.postDiNucleotideStratifier}, {1, false, new Pair<>('T', 'G'), ReadBaseStratification.postDiNucleotideStratifier}, {2, false, new Pair<>('A', 'T'), ReadBaseStratification.postDiNucleotideStratifier}, {3, false, new Pair<>('C', 'A'), ReadBaseStratification.postDiNucleotideStratifier}, {4, false, new Pair<>('C', 'C'), ReadBaseStratification.postDiNucleotideStratifier}, {5, false, new Pair<>('C', 'C'), ReadBaseStratification.postDiNucleotideStratifier}, {6, false, new Pair<>('C', 'C'), ReadBaseStratification.postDiNucleotideStratifier}, {7, false, new Pair<>('T', 'C'), ReadBaseStratification.postDiNucleotideStratifier}, {8, false, null, ReadBaseStratification.postDiNucleotideStratifier}, {0, true, null, ReadBaseStratification.preDiNucleotideStratifier}, {1, true, new Pair<>('C', 'A'), ReadBaseStratification.preDiNucleotideStratifier}, {2, true, new Pair<>('A', 'T'), ReadBaseStratification.preDiNucleotideStratifier}, {3, true, new Pair<>('T', 'G'), ReadBaseStratification.preDiNucleotideStratifier}, {4, true, new Pair<>('G', 'G'), ReadBaseStratification.preDiNucleotideStratifier}, {5, true, new Pair<>('G', 'G'), ReadBaseStratification.preDiNucleotideStratifier}, {6, true, new Pair<>('G', 'G'), ReadBaseStratification.preDiNucleotideStratifier}, {7, true, new Pair<>('G', 'A'), ReadBaseStratification.preDiNucleotideStratifier}, {8, true, null, ReadBaseStratification.preDiNucleotideStratifier}, {-1, false, null, ReadBaseStratification.preDiNucleotideStratifier}, {0, false, new Pair<>('T', 'G'), ReadBaseStratification.preDiNucleotideStratifier}, {1, false, new Pair<>('A', 'T'), ReadBaseStratification.preDiNucleotideStratifier}, {2, false, new Pair<>('C', 'A'), ReadBaseStratification.preDiNucleotideStratifier}, {3, false, new Pair<>('C', 'C'), ReadBaseStratification.preDiNucleotideStratifier}, {4, false, new Pair<>('C', 'C'), ReadBaseStratification.preDiNucleotideStratifier}, {5, false, new Pair<>('C', 'C'), ReadBaseStratification.preDiNucleotideStratifier}, {6, false, new Pair<>('T', 'C'), ReadBaseStratification.preDiNucleotideStratifier}, {7, false, null, ReadBaseStratification.preDiNucleotideStratifier}, {-1, true, null, ReadBaseStratification.homoPolymerLengthStratifier}, {0, true, 0, ReadBaseStratification.homoPolymerLengthStratifier}, {1, true, 1, ReadBaseStratification.homoPolymerLengthStratifier}, {2, true, 1, ReadBaseStratification.homoPolymerLengthStratifier}, {3, true, 1, ReadBaseStratification.homoPolymerLengthStratifier}, {4, true, 1, ReadBaseStratification.homoPolymerLengthStratifier}, {5, true, 2, ReadBaseStratification.homoPolymerLengthStratifier}, {6, true, 3, ReadBaseStratification.homoPolymerLengthStratifier}, {7, true, 4, ReadBaseStratification.homoPolymerLengthStratifier}, {8, true, null, ReadBaseStratification.homoPolymerLengthStratifier}, {-1, false, null, ReadBaseStratification.homoPolymerLengthStratifier}, {0, false, 1, ReadBaseStratification.homoPolymerLengthStratifier}, {1, false, 1, ReadBaseStratification.homoPolymerLengthStratifier}, {2, false, 4, ReadBaseStratification.homoPolymerLengthStratifier}, {3, false, 3, ReadBaseStratification.homoPolymerLengthStratifier}, {4, false, 2, ReadBaseStratification.homoPolymerLengthStratifier}, {5, false, 1, ReadBaseStratification.homoPolymerLengthStratifier}, {6, false, 1, ReadBaseStratification.homoPolymerLengthStratifier}, {7, false, 0, ReadBaseStratification.homoPolymerLengthStratifier}, {8, false, null, ReadBaseStratification.homoPolymerLengthStratifier}, {0, true, null, ReadBaseStratification.homopolymerStratifier}, {1, true, new Pair<>(1, new Pair<>('C', 'A')), ReadBaseStratification.homopolymerStratifier}, {2, true, new Pair<>(1, new Pair<>('A', 'T')), ReadBaseStratification.homopolymerStratifier}, {3, true, new Pair<>(1, new Pair<>('T', 'G')), ReadBaseStratification.homopolymerStratifier}, {4, true, new Pair<>(1, new Pair<>('G', 'G')), ReadBaseStratification.homopolymerStratifier}, {5, true, new Pair<>(2, new Pair<>('G', 'G')), ReadBaseStratification.homopolymerStratifier}, {6, true, new Pair<>(3, new Pair<>('G', 'G')), ReadBaseStratification.homopolymerStratifier}, {7, true, new Pair<>(4, new Pair<>('G', 'A')), ReadBaseStratification.homopolymerStratifier}, {8, true, null, ReadBaseStratification.homopolymerStratifier}, {-1, false, null, ReadBaseStratification.homopolymerStratifier}, {0, false, new Pair<>(1, new Pair<>('T', 'G')), ReadBaseStratification.homopolymerStratifier}, {1, false, new Pair<>(1, new Pair<>('A', 'T')), ReadBaseStratification.homopolymerStratifier}, {2, false, new Pair<>(4, new Pair<>('C', 'A')), ReadBaseStratification.homopolymerStratifier}, {3, false, new Pair<>(3, new Pair<>('C', 'C')), ReadBaseStratification.homopolymerStratifier}, {4, false, new Pair<>(2, new Pair<>('C', 'C')), ReadBaseStratification.homopolymerStratifier}, {5, false, new Pair<>(1, new Pair<>('C', 'C')), ReadBaseStratification.homopolymerStratifier}, {6, false, new Pair<>(1, new Pair<>('T', 'C')), ReadBaseStratification.homopolymerStratifier}, {7, false, null, ReadBaseStratification.homopolymerStratifier}, {0, true, null, ReadBaseStratification.oneBasePaddedContextStratifier}, {1, true, "CAT", ReadBaseStratification.oneBasePaddedContextStratifier}, {2, true, "ATG", ReadBaseStratification.oneBasePaddedContextStratifier}, {3, true, "TGG", ReadBaseStratification.oneBasePaddedContextStratifier}, {4, true, "GGG", ReadBaseStratification.oneBasePaddedContextStratifier}, {5, true, "GGG", ReadBaseStratification.oneBasePaddedContextStratifier}, {6, true, "GGA", ReadBaseStratification.oneBasePaddedContextStratifier}, {7, true, null, ReadBaseStratification.oneBasePaddedContextStratifier}, {0, false, null, ReadBaseStratification.oneBasePaddedContextStratifier}, {1, false, "ATG", ReadBaseStratification.oneBasePaddedContextStratifier}, {2, false, "CAT", ReadBaseStratification.oneBasePaddedContextStratifier}, {3, false, "CCA", ReadBaseStratification.oneBasePaddedContextStratifier}, {4, false, "CCC", ReadBaseStratification.oneBasePaddedContextStratifier}, {5, false, "CCC", ReadBaseStratification.oneBasePaddedContextStratifier}, {6, false, "TCC", ReadBaseStratification.oneBasePaddedContextStratifier}, {7, false, null, ReadBaseStratification.oneBasePaddedContextStratifier}, {0, true, null, ReadBaseStratification.twoBasePaddedContextStratifier}, {1, true, null, ReadBaseStratification.twoBasePaddedContextStratifier}, {2, true, "CATGG", ReadBaseStratification.twoBasePaddedContextStratifier}, {3, true, "ATGGG", ReadBaseStratification.twoBasePaddedContextStratifier}, {4, true, "TGGGG", ReadBaseStratification.twoBasePaddedContextStratifier}, {5, true, "GGGGA", ReadBaseStratification.twoBasePaddedContextStratifier}, {6, true, null, ReadBaseStratification.twoBasePaddedContextStratifier}, {7, true, null, ReadBaseStratification.twoBasePaddedContextStratifier}, {0, false, null, ReadBaseStratification.twoBasePaddedContextStratifier}, {1, false, null, ReadBaseStratification.twoBasePaddedContextStratifier}, {2, false, "CCATG", ReadBaseStratification.twoBasePaddedContextStratifier}, {3, false, "CCCAT", ReadBaseStratification.twoBasePaddedContextStratifier}, {4, false, "CCCCA", ReadBaseStratification.twoBasePaddedContextStratifier}, {5, false, "TCCCC", ReadBaseStratification.twoBasePaddedContextStratifier}, {6, false, null, ReadBaseStratification.twoBasePaddedContextStratifier}, {7, false, null, ReadBaseStratification.twoBasePaddedContextStratifier}, {0, true, "all", ReadBaseStratification.nonStratifier}, {1, true, "all", ReadBaseStratification.nonStratifier}, {2, true, "all", ReadBaseStratification.nonStratifier}, {3, true, "all", ReadBaseStratification.nonStratifier}, {4, true, "all", ReadBaseStratification.nonStratifier}, {5, true, "all", ReadBaseStratification.nonStratifier}, {6, true, "all", ReadBaseStratification.nonStratifier}, {7, true, "all", ReadBaseStratification.nonStratifier}, {0, false, "all", ReadBaseStratification.nonStratifier}, {1, false, "all", ReadBaseStratification.nonStratifier}, {2, false, "all", ReadBaseStratification.nonStratifier}, {3, false, "all", ReadBaseStratification.nonStratifier}, {4, false, "all", ReadBaseStratification.nonStratifier}, {5, false, "all", ReadBaseStratification.nonStratifier}, {6, false, "all", ReadBaseStratification.nonStratifier}, {7, false, "all", ReadBaseStratification.nonStratifier}, {7, false, ReadBaseStratification.ReadDirection.NEGATIVE, ReadBaseStratification.readDirectionStratifier}, {7, true, ReadBaseStratification.ReadDirection.POSITIVE, ReadBaseStratification.readDirectionStratifier}, {1, false, (Math.round(100.0 * 5 / 8)) / 100.0, ReadBaseStratification.gcContentStratifier}, {1, false, 93, ReadBaseStratification.flowCellTileStratifier}, {1, false, "rgID", ReadBaseStratification.readgroupStratifier}, {1, false, ReadBaseStratification.ReadOrdinality.FIRST, ReadBaseStratification.readOrdinalityStratifier}, {1, true, ReadBaseStratification.ReadDirection.POSITIVE, ReadBaseStratification.readDirectionStratifier}, {1, false, ReadBaseStratification.ReadDirection.NEGATIVE, ReadBaseStratification.readDirectionStratifier}, {1, true, ReadBaseStratification.PairOrientation.F1R2, ReadBaseStratification.readOrientationStratifier}, {1, false, ReadBaseStratification.PairOrientation.F2R1, ReadBaseStratification.readOrientationStratifier}, {0, true, ReadBaseStratification.CycleBin.QUINTILE_1, ReadBaseStratification.binnedReadCycleStratifier}, {1, true, ReadBaseStratification.CycleBin.QUINTILE_2, ReadBaseStratification.binnedReadCycleStratifier}, {2, true, ReadBaseStratification.CycleBin.QUINTILE_2, ReadBaseStratification.binnedReadCycleStratifier}, {3, true, ReadBaseStratification.CycleBin.QUINTILE_3, ReadBaseStratification.binnedReadCycleStratifier}, {4, true, ReadBaseStratification.CycleBin.QUINTILE_4, ReadBaseStratification.binnedReadCycleStratifier}, {5, true, ReadBaseStratification.CycleBin.QUINTILE_4, ReadBaseStratification.binnedReadCycleStratifier}, {6, true, ReadBaseStratification.CycleBin.QUINTILE_5, ReadBaseStratification.binnedReadCycleStratifier}, {7, true, ReadBaseStratification.CycleBin.QUINTILE_5, ReadBaseStratification.binnedReadCycleStratifier}, {7, false, ReadBaseStratification.CycleBin.QUINTILE_1, ReadBaseStratification.binnedReadCycleStratifier}, {6, false, ReadBaseStratification.CycleBin.QUINTILE_2, ReadBaseStratification.binnedReadCycleStratifier}, {5, false, ReadBaseStratification.CycleBin.QUINTILE_2, ReadBaseStratification.binnedReadCycleStratifier}, {4, false, ReadBaseStratification.CycleBin.QUINTILE_3, ReadBaseStratification.binnedReadCycleStratifier}, {3, false, ReadBaseStratification.CycleBin.QUINTILE_4, ReadBaseStratification.binnedReadCycleStratifier}, {2, false, ReadBaseStratification.CycleBin.QUINTILE_4, ReadBaseStratification.binnedReadCycleStratifier}, {1, false, ReadBaseStratification.CycleBin.QUINTILE_5, ReadBaseStratification.binnedReadCycleStratifier}, {0, false, ReadBaseStratification.CycleBin.QUINTILE_5, ReadBaseStratification.binnedReadCycleStratifier}, {0, true, 1, ReadBaseStratification.baseCycleStratifier}, {1, true, 2, ReadBaseStratification.baseCycleStratifier}, {2, true, 3, ReadBaseStratification.baseCycleStratifier}, {3, true, 4, ReadBaseStratification.baseCycleStratifier}, {4, true, 5, ReadBaseStratification.baseCycleStratifier}, {5, true, 6, ReadBaseStratification.baseCycleStratifier}, {6, true, 7, ReadBaseStratification.baseCycleStratifier}, {7, true, 8, ReadBaseStratification.baseCycleStratifier}, {7, false, 1, ReadBaseStratification.baseCycleStratifier}, {6, false, 2, ReadBaseStratification.baseCycleStratifier}, {5, false, 3, ReadBaseStratification.baseCycleStratifier}, {4, false, 4, ReadBaseStratification.baseCycleStratifier}, {3, false, 5, ReadBaseStratification.baseCycleStratifier}, {2, false, 6, ReadBaseStratification.baseCycleStratifier}, {1, false, 7, ReadBaseStratification.baseCycleStratifier}, {0, false, 8, ReadBaseStratification.baseCycleStratifier}, //in order to curb huge insert lengths that arise from chimeric reads, //the insert-length stratifier caps the insert length by 10 * read-length {0, true, Math.min(100, 10 * 8), ReadBaseStratification.insertLengthStratifier}, {0, true, (byte) 'A', ReadBaseStratification.baseQualityStratifier}, {1, true, (byte) 'B', ReadBaseStratification.baseQualityStratifier}, {2, true, (byte) 'C', ReadBaseStratification.baseQualityStratifier}, {3, true, (byte) 'D', ReadBaseStratification.baseQualityStratifier}, {4, true, (byte) 'E', ReadBaseStratification.baseQualityStratifier}, {5, true, (byte) 'F', ReadBaseStratification.baseQualityStratifier}, {6, true, (byte) 'G', ReadBaseStratification.baseQualityStratifier}, {7, true, (byte) 'H', ReadBaseStratification.baseQualityStratifier}, {0, true, 40, ReadBaseStratification.mappingQualityStratifier}, }; } @Test(dataProvider = "baseStratifierData") public void testReadBaseStratifier(final int offset, final boolean readStrandPositive, final Object expectedStratum, final ReadBaseStratification.RecordAndOffsetStratifier<?> recordAndOffsetStratifier) { final SAMSequenceRecord samSequenceRecord = new SAMSequenceRecord("chr1", 2_000_000); final SAMFileHeader samFileHeader = new SAMFileHeader(); samFileHeader.addSequence(samSequenceRecord); final SAMReadGroupRecord readGroupRecord = new SAMReadGroupRecord("rgID"); samFileHeader.addReadGroup(readGroupRecord); final SAMRecord samRecord = new SAMRecord(samFileHeader); samRecord.setReadName("62A40AAXX101028:2:93:3981:7576"); samRecord.setAttribute(SAMTag.RG.name(), readGroupRecord.getId()); samRecord.setAttribute(SAMTag.NM.name(), 1); samRecord.setReadBases("CATGGGGA".getBytes()); samRecord.setBaseQualities("ABCDEFGH".getBytes()); samRecord.setInferredInsertSize(100); samRecord.setFirstOfPairFlag(true); samRecord.setSecondOfPairFlag(false); samRecord.setReadUnmappedFlag(false); samRecord.setMateUnmappedFlag(false); samRecord.setReadPairedFlag(true); samRecord.setMateNegativeStrandFlag(readStrandPositive); samRecord.setReadNegativeStrandFlag(!readStrandPositive); samRecord.setMappingQuality(40); samRecord.setAlignmentStart(1); samRecord.setReferenceIndex(0); SamLocusIterator.RecordAndOffset recordAndOffset = new SamLocusIterator.RecordAndOffset(samRecord, offset); SamLocusIterator.LocusInfo locusInfo = new SamLocusIterator.LocusInfo(samSequenceRecord, 1); final boolean offSetOOB = offset < 0 || offset >= samRecord.getReadBases().length; final SAMLocusAndReference locusAndReference = new SAMLocusAndReference(locusInfo, offSetOOB ? (byte) 'N' : samRecord.getReadBases()[offset]); Assert.assertEquals(recordAndOffsetStratifier.stratify(recordAndOffset, locusAndReference), expectedStratum, recordAndOffsetStratifier.getSuffix()); } @DataProvider public Object[][] homopolymerStratifierData() { return new Object[][]{ {-1, true, (byte) 'G', null, ReadBaseStratification.homoPolymerLengthStratifier}, {0, true, (byte) 'G', 0, ReadBaseStratification.homoPolymerLengthStratifier}, {1, true, (byte) 'G', 1, ReadBaseStratification.homoPolymerLengthStratifier}, {2, true, (byte) 'G', 1, ReadBaseStratification.homoPolymerLengthStratifier}, {3, true, (byte) 'G', 1, ReadBaseStratification.homoPolymerLengthStratifier}, {4, true, (byte) 'G', 1, ReadBaseStratification.homoPolymerLengthStratifier}, {5, true, (byte) 'G', 2, ReadBaseStratification.homoPolymerLengthStratifier}, {6, true, (byte) 'G', 3, ReadBaseStratification.homoPolymerLengthStratifier}, {7, true, (byte) 'G', 4, ReadBaseStratification.homoPolymerLengthStratifier}, {8, true, (byte) 'G', 1, ReadBaseStratification.homoPolymerLengthStratifier}, {-1, false, (byte) 'G', null, ReadBaseStratification.homoPolymerLengthStratifier}, {0, false, (byte) 'G', 1, ReadBaseStratification.homoPolymerLengthStratifier}, {1, false, (byte) 'G', 1, ReadBaseStratification.homoPolymerLengthStratifier}, {2, false, (byte) 'G', 4, ReadBaseStratification.homoPolymerLengthStratifier}, {3, false, (byte) 'G', 3, ReadBaseStratification.homoPolymerLengthStratifier}, {4, false, (byte) 'G', 2, ReadBaseStratification.homoPolymerLengthStratifier}, {5, false, (byte) 'G', 1, ReadBaseStratification.homoPolymerLengthStratifier}, {6, false, (byte) 'G', 9, ReadBaseStratification.homoPolymerLengthStratifier}, {7, false, (byte) 'G', 8, ReadBaseStratification.homoPolymerLengthStratifier}, {8, false, (byte) 'G', 7, ReadBaseStratification.homoPolymerLengthStratifier}, {9, false, (byte) 'G', 6, ReadBaseStratification.homoPolymerLengthStratifier}, {10, false, (byte) 'G', 5, ReadBaseStratification.homoPolymerLengthStratifier}, {11, false, (byte) 'G', 4, ReadBaseStratification.homoPolymerLengthStratifier}, {12, false, (byte) 'G', 3, ReadBaseStratification.homoPolymerLengthStratifier}, {13, false, (byte) 'G', 2, ReadBaseStratification.homoPolymerLengthStratifier}, {14, false, (byte) 'G', 1, ReadBaseStratification.homoPolymerLengthStratifier}, {15, false, (byte) 'G', 0, ReadBaseStratification.homoPolymerLengthStratifier}, {16, false, (byte) 'G', null, ReadBaseStratification.homoPolymerLengthStratifier}, {7, true, (byte) 'A', new Pair<>(ReadBaseStratification.LongShortHomopolymer.SHORT_HOMOPOLYMER, new Pair<>('G', 'A')), ReadBaseStratification.binnedHomopolymerStratifier.get()}, {8, true, (byte) 'A', new Pair<>(ReadBaseStratification.LongShortHomopolymer.SHORT_HOMOPOLYMER, new Pair<>('A', 'A')), ReadBaseStratification.binnedHomopolymerStratifier.get()}, {9, true, (byte) 'A', new Pair<>(ReadBaseStratification.LongShortHomopolymer.SHORT_HOMOPOLYMER, new Pair<>('A', 'A')), ReadBaseStratification.binnedHomopolymerStratifier.get()}, {10, true, (byte) 'A', new Pair<>(ReadBaseStratification.LongShortHomopolymer.SHORT_HOMOPOLYMER, new Pair<>('A', 'A')), ReadBaseStratification.binnedHomopolymerStratifier.get()}, {11, true, (byte) 'A', new Pair<>(ReadBaseStratification.LongShortHomopolymer.SHORT_HOMOPOLYMER, new Pair<>('A', 'A')), ReadBaseStratification.binnedHomopolymerStratifier.get()}, {12, true, (byte) 'A', new Pair<>(ReadBaseStratification.LongShortHomopolymer.SHORT_HOMOPOLYMER, new Pair<>('A', 'A')), ReadBaseStratification.binnedHomopolymerStratifier.get()}, {13, true, (byte) 'A', new Pair<>(ReadBaseStratification.LongShortHomopolymer.LONG_HOMOPOLYMER, new Pair<>('A', 'A')), ReadBaseStratification.binnedHomopolymerStratifier.get()}, {14, true, (byte) 'A', new Pair<>(ReadBaseStratification.LongShortHomopolymer.LONG_HOMOPOLYMER, new Pair<>('A', 'A')), ReadBaseStratification.binnedHomopolymerStratifier.get()}, {15, true, (byte) 'A', new Pair<>(ReadBaseStratification.LongShortHomopolymer.LONG_HOMOPOLYMER, new Pair<>('A', 'A')), ReadBaseStratification.binnedHomopolymerStratifier.get()}, {16, true, (byte) 'A', null, ReadBaseStratification.binnedHomopolymerStratifier.get()}, }; } @Test(dataProvider = "homopolymerStratifierData") public void testHomopolymerLength(final int offset, final boolean readStrandPositive, final byte referenceBase, final Object expectedStratum, final ReadBaseStratification.RecordAndOffsetStratifier<?> recordAndOffsetStratifier) { final SAMSequenceRecord samSequenceRecord = new SAMSequenceRecord("chr1", 200); final SAMFileHeader samFileHeader = new SAMFileHeader(); final SAMRecord samRecord = new SAMRecord(samFileHeader); samRecord.setReadBases("CATGGGGAAAAAAAAA".getBytes()); samRecord.setReadUnmappedFlag(false); samRecord.setReadNegativeStrandFlag(!readStrandPositive); samRecord.setAlignmentStart(1); SamLocusIterator.RecordAndOffset recordAndOffset = new SamLocusIterator.RecordAndOffset(samRecord, offset); SamLocusIterator.LocusInfo locusInfo = new SamLocusIterator.LocusInfo(samSequenceRecord, 1); final SAMLocusAndReference locusAndReference = new SAMLocusAndReference(locusInfo, referenceBase); Assert.assertEquals(recordAndOffsetStratifier.stratify(recordAndOffset, locusAndReference), expectedStratum); } @Test() public void testHomopolymerLength2() { final SAMSequenceRecord samSequenceRecord = new SAMSequenceRecord("chr1", 2_000_000); final SAMFileHeader samFileHeader = new SAMFileHeader(); samFileHeader.addSequence(samSequenceRecord); final SAMRecord samRecord = new SAMRecord(samFileHeader); final String refString = "GGT"; final String recString = "GGa"; samRecord.setReadBases(recString.getBytes()); samRecord.setReadUnmappedFlag(false); samRecord.setReadNegativeStrandFlag(false); samRecord.setAlignmentStart(1); samRecord.setReferenceIndex(0); SamLocusIterator.RecordAndOffset recordAndOffset = new SamLocusIterator.RecordAndOffset(samRecord, 2); SamLocusIterator.LocusInfo locusInfo = new SamLocusIterator.LocusInfo(samSequenceRecord, 1); final SAMLocusAndReference locusAndReference = new SAMLocusAndReference(locusInfo, refString.getBytes()[2]); Assert.assertEquals(ReadBaseStratification.homoPolymerLengthStratifier.stratify(recordAndOffset, locusAndReference), (Integer) 2); } @DataProvider public Iterator<Object[]> readsForChimericTest() { SAMRecordSetBuilder records = new SAMRecordSetBuilder(); records.addPair("PROPER_1", 0, 100, 400); records.addPair("PROPER_2", 1, 600, 400); records.addPair("PROPER_3", 0, 100, 400, false, false, "36M", "36M", false, true, 30); records.addPair("PROPER_4", 0, 600, 400, false, false, "36M", "36M", true, true, 30); records.addPair("DISCORDANT_1", 0, 1, 100, 100, false, false, "36M", "36M", true, true, false, false, 30); records.addPair("DISCORDANT_2", 1, 0, 1000, 100, false, false, "36M", "36M", false, true, false, false, 30); records.addPair("DISCORDANT_3", 0, 6, 2000, 100, false, false, "36M", "36M", true, false, false, false, 30); records.addPair("DISCORDANT_4", 5, 2, 10000, 100, false, false, "36M", "36M", false, false, false, false, 30); records.addPair("IMPROPER_1", 0, 100, 400, false, false, "36M", "36M", true, false, 30).forEach(s -> s.setProperPairFlag(false)); records.addPair("IMPROPER_2", 1, 600, 400, false, false, "36M", "36M", true, false, 30).forEach(s -> s.setProperPairFlag(false)); records.addPair("IMPROPER_3", 0, 100, 400, false, false, "36M", "36M", false, true, 30).forEach(s -> s.setProperPairFlag(false)); records.addPair("IMPROPER_4", 0, 600, 400, false, false, "36M", "36M", true, false, 30).forEach(s -> s.setProperPairFlag(false)); records.addPair("UNKNOWN_1", 0, -1, 100, 0, false, true, "36M", "36M", true, true, false, false, 30); records.addPair("UNKNOWN_2", 1, -1, 1000, 0, false, true, "36M", "36M", false, true, false, false, 30); records.addPair("UNKNOWN_3", -1, 6, 0, 100, true, false, "36M", "36M", true, false, false, false, 30); records.addPair("UNKNOWN_4", -1, 2, 0, 100, true, false, "36M", "36M", false, false, false, false, 30); addChimericRead(records, "CHIMERIC_1", 0, 2, 100, 200, 400, 300, true, false, true, true); addChimericRead(records, "CHIMERIC_2", 0, 2, 300, 100, 100, 100, true, true, true, true); addChimericRead(records, "CHIMERIC_3", 0, 2, 500, 100, 100, 100, true, false, true, false); addChimericRead(records, "CHIMERIC_4", 0, 2, 100, 700, 100, 100, false, true, true, false); return records.getRecords() .stream() .filter(r -> !r.isSecondaryOrSupplementary()) .map(r -> new Object[]{r, ReadBaseStratification.ProperPaired.valueOf(r.getReadName().replaceAll("_.*", ""))}) .collect(Collectors.toList()) .iterator(); } private List<SAMRecord> addChimericRead(final SAMRecordSetBuilder records, final String name, final int contig, final int contig_sup, final int start1, final int start2, final int start_sup1, final int start_sup2, final boolean strand1, final boolean strand2, final boolean strand_sup1, final boolean strand_sup2) { final List<SAMRecord> chimeric = records.addPair(name, contig, contig, start1, start2, false, false, "20M16S", "15S21M", strand1, strand2, false, false, 30); final List<SAMRecord> chimeric_sup = records.addPair(name, contig_sup, start_sup1, start_sup2, false, false, "16S20M", "21M15S", strand_sup1, strand_sup2, false, false, 30); chimeric_sup.forEach(s -> s.setSupplementaryAlignmentFlag(true)); IntStream.range(0, 2).forEach(i -> chimeric.get(i).setAttribute(SAMTag.SA.toString(), AbstractAlignmentMerger.encodeMappingInformation(chimeric_sup.get(i)))); return chimeric_sup; } @Test(dataProvider = "readsForChimericTest") public void testChimericStratifier(final SAMRecord sam, final ReadBaseStratification.ProperPaired type) { Assert.assertEquals(ReadBaseStratification.ProperPaired.of(sam), type); } }
mit
gatsbyjs/gatsby
packages/gatsby/src/schema/__tests__/kitchen-sink.js
8858
// @flow const { SchemaComposer } = require(`graphql-compose`) const { graphql, GraphQLSchema, GraphQLNonNull, GraphQLList, GraphQLObjectType, getNamedType, } = require(`graphql`) const { store } = require(`../../redux`) const { actions } = require(`../../redux/actions`) const { build } = require(`../index`) const fs = require(`fs-extra`) const path = require(`path`) const { slash } = require(`gatsby-core-utils`) const withResolverContext = require(`../context`) jest.mock(`../../utils/api-runner-node`) const apiRunnerNode = require(`../../utils/api-runner-node`) jest.mock(`gatsby-cli/lib/reporter`, () => { return { log: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), activityTimer: () => { return { start: jest.fn(), setStatus: jest.fn(), end: jest.fn(), } }, phantomActivity: () => { return { start: jest.fn(), end: jest.fn(), } }, } }) // XXX(freiksenet): Expand describe(`Kitchen sink schema test`, () => { let schema let schemaComposer const runQuery = query => graphql( schema, query, undefined, withResolverContext({ schema, schemaComposer, context: {}, customContext: {}, }) ) beforeAll(async () => { apiRunnerNode.mockImplementation((api, ...args) => { if (api === `setFieldsOnGraphQLNodeType`) { return mockSetFieldsOnGraphQLNodeType(...args) } else if (api === `createResolvers`) { return mockCreateResolvers(...args) } else { return [] } }) const nodes = JSON.parse( fs .readFileSync( path.join(__dirname, `./fixtures/kitchen-sink.json`), `utf-8` ) .replace(/<PROJECT_ROOT>/g, slash(process.cwd())) ) store.dispatch({ type: `DELETE_CACHE` }) nodes.forEach(node => actions.createNode(node, { name: `test` })(store.dispatch) ) store.dispatch({ type: `CREATE_TYPES`, payload: ` interface Post implements Node { id: ID! code: String } type PostsJson implements Node & Post @infer { id: ID! time: Date @dateformat(locale: "fi", formatString: "DD MMMM") code: String image: File @fileByRelativePath } `, }) buildThirdPartySchemas().forEach(schema => store.dispatch({ type: `ADD_THIRD_PARTY_SCHEMA`, payload: schema, }) ) await build({}) schema = store.getState().schema schemaComposer = store.getState().schemaCustomization.composer }) it(`passes kitchen sink query`, async () => { expect( await runQuery(` { interface: allPost(sort: { fields: id }, limit: 1) { nodes { id code ... on PostsJson { time image { childImageSharp { id } childrenImageSharp { id } } } } } sort: allPostsJson(sort: { fields: likes, order: ASC }, limit: 2) { edges { node { id idWithDecoration time(formatString: "DD.MM.YYYY") localeString: time(locale: "ru") localeFormat: time(formatString: "DD MMMM YYYY") defaultTime: time code likes comment image { childImageSharp { id } childrenImageSharp { id } } _3invalidKey } } } filter: allPostsJson(filter: { likes: { eq: null } }, limit: 2) { edges { node { id comment } } } resolveFilter: postsJson( idWithDecoration: { eq: "decoration-1601601194425654597" } ) { id idWithDecoration likes } createResolvers: likedEnough { id likes code } thirdPartyStuff { text child { ... on ThirdPartyStuff { text } ... on ThirdPartyStuff2 { foo } } } thirdPartyUnion { ... on ThirdPartyStuff { text } ... on ThirdPartyStuff2 { foo } } thirdPartyInterface { ... on ThirdPartyStuff3 { text } } builtIntPage: sitePage(id: { eq: "SitePage /1685001452849004065/" }) { pageContext } } `) ).toMatchSnapshot() }, 30000) it(`correctly resolves nested Query types from third-party types`, () => { const queryFields = schema.getQueryType().getFields() ;[`relay`, `relay2`, `query`, `manyQueries`].forEach(fieldName => expect(getNamedType(queryFields[fieldName].type)).toBe( schema.getQueryType() ) ) expect(schema.getType(`Nested`).getFields().query.type).toBe( schema.getQueryType() ) }) }) const buildThirdPartySchemas = () => { const schemaComposer = new SchemaComposer() schemaComposer.addTypeDefs(` type ThirdPartyStuff { text: String child: ThirdPartyUnion2 } type ThirdPartyStuff2 { foo: String } union ThirdPartyUnion = ThirdPartyStuff | ThirdPartyStuff2 interface ThirdPartyInterface { text: String relay: Query } type ThirdPartyStuff3 implements ThirdPartyInterface { text: String relay: Query } union ThirdPartyUnion2 = ThirdPartyStuff | ThirdPartyStuff2 type Query { thirdPartyStuff: ThirdPartyStuff thirdPartyUnion: ThirdPartyUnion thirdPartyInterface: ThirdPartyInterface relay: Query relay2: [Query]! } `) schemaComposer .getUTC(`ThirdPartyUnion`) .setResolveType(() => `ThirdPartyStuff`) schemaComposer .getUTC(`ThirdPartyUnion2`) .setResolveType(() => `ThirdPartyStuff`) schemaComposer .getIFTC(`ThirdPartyInterface`) .setResolveType(() => `ThirdPartyStuff3`) schemaComposer.Query.extendField(`thirdPartyStuff`, { resolve() { return { text: `Hello third-party schema!`, child: { text: `Hello from children!`, }, } }, }) schemaComposer.Query.extendField(`thirdPartyUnion`, { resolve() { return { text: `Hello third-party schema!`, child: { text: `Hello from children!`, }, } }, }) schemaComposer.Query.extendField(`thirdPartyInterface`, { resolve() { return { text: `Hello third-party schema!`, } }, }) schemaComposer.addSchemaMustHaveType( schemaComposer.getOTC(`ThirdPartyStuff3`) ) // Query type with non-default name const RootQueryType = new GraphQLObjectType({ name: `RootQueryType`, fields: () => { return { query: { type: RootQueryType }, manyQueries: { type: new GraphQLNonNull(new GraphQLList(RootQueryType)), }, nested: { type: Nested }, } }, }) const Nested = new GraphQLObjectType({ name: `Nested`, fields: () => { return { query: { type: RootQueryType }, } }, }) const schema = new GraphQLSchema({ query: RootQueryType }) return [schemaComposer.buildSchema(), schema] } const mockSetFieldsOnGraphQLNodeType = async ({ type: { name } }) => { if (name === `PostsJson`) { return [ { idWithDecoration: { type: `String`, resolve(parent) { return `decoration-${parent.id}` }, }, }, ] } else { return [] } } const mockCreateResolvers = ({ createResolvers }) => { createResolvers({ Query: { likedEnough: { type: `[PostsJson]`, async resolve(parent, args, context) { const { entries } = await context.nodeModel.findAll({ type: `PostsJson`, query: { limit: 2, skip: 0, filter: { likes: { ne: null, gt: 5, }, }, sort: { fields: [`likes`], order: [`DESC`], }, }, }) return entries }, }, }, }) }
mit
Egg4/egg-framework
src/Controller/Generic.php
1790
<?php namespace Egg\Controller; class Generic extends AbstractController { protected $container; protected $resource; protected $repository; public function __construct(array $settings = []) { parent::__construct(array_merge([ 'container' => null, 'resource' => null, ], $settings)); $this->container = $this->settings['container']; $this->resource = $this->settings['resource']; $this->repository = $this->container['repository'][$this->resource]; } public function select(array $filterParams, array $sortParams, array $rangeParams) { return $this->repository->selectAll($filterParams, $sortParams, $rangeParams); } public function search(array $filterParams, array $sortParams, array $rangeParams) { return $this->repository->selectAll($filterParams, $sortParams, $rangeParams); } public function read($id) { $entity = $this->repository->selectOneById($id); return $entity; } public function create(array $params) { $id = $this->repository->insert($params); $entity = $this->repository->selectOneById($id); return $entity; } public function replace($id, array $params) { return $this->update($id, $params); } public function update($id, array $params) { $this->repository->updateById($params, $id); $entity = $this->repository->selectOneById($id); return $entity; } public function delete($id) { $this->repository->deleteById($id); } public function __call($action, $arguments) { throw new \Exception(sprintf('Create a custom controller for "%s" "%s"', $this->resource, $action)); } }
mit
loren-osborn/php-mem-managed
tests/Internals/ProxyClassFactoryTest.php
5727
<?php namespace LinuxDr\MemManaged\Tests\Internals; use DateTime; use ReflectionClass; use PHPUnit_Framework_TestCase; use LinuxDr\MemManaged\Internals\ProxyClassFactory; final class ProxyClassFactoryTest_TestFinalClass { } interface ProxyClassFactoryTest_TestInterface { public function foo(); } interface ProxyClassFactoryTest_TestParentInterface { public function bar(); } interface ProxyClassFactoryTest_TestChildInterface extends ProxyClassFactoryTest_TestParentInterface { public function baz(); } final class ProxyClassFactoryTest_TestFinalClassHavingInterface implements ProxyClassFactoryTest_TestInterface { public function foo() { } } final class ProxyClassFactoryTest_TestFinalClassHavingAllInterface implements ProxyClassFactoryTest_TestInterface, ProxyClassFactoryTest_TestParentInterface, ProxyClassFactoryTest_TestChildInterface { public function foo() { } public function bar() { } public function baz() { } } final class ProxyClassFactoryTest_TestFinalClassHavingAllInterfacesDifferentOrder implements ProxyClassFactoryTest_TestChildInterface, ProxyClassFactoryTest_TestInterface { public function foo() { } public function bar() { } public function baz() { } } class ProxyClassFactoryTest extends PHPUnit_Framework_TestCase { public function testCreate() { // /* // * "yeild" is new in PHP 5.5, but gives us a quick way to create an // * object implementing "Iterator" // */ // $simpleGenFunc = (function () { // for ($i = 1; $i <= 3; $i++) { // yield $i; // } // }); // $simpleGenerator = $simpleGenFunc(); $factory = new ProxyClassFactory(); $finalClassObj = new ProxyClassFactoryTest_TestFinalClass(); $finalClassProxyClass = $factory->getProxyClassName($finalClassObj); $this->assertEquals( "LinuxDr\\MemManaged\\Internals\\ObjectProxy", $finalClassProxyClass, "Expected value for final class or class with final public methods"); $finalClassWithInterface = new ProxyClassFactoryTest_TestFinalClassHavingInterface(); $interfaceClassProxyClass = $factory->getProxyClassName($finalClassWithInterface); $proxySpec = array('interfaces' => array("LinuxDr\\MemManaged\\Tests\\Internals\\ProxyClassFactoryTest_TestInterface")); $classNameSuffix = sha1(json_encode($proxySpec)); $this->assertEquals( "LinuxDr\\MemManaged\\Internals\\ObjectProxy\\DynamicallyGenerated\\ObjProxy_" . $classNameSuffix, $interfaceClassProxyClass, "Final classes (or classes wth final methods) that implement interfaces should " . "illicit proxy implementing those interfaces"); $finalClassWithAllInterfaces = new ProxyClassFactoryTest_TestFinalClassHavingAllInterface(); $finalClassWithAllInterfaces2 = new ProxyClassFactoryTest_TestFinalClassHavingAllInterfacesDifferentOrder(); $allInterfacesClassProxyClass = $factory->getProxyClassName($finalClassWithAllInterfaces); $allInterfacesClassProxyClass2 = $factory->getProxyClassName($finalClassWithAllInterfaces2); $proxySpec = array('interfaces' => array( "LinuxDr\\MemManaged\\Tests\\Internals\\ProxyClassFactoryTest_TestChildInterface", "LinuxDr\\MemManaged\\Tests\\Internals\\ProxyClassFactoryTest_TestInterface")); $classNameSuffix = sha1(json_encode($proxySpec)); $this->assertEquals( "LinuxDr\\MemManaged\\Internals\\ObjectProxy\\DynamicallyGenerated\\ObjProxy_" . $classNameSuffix, $allInterfacesClassProxyClass, "Final classes (or classes wth final methods) that implement interfaces should " . "illicit proxy implementing those interfaces in an unambiguous order"); $this->assertEquals( "LinuxDr\\MemManaged\\Internals\\ObjectProxy\\DynamicallyGenerated\\ObjProxy_" . $classNameSuffix, $allInterfacesClassProxyClass2, "Final classes (or classes wth final methods) that implement interfaces should " . "illicit proxy implementing those interfaces in an unambiguous order"); $this->assertEquals( $allInterfacesClassProxyClass, $allInterfacesClassProxyClass2, "Final classes (or classes wth final methods) that implement interfaces should " . "illicit proxy implementing those interfaces in an unambiguous order"); $normalClassObj = new DateTime(); $normalClassProxyClass = $factory->getProxyClassName($normalClassObj); $proxySpec = array('parent' => 'DateTime'); $classNameSuffix = sha1(json_encode($proxySpec)); $this->assertEquals( "LinuxDr\\MemManaged\\Internals\\ObjectProxy\\DynamicallyGenerated\\ObjProxy_" . $classNameSuffix, $normalClassProxyClass, "Normal classes should just be based on the class name."); $normalClassWithPublicPropertiesObj = new ReflectionClass($normalClassObj); $normalClassWithPublicPropertiesProxyClass = $factory->getProxyClassName($normalClassWithPublicPropertiesObj); $proxySpec = array('interfaces' => array('Reflector')); $classNameSuffix = sha1(json_encode($proxySpec)); $this->assertEquals( "LinuxDr\\MemManaged\\Internals\\ObjectProxy\\DynamicallyGenerated\\ObjProxy_" . $classNameSuffix, $normalClassWithPublicPropertiesProxyClass, "Normal classes with public properties can't be inherited from properly."); } }
mit
wrutra/instant_messenger
include/tcp_session.hpp
1814
#ifndef TCP_SESSION_HPP #define TCP_SESSION_HPP #include <deque> #include <memory> #include <boost/asio.hpp> #include "session_handler.hpp" #include "message_handler.hpp" #include "message.hpp" using tcp = boost::asio::ip::tcp; // class manages single tcp connection and provides methods for handling // reading and writing messages in boost::asio io_service.run() loop // // message_handler handles send and received messages // session_handler handles printing error messages // and situation when session is no longer valid and should be removed // from the system (e.g. removing session from container holding all active sessions) class tcp_session : public std::enable_shared_from_this<tcp_session> { public: tcp_session(boost::asio::io_service& io_service, session_handler<tcp_session>& session_handler_, message_handler& message_handler_); ~tcp_session(); tcp::socket& socket(); void start(); void stop(); void name(std::string str); std::string name(); void send_message(message msg); std::string socket_info(); void print_socket_alert(const std::string& str); private: void read_header(); void read_body(); void write(); void handle_read_header(const boost::system::error_code& error); void handle_read_body(const boost::system::error_code& error); void handle_write(const boost::system::error_code& error); tcp::socket socket_; session_handler<tcp_session>& session_handler_; message_handler& message_handler_; bool sending; std::string name_; message_queue send_msgs; message read_msg; }; #endif // TCP_SESSION_HPP
mit
bkon/aws-as-code
lib/aws_as_code/dsl/ec2_instances.rb
547
# frozen_string_literal: true EC2_INSTANCE_CLASSES = %w( c3.2xlarge c3.4xlarge c3.8xlarge c3.large c3.xlarge c4.2xlarge c4.4xlarge c4.8xlarge c4.large c4.xlarge d2.2xlarge d2.4xlarge d2.xlarge d3.8xlarge g2.2xlarge g2.8xlarge i2.2xlarge i2.4xlarge i2.8xlarge i2.xlarge m3.2xlarge m3.large m3.medium m3.xlarge m4.10xlarge m4.2xlarge m4.4xlarge m4.large m4.xlarge r3.2xlarge r3.4xlarge r3.8xlarge r3.large r3.xlarge t2.large t2.medium t2.micro t2.nano t2.small ).freeze
mit
nickjbenson/Platforming
Assets/Plugins/RealtimeCSG/Editor/Scripts/EditorWindows/ExportedModelEditor.cs
3392
using System.Collections.Generic; using UnityEditor; using UnityEngine; using InternalRealtimeCSG; using UnityEngine.SceneManagement; namespace RealtimeCSG { #if !DEMO [CustomEditor(typeof(CSGModelExported))] [CanEditMultipleObjects] [System.Reflection.Obfuscation(Exclude = true)] internal sealed class ExportedModelEditor : Editor { public override void OnInspectorGUI() { GUILayout.BeginVertical(GUI.skin.box); { GUILayout.Label("A hidden CSG model, and all it's brushes and operations, is contained by this object. This will automatically be removed at build time.", GUIStyleUtility.wrapLabel); GUILayout.Space(10); if (GUILayout.Button("Revert back to CSG model")) { Undo.IncrementCurrentGroup(); var groupIndex = Undo.GetCurrentGroup(); Undo.SetCurrentGroupName("Reverted to former CSG model"); try { var selection = new List<UnityEngine.Object>(); var updateScenes = new HashSet<Scene>(); foreach (var target in targets) { var exportedModel = target as CSGModelExported; if (!exportedModel) continue; exportedModel.disarm = true; exportedModel.hideFlags = HideFlags.DontSaveInBuild; updateScenes.Add(exportedModel.gameObject.scene); if (exportedModel.containedModel) { Undo.RecordObject(exportedModel.containedModel, "Revert model"); selection.Add(exportedModel.containedModel.gameObject); exportedModel.containedModel.transform.SetParent(exportedModel.transform.parent, true); exportedModel.containedModel.transform.SetSiblingIndex(exportedModel.transform.GetSiblingIndex()); exportedModel.containedModel.gameObject.SetActive(true); exportedModel.containedModel.gameObject.hideFlags = HideFlags.None; EditorUtility.SetDirty(exportedModel.containedModel); Undo.DestroyObjectImmediate(exportedModel); } else { MeshInstanceManager.ReverseExport(exportedModel); selection.Add(exportedModel.gameObject); EditorUtility.SetDirty(exportedModel); Undo.DestroyObjectImmediate(exportedModel); } } Selection.objects = selection.ToArray(); InternalCSGModelManager.skipRefresh = true; BrushOutlineManager.ClearOutlines(); //CSGModelManager.Refresh(forceHierarchyUpdate: true); InternalCSGModelManager.Rebuild(); foreach (var scene in updateScenes) UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(scene); } finally { InternalCSGModelManager.skipRefresh = false; Undo.CollapseUndoOperations(groupIndex); } } } GUILayout.Space(30); if (GUILayout.Button("Remove hidden CSG model")) { Undo.IncrementCurrentGroup(); var groupIndex = Undo.GetCurrentGroup(); Undo.SetCurrentGroupName("Removed hidden CSG model"); Undo.RecordObject(this, "Removed hidden CSG model"); foreach (var target in targets) { var exportedModel = target as CSGModelExported; if (!exportedModel) continue; exportedModel.DestroyModel(undoable: true); Undo.DestroyObjectImmediate(exportedModel); } Undo.CollapseUndoOperations(groupIndex); } GUILayout.Space(10); GUILayout.EndVertical(); } } #endif }
mit
egeis/CSC-505-Graphics
src/main/java/com/graphics/shapes/Line.java
2507
package main.java.com.graphics.shapes; import java.awt.Color; import main.java.com.graphics.shapes.utils.GraphicsObject; import main.java.com.graphics.shapes.utils.Point; /** * * @author Richard Coan */ public class Line extends GraphicsObject { public Line(Point start, Point end) { //Distances int dx = Math.abs(end.x - start.x); int dy = Math.abs(end.y - start.y); //Step increase or decrease int sx = (start.x<end.x)?1:-1; int sy = (start.y<end.y)?1:-1; int error = dx - dy; int x = start.x; int y = start.y; while(true) { double r, g, b, a; if(start.x == end.x) { r = (int) ( ((float) y - start.y) / ((float) end.y - start.y) * (end.color.getRed() - start.color.getRed()) + start.color.getRed() ); g = (int) ( ((float) y - start.y) / ((float) end.y - start.y) * (end.color.getBlue() - start.color.getBlue()) + start.color.getBlue() ); b = (int) ( ((float) y - start.y) / ((float) end.y - start.y) * (end.color.getGreen() - start.color.getGreen()) + start.color.getGreen() ); a = (int) ( ((float) y - start.y) / ((float) end.y - start.y) * (end.color.getAlpha() - start.color.getAlpha()) + start.color.getAlpha()); } else { r = (int) ( ((float) x - start.x) / ((float) end.x - start.x) * (end.color.getRed() - start.color.getRed()) + start.color.getRed() ); g = (int) ( ((float) x - start.x) / ((float) end.x - start.x) * (end.color.getBlue() - start.color.getBlue()) + start.color.getBlue() ); b = (int) ( ((float) x - start.x) / ((float) end.x - start.x) * (end.color.getGreen() - start.color.getGreen()) + start.color.getGreen() ); a = (int) ( ((float) x - start.x) / ((float) end.x - start.x) * (end.color.getAlpha() - start.color.getAlpha()) + start.color.getAlpha() ); } Color color = new Color((int) r, (int) g, (int) b, (int) a); points.add(new Point(x,y, color)); if(x == end.x && y == end.y) break; int e2 = 2 * error; if( e2 > (-dy) ) { error -= dy; x += sx; } if( e2 < dx ) { error += dx; y += sy; } } } }
mit
M0dz145/Kiwapp
app/src/main/java/chevalierx/kiwapp/controllers/ModalEvenementController.java
25472
package chevalierx.kiwapp.controllers; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.*; import chevalierx.kiwapp.activities.MainActivity; import chevalierx.kiwapp.R; import chevalierx.kiwapp.models.DAO.DossierClientDAO; import chevalierx.kiwapp.models.DAO.EvenementCategorieDAO; import chevalierx.kiwapp.models.DAO.EvenementDAO; import chevalierx.kiwapp.models.DossierClient; import chevalierx.kiwapp.models.Evenement; import chevalierx.kiwapp.models.EvenementCategorie; import chevalierx.kiwapp.utils.animations.AnimationHelper; import chevalierx.kiwapp.utils.dates.DateTimePickerHelper; import chevalierx.kiwapp.utils.dates.SimpleDateFormatUtils; import chevalierx.kiwapp.utils.threads.HandlerHelper; import es.dmoral.toasty.Toasty; import top.wefor.circularanim.CircularAnim; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ModalEvenementController { private MainActivity mainActivity; private static ModalEvenementController mInstance = null; private View modalEventView = null, modalEventFieldsContainerView, modalEventDossierClientContainerView, modalEventCompteRenduContainerView; private boolean modalIsOpen = false; private Button modalEventCancelButton, modalEventSaveButton; private RelativeLayout mainActivityRelativeLayout; private TextView modalEventLibelleTextView, modalEventDateDebutTextView, modalEventCompteRendu, modalEventLibelleFieldView; private AutoCompleteTextView modalEventDossierClientAutocompleteTextView; private AnimationHelper modalEventFieldsContainerViewAnimationHelper = null, modalEventLibelleFieldViewAnimationHelper = null, modalEventDossierClientAutocompleteTextViewAnimationHelper = null, modalEventCompteRenduAnimationHelper = null; private Spinner modalEventCategorySpinner; private DateTimePickerHelper dateTimePickerHelper; private Evenement evenement; private boolean isUpdateEvenement = false; /** * Constructor * * @param mainActivity */ private ModalEvenementController(MainActivity mainActivity) { this.mainActivity = mainActivity; // Récupération du layout LayoutInflater inflater = (LayoutInflater) mainActivity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); modalEventView = inflater.inflate(R.layout.modal_event, null); // Ajout du layout sur la page principale mainActivityRelativeLayout = (RelativeLayout) mainActivity.findViewById(R.id.activity_main); mainActivityRelativeLayout.addView(modalEventView); modalEventView.post(() -> new HandlerHelper(mainActivity.getApplicationContext()).runOnUiThread(() -> { // Cache le layout modalEventView.setVisibility(View.GONE); // Listener for cancel button modalEventCancelButton = (Button) modalEventView.findViewById(R.id.modalEventButtonCancel); modalEventCancelButton.setOnClickListener(buttonClicked -> hideEditEvenementModal(buttonClicked)); // Listener for save button modalEventSaveButton = (Button) modalEventView.findViewById(R.id.modalEventButtonSave); modalEventSaveButton.setOnClickListener(buttonClicked -> saveEvenement()); modalEventLibelleTextView = (TextView) modalEventView.findViewById(R.id.modalEventLibelle); modalEventLibelleFieldView = (TextView) modalEventView.findViewById(R.id.modalEventLibelleField); modalEventDateDebutTextView = (TextView) modalEventView.findViewById(R.id.modalEventDateDebut); modalEventCompteRendu = (TextView) modalEventView.findViewById(R.id.modalEventCompteRendu); modalEventCompteRenduContainerView = modalEventView.findViewById(R.id.modalEventCompteRenduContainer); modalEventDossierClientContainerView = modalEventView.findViewById(R.id.modalEventDossierClientContainer); modalEventFieldsContainerView = modalEventView.findViewById(R.id.modalEventFieldsContainer); // Initialisation du datetime picker dateTimePickerHelper = new DateTimePickerHelper(mainActivity, modalEventDateDebutTextView); // Lors du du click sur la view "modalEventView", "modalEventCompteRendu" sera unfocus KeyboardController.getInstance(mainActivity) .setUnfocusView(modalEventCompteRendu) .onClick(modalEventView); // Listener for focus "compte rendu" modalEventCompteRendu.setOnFocusChangeListener((v, hasFocus) -> { if(hasFocus) { showOnlyCompteRenduField(true); } else { showOnlyCompteRenduField(false); } }); refreshSpinnerAndAutocompleteFields(); // Lors du du click sur la view "modalEventView", "modalEventDossierClientAutocompleteTextView" sera unfocus KeyboardController.getInstance(mainActivity) .setUnfocusView(modalEventDossierClientAutocompleteTextView) .onClick(modalEventView); // Listener for focus client field modalEventDossierClientAutocompleteTextView.setOnFocusChangeListener((v, hasFocus) -> { if(hasFocus) { showOnlyClientField(true); } else { showOnlyClientField(false); } }); // Set la modal comme fermée setModalIsOpen(false); // modalEventCouleurSpinner = (Spinner) modalEventView.findViewById(R.id.modalEventCouleur); // List<EvenementCouleur> evenementCouleurList = new EvenementCouleurDAO(mainActivity.getApplicationContext()).getAllCouleurs(); // List<String> evenementCouleurName = new ArrayList<>(evenementCouleurList.size()); // // //noinspection Convert2streamapi // for(EvenementCouleur evenementCouleur : evenementCouleurList) { // evenementCouleurName.add(evenementCouleur.getCodeHex()); // } // // // Create the adapter and set it to the AutoCompleteTextView // ArrayAdapter<String> adapter = new ArrayAdapter<>(mainActivity.getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, evenementCategorieName); // adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // modalEventCategorySpinner.setAdapter(adapter); })); } /** * Initialise la class (revient à faire "getInstance()") * * @param mainActivity */ public static void initEditEvenementController(MainActivity mainActivity) { ModalEvenementController.getInstance(mainActivity); } /** * Récupère l'instance de la class (singleton) * * @param mainActivity * @return */ public static ModalEvenementController getInstance(MainActivity mainActivity) { if(mInstance == null) { mInstance = new ModalEvenementController(mainActivity); } return mInstance; } public void refreshSpinnerAndAutocompleteFields() { /** SPINNER CATEGORIE */ List<EvenementCategorie> evenementCategorieList = new EvenementCategorieDAO(mainActivity.getApplicationContext()).getAllCategories(); List<String> evenementCategorieName = new ArrayList<>(evenementCategorieList.size()); //noinspection Convert2streamapi for(EvenementCategorie evenementCategorie : evenementCategorieList) { evenementCategorieName.add(evenementCategorie.getLibelle()); } // Create the adapter and set it to the Spinner ArrayAdapter<String> adapterForSpinner = new ArrayAdapter<>(mainActivity.getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, evenementCategorieName); adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); modalEventCategorySpinner = (Spinner) modalEventView.findViewById(R.id.modalEventCategory); modalEventCategorySpinner.setAdapter(adapterForSpinner); /** AUTOCOMPLETETEXTVIEW DOSSIER CLIENT */ List<DossierClient> dossierClientList = new DossierClientDAO(mainActivity.getApplicationContext()).getAllDossierClients(null); List<String> dossierClientNames = new ArrayList<>(dossierClientList.size()); //noinspection Convert2streamapi for(DossierClient dossierClient : dossierClientList) { dossierClientNames.add(dossierClient.getNom() + " " + dossierClient.getPrenom()); } // Creating the instance of ArrayAdapter ArrayAdapter<String> adapterForAutocompleteTextView = new ArrayAdapter<>(mainActivity.getApplicationContext(), android.R.layout.select_dialog_item, dossierClientNames); modalEventDossierClientAutocompleteTextView = (AutoCompleteTextView) modalEventView.findViewById(R.id.modalEventDossierClient); modalEventDossierClientAutocompleteTextView.setThreshold(1); // will start working from first character modalEventDossierClientAutocompleteTextView.setAdapter(adapterForAutocompleteTextView); // setting the adapter data into the AutoCompleteTextView } /** * Vide tous les champs de la modal */ public void clearInputFields() { modalEventLibelleTextView.setText(""); Date actualDateSelected = CalendarController.getInstance(mainActivity).getActualDate(); modalEventDateDebutTextView.setText(SimpleDateFormatUtils.getOnlyDay(actualDateSelected)); modalEventCategorySpinner.setSelection(0); modalEventDossierClientAutocompleteTextView.setText(""); modalEventCompteRendu.setText(""); } /** * Affiche ou non seulement le champ "Compte rendu" * * @param show */ private void showOnlyCompteRenduField(boolean show) { if(show) { new HandlerHelper(mainActivity.getApplicationContext()).runOnUiThread(() -> { modalEventDossierClientAutocompleteTextViewAnimationHelper = new AnimationHelper(modalEventDossierClientContainerView, AnimationHelper.ANIMATION_HEIGHT, null).hideItem(); modalEventFieldsContainerViewAnimationHelper = new AnimationHelper(modalEventFieldsContainerView, AnimationHelper.ANIMATION_HEIGHT, null).hideItem(); modalEventLibelleFieldViewAnimationHelper = new AnimationHelper(modalEventLibelleFieldView, AnimationHelper.ANIMATION_HEIGHT, null).hideItem(); }); } else if(modalEventDossierClientAutocompleteTextViewAnimationHelper != null && modalEventFieldsContainerViewAnimationHelper != null && modalEventLibelleFieldViewAnimationHelper != null) { new HandlerHelper(mainActivity.getApplicationContext()).runOnUiThread(() -> { modalEventDossierClientAutocompleteTextViewAnimationHelper.showItem(modalEventDossierClientAutocompleteTextViewAnimationHelper.getInitialHeigthView(), modalEventDossierClientAutocompleteTextViewAnimationHelper.getInitialWidthView()); modalEventFieldsContainerViewAnimationHelper.showItem(modalEventFieldsContainerViewAnimationHelper.getInitialHeigthView(), modalEventFieldsContainerViewAnimationHelper.getInitialWidthView()); modalEventLibelleFieldViewAnimationHelper.showItem(modalEventLibelleFieldViewAnimationHelper.getInitialHeigthView(), modalEventLibelleFieldViewAnimationHelper.getInitialWidthView()); }); } else { Log.e(ModalEvenementController.class.getName(), "Impossible d'afficher l'item car l'animation n'est pas définit"); } } /** * Affiche ou non seulement le champ "Client" * * @param show */ private void showOnlyClientField(boolean show) { if(show) { new HandlerHelper(mainActivity.getApplicationContext()).runOnUiThread(() -> { modalEventFieldsContainerViewAnimationHelper = new AnimationHelper(modalEventFieldsContainerView, AnimationHelper.ANIMATION_HEIGHT, null).hideItem(); modalEventLibelleFieldViewAnimationHelper = new AnimationHelper(modalEventLibelleFieldView, AnimationHelper.ANIMATION_HEIGHT, null).hideItem(); modalEventCompteRenduAnimationHelper = new AnimationHelper(modalEventCompteRenduContainerView, AnimationHelper.ANIMATION_HEIGHT, null).hideItem(); }); } else if(modalEventFieldsContainerViewAnimationHelper != null && modalEventLibelleFieldViewAnimationHelper != null && modalEventCompteRenduAnimationHelper != null) { new HandlerHelper(mainActivity.getApplicationContext()).runOnUiThread(() -> { modalEventFieldsContainerViewAnimationHelper.showItem(modalEventFieldsContainerViewAnimationHelper.getInitialHeigthView(), modalEventFieldsContainerViewAnimationHelper.getInitialWidthView()); modalEventLibelleFieldViewAnimationHelper.showItem(modalEventLibelleFieldViewAnimationHelper.getInitialHeigthView(), modalEventLibelleFieldViewAnimationHelper.getInitialWidthView()); modalEventCompteRenduAnimationHelper.showItem(modalEventCompteRenduAnimationHelper.getInitialHeigthView(), modalEventCompteRenduAnimationHelper.getInitialWidthView()); }); } else { Log.e(ModalEvenementController.class.getName(), "Impossible d'afficher l'item car l'animation n'est pas définit"); } } /** * Permet de setter l'évènement à modifier * * @param evenement * @return */ public ModalEvenementController setEvenement(Evenement evenement) { this.evenement = evenement; if(evenement.getId() == 0) { // Nouvel évènement this.isUpdateEvenement = false; clearInputFields(); } else { this.isUpdateEvenement = true; // Libelle modalEventLibelleTextView.setText(evenement.getLibelle()); // Catégorie if(evenement.getCategorie() != null) { modalEventCategorySpinner.setSelection((int) evenement.getCategorie().getId()); } else { modalEventCategorySpinner.setSelection(0); } // Dossier client DossierClient dossierClient = evenement.getDossierClient(mainActivity.getApplicationContext()); if(dossierClient != null) { modalEventDossierClientAutocompleteTextView.setText(dossierClient.getNom() + " " + dossierClient.getPrenom()); } else { modalEventDossierClientAutocompleteTextView.setText(""); } // Compte rendu if(evenement.getCompteRendu() != null) { modalEventCompteRendu.setText(evenement.getCompteRendu()); } // Date try { modalEventDateDebutTextView.setText(SimpleDateFormatUtils.getDateAndTimeFrench(evenement.getDateDebut())); DateTimePickerHelper.setCalendarTime(SimpleDateFormatUtils.parseFromFrenchDate(String.valueOf(modalEventDateDebutTextView.getText() + ":00"))); } catch(ParseException e) { e.printStackTrace(); } } return this; } /** * Vérifie si les champs sont valides * * @return */ private boolean checkValidFields() { boolean isValid = false; String errorMessage = ""; // Check libelle if(modalEventLibelleTextView.getText().length() > 0) { String dateDebut = modalEventDateDebutTextView.getText().toString(); // Check date début if(dateDebut.indexOf("/") != -1 && dateDebut.indexOf(":") != -1) { // Check dossier client if(modalEventDossierClientAutocompleteTextView.getText().length() > 0) { DossierClient dossierClient = getDossierClientByAutocompleteText(); if(dossierClient != null) { isValid = true; } else { modalEventDossierClientAutocompleteTextView.requestFocus(); errorMessage = "Le client rentré n'est pas correcte ou n'existe pas dans la base de données, veuillez réessayer"; } } else { isValid = true; } } else { modalEventDateDebutTextView.requestFocus(); errorMessage = "La date de début n'est pas valide, veuillez sélectionner une date valide"; } } else { modalEventLibelleTextView.requestFocus(); errorMessage = "Veuillez sélectionner un libellé"; } if(!isValid) { Toasty.error(mainActivity.getApplicationContext(), errorMessage, Toast.LENGTH_LONG, false).show(); } return isValid; } /** * Récupère le dossier client depuis le champ "client" de la modal * * @return */ private DossierClient getDossierClientByAutocompleteText() { String nameAndSurname = String.valueOf(modalEventDossierClientAutocompleteTextView.getText()); if(nameAndSurname.length() > 0) { // Si le champs n'est pas vide int splitIndex = nameAndSurname.lastIndexOf(" "); if(splitIndex > 0) { // On récupère le nom String name = nameAndSurname.substring(0, splitIndex).trim(); // On récupère le prénom String surname = nameAndSurname.substring(splitIndex, nameAndSurname.length()).trim(); // On recherche le dossier client correspondant return new DossierClientDAO(mainActivity.getApplicationContext()).findDossierClientByNames(name, surname); } } return null; } /** * Permet de setter un Evenement depuis les champs de la modal */ private void setEvenementWithFields() { // Libelle evenement.setLibelle(modalEventLibelleTextView.getText().toString().trim()); // Catégorie evenement.setCategorie(modalEventCategorySpinner.getSelectedItemId()); // Dossier client DossierClient dossierClient = getDossierClientByAutocompleteText(); if(dossierClient != null) { evenement.setDossierClient(dossierClient.getId()); } else { evenement.setDossierClient(-1); // Revient à setter le dossier client à null } // Date de début try { evenement.setDateDebut(SimpleDateFormatUtils.parseFromFrenchDate(modalEventDateDebutTextView.getText().toString() + ":00")); } catch(ParseException e) { e.printStackTrace(); } // Compte rendu evenement.setCompteRendu(modalEventCompteRendu.getText().toString().trim()); } /** * Permet de sauvegarder l'évènement */ public void saveEvenement() { if(checkValidFields()) { // On vérifie si les fields sont valides if(this.isUpdateEvenement) { // On update un évènement Evenement oldEvenement = evenement.clone(); // On set l'Evenement setEvenementWithFields(); // On update l'Evenement Evenement evenementUpdated = new EvenementDAO(mainActivity.getApplicationContext()).updateEvenement(evenement); if(evenementUpdated != null) { // Vérifie si l'évènement a bien été update CalendarController calendarController = CalendarController.getInstance(mainActivity); calendarController.updateEventByEvenement(evenement, oldEvenement); // On refresh le tout calendarController.refreshHack(); // On ferme la modal hideEditEvenementModal(modalEventSaveButton); Toasty.success(mainActivity.getApplicationContext(), "\"" + evenementUpdated.getLibelle() + "\" a été mis à jour", Toast.LENGTH_SHORT, false).show(); } else { Toasty.error(mainActivity.getApplicationContext(), "Impossible de modifier l'évènement, veuillez réessayer ultérieurement", Toast.LENGTH_LONG, false).show(); } } else { // On créer un nouvel évènement setEvenementWithFields(); try { // On créer le nouvel Evenement DossierClient dossierClient = evenement.getDossierClient(mainActivity.getApplicationContext()); Evenement newEvenement = new EvenementDAO(mainActivity.getApplicationContext()).createEvenement( null, evenement.getLibelle(), SimpleDateFormatUtils.getDateAndTimeUS(evenement.getDateDebut()), null, evenement.getCompteRendu(), "true", (int) evenement.getCategorie().getId(), null, dossierClient != null ? (int) dossierClient.getId() : -1, null ); if(newEvenement == null) { Toasty.error(mainActivity.getApplicationContext(), "Une erreur est survenue lors de la création de l'évènement, veuillez réessayer ultérieurement", Toast.LENGTH_LONG, false).show(); } else { // On l'ajoute au calendrier CalendarController calendarController = CalendarController.getInstance(mainActivity); calendarController.addEventByEvenement(newEvenement); calendarController.getCompactCalendarView().setCurrentDate(newEvenement.getDateDebut()); calendarController.setDate(newEvenement.getDateDebut()); // On ferme la modal hideEditEvenementModal(modalEventSaveButton); Toasty.success(mainActivity.getApplicationContext(), "L'évènement \"" + newEvenement.getLibelle() + "\" a bien été créé", Toast.LENGTH_LONG, false).show(); } } catch(ParseException e) { e.printStackTrace(); } } } } /** * Permet de savoir si la modal est affichée ou non * * @return */ public boolean modalIsOpen() { return modalIsOpen; } /** * Setter modalIsOpen, permet de désactiver ou activer le focus des champs pour éviter que le clavier se focus dessus * * @param modalIsOpen * @return */ public void setModalIsOpen(boolean modalIsOpen) { this.modalIsOpen = modalIsOpen; this.modalEventLibelleTextView.setFocusable(modalIsOpen); this.modalEventLibelleTextView.setFocusableInTouchMode(modalIsOpen); this.modalEventCompteRendu.setFocusable(modalIsOpen); this.modalEventCompteRendu.setFocusableInTouchMode(modalIsOpen); this.modalEventDossierClientAutocompleteTextView.setFocusable(modalIsOpen); this.modalEventDossierClientAutocompleteTextView.setFocusableInTouchMode(modalIsOpen); } /** * Permet de fermer la modal * * @param triggerView */ public ModalEvenementController hideEditEvenementModal(View triggerView) { if(this.modalIsOpen()) { modalEventView.post(() -> new HandlerHelper(mainActivity.getApplicationContext()).runOnUiThread(() -> { CircularAnim.VisibleBuilder circularAnimBuilder = CircularAnim.hide(modalEventView); if(triggerView != null) { circularAnimBuilder.triggerView(triggerView); } Log.i(ModalEvenementController.class.getName(), "Hide EditEvenement modal"); circularAnimBuilder.go(() -> { setModalIsOpen(false); Log.i(ModalEvenementController.class.getName(), "EditEvenement modal is hide"); }); })); } return this; } /** * Permet d'afficher la modal * * @param triggerView */ public ModalEvenementController showEditEvenementModal(View triggerView) { if(!this.modalIsOpen()) { modalEventView.post(() -> new HandlerHelper(mainActivity.getApplicationContext()).runOnUiThread(() -> { CircularAnim.VisibleBuilder circularAnimBuilder = CircularAnim.show(modalEventView); if(triggerView != null) { circularAnimBuilder.triggerView(triggerView); } Log.i(ModalEvenementController.class.getName(), "Show EditEvenement modal"); circularAnimBuilder.go(() -> { setModalIsOpen(true); Log.i(ModalEvenementController.class.getName(), "EditEvenement modal is show"); }); })); } return this; } }
mit
dolanmiu/docx
src/file/values.ts
9012
// Runtime checks and cleanup for value types in the spec that aren't easily expressed through our type system. // These will help us to prevent silent failures and corrupted documents. // // Most of the rest of the types not defined here are either aliases of existing types or enumerations. // Enumerations should probably just be implemented as enums, with instructions to end-users, without a runtime check. // <xsd:simpleType name="ST_DecimalNumber"> // <xsd:restriction base="xsd:integer"/> // </xsd:simpleType> export function decimalNumber(val: number): number { if (isNaN(val)) { throw new Error(`Invalid value '${val}' specified. Must be an integer.`); } return Math.floor(val); } // <xsd:simpleType name="ST_UnsignedDecimalNumber"> // <xsd:restriction base="xsd:unsignedLong"/> // </xsd:simpleType> export function unsignedDecimalNumber(val: number): number { const value = decimalNumber(val); if (value < 0) { throw new Error(`Invalid value '${val}' specified. Must be a positive integer.`); } return value; } // The xsd:hexBinary type represents binary data as a sequence of binary octets. // It uses hexadecimal encoding, where each binary octet is a two-character hexadecimal number. // Lowercase and uppercase letters A through F are permitted. For example, 0FB8 and 0fb8 are two // equal xsd:hexBinary representations consisting of two octets. // http://www.datypic.com/sc/xsd/t-xsd_hexBinary.html function hexBinary(val: string, length: number): string { const expectedLength = length * 2; if (val.length !== expectedLength || isNaN(Number("0x" + val))) { throw new Error(`Invalid hex value '${val}'. Expected ${expectedLength} digit hex value`); } return val; } // <xsd:simpleType name="ST_LongHexNumber"> // <xsd:restriction base="xsd:hexBinary"> // <xsd:length value="4"/> // </xsd:restriction> // </xsd:simpleType> export function longHexNumber(val: string): string { return hexBinary(val, 4); } // <xsd:simpleType name="ST_ShortHexNumber"> // <xsd:restriction base="xsd:hexBinary"> // <xsd:length value="2"/> // </xsd:restriction> // </xsd:simpleType> export function shortHexNumber(val: string): string { return hexBinary(val, 2); } // <xsd:simpleType name="ST_UcharHexNumber"> // <xsd:restriction base="xsd:hexBinary"> // <xsd:length value="1"/> // </xsd:restriction> // </xsd:simpleType> export function uCharHexNumber(val: string): string { return hexBinary(val, 1); } // <xsd:simpleType name="ST_LongHexNumber"> // <xsd:restriction base="xsd:hexBinary"> // <xsd:length value="4"/> // </xsd:restriction> // </xsd:simpleType> // <xsd:simpleType name="ST_UniversalMeasure"> // <xsd:restriction base="xsd:string"> // <xsd:pattern value="-?[0-9]+(\.[0-9]+)?(mm|cm|in|pt|pc|pi)"/> // </xsd:restriction> // </xsd:simpleType> export function universalMeasureValue(val: string): string { const unit = val.slice(-2); if (!universalMeasureUnits.includes(unit)) { throw new Error(`Invalid unit '${unit}' specified. Valid units are ${universalMeasureUnits.join(", ")}`); } const amount = val.substring(0, val.length - 2); if (isNaN(Number(amount))) { throw new Error(`Invalid value '${amount}' specified. Expected a valid number.`); } return `${Number(amount)}${unit}`; } const universalMeasureUnits = ["mm", "cm", "in", "pt", "pc", "pi"]; // <xsd:simpleType name="ST_PositiveUniversalMeasure"> // <xsd:restriction base="ST_UniversalMeasure"> // <xsd:pattern value="[0-9]+(\.[0-9]+)?(mm|cm|in|pt|pc|pi)"/> // </xsd:restriction> // </xsd:simpleType> export function positiveUniversalMeasureValue(val: string): string { const value = universalMeasureValue(val); if (parseFloat(value) < 0) { throw new Error(`Invalid value '${value}' specified. Expected a positive number.`); } return value; } // <xsd:simpleType name="ST_HexColor"> // <xsd:union memberTypes="ST_HexColorAuto s:ST_HexColorRGB"/> // </xsd:simpleType> // <xsd:simpleType name="ST_HexColorAuto"> // <xsd:restriction base="xsd:string"> // <xsd:enumeration value="auto"/> // </xsd:restriction> // </xsd:simpleType> // <xsd:simpleType name="ST_HexColorRGB"> // <xsd:restriction base="xsd:hexBinary"> // <xsd:length value="3" fixed="true"/> // </xsd:restriction> // </xsd:simpleType> export function hexColorValue(val: string): string { if (val === "auto") { return val; } // It's super common to see colors prefixed with a pound, but technically invalid here. // Most clients work with it, but strip it off anyway for strict compliance. const color = val.charAt(0) === "#" ? val.substring(1) : val; return hexBinary(color, 3); } // <xsd:simpleType name="ST_SignedTwipsMeasure"> // <xsd:union memberTypes="xsd:integer s:ST_UniversalMeasure"/> // </xsd:simpleType> export function signedTwipsMeasureValue(val: string | number): string | number { return typeof val === "string" ? universalMeasureValue(val) : decimalNumber(val); } // <xsd:simpleType name="ST_HpsMeasure"> // <xsd:union memberTypes="s:ST_UnsignedDecimalNumber s:ST_PositiveUniversalMeasure"/> // </xsd:simpleType> export function hpsMeasureValue(val: string | number): string | number { return typeof val === "string" ? positiveUniversalMeasureValue(val) : unsignedDecimalNumber(val); } // <xsd:simpleType name="ST_SignedHpsMeasure"> // <xsd:union memberTypes="xsd:integer s:ST_UniversalMeasure"/> // </xsd:simpleType> export function signedHpsMeasureValue(val: string | number): string | number { return typeof val === "string" ? universalMeasureValue(val) : decimalNumber(val); } // <xsd:simpleType name="ST_TwipsMeasure"> // <xsd:union memberTypes="ST_UnsignedDecimalNumber ST_PositiveUniversalMeasure"/> // </xsd:simpleType> export function twipsMeasureValue(val: string | number): string | number { return typeof val === "string" ? positiveUniversalMeasureValue(val) : unsignedDecimalNumber(val); } // <xsd:simpleType name="ST_Percentage"> // <xsd:restriction base="xsd:string"> // <xsd:pattern value="-?[0-9]+(\.[0-9]+)?%"/> // </xsd:restriction> // </xsd:simpleType> export function percentageValue(val: string): string { if (val.slice(-1) !== "%") { throw new Error(`Invalid value '${val}'. Expected percentage value (eg '55%')`); } const percent = val.substring(0, val.length - 1); if (isNaN(Number(percent))) { throw new Error(`Invalid value '${percent}' specified. Expected a valid number.`); } return `${Number(percent)}%`; } // <xsd:simpleType name="ST_MeasurementOrPercent"> // <xsd:union memberTypes="ST_DecimalNumberOrPercent s:ST_UniversalMeasure"/> // </xsd:simpleType> // <xsd:simpleType name="ST_DecimalNumberOrPercent"> // <xsd:union memberTypes="ST_UnqualifiedPercentage s:ST_Percentage"/> // </xsd:simpleType> // <xsd:simpleType name="ST_UnqualifiedPercentage"> // <xsd:restriction base="xsd:integer"/> // </xsd:simpleType> export function measurementOrPercentValue(val: number | string): number | string { if (typeof val === "number") { return decimalNumber(val); } if (val.slice(-1) === "%") { return percentageValue(val); } return universalMeasureValue(val); } // <xsd:simpleType name="ST_EighthPointMeasure"> // <xsd:restriction base="s:ST_UnsignedDecimalNumber"/> // </xsd:simpleType> export const eighthPointMeasureValue = unsignedDecimalNumber; // <xsd:simpleType name="ST_PointMeasure"> // <xsd:restriction base="s:ST_UnsignedDecimalNumber"/> // </xsd:simpleType> export const pointMeasureValue = unsignedDecimalNumber; // <xsd:simpleType name="ST_DateTime"> // <xsd:restriction base="xsd:dateTime"/> // </xsd:simpleType> // // http://www.datypic.com/sc/xsd/t-xsd_dateTime.html // The type xsd:dateTime represents a specific date and time in the format // CCYY-MM-DDThh:mm:ss.sss, which is a concatenation of the date and time forms, // separated by a literal letter "T". All of the same rules that apply to the date // and time types are applicable to xsd:dateTime as well. // // An optional time zone expression may be added at the end of the value. // The letter Z is used to indicate Coordinated Universal Time (UTC). All other time // zones are represented by their difference from Coordinated Universal Time in the // format +hh:mm, or -hh:mm. These values may range from -14:00 to 14:00. For example, // US Eastern Standard Time, which is five hours behind UTC, is represented as -05:00. // If no time zone value is present, it is considered unknown; it is not assumed to be UTC. // // Luckily, js has this format built in already. See: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString export function dateTimeValue(val: Date): string { return val.toISOString(); }
mit
MTASZTAKI/ApertusVR
plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/deps/v8/src/heap/scavenger.cc
7064
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/heap/scavenger.h" #include "src/heap/barrier.h" #include "src/heap/heap-inl.h" #include "src/heap/mark-compact-inl.h" #include "src/heap/objects-visiting-inl.h" #include "src/heap/scavenger-inl.h" #include "src/heap/sweeper.h" #include "src/objects-body-descriptors-inl.h" namespace v8 { namespace internal { class IterateAndScavengePromotedObjectsVisitor final : public ObjectVisitor { public: IterateAndScavengePromotedObjectsVisitor(Heap* heap, Scavenger* scavenger, bool record_slots) : heap_(heap), scavenger_(scavenger), record_slots_(record_slots) {} inline void VisitPointers(HeapObject* host, Object** start, Object** end) final { for (Address slot_address = reinterpret_cast<Address>(start); slot_address < reinterpret_cast<Address>(end); slot_address += kPointerSize) { Object** slot = reinterpret_cast<Object**>(slot_address); Object* target = *slot; scavenger_->PageMemoryFence(target); if (target->IsHeapObject()) { if (heap_->InFromSpace(target)) { scavenger_->ScavengeObject(reinterpret_cast<HeapObject**>(slot), HeapObject::cast(target)); target = *slot; scavenger_->PageMemoryFence(target); if (heap_->InNewSpace(target)) { SLOW_DCHECK(target->IsHeapObject()); SLOW_DCHECK(heap_->InToSpace(target)); RememberedSet<OLD_TO_NEW>::Insert(Page::FromAddress(slot_address), slot_address); } SLOW_DCHECK(!MarkCompactCollector::IsOnEvacuationCandidate( HeapObject::cast(target))); } else if (record_slots_ && MarkCompactCollector::IsOnEvacuationCandidate( HeapObject::cast(target))) { heap_->mark_compact_collector()->RecordSlot(host, slot, target); } } } } private: Heap* const heap_; Scavenger* const scavenger_; const bool record_slots_; }; Scavenger::Scavenger(Heap* heap, bool is_logging, CopiedList* copied_list, PromotionList* promotion_list, int task_id) : heap_(heap), promotion_list_(promotion_list, task_id), copied_list_(copied_list, task_id), local_pretenuring_feedback_(kInitialLocalPretenuringFeedbackCapacity), copied_size_(0), promoted_size_(0), allocator_(heap), is_logging_(is_logging), is_incremental_marking_(heap->incremental_marking()->IsMarking()), is_compacting_(heap->incremental_marking()->IsCompacting()) {} void Scavenger::IterateAndScavengePromotedObject(HeapObject* target, int size) { // We are not collecting slots on new space objects during mutation thus we // have to scan for pointers to evacuation candidates when we promote // objects. But we should not record any slots in non-black objects. Grey // object's slots would be rescanned. White object might not survive until // the end of collection it would be a violation of the invariant to record // its slots. const bool record_slots = is_compacting_ && heap()->incremental_marking()->atomic_marking_state()->IsBlack(target); IterateAndScavengePromotedObjectsVisitor visitor(heap(), this, record_slots); target->IterateBody(target->map()->instance_type(), size, &visitor); } void Scavenger::AddPageToSweeperIfNecessary(MemoryChunk* page) { AllocationSpace space = page->owner()->identity(); if ((space == OLD_SPACE) && !page->SweepingDone()) { heap()->mark_compact_collector()->sweeper()->AddPage( space, reinterpret_cast<Page*>(page), Sweeper::READD_TEMPORARY_REMOVED_PAGE); } } void Scavenger::ScavengePage(MemoryChunk* page) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "Scavenger::ScavengePage"); CodePageMemoryModificationScope memory_modification_scope(page); RememberedSet<OLD_TO_NEW>::Iterate( page, [this](Address addr) { return CheckAndScavengeObject(heap_, addr); }, SlotSet::KEEP_EMPTY_BUCKETS); RememberedSet<OLD_TO_NEW>::IterateTyped( page, [this](SlotType type, Address host_addr, Address addr) { return UpdateTypedSlotHelper::UpdateTypedSlot( heap_->isolate(), type, addr, [this](Object** addr) { return CheckAndScavengeObject(heap(), reinterpret_cast<Address>(addr)); }); }); AddPageToSweeperIfNecessary(page); } void Scavenger::Process(OneshotBarrier* barrier) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "Scavenger::Process"); // Threshold when to switch processing the promotion list to avoid // allocating too much backing store in the worklist. const int kProcessPromotionListThreshold = kPromotionListSegmentSize / 2; ScavengeVisitor scavenge_visitor(heap(), this); const bool have_barrier = barrier != nullptr; bool done; size_t objects = 0; do { done = true; ObjectAndSize object_and_size; while ((promotion_list_.LocalPushSegmentSize() < kProcessPromotionListThreshold) && copied_list_.Pop(&object_and_size)) { scavenge_visitor.Visit(object_and_size.first); done = false; if (have_barrier && ((++objects % kInterruptThreshold) == 0)) { if (!copied_list_.IsGlobalPoolEmpty()) { barrier->NotifyAll(); } } } while (promotion_list_.Pop(&object_and_size)) { HeapObject* target = object_and_size.first; int size = object_and_size.second; DCHECK(!target->IsMap()); IterateAndScavengePromotedObject(target, size); done = false; if (have_barrier && ((++objects % kInterruptThreshold) == 0)) { if (!promotion_list_.IsGlobalPoolEmpty()) { barrier->NotifyAll(); } } } } while (!done); } void Scavenger::Finalize() { heap()->MergeAllocationSitePretenuringFeedback(local_pretenuring_feedback_); heap()->IncrementSemiSpaceCopiedObjectSize(copied_size_); heap()->IncrementPromotedObjectsSize(promoted_size_); allocator_.Finalize(); } void RootScavengeVisitor::VisitRootPointer(Root root, const char* description, Object** p) { ScavengePointer(p); } void RootScavengeVisitor::VisitRootPointers(Root root, const char* description, Object** start, Object** end) { // Copy all HeapObject pointers in [start, end) for (Object** p = start; p < end; p++) ScavengePointer(p); } void RootScavengeVisitor::ScavengePointer(Object** p) { Object* object = *p; if (!heap_->InNewSpace(object)) return; scavenger_->ScavengeObject(reinterpret_cast<HeapObject**>(p), reinterpret_cast<HeapObject*>(object)); } } // namespace internal } // namespace v8
mit
error454/ShiVa-Proof-Of-Concept
random/Resources/Scripts/RandomNumber_State_Random_onEnter.lua
688
-------------------------------------------------------------------------------- -- State............ : Random -- Author........... : -- Description...... : -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function RandomNumber.Random_onEnter ( ) -------------------------------------------------------------------------------- -- -- Write your code here, using 'this' as current AI instance. -- -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
mit
jon-chen/ThingsOfInternet
ThingsOfInternet/Commands/SetAwayStatusCommand.cs
1471
using System; using System.Threading.Tasks; using ThingsOfInternet.Models; using ThingsOfInternet.ViewModels; using Unity = Microsoft.Practices.Unity; using ThingsOfInternet.Services; namespace ThingsOfInternet.Commands { public class SetAwayStatusCommand : SparkCoreConfigureCommand { [Unity.Dependency] protected ThingsService ThingsService { get; set; } #region implemented abstract members of SparkCoreConfigureCommand protected override bool IsBusy { get { return viewModel.IsResetHomeStatusBusy; } set { viewModel.IsResetHomeStatusBusy = value; } } protected override string[] PropertiesToSerialize { get { return new [] { SwitchConfigProperties.HomeStatus, SwitchConfigProperties.MobileId }; } } protected override SwitchConfig SwitchConfig { get { return new SwitchConfig { HomeStatus = HomeStatus.Away, MobileId = String.Format("{0:X}", ThingsService.GetMobileIdentifier().GetHashCode()) }; } } protected override void RevertValue() { } #endregion public override bool CanExecute(object parameter) { return base.CanExecute(parameter) && ((ThingViewModel)parameter).IsHomeOnlyModeEnabled; } } }
mit
spacedoc/spacedoc
packages/spacedoc/test/build.js
1264
const {expect} = require('chai'); const {Spacedoc} = require('..'); const mockVinyl = require('./util/mock-vinyl'); const TEST_FILE = mockVinyl('test/fixtures/example.md'); const TEST_FILE_ALT = mockVinyl('test/fixtures/example-alt-layout.md'); describe('Spacedoc.build()', () => { it('builds an HTML file from the data of a page', () => { const s = new Spacedoc().config({ theme: 'test/fixtures/theme' }); const output = s.build({kittens: 'kittens', meta: {}}); expect(output).to.be.a('string'); expect(output).to.contain('<p>kittens'); }); it('throws Pug errors', () => { const s = new Spacedoc().config({ theme: 'test/fixtures/theme-broken' }); expect(s.build).to.throw(Error); }); it('allows Front Matter to be retained on the page', () => { const s = new Spacedoc().config({ theme: 'test/fixtures/theme', keepFm: true }); return expect(s.parse(TEST_FILE).then(data => s.build(data))).to.eventually.contain('---'); }); it('allows an alternate layout to be used', () => { const s = new Spacedoc().config({ theme: 'test/fixtures/theme' }); return expect(s.parse(TEST_FILE_ALT).then(data => s.build(data))).to.eventually.contain('<p>Puppies'); }); });
mit
daleholborow/iayos.flashcardapi
backend/iayos.flashcardapi.DomainModel/Infrastructure/IModelHasGuid.cs
382
using System; namespace iayos.flashcardapi.DomainModel.Infrastructure { /// <summary> /// Will have a globally unique identifier /// </summary> public interface IModelHasGuid { /// <summary> /// Property to store globally unique id (TODO: SHOULD be generated as a sequential GUID to ensure it doesnt blow up DB indexing) /// </summary> Guid Id { get; set; } } }
mit
neofob/sile
languages/tr.lua
5293
-- Quotes may be part of a word in Turkish SILE.nodeMakers.tr = SILE.nodeMakers.unicode { isWordType = { cm = true, qu = true }, } SILE.hyphenator.languages["tr"] = {} SILE.hyphenator.languages["tr"].patterns = { "2a1", "2â1", "2e1", "2ı1", "2i1", "2î1", "2o1", "2ö1", "2u1", "2ü1", "2û1", -- allow hyphen either side of consonants "1b1", "1c1", "1ç1", "1d1", "1f1", "1g1", "1ğ1", "1h1", "1j1", "1k1", "1l1", "1m1", "1n1", "1p1", "1r1", "1s1", "1ş1", "1t1", "1v1", "1y1", "1z1", -- prevent a-cak/e-cek at end of word "2a2cak.", "2e2cek.", -- prohibit hyphen before pair of consonants -- many pairs generated here are impossible anyway "2bb", "2bc", "2bç", "2bd", "2bf", "2bg", "2bğ", "2bh", "2bj", "2bk", "2bl", "2bm", "2bn", "2bp", "2br", "2bs", "2bş", "2bt", "2bv", "2by", "2bz", "2cb", "2cc", "2cç", "2cd", "2cf", "2cg", "2cğ", "2ch", "2cj", "2ck", "2cl", "2cm", "2cn", "2cp", "2cr", "2cs", "2cş", "2ct", "2cv", "2cy", "2cz", "2çb", "2çc", "2çç", "2çd", "2çf", "2çg", "2çğ", "2çh", "2çj", "2çk", "2çl", "2çm", "2çn", "2çp", "2çr", "2çs", "2çş", "2çt", "2çv", "2çy", "2çz", "2db", "2dc", "2dç", "2dd", "2df", "2dg", "2dğ", "2dh", "2dj", "2dk", "2dl", "2dm", "2dn", "2dp", "2dr", "2ds", "2dş", "2dt", "2dv", "2dy", "2dz", "2fb", "2fc", "2fç", "2fd", "2ff", "2fg", "2fğ", "2fh", "2fj", "2fk", "2fl", "2fm", "2fn", "2fp", "2fr", "2fs", "2fş", "2ft", "2fv", "2fy", "2fz", "2gb", "2gc", "2gç", "2gd", "2gf", "2gg", "2gğ", "2gh", "2gj", "2gk", "2gl", "2gm", "2gn", "2gp", "2gr", "2gs", "2gş", "2gt", "2gv", "2gy", "2gz", "2ğb", "2ğc", "2ğç", "2ğd", "2ğf", "2ğg", "2ğğ", "2ğh", "2ğj", "2ğk", "2ğl", "2ğm", "2ğn", "2ğp", "2ğr", "2ğs", "2ğş", "2ğt", "2ğv", "2ğy", "2ğz", "2hb", "2hc", "2hç", "2hd", "2hf", "2hg", "2hğ", "2hh", "2hj", "2hk", "2hl", "2hm", "2hn", "2hp", "2hr", "2hs", "2hş", "2ht", "2hv", "2hy", "2hz", "2jb", "2jc", "2jç", "2jd", "2jf", "2jg", "2jğ", "2jh", "2jj", "2jk", "2jl", "2jm", "2jn", "2jp", "2jr", "2js", "2jş", "2jt", "2jv", "2jy", "2jz", "2kb", "2kc", "2kç", "2kd", "2kf", "2kg", "2kğ", "2kh", "2kj", "2kk", "2kl", "2km", "2kn", "2kp", "2kr", "2ks", "2kş", "2kt", "2kv", "2ky", "2kz", "2lb", "2lc", "2lç", "2ld", "2lf", "2lg", "2lğ", "2lh", "2lj", "2lk", "2ll", "2lm", "2ln", "2lp", "2lr", "2ls", "2lş", "2lt", "2lv", "2ly", "2lz", "2mb", "2mc", "2mç", "2md", "2mf", "2mg", "2mğ", "2mh", "2mj", "2mk", "2ml", "2mm", "2mn", "2mp", "2mr", "2ms", "2mş", "2mt", "2mv", "2my", "2mz", "2nb", "2nc", "2nç", "2nd", "2nf", "2ng", "2nğ", "2nh", "2nj", "2nk", "2nl", "2nm", "2nn", "2np", "2nr", "2ns", "2nş", "2nt", "2nv", "2ny", "2nz", "2pb", "2pc", "2pç", "2pd", "2pf", "2pg", "2pğ", "2ph", "2pj", "2pk", "2pl", "2pm", "2pn", "2pp", "2pr", "2ps", "2pş", "2pt", "2pv", "2py", "2pz", "2rb", "2rc", "2rç", "2rd", "2rf", "2rg", "2rğ", "2rh", "2rj", "2rk", "2rl", "2rm", "2rn", "2rp", "2rr", "2rs", "2rş", "2rt", "2rv", "2ry", "2rz", "2sb", "2sc", "2sç", "2sd", "2sf", "2sg", "2sğ", "2sh", "2sj", "2sk", "2sl", "2sm", "2sn", "2sp", "2sr", "2ss", "2sş", "2st", "2sv", "2sy", "2sz", "2şb", "2şc", "2şç", "2şd", "2şf", "2şg", "2şğ", "2şh", "2şj", "2şk", "2şl", "2şm", "2şn", "2şp", "2şr", "2şs", "2şş", "2şt", "2şv", "2şy", "2şz", "2tb", "2tc", "2tç", "2td", "2tf", "2tg", "2tğ", "2th", "2tj", "2tk", "2tl", "2tm", "2tn", "2tp", "2tr", "2ts", "2tş", "2tt", "2tv", "2ty", "2tz", "2vb", "2vc", "2vç", "2vd", "2vf", "2vg", "2vğ", "2vh", "2vj", "2vk", "2vl", "2vm", "2vn", "2vp", "2vr", "2vs", "2vş", "2vt", "2vv", "2vy", "2vz", "2yb", "2yc", "2yç", "2yd", "2yf", "2yg", "2yğ", "2yh", "2yj", "2yk", "2yl", "2ym", "2yn", "2yp", "2yr", "2ys", "2yş", "2yt", "2yv", "2yy", "2yz", "2zb", "2zc", "2zç", "2zd", "2zf", "2zg", "2zğ", "2zh", "2zj", "2zk", "2zl", "2zm", "2zn", "2zp", "2zr", "2zs", "2zş", "2zt", "2zv", "2zy", "2zz", -- allow hyphen between vowels, but not after second vowel of pair -- several phonetically impossible pairs here "a3a2", "a3â2", "a3e2", "a3ı2", "a3i2", "a3î2", "a3o2", "a3ö2", "a3u2", "a3ü2", "a3û2", "â3a2", "â3â2", "â3e2", "â3ı2", "â3i2", "â3î2", "â3o2", "â3ö2", "â3u2", "â3ü2", "â3û2", "e3a2", "e3â2", "e3e2", "e3ı2", "e3i2", "e3î2", "e3o2", "e3ö2", "e3u2", "e3ü2", "e3û2", "ı3a2", "ı3â2", "ı3e2", "ı3ı2", "ı3i2", "ı3î2", "ı3o2", "ı3ö2", "ı3u2", "ı3ü2", "ı3û2", "i3a2", "i3â2", "i3e2", "i3ı2", "i3i2", "i3î2", "i3o2", "i3ö2", "i3u2", "i3ü2", "i3û2", "î3a2", "î3â2", "î3e2", "î3ı2", "î3i2", "î3î2", "î3o2", "î3ö2", "î3u2", "î3ü2", "î3û2", "o3a2", "o3â2", "o3e2", "o3ı2", "o3i2", "o3î2", "o3o2", "o3ö2", "o3u2", "o3ü2", "o3û2", "ö3a2", "ö3â2", "ö3e2", "ö3ı2", "ö3i2", "ö3î2", "ö3o2", "ö3ö2", "ö3u2", "ö3ü2", "ö3û2", "u3a2", "u3â2", "u3e2", "u3ı2", "u3i2", "u3î2", "u3o2", "u3ö2", "u3u2", "u3ü2", "u3û2", "ü3a2", "ü3â2", "ü3e2", "ü3ı2", "ü3i2", "ü3î2", "ü3o2", "ü3ö2", "ü3u2", "ü3ü2", "ü3û2", "û3a2", "û3â2", "û3e2", "û3ı2", "û3i2", "û3î2", "û3o2", "û3ö2", "û3u2", "û3ü2", "û3û2", -- a couple of consonant-clusters "tu4r4k", "m1t4rak", } -- Internationalisation stuff SILE.doTexlike([[% \define[command=tableofcontents:title]{İçindekiler}% \define[command=book:chapter:pre:tr]{Bölüm }% ]])
mit
mapbox/mapbox-sdk-py
tests/test_directions.py
9042
from cachecontrol.cache import DictCache import mapbox import pytest import responses points = [{ "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ -87.33787536621092, 36.539156961321574]}}, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ -88.2476806640625, 36.92217534275667]}}] def test_class_attrs(): """Get expected class attr values""" serv = mapbox.Directions() assert serv.api_name == 'directions' assert serv.api_version == 'v5' @responses.activate @pytest.mark.parametrize("cache", [None, DictCache()]) def test_directions(cache): with open('tests/moors.json') as fh: body = fh.read() responses.add( responses.GET, 'https://api.mapbox.com/directions/v5/mapbox/driving/' + '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test', match_querystring=True, body=body, status=200, content_type='application/json') res = mapbox.Directions(access_token='pk.test', cache=cache).directions(points) assert res.status_code == 200 assert 'distance' in res.json()['routes'][0].keys() @responses.activate def test_directions_geojson(): with open('tests/moors.json') as fh: body = fh.read() responses.add( responses.GET, 'https://api.mapbox.com/directions/v5/mapbox/driving/' '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test', match_querystring=True, body=body, status=200, content_type='application/json') res = mapbox.Directions(access_token='pk.test').directions(points) fc = res.geojson() assert fc['type'] == 'FeatureCollection' assert fc['features'][0]['geometry']['type'] == 'LineString' @responses.activate def test_directions_geojson_as_geojson(): with open('tests/moors_geojson.json') as fh: body = fh.read() responses.add( responses.GET, 'https://api.mapbox.com/directions/v5/mapbox/driving/' '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test' '&geometries=geojson', match_querystring=True, body=body, status=200, content_type='application/json') res = mapbox.Directions(access_token='pk.test').directions( points, geometries='geojson') fc = res.geojson() assert fc['type'] == 'FeatureCollection' assert fc['features'][0]['geometry']['type'] == 'LineString' def test_invalid_profile(): with pytest.raises(ValueError): mapbox.Directions(access_token='pk.test').directions( points, profile='bogus') @responses.activate def test_direction_params(): params = "&alternatives=false&geometries=polyline&overview=false&steps=false" \ "&continue_straight=false&annotations=distance%2Cspeed&language=en" \ "&radiuses=10%3Bunlimited" responses.add( responses.GET, 'https://api.mapbox.com/directions/v5/mapbox/driving/' '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test' + params, match_querystring=True, body="not important, only testing URI templating", status=200, content_type='application/json') res = mapbox.Directions(access_token='pk.test').directions( points, alternatives=False, geometries='polyline', overview=False, continue_straight=True, annotations=['distance', 'speed'], language='en', waypoint_snapping=[10, 'unlimited'], steps=False) assert res.status_code == 200 @responses.activate def test_direction_backwards_compat(): """Ensure old calls to directions method work against v5 API """ responses.add( responses.GET, 'https://api.mapbox.com/directions/v5/mapbox/cycling/' '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test' '&geometries=polyline', match_querystring=True, body="not important, only testing URI templating", status=200, content_type='application/json') res = mapbox.Directions(access_token='pk.test').directions( points, geometry='polyline', # plural in v5 profile='mapbox.cycling', # '/' delimited in v5 ) # TODO instructions parameter removed in v5 assert res.status_code == 200 @responses.activate def test_direction_bearings(): responses.add( responses.GET, 'https://api.mapbox.com/directions/v5/mapbox/driving/' '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test' '&radiuses=10%3B20&bearings=270%2C45%3B315%2C90', match_querystring=True, body="not important, only testing URI templating", status=200, content_type='application/json') res = mapbox.Directions(access_token='pk.test').directions( points, waypoint_snapping=[(10, 270, 45), (20, 315, 90)]) assert res.status_code == 200 @responses.activate def test_direction_bearings_none(): responses.add( responses.GET, 'https://api.mapbox.com/directions/v5/mapbox/driving/' '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test' '&radiuses=10%3B20&bearings=%3B315%2C90', match_querystring=True, body="not important, only testing URI templating", status=200, content_type='application/json') res = mapbox.Directions(access_token='pk.test').directions( points, waypoint_snapping=[10, (20, 315, 90)]) assert res.status_code == 200 def test_invalid_geom_encoding(): service = mapbox.Directions(access_token='pk.test') with pytest.raises(mapbox.errors.ValidationError): service._validate_geom_encoding('wkb') def test_v4_profile_aliases(): service = mapbox.Directions(access_token='pk.test') assert 'mapbox/cycling' == service._validate_profile('mapbox.cycling') def test_invalid_annotations(): service = mapbox.Directions(access_token='pk.test') with pytest.raises(mapbox.errors.InvalidParameterError): service._validate_annotations(['awesomeness']) def test_invalid_geom_overview(): service = mapbox.Directions(access_token='pk.test') with pytest.raises(mapbox.errors.InvalidParameterError): service._validate_geom_overview('infinite') def test_invalid_radiuses(): service = mapbox.Directions(access_token='pk.test') with pytest.raises(mapbox.errors.InvalidParameterError) as e: service._validate_radius('forever') assert 'not a valid radius' in str(e) def test_invalid_number_of_bearings(): service = mapbox.Directions(access_token='pk.test') with pytest.raises(mapbox.errors.InvalidParameterError) as e: service._validate_snapping([1, 2, 3], points) assert 'exactly one' in str(e) def test_invalid_bearing_tuple(): service = mapbox.Directions(access_token='pk.test') with pytest.raises(mapbox.errors.InvalidParameterError) as e: service._validate_snapping([(270, 45, 'extra'), (315,)], points) assert 'bearing tuple' in str(e) def test_snapping_bearing_none(): service = mapbox.Directions(access_token='pk.test') bearings, radii = service._validate_snapping([(10, 270, 45), None], points) assert bearings == [(270, 45), None] assert radii == [10, None] def test_snapping_radii_none(): service = mapbox.Directions(access_token='pk.test') bearings, radii = service._validate_snapping([(10, 270, 45), None], points) assert bearings == [(270, 45), None] assert radii == [10, None] def test_validate_radius_none(): service = mapbox.Directions(access_token='pk.test') assert service._validate_radius(None) is None def test_validate_radius_unlimited(): service = mapbox.Directions(access_token='pk.test') assert service._validate_radius('unlimited') == 'unlimited' def test_validate_radius_invalid(): service = mapbox.Directions(access_token='pk.test') with pytest.raises(mapbox.errors.InvalidParameterError) as e: service._validate_radius(-1) with pytest.raises(mapbox.errors.InvalidParameterError) as e: service._validate_radius('nothing') def test_invalid_bearing_domain(): service = mapbox.Directions(access_token='pk.test') with pytest.raises(mapbox.errors.InvalidParameterError) as e: service._validate_snapping([(-1, 90), (315, 90)], points) assert 'between 0 and 360' in str(e) def test_bearings_without_radius(): with pytest.raises(TypeError): mapbox.Directions(access_token='pk.test').directions( waypoint_snapping=[(270, 45), (270, 45)]) def test_validate_snapping(): service = mapbox.Directions(access_token='pk.test') snaps = service._validate_snapping( [(1, 1, 1), u'unlimited'], [None, None]) assert snaps == ([(1, 1), None], [1, 'unlimited'])
mit
havencruise/emberjam
conf/settings_override/default/other.py
31
USE_THOUSAND_SEPARATOR = True
mit
nguyenrm/HauntedCastle
HauntedCastle1.java/src/HauntedCastle.java
5094
import java.util.Scanner; public class HauntedCastle { public static void main(String[] args) { // verify eclipse System.out.println("Welcome to the Haunted Castle"); // create a scanner object Scanner input = new Scanner(System.in); // Start the project System.out.println("Tai, Mai, and Sey are in a haunted castle. "); System.out.println("The group is in the castle because of their curiosity \n, and they also always want to be in a haunted place. \nHowever, they are lost. "); System.out.println("They must decide what to do next."); //Give print statement to ask what they are going to do System.out.println("Do you want to split up or stay together \nas a group to continue the adventure?"); System.out.println("1 = stay together, 2 = split up"); int Decision = input.nextInt(); // Ask the group to choose the door if (Decision == 1) { //boolean System.out.println("The group decided to stay together. \nThey proceed to walk toward a dark hallway."); System.out.println("They see 3 doors, red (1), yellow(2), and blue(3). \nThey must choose which door to open"); int door = input.nextInt(); // The item that is inside each door switch (door % 4) { //switch statement case 1: System.out.println("They choose the red door. \nThey would find a torch."); break; case 2: System.out.println("They choose the yellow door and find a flashlight."); break; case 3: System.out.println("Blue door is choosen. Nothing is in there."); break; } if (door <= 2 ){ //with the flashlight/torch, they all survive. System.out.println("A dark figure suddenly appears in front of them. \nThey use the torch/flashlight and point it against the dark figure. \nThe figure runs away."); // Insert a built in math function System.out.println("Sey sees a weird circular object on the wall, \nshe guesses its angle is about 30 degrees. \nSey then turns around and asks Tai to convert it to radians"); double answer = Math.toRadians(30); // Degree to Radian // Print the answer System.out.println("Tai says: Easy, the answer is: " + answer); System.out.println("The group all smile happily and continue to proceed."); // Encounter the door password System.out.println("They encounter a big door. Woohoo! It seems like it's the way out. \nHowever, they notice a letter pad on the door. \nIt asks for a password using the alphabet."); // Guessing the password String[] words = { "password" }; int numberOfMisses = 0 ; do { int i = intRandom(0, words.length - 1); char[] word = words[i].toCharArray(); boolean[] mask = new boolean[word.length]; int numberOfCorrectGuess = 0; while (numberOfCorrectGuess != word.length) { System.out.print("(Guess) Enter a letter in word "); // Print out result for (int j = 0; j < word.length; j++) { if (mask[j]) System.out.print(word[j]); else System.out.print("*"); } System.out.print(">"); char guess = input.next().charAt(0); // Checking boolean miss = true; boolean repeat = false; for (int j = 0; j < word.length; j++) { if (word[j] == guess) { if (mask[j] != true) { mask[j] = true; numberOfCorrectGuess++; } else { repeat = true; break; } miss = false; } } if (miss) numberOfMisses++; if (repeat) System.out.println(guess + " is already in the word"); } System.out.println("The password is " + String.valueOf(word) +"\nYou did great! The door is unlocked. The group gets out of the haunted castle. \nThey can't wait to tell their classmates about the amazing experience inside the castle. \nTHE END"); } while (numberOfMisses < 0); } else if (door == 3 ){// They dont have anything to stand against the figure, ended up dying. System.out.println("They don't have anything to fight against the dark figure. \nTai, Mai, and Sey are too afraid that they all pass out. \nGame ends here."); } else if (Decision == 2) { customPrintOutStatement(); } } //A multidimensional array that holds the three hostages as a team //declares the array of players int [] [] players = new int [1] [3]; //Assign a for loop for(int i = 0; i < players.length; i++){ for(int j = 0; j < players[i].length; j++){ } } } private static void customPrintOutStatement() { System.out.print("The group decides split up. \nThey start to walk on their own direction. \nThey would all get lost and die in the castle alone. \nTHE END"); } public static int intRandom(int lowerBound, int upperBound) { return (int) (lowerBound + Math.random() * (upperBound - lowerBound + 1)); } }
mit
rusty1s/koa2-rest-api
server/db/index.js
1530
'use strict'; import mongoose from 'mongoose'; import { localClient, adminUser } from './config'; import Client from '../models/client'; import User from '../models/user'; export function connectDatabase(uri) { return new Promise((resolve, reject) => { mongoose.connection .on('error', error => reject(error)) .on('close', () => console.log('Database connection closed.')) .once('open', () => resolve(mongoose.connections[0])); mongoose.connect(uri); }); } export async function registerLocalClient() { return new Promise((resolve, reject) => { (async () => { try { const client = await Client.findOne({ id: localClient.id }); if (!client) { await Client.create({ name: localClient.name, id: localClient.id, secret: localClient.secret, trusted: true, }); } resolve(); } catch (error) { reject(error); } })(); }); } export async function registerAdminUser() { return new Promise((resolve, reject) => { (async () => { try { const user = await User.findOne({ email: adminUser.email }); if (!user) { await User.create({ name: adminUser.name, email: adminUser.email, password: adminUser.password, confirm_password: adminUser.password, admin: true, }); } resolve(); } catch (error) { reject(error); } })(); }); }
mit
bennybi/yii2-cza-base
vendor/assets/jstree/TreeAsset.php
674
<?php /** * refer to arogachev\tree\assets\TreeAsset */ namespace cza\base\vendor\assets\jstree; use yii\web\AssetBundle; class TreeAsset extends AssetBundle { /** * @inheritdoc */ public $sourcePath = '@cza/base/vendor/assets/jstree/src'; /** * @inheritdoc */ public $publishOptions = [ 'forceCopy' => YII_DEBUG, ]; /** * @inheritdoc */ public $js = [ 'js/tree.js', ]; public $css = [ 'css/themes/proton/style.css', ]; /** * @inheritdoc */ public $depends = [ 'yii\web\YiiAsset', 'cza\base\vendor\assets\jstree\JsTreeAsset', ]; }
mit
Rudolfking/TreatLookaheadMatcher
hu.bme.mit.inf.TreatEngine/src/hu/bme/mit/inf/treatengine/MyFeatureListeners.java
30120
package hu.bme.mit.inf.treatengine; import hu.bme.mit.inf.lookaheadmatcher.LookaheadMatcherInterface; import hu.bme.mit.inf.lookaheadmatcher.impl.AheadStructure; import hu.bme.mit.inf.lookaheadmatcher.impl.AxisConstraint; import hu.bme.mit.inf.lookaheadmatcher.impl.LookaheadMatching; import hu.bme.mit.inf.lookaheadmatcher.impl.RelationConstraint; import hu.bme.mit.inf.lookaheadmatcher.impl.TypeConstraint; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.incquery.runtime.base.api.DataTypeListener; import org.eclipse.incquery.runtime.base.api.FeatureListener; import org.eclipse.incquery.runtime.base.api.IncQueryBaseIndexChangeListener; import org.eclipse.incquery.runtime.base.api.InstanceListener; import org.eclipse.incquery.runtime.base.api.NavigationHelper; import org.eclipse.incquery.runtime.matchers.psystem.PQuery; import org.eclipse.incquery.runtime.matchers.psystem.PVariable; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multiset; public class MyFeatureListeners { private LookaheadMatcherTreat treat; private NavigationHelper navHelper; public MyFeatureListeners(LookaheadMatcherTreat treat, NavigationHelper navigationHelper) { this.treat = treat; this.navHelper = navigationHelper; } private boolean isModified; public IncQueryBaseIndexChangeListener baseIndexChangeListener = new IncQueryBaseIndexChangeListener() { @Override public boolean onlyOnIndexChange() { return true; } @Override public void notifyChanged(boolean indexChanged) { // if (modelChanges != null && modelChanges.size() > 0) // System.out.println("[MAGIC] After magic collect:" + modelChanges.size()); MagicProcessor(); // remove list return; } }; // captures an "instance" (eclass) change (insertion, deletion) then copies and modifies the aheadstructures to match insertion/deletion, then runs a patternmatcher, then updates the cached matchings public InstanceListener classListener = new InstanceListener() { @Override public void instanceInserted(EClass clazz, EObject instance) { // System.out.println("[Instance] inserted!"); modelChanges.add(new EClassChange(clazz, instance, true)); // // // // // InstanceDelta instInsert = new InstanceDelta(clazz, instance, true); // System.out.println("[ECLASS] Update affected patterns' matchings started!"); // long start = System.currentTimeMillis(); // // changes: // ArrayList<ModelDelta> deltas = new ArrayList<ModelDelta>(); // // // check all patterns affected! // for (PQuery maybeModPattern : LookaheadMatcherTreat.RelativeSet.get(clazz)) // { // // this lookvariable should be ---> this object (the matcher will bind it) // HashMap<PVariable, Object> knownLocalAndParameters = new HashMap<PVariable, Object>(); // // // get cached pattern structures // ArrayList<AheadStructure> cachedStructures = LookaheadMatcherTreat.GodSetStructures.get(maybeModPattern); // for (AheadStructure aSn : cachedStructures) // { // // find all typeConstraints (eclass affected!) // for (AxisConstraint tC : aSn.SearchedConstraints) // { // if (tC instanceof TypeConstraint) // { // if (((TypeConstraint) tC).getType().equals(clazz)) // { // // affected typeconstraint's lookvariable should be bound!! // knownLocalAndParameters.put(((TypeConstraint) tC).getTypedVariable(), instance); // } // } // } // } // isModified = false; // ArrayList<AheadStructure> newStructs = createNewFromOldTypeC(true, clazz, instance, cachedStructures); // if (isModified == false) // continue; // // the new matches that'll appear in matching // MultiSet<LookaheadMatching> newbies = lookaheadMatcher.searchChangesAll(treat.getIncQueryEngine(), maybeModPattern, (ArrayList<AheadStructure>)newStructs.clone(), knownLocalAndParameters, null); // // // a new map to store a matching and whether it is added or removed // HashMultimap<LookaheadMatching, Boolean> newMatchingsAndAddition = HashMultimap.create(); // // // iterate over multiset and create delta // for (Entry<LookaheadMatching, Integer> inners : newbies.getInnerMap().entrySet()) // { // for (int pi = 0; pi < inners.getValue(); pi++) // newMatchingsAndAddition.put(inners.getKey(), true); // the count in multiset (more of tha same found: more changes) // } // // delta needed to propagate the changes // if (newMatchingsAndAddition.size()>0) // { // ModelDelta d = new ModelDelta(maybeModPattern, newMatchingsAndAddition); // deltas.add(d); // } // } // // apply deltas (depth apply!) // for (ModelDelta delta : deltas) // { // AdvancedDeltaProcessor.getInstance().ReceiveDelta(delta); // } // AdvancedDeltaProcessor.getInstance().ProcessReceivedDeltaSet(); // // match based on the new structs! // System.out.println("[ECLASS] Update matchings finished! Time:" + Long.toString(System.currentTimeMillis() - start)); } @Override public void instanceDeleted(EClass clazz, EObject instance) { System.out.println("[Instance] deleted!"); modelChanges.add(new EClassChange(clazz, instance, false)); // // // // // InstanceDelta instRemov = new InstanceDelta(clazz, instance, false); // System.out.println("[ECLASS] Delete affected patterns' matchings if class instance used in them started!"); // long start = System.currentTimeMillis(); // // // changes: // ArrayList<ModelDelta> deltas = new ArrayList<ModelDelta>(); // // for (PQuery maybeModPattern : LookaheadMatcherTreat.RelativeSet.get(clazz)) // { // // this lookvariable should be ---> this object (the matcher will bind it) // HashMap<PVariable, Object> knownLocalAndParameters = new HashMap<PVariable, Object>(); // // isModified = false; // ArrayList<AheadStructure> cachedStructures = LookaheadMatcherTreat.GodSetStructures.get(maybeModPattern); // for (AheadStructure aSn : cachedStructures) // { // // find all typeConstraints (eclass affected!) // for (AxisConstraint tC : aSn.SearchedConstraints) // { // if (tC instanceof TypeConstraint) // { // if (((TypeConstraint) tC).getType().equals(clazz)) // { // // affected typeconstraint's lookvariable should be bound!! // knownLocalAndParameters.put(((TypeConstraint) tC).getTypedVariable(), instance); // } // } // } // } // // isModified = false; // ArrayList<AheadStructure> newStructs = createNewFromOldTypeC(true, clazz, instance, LookaheadMatcherTreat.GodSetStructures.get(maybeModPattern)); // if (isModified) // { // // the new matches that'll appear in matching // MultiSet<LookaheadMatching> newbies_todelete = lookaheadMatcher.searchChangesAll(treat.getIncQueryEngine(), maybeModPattern, newStructs, knownLocalAndParameters, null); // // // a new map to store a matching and whether it is added or removed // HashMultimap<LookaheadMatching, Boolean> newMatchingsAndRemoval = HashMultimap.create(); // // // iterate over multiset and create delta // for (Entry<LookaheadMatching, Integer> inners : newbies_todelete.getInnerMap().entrySet()) // { // for (int pi = 0; pi < inners.getValue(); pi++) // newMatchingsAndRemoval.put(inners.getKey(), false); // the count in multiset (more of tha same found: more changes), false: deleted!! // } // // delta needed to propagate the changes // if (newMatchingsAndRemoval.size()>0) // { // ModelDelta d = new ModelDelta(maybeModPattern, newMatchingsAndRemoval); // deltas.add(d); // } // } // } // // // apply deltas (depth apply!) // for (ModelDelta delta : deltas) // { // AdvancedDeltaProcessor.getInstance().ReceiveDelta(delta); // } // AdvancedDeltaProcessor.getInstance().ProcessReceivedDeltaSet(); // // System.out.println("[ECLASS] Delete affected patterns' matchings ended! Time:" + Long.toString(System.currentTimeMillis() - start)); } }; // listens to datatype changes, works as the instancelistener, but uses relation structure update (matches relations by hand before matching) public DataTypeListener dataTypeListener = new DataTypeListener() { @Override public void dataTypeInstanceInserted(EDataType type, Object instance, boolean firstOccurrence) { System.out.println("[EDataType] inserted!"); modelChanges.add(new EDataTypeChange(type, instance, true)); // DatatypeDelta dataInser = new DatatypeDelta(type, instance, true); // System.out.println("[EDATATYPE] Update affected patterns' matchings started!"); // long start = System.currentTimeMillis(); // // // changes: // ArrayList<ModelDelta> deltas = new ArrayList<ModelDelta>(); // // for (PQuery maybeModPattern : LookaheadMatcherTreat.RelativeSet.get(type)) // { // // this lookvariable should be ---> this object (the matcher will bind it) // HashMap<PVariable, Object> knownLocalAndParameters = new HashMap<PVariable, Object>(); // // isModified = false; // ArrayList<AheadStructure> cachedStructures = LookaheadMatcherTreat.GodSetStructures.get(maybeModPattern); // for (AheadStructure aSn : cachedStructures) // { // // find all typeConstraints (eclass affected!) // for (AxisConstraint tC : aSn.SearchedConstraints) // { // if (tC instanceof TypeConstraint) // { // if (((TypeConstraint) tC).getType().equals(type)) // { // // affected typeconstraint's lookvariable should be bound!! // knownLocalAndParameters.put(((TypeConstraint) tC).getTypedVariable(), instance); // } // } // } // } // isModified = false; // ArrayList<AheadStructure> newStructs = createNewFromOldTypeC(true, type, instance, cachedStructures); // // the new matches that'll appear in matching // if (isModified == false) // continue; // // MultiSet<LookaheadMatching> newbies_toadd = lookaheadMatcher.searchChangesAll(treat.getIncQueryEngine(), maybeModPattern, (ArrayList<AheadStructure>)newStructs.clone(), knownLocalAndParameters, null); // // // a new map to store a matching and whether it is added or removed // HashMultimap<LookaheadMatching, Boolean> newMatchingsAndAddition = HashMultimap.create(); // // // iterate over multiset and create delta // for (Entry<LookaheadMatching, Integer> inners : newbies_toadd.getInnerMap().entrySet()) // { // for (int pi = 0; pi < inners.getValue(); pi++) // newMatchingsAndAddition.put(inners.getKey(), true); // the count in multiset (more of tha same found: more changes) // } // // delta needed to propagate the changes // if (newMatchingsAndAddition.size()>0) // { // ModelDelta d = new ModelDelta(maybeModPattern, newMatchingsAndAddition); // deltas.add(d); // } // } // // for (ModelDelta delta : deltas) // { // AdvancedDeltaProcessor.getInstance().ReceiveDelta(delta); // } // AdvancedDeltaProcessor.getInstance().ProcessReceivedDeltaSet(); // // // match based on the new structs! // System.out.println("[EDATATYPE] Update matchings finished! Time:" + Long.toString(System.currentTimeMillis() - start)); } @Override public void dataTypeInstanceDeleted(EDataType type, Object instance, boolean firstOccurrence) { System.out.println("[EDataType] deleted!"); modelChanges.add(new EDataTypeChange(type, instance, false)); // // changes: // ArrayList<ModelDelta> deltas = new ArrayList<ModelDelta>(); // // // DatatypeDelta dataDelete = new DatatypeDelta(type, instance, false); // System.out.println("[EDATATYPE] Delete affected patterns' matchings if class instance used in them started!"); // long start = System.currentTimeMillis(); // // for (PQuery maybeModPattern : LookaheadMatcherTreat.RelativeSet.get(type)) // { // HashMap<PVariable, Object> knownLocalAndParameters = new HashMap<PVariable, Object>(); // // isModified = false; // ArrayList<AheadStructure> cachedStructures = LookaheadMatcherTreat.GodSetStructures.get(maybeModPattern); // for (AheadStructure aSn : cachedStructures) // { // // find all typeConstraints (eclass affected!) // for (AxisConstraint tC : aSn.SearchedConstraints) // { // if (tC instanceof TypeConstraint) // { // if (((TypeConstraint) tC).getType().equals(type)) // { // // affected typeconstraint's lookvariable should be bound!! // knownLocalAndParameters.put(((TypeConstraint) tC).getTypedVariable(), instance); // } // } // } // } // // ArrayList<AheadStructure> newStructs = createNewFromOldTypeC(false, type, instance, LookaheadMatcherTreat.GodSetStructures.get(maybeModPattern)); // if (isModified) // { // // the new matches that'll appear in matching // MultiSet<LookaheadMatching> newbies_todelete = lookaheadMatcher.searchChangesAll(treat.getIncQueryEngine(), maybeModPattern, newStructs, knownLocalAndParameters, null); // // // a new map to store a matching and whether it is added or removed // HashMultimap<LookaheadMatching, Boolean> newMatchingsAndRemoval = HashMultimap.create(); // // // iterate over multiset and create delta // for (Entry<LookaheadMatching, Integer> inners : newbies_todelete.getInnerMap().entrySet()) // { // for (int pi = 0; pi < inners.getValue(); pi++) // newMatchingsAndRemoval.put(inners.getKey(), false); // the count in multiset (more of tha same found: more changes), false: deleted!! // } // // delta needed to propagate the changes // if (newMatchingsAndRemoval.size()>0) // { // ModelDelta d = new ModelDelta(maybeModPattern, newMatchingsAndRemoval); // deltas.add(d); // } // } // } // // for (ModelDelta delta : deltas) // { // AdvancedDeltaProcessor.getInstance().ReceiveDelta(delta); // } // AdvancedDeltaProcessor.getInstance().ProcessReceivedDeltaSet(); // // System.out.println("[EDATATYPE] Delete affected patterns' matchings ended! Time:" + Long.toString(System.currentTimeMillis() - start)); } }; // listens to structuralfeature changes, uses relation modification, others are like instancelistener) public FeatureListener featureListener = new FeatureListener() { @Override public void featureInserted(EObject host, EStructuralFeature feature, Object value) { // System.out.println("[Feature] inserted!"); modelChanges.add(new EFeatureChange(host, feature, value, true)); // // // // Delta featureInser = new FeatureDelta(feature, host, true, value); // System.out.println("[ESTRUCTURALFEATURE] Update affected patterns' matchings started!"); // long start = System.currentTimeMillis(); // // changes: // ArrayList<ModelDelta> deltas = new ArrayList<ModelDelta>(); // // for (PQuery maybeModPattern : LookaheadMatcherTreat.RelativeSet.get(feature)) // { // // this lookvariable should be ---> this object (the matcher will bind it) // HashMap<PVariable, Object> knownLocalAndParameters = new HashMap<PVariable, Object>(); // // isModified = false; // ArrayList<AheadStructure> cachedStructures = LookaheadMatcherTreat.GodSetStructures.get(maybeModPattern); // for (AheadStructure aSn : cachedStructures) // { // // find all relationConstraints // for (AxisConstraint rC : aSn.SearchedConstraints) // { // if (rC instanceof RelationConstraint) // { // if (((RelationConstraint) rC).getEdge().equals(feature)) // { // // affected relaconstraint's lookvariables should be bound!! // knownLocalAndParameters.put(((RelationConstraint) rC).getSource(), host); // knownLocalAndParameters.put(((RelationConstraint) rC).getTarget(), value); // } // } // } // } // // isModified = false; // // manual satisfy: // ArrayList<AheadStructure> newStructs = createNewFromOldRelaC(host, value, feature, LookaheadMatcherTreat.GodSetStructures.get(maybeModPattern)); // if (isModified == false) // continue; // // the new matches that'll appear in matching // MultiSet<LookaheadMatching> newbies_toadd = lookaheadMatcher.searchChangesAll(treat.getIncQueryEngine(), maybeModPattern, newStructs, knownLocalAndParameters, null); // // // a new map to store a matching and whether it is added or removed // HashMultimap<LookaheadMatching, Boolean> newMatchingsAndAddition = HashMultimap.create(); // // // iterate over multiset and create delta // for (Entry<LookaheadMatching, Integer> inners : newbies_toadd.getInnerMap().entrySet()) // { // for (int pi = 0; pi < inners.getValue(); pi++) // newMatchingsAndAddition.put(inners.getKey(), true); // the count in multiset (more of tha same found: more changes) // } // // delta needed to propagate the changes // if (newMatchingsAndAddition.size()>0) // { // ModelDelta d = new ModelDelta(maybeModPattern, newMatchingsAndAddition); // deltas.add(d); // } // } // // apply deltas // for (ModelDelta delta : deltas) // { // AdvancedDeltaProcessor.getInstance().ReceiveDelta(delta); // } // AdvancedDeltaProcessor.getInstance().ProcessReceivedDeltaSet(); // // System.out.println("[ESTRUCTURALFEATURE] Update matchings finished! Time:" + Long.toString(System.currentTimeMillis() - start)); } @Override public void featureDeleted(EObject host, EStructuralFeature feature, Object value) { //System.out.println("[Feature] deleted!"); modelChanges.add(new EFeatureChange(host, feature, value, false)); // // // Delta featureDeleted = new FeatureDelta(feature, host, false, value); // System.out.println("[ESTRUCTURALFEATURE] Delete affected patterns' matchings if class instance used in them started!"); // long start = System.currentTimeMillis(); // // // changes: // ArrayList<ModelDelta> deltas = new ArrayList<ModelDelta>(); // // for (PQuery maybeModPattern : LookaheadMatcherTreat.RelativeSet.get(feature)) // { // // this lookvariable should be ---> this object (the matcher will bind it) // HashMap<PVariable, Object> knownLocalAndParameters = new HashMap<PVariable, Object>(); // // isModified = false; // ArrayList<AheadStructure> cachedStructures = LookaheadMatcherTreat.GodSetStructures.get(maybeModPattern); // for (AheadStructure aSn : cachedStructures) // { // // find all relationConstraints // for (AxisConstraint rC : aSn.SearchedConstraints) // { // if (rC instanceof RelationConstraint) // { // if (((RelationConstraint) rC).getEdge().equals(feature)) // { // // affected relaconstraint's lookvariables should be bound!! // knownLocalAndParameters.put(((RelationConstraint) rC).getSource(), host); // knownLocalAndParameters.put(((RelationConstraint) rC).getTarget(), value); // } // } // } // } // // isModified = false; // // manual satisfy: // ArrayList<AheadStructure> newStructs = createNewFromOldRelaC(host, value, feature, LookaheadMatcherTreat.GodSetStructures.get(maybeModPattern)); // if (isModified) // { // // the new matches that'll appear in matching based on manually satisfied structure // MultiSet<LookaheadMatching> newbies_toremove = lookaheadMatcher.searchChangesAll(treat.getIncQueryEngine(), maybeModPattern, newStructs, knownLocalAndParameters, null); // // // a new map to store a matching and whether it is added or removed // HashMultimap<LookaheadMatching, Boolean> newMatchingsAndRemoval = HashMultimap.create(); // // // iterate over multiset and create delta // for (Entry<LookaheadMatching, Integer> inners : newbies_toremove.getInnerMap().entrySet()) // { // for (int pi = 0; pi < inners.getValue(); pi++) // newMatchingsAndRemoval.put(inners.getKey(), false); // the count in multiset (more of the same found: more changes) // } // // delta needed to propagate the changes // if (newMatchingsAndRemoval.size()>0) // { // ModelDelta d = new ModelDelta(maybeModPattern, newMatchingsAndRemoval); // deltas.add(d); // } // } // } // // apply deltas // for (ModelDelta delta : deltas) // { // AdvancedDeltaProcessor.getInstance().ReceiveDelta(delta); // } // AdvancedDeltaProcessor.getInstance().ProcessReceivedDeltaSet(); // // System.out.println("[ESTRUCTURALFEATURE] Delete affected patterns' matchings ended! Time:" + Long.toString(System.currentTimeMillis() - start)); // } }; private List<ModelChange> modelChanges = new ArrayList<ModelChange>(); public void MagicProcessor() { if (modelChanges == null) { modelChanges = new ArrayList<ModelChange>(); return; } else if (modelChanges.size() == 0) return; // else go! // gets all model deltas and processes! //System.out.println("[MAGIC] Update match set based on model change started..."); long start = System.currentTimeMillis(); Set<PQuery> affecteds = new HashSet<PQuery>(); for (ModelChange change : modelChanges) { if (change instanceof EFeatureChange) affecteds.addAll(LookaheadMatcherTreat.RelativeSet.get(((EFeatureChange) change).getChangedFeature())); if (change instanceof EClassChange) affecteds.addAll(LookaheadMatcherTreat.RelativeSet.get(((EClassChange) change).getChange())); if (change instanceof EDataTypeChange) affecteds.addAll(LookaheadMatcherTreat.RelativeSet.get(((EDataTypeChange) change).getChange())); } ArrayList<ModelDelta> deltas = new ArrayList<ModelDelta>(); for (PQuery affectedQuery : affecteds) { ArrayList<AheadStructure> cachedStructures = LookaheadMatcherTreat.GodSetStructures.get(affectedQuery); // deliver deltas for pattern! for (ModelChange change : modelChanges) { for (AheadStructure aSn : cachedStructures) { for (AxisConstraint rC : aSn.SearchedConstraints) { if (rC instanceof RelationConstraint && change instanceof EFeatureChange) { EFeatureChange changenow = (EFeatureChange) change; if (((RelationConstraint) rC).getEdge().equals(changenow.getChangedFeature())) rC.putToMailbox(change); } else if (rC instanceof TypeConstraint && change instanceof EDataTypeChange) { EDataTypeChange changenow = (EDataTypeChange) change; if (((TypeConstraint) rC).getType().equals(changenow.getChange())) rC.putToMailbox(change); } if (rC instanceof TypeConstraint && change instanceof EClassChange) { EClassChange changenow = (EClassChange) change; if (((TypeConstraint) rC).getType().equals(changenow.getChange())) rC.putToMailbox(change); } } } } for (ModelChange change : modelChanges) { // process this change: first remove all deltas from constraints with this change for (AheadStructure aSn : cachedStructures) { for (AxisConstraint rC : aSn.SearchedConstraints) { if (rC.hasMailboxContent()) { if (rC.getMailboxContent().contains(change)) rC.removeFromMailbox(change); } } } // apply modelchange: HashMap<PVariable, Object> knownLocalAndParameters = new HashMap<PVariable, Object>(); for (AheadStructure aSn : cachedStructures) { // find all relationConstraints for (AxisConstraint rC : aSn.SearchedConstraints) { if (rC instanceof RelationConstraint && change instanceof EFeatureChange) { EFeatureChange changenow = (EFeatureChange) change; if (((RelationConstraint) rC).getEdge().equals(changenow.getChangedFeature())) { // affected relaconstraint's lookvariables should be bound!! knownLocalAndParameters.put(((RelationConstraint) rC).getSource(), changenow.getHost()); knownLocalAndParameters.put(((RelationConstraint) rC).getTarget(), changenow.getInstance()); } } else if (rC instanceof TypeConstraint && change instanceof EDataTypeChange) { EDataTypeChange changenow = (EDataTypeChange) change; if (((TypeConstraint) rC).getType().equals(changenow.getChange())) { // affected typeconstraint's lookvariable should be bound!! knownLocalAndParameters.put(((TypeConstraint) rC).getTypedVariable(), changenow.getInstance()); } } if (rC instanceof TypeConstraint && change instanceof EClassChange) { EClassChange changenow = (EClassChange) change; if (((TypeConstraint) rC).getType().equals(changenow.getChange())) { // affected typeconstraint's lookvariable should be bound!! knownLocalAndParameters.put(((TypeConstraint) rC).getTypedVariable(), changenow.getInstance()); } } } } // manual satisfy and clone cachedStructures (createNew* clones input): ArrayList<AheadStructure> newStructs = null; isModified = false; if ( change instanceof EFeatureChange) { EFeatureChange changenow = (EFeatureChange) change; newStructs = createNewFromOldRelaC(changenow.getHost(), changenow.getInstance(), changenow.getChangedFeature(), cachedStructures); } else if (change instanceof EDataTypeChange) { EDataTypeChange changenow = (EDataTypeChange) change; newStructs = createNewFromOldTypeC(false, changenow.getChange(), changenow.getInstance(), cachedStructures); } if (change instanceof EClassChange) { EClassChange changenow = (EClassChange) change; newStructs = createNewFromOldTypeC(false, changenow.getChange(), changenow.getInstance(), cachedStructures); } if (isModified) { // the new matches that'll appear in matching based on manually satisfied structure Multiset<LookaheadMatching> newbies_toExamine = (new LookaheadMatcherInterface(this.navHelper)).searchChangesAll(treat.getIncQueryEngine(), affectedQuery, newStructs, knownLocalAndParameters, new TreatConstraintEnumerator(this.navHelper)); // a new map to store a matching and whether it is added or removed HashMultimap<LookaheadMatching, Boolean> newMatchingsAndChange = HashMultimap.create(); // iterate over multiset and create delta for (com.google.common.collect.Multiset.Entry<LookaheadMatching> inners : newbies_toExamine.entrySet()) { for (int pi = 0; pi < inners.getCount(); pi++) newMatchingsAndChange.put(inners.getElement(), change.isAddition()); } // delta needed to propagate the changes if (newMatchingsAndChange.size() > 0) { ModelDelta d = new ModelDelta(affectedQuery, newMatchingsAndChange); deltas.add(d); } } } } // apply deltas for (ModelDelta delta : deltas) { //System.out.println("Propagate a delta: " + delta.getPattern().getFullyQualifiedName()); AdvancedDeltaProcessor.getInstance().ReceiveDelta(delta); } AdvancedDeltaProcessor.getInstance().ProcessReceivedDeltaSet(); //System.out.println("[MAGIC] Update match set based on model change ended! Time:" + Long.toString(System.currentTimeMillis() - start)); // finally: modelChanges = new ArrayList<ModelChange>(); } // modifies the aheadstructures according to eclass change - matches the constraint by hand (found, not searched, matchingvariables put) private ArrayList<AheadStructure> createNewFromOldTypeC(boolean isEClass, EClassifier clazzortype, Object instance, ArrayList<AheadStructure> gotStructs) { ArrayList<AheadStructure> newStructs = new ArrayList<AheadStructure>(); for (AheadStructure aSn : gotStructs) { AheadStructure newaSn = aSn.clone(); for (AxisConstraint tC : newaSn.SearchedConstraints) { if (tC instanceof TypeConstraint) { if (((TypeConstraint) tC).getType().equals(clazzortype)) { newaSn.FoundConstraints.add(tC); newaSn.SearchedConstraints.remove(tC); isModified = true; break; } } } newStructs.add(newaSn); } return newStructs; } // modifies the aheadstructures according to estructuralfeature change - matches the constraint by hand (found, not searched, matchingvariables put) private ArrayList<AheadStructure> createNewFromOldRelaC(EObject host, Object target, EStructuralFeature edge, ArrayList<AheadStructure> gotStructs) { ArrayList<AheadStructure> newStructs = new ArrayList<AheadStructure>(); for (AheadStructure aSn : gotStructs) { AheadStructure newaSn = aSn.clone(); for (AxisConstraint rC : newaSn.SearchedConstraints) { if (rC instanceof RelationConstraint) { if (((RelationConstraint) rC).getEdge().equals(edge)) { // and make constraint "found" newaSn.FoundConstraints.add(rC); newaSn.SearchedConstraints.remove(rC); isModified = true; break; } } } newStructs.add(newaSn); } return newStructs; } }
mit
amironov73/ManagedIrbis
Source/Classic/Libs/ManagedIrbis/Source/Systematization/UdkException.cs
1428
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* UdkException.cs -- исключение, возникающее при работе с УДК * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using JetBrains.Annotations; #endregion namespace ManagedIrbis.Systematization { /// <summary> /// Исключение, возникающее при работе с УДК. /// </summary> [PublicAPI] public sealed class UdkException : IrbisException { #region Construciton /// <summary> /// Конструктор. /// </summary> public UdkException() { } #endregion /// <summary> /// Конструктор. /// </summary> public UdkException ( [CanBeNull] string message ) : base(message) { } /// <summary> /// Конструктор. /// </summary> public UdkException ( [CanBeNull] string message, [CanBeNull] Exception innerException ) : base(message, innerException) { } } }
mit
joeyfromspace/hdtracks-backend-keystone
models/ShoppingCartItem.js
1006
var keystone = require('keystone'), Types = keystone.Field.Types; /** * ShoppingCartItem Model */ var ShoppingCartItem = new keystone.List('ShoppingCartItem', { track: true, defaultSort: '-updatedAt' }); /** * ShoppingCartItem Schema */ ShoppingCartItem.add({ product: { type: Types.Relationship, ref: 'Product' }, format: { type: Types.Relationship, ref: 'DownloadFormat'}, description: { type: Types.Text }, quantity: { type: Types.Number, 'default': 1, required: true }, price: { type: Types.Money, format: false, 'default': 0, required: true }, discount: { type: Types.Money, format: false, 'default': 0, required: true }, rowTotal: { type: Types.Money, format: false, 'default': 0, required: true }, link: { type: Types.Url } }); /** * Virtuals */ /** * Methods */ ShoppingCartItem.schema.pre('save', function(next) { this.rowTotal = (this.price - this.discount) * this.quantity; return next(); }); /** * Relationships */ ShoppingCartItem.register();
mit
jclif/serinette
lib/serinette/utils.rb
115
require_relative 'utils/file_name' require_relative 'utils/sox_wrapper' module Serinette module Utils end end
mit
danliris/dl-models
src/production/finishing-printing/kanban-validator.js
2367
require("should"); // var validateProductionOrder = require('../../sales/production-order-validator'); // var validateProductionOrderDetail = require('../../sales/production-order-detail-validator'); // var validateCart = require('./cart-validator'); // var validateInstruction = require('../../master/instruction-validator'); module.exports = function(data) { data.should.not.equal(null); data.should.instanceOf(Object); data.should.have.property('code'); data.code.should.instanceof(String); data.should.have.property('productionOrderId'); data.productionOrderId.should.instanceOf(Object); data.should.have.property('productionOrder'); data.productionOrder.should.instanceOf(Object); // validateProductionOrder(data.productionOrder); data.should.have.property('selectedProductionOrderDetail'); data.selectedProductionOrderDetail.should.instanceof(Object); // validateProductionOrderDetail(data.selectedProductionOrderDetail); data.should.have.property('cart'); data.cart.should.instanceof(Object); // validateCart(data.cart); data.should.have.property('instructionId'); data.instructionId.should.instanceOf(Object); data.should.have.property('instruction'); data.instruction.should.instanceof(Object); // validateInstruction(data.instruction); data.should.have.property('grade'); data.grade.should.instanceof(String); data.should.have.property('isComplete'); data.isComplete.should.instanceof(Boolean); data.should.have.property('currentStepIndex'); data.currentStepIndex.should.instanceof(Number); data.should.have.property('currentQty'); data.currentQty.should.instanceof(Number); data.should.have.property('goodOutput'); data.goodOutput.should.instanceof(Number); data.should.have.property('badOutput'); data.badOutput.should.instanceof(Number); data.should.have.property('oldKanbanId'); data.oldKanbanId.should.instanceof(Object); data.should.have.property('oldKanban'); data.oldKanban.should.instanceof(Object); data.should.have.property('isBadOutput'); data.isBadOutput.should.instanceof(Boolean); data.should.have.property('isReprocess'); data.isReprocess.should.instanceof(Boolean); data.should.have.property('isInactive'); data.isInactive.should.instanceof(Boolean); };
mit
enettolima/magento-training
magento2ce/app/code/Magento/SalesRule/view/frontend/web/js/action/cancel-coupon.js
1931
/** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ /** * Customer store credit(balance) application */ /*global define,alert*/ define( [ 'jquery', 'Magento_Checkout/js/model/quote', 'Magento_Checkout/js/model/resource-url-manager', 'Magento_Checkout/js/model/error-processor', 'Magento_SalesRule/js/model/payment/discount-messages', 'mage/storage', 'Magento_Checkout/js/action/get-payment-information', 'Magento_Checkout/js/model/totals', 'mage/translate' ], function ($, quote, urlManager, errorProcessor, messageContainer, storage, getPaymentInformationAction, totals, $t) { 'use strict'; return function (isApplied, isLoading) { var quoteId = quote.getQuoteId(), url = urlManager.getCancelCouponUrl(quoteId), message = $t('Your coupon was successfully removed.'); messageContainer.clear(); return storage.delete( url, false ).done( function () { var deferred = $.Deferred(); totals.isLoading(true); getPaymentInformationAction(deferred); $.when(deferred).done(function () { isApplied(false); totals.isLoading(false); }); messageContainer.addSuccessMessage({ 'message': message }); } ).fail( function (response) { totals.isLoading(false); errorProcessor.process(response, messageContainer); } ).always( function () { isLoading(false); } ); }; } );
mit
HoistRnD/azure-web-server
test/testSetup.js
150
/*jshint sub:true*/ 'use strict'; process.env['NODE_ENV'] = 'test'; var chai = require('chai'); chai.use(require('chai-as-promised')); chai.should();
mit
monicajimenez/weas
resources/views/request/modal_rfc_request_reference.blade.php
2271
<div id="modal_rfc_request_reference" class="modal"> <div class="modal-content"> <h5>Reference Number (RFC):</h5> <select id="rfc_request_reference"> <option value="" disabled selected>Choose your option</option> @foreach($granted_request_types as $request_type) <option value="{{$request_type->req_code}}.{{$request_type->project_no}}.{{$request_type->req_desc}}"> {{$request_type->req_code}} - {{$request_type->req_desc}} - {{$request_type->project_no}} </option> @endforeach </select> <label>Project Name</label> <!-- Table of RFC Reference Numbers --> <div class="row"> <div class="col l10"> <table class="responsive-table" id="table_rfc_request_reference"> <thead class=""> <tr> <th data-field="rfc_request_reference_code" class="index center-align"> RFC Reference Code </th> <th data-field="rfc_request_reference_owners_name" class="center-align"> Owner's Name </th> <th data-field="rfc_request_reference_lot_code" class="center-align"> Lot Code </th> <th data-field="rfc_request_reference_add" class="center-align"> Add </th> </tr> </thead> <tbody class="center-align"> </tbody> </table> </div> </div> <!-- End: Table of RFC Reference Numbers --> <div class="row"> <div class="col l10 center"> <div class="preloader-wrapper big active"> <div class="spinner-layer spinner-blue-only"> <div class="circle-clipper left"> <div class="circle"></div> </div> <div class="gap-patch"> <div class="circle"></div> </div> <div class="circle-clipper right"> <div class="circle"></div> </div> </div> </div> </div> </div> <div class="align-right"> <a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat">Back</a> </div> </div> </div>
mit
InteractiveIntelligence/HackathonIVRExamples
DotNetIvr/DotNetIvrService/Actions/PlayActionResponse.cs
321
using System.Runtime.Serialization; namespace ININ.Alliances.DotNetIvr.Actions { [DataContract] public class PlayActionResponse : ActionResponse { [DataMember] public string action {get { return "play"; } set{}} [DataMember] public string message { get; set; } } }
mit
DebOM/DebOM.github.io
js/init-particles.js
2525
particlesJS('particles', { "particles": { "number": { "value": 50, "density": { "enable": true, "value_area": 800 } }, "color": { "value": "#ffffff" }, "shape": { "type": "circle", "stroke": { "width": 0, "color": "#000000" }, "polygon": { "nb_sides": 5 }, "image": { "src": "img/github.svg", "width": 100, "height": 100 } }, "opacity": { "value": 0.5, "random": false, "anim": { "enable": false, "speed": 1.5, "opacity_min": 0.1, "sync": false } }, "size": { "value": 3, "random": true, "anim": { "enable": false, "speed": 40, "size_min": 0.1, "sync": false } }, "line_linked": { "enable": true, "distance": 150, "color": "#ffffff", "opacity": 0.4, "width": 1 }, "move": { "enable": true, "speed": 6, "direction": "none", "random": false, "straight": false, "out_mode": "out", "attract": { "enable": false, "rotateX": 600, "rotateY": 1200 } } }, "interactivity": { "detect_on": "canvas", "events": { "onhover": { "enable": true, "mode": "repulse" }, "onclick": { "enable": false, "mode": "push" }, "resize": true }, "modes": { "grab": { "distance": 400, "line_linked": { "opacity": 1 } }, "bubble": { "distance": 400, "size": 40, "duration": 2, "opacity": 8, "speed": 3 }, "repulse": { "distance": 200 }, "push": { "particles_nb": 4 }, "remove": { "particles_nb": 2 } } }, "retina_detect": true, "config_demo": { "hide_card": false, "background_color": "#b61924", "background_image": "", "background_position": "50% 50%", "background_repeat": "no-repeat", "background_size": "cover" } } );
mit
cubeme/ssharp
Tests/Diagnostics/FaultEffects/Invalid/non-public nested.cs
2074
// The MIT License (MIT) // // Copyright (c) 2014-2016, Institute for Software & Systems Engineering // // 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. namespace Tests.Diagnostics.FaultEffects.Invalid { using SafetySharp.Compiler.Analyzers; using SafetySharp.Modeling; [Diagnostic(DiagnosticIdentifier.FaultEffectAccessibility, 35, 23, 2, "Tests.Diagnostics.FaultEffects.Invalid.Nested2.E1")] [Diagnostic(DiagnosticIdentifier.FaultEffectAccessibility, 40, 25, 2, "Tests.Diagnostics.FaultEffects.Invalid.Nested2.E2")] [Diagnostic(DiagnosticIdentifier.FaultEffectAccessibility, 45, 34, 2, "Tests.Diagnostics.FaultEffects.Invalid.Nested2.E3")] [Diagnostic(DiagnosticIdentifier.FaultEffectAccessibility, 50, 24, 2, "Tests.Diagnostics.FaultEffects.Invalid.Nested2.E4")] public class Nested2 : Component { [FaultEffect] private class E1 : Nested2 { } [FaultEffect] protected class E2 : Nested2 { } [FaultEffect] protected internal class E3 : Nested2 { } [FaultEffect] internal class E4 : Nested2 { } } }
mit
cloudmodel/cloudmodel
spec/dummy/config/application.rb
2085
require_relative "boot" require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" # require "active_record/railtie" # require "active_storage/engine" require "action_controller/railtie" require "action_mailer/railtie" # require "action_mailbox/engine" # require "action_text/engine" require "action_view/railtie" # require "action_cable/engine" require "sprockets/railtie" require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Dummy class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.1 # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de config.generators do |g| g.orm :mongoid g.template_engine false g.javascript_engine false g.stylesheet_engine false g.test_framework :rspec g.integration_tool false g.fixture_replacement false g.helper false end end end
mit
BAM-X/Flask-seed
app/config.py
406
import os class LocalConfig(object): ENV = 'local' DATABASE_URI = 'file:app.db' DEBUG = True class TestConfig(object): ENV = 'test' DATABASE_URI = 'file::memory:?cache=shared' DEBUG = True CONFIGS = { 'local': LocalConfig, 'test': TestConfig, } def get_config(env): return CONFIGS.get(env) def get_current_config(): return get_config(os.environ['APP_ENV'])
mit
ftrader-bitcoinabc/bitcoin-abc
test/functional/interface_bitcoin_cli.py
4596
#!/usr/bin/env python3 # Copyright (c) 2017-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoin-cli""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_raises_process_error, get_auth_cookie, ) class TestBitcoinCli(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): """Main test logic""" cli_response = self.nodes[0].cli("-version").send_cli() assert "Bitcoin ABC RPC client version" in cli_response self.log.info( "Compare responses from gewalletinfo RPC and `bitcoin-cli getwalletinfo`") cli_response = self.nodes[0].cli.getwalletinfo() rpc_response = self.nodes[0].getwalletinfo() assert_equal(cli_response, rpc_response) self.log.info( "Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`") cli_response = self.nodes[0].cli.getblockchaininfo() rpc_response = self.nodes[0].getblockchaininfo() assert_equal(cli_response, rpc_response) user, password = get_auth_cookie(self.nodes[0].datadir) self.log.info("Test -stdinrpcpass option") assert_equal(0, self.nodes[0].cli( '-rpcuser={}'.format(user), '-stdinrpcpass', input=password).getblockcount()) assert_raises_process_error(1, "Incorrect rpcuser or rpcpassword", self.nodes[0].cli( '-rpcuser={}'.format(user), '-stdinrpcpass', input="foo").echo) self.log.info("Test -stdin and -stdinrpcpass") assert_equal(["foo", "bar"], self.nodes[0].cli('-rpcuser={}'.format(user), '-stdin', '-stdinrpcpass', input=password + "\nfoo\nbar").echo()) assert_raises_process_error(1, "Incorrect rpcuser or rpcpassword", self.nodes[0].cli( '-rpcuser={}'.format(user), '-stdin', '-stdinrpcpass', input="foo").echo) self.log.info("Test connecting to a non-existing server") assert_raises_process_error( 1, "Could not connect to the server", self.nodes[0].cli('-rpcport=1').echo) self.log.info("Test connecting with non-existing RPC cookie file") assert_raises_process_error(1, "Could not locate RPC credentials", self.nodes[0].cli( '-rpccookiefile=does-not-exist', '-rpcpassword=').echo) self.log.info("Make sure that -getinfo with arguments fails") assert_raises_process_error( 1, "-getinfo takes no arguments", self.nodes[0].cli('-getinfo').help) self.log.info( "Compare responses from `bitcoin-cli -getinfo` and the RPCs data is retrieved from.") cli_get_info = self.nodes[0].cli('-getinfo').send_cli() wallet_info = self.nodes[0].getwalletinfo() network_info = self.nodes[0].getnetworkinfo() blockchain_info = self.nodes[0].getblockchaininfo() assert_equal(cli_get_info['version'], network_info['version']) assert_equal(cli_get_info['protocolversion'], network_info['protocolversion']) assert_equal(cli_get_info['walletversion'], wallet_info['walletversion']) assert_equal(cli_get_info['balance'], wallet_info['balance']) assert_equal(cli_get_info['blocks'], blockchain_info['blocks']) assert_equal(cli_get_info['timeoffset'], network_info['timeoffset']) assert_equal(cli_get_info['connections'], network_info['connections']) assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy']) assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty']) assert_equal(cli_get_info['testnet'], blockchain_info['chain'] == "test") assert_equal(cli_get_info['balance'], wallet_info['balance']) assert_equal(cli_get_info['keypoololdest'], wallet_info['keypoololdest']) assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize']) assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee']) assert_equal(cli_get_info['relayfee'], network_info['relayfee']) # unlocked_until is not tested because the wallet is not encrypted if __name__ == '__main__': TestBitcoinCli().main()
mit
blueskyfish/bicycle-manager-android
bicycle-manager/src/main/java/de/blueskyfish/bicycle/battery/BatteryListFragment.java
8893
/* * The MIT License (MIT) * Copyright (c) 2017 BlueSkyFish * * bicycle-manager-android - https://github.com/blueskyfish/bicycle-manager-android.git */ package de.blueskyfish.bicycle.battery; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cocosw.bottomsheet.BottomSheet; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.List; import de.blueskyfish.bicycle.BaseFragment; import de.blueskyfish.bicycle.FloatingButtonKind; import de.blueskyfish.bicycle.R; import de.blueskyfish.bicycle.helper.Delay; import de.blueskyfish.bicycle.helper.Formatter; import de.blueskyfish.bicycle.helper.Logger; import de.blueskyfish.bicycle.http.DiagnoseManager; import de.blueskyfish.bicycle.http.HttpManager; import de.blueskyfish.bicycle.http.StatusCheck; import de.blueskyfish.httpclient.HttpRequest; import de.blueskyfish.httpclient.HttpResponse; import de.blueskyfish.httpclient.PathBuilder; /** * A simple {@link BaseFragment} subclass. */ public class BatteryListFragment extends BaseFragment { private SwipeRefreshLayout mSwipeRefresh; private RecyclerView mBatteryList; private BatteryListAdapter mAdapter; private HttpManager mHttpManager; private ObjectMapper mMapper; private Formatter mFormatter; public BatteryListFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHttpManager = getBicycleApplication().getHttpManager(); mMapper = getBicycleApplication().getMapper(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_battery_list, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mBatteryList = (RecyclerView) view.findViewById(R.id.battery_list); mBatteryList.setHasFixedSize(true); // update the layout manager LinearLayoutManager linearManager = new LinearLayoutManager(getActivity()); linearManager.setOrientation(LinearLayoutManager.VERTICAL); mBatteryList.setLayoutManager(linearManager); mFormatter = getBicycleApplication().getFormatter(); mAdapter = new BatteryListAdapter(batteryItemClick, mFormatter); mBatteryList.setAdapter(mAdapter); mSwipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container); mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { doRefreshBatteryList(); } }); } @Override public void onResume() { super.onResume(); getMiddlewareHandler().changeFloatingButton(FloatingButtonKind.BATTERY, addBatteryListener); getMiddlewareHandler().post(new Runnable() { @Override public void run() { GetBatteryListRequest request = new GetBatteryListRequest(); request.execute("battery"); } }, Delay.START_REQUEST); } @Override public void onDetach() { super.onDetach(); mSwipeRefresh = null; mBatteryList = null; mAdapter = null; mHttpManager = null; mMapper = null; mFormatter = null; } private void doBatteryItemClick(final View view) { final int itemPosition = mBatteryList.getChildLayoutPosition(view); getMiddlewareHandler().post(new Runnable() { @Override public void run() { doShowButtonSheet(itemPosition); } }, Delay.START_BOTTOM_SHEET); } private void doShowButtonSheet(int itemPosition) { final BatteryItem item = mAdapter.getItem(itemPosition); new BottomSheet.Builder(getActivity(), R.style.AppTheme_Dialog_BottomSheet) .sheet(R.menu.menu_battery_list) .title(mFormatter.getBatteryTitle(item.getDate(), item.getDistance())) .grid() .listener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { doBatteryItemActionClick(which, item); } }) .show(); } private void doBatteryItemActionClick(int action, BatteryItem item) { Bundle args = new Bundle(); args.putInt(BatteryDefine.PARAM_BATTERY_ID, item.getId()); switch (action) { case R.id.action_detail: getMiddlewareHandler().onAction(R.string.fragment_battery_detail, args); break; case R.id.action_edit: getMiddlewareHandler().onAction(R.string.fragment_battery_edit, args); break; case R.id.action_delete: getMiddlewareHandler().onAction(R.string.fragment_battery_delete, args); break; } } private void doRefreshBatteryList() { mSwipeRefresh.setRefreshing(true); getMiddlewareHandler().post(new Runnable() { @Override public void run() { GetBatteryListRequest request = new GetBatteryListRequest(); request.execute("battery"); } }, Delay.START_REQUEST); } private final View.OnClickListener addBatteryListener = new View.OnClickListener() { @Override public void onClick(View v) { Bundle args = new Bundle(); args.putInt(BatteryDefine.PARAM_BATTERY_ID, 0); getMiddlewareHandler().onAction(R.string.fragment_battery_edit, args); } }; private final View.OnClickListener batteryItemClick = new View.OnClickListener() { @Override public void onClick(View view) { doBatteryItemClick(view); } }; /** * Starts and executes a request to get the battery list */ private class GetBatteryListRequest extends AsyncTask<Object, Void, List<BatteryItem>> { @Override protected List<BatteryItem> doInBackground(Object... params) { String url = PathBuilder.toUrl(params); HttpRequest request = HttpRequest.buildGET(url); HttpResponse response = mHttpManager.execute(request); int statusCode = response.getStatusCode(); if (response.hasError()) { Logger.debug("error result: %s", response.getContent()); showRequestError(statusCode); return EMPTY_LIST; } String content = response.getContent(); try { ResultBatteryList result = mMapper.readValue(content, ResultBatteryList.class); if (StatusCheck.isOkay(result)) { return result.getBatteryList(); } showRequestError(statusCode); } catch (IOException e) { getMiddlewareHandler() .makeSnackbar(R.string.battery_list_mapper_error) .show(); } finally { Logger.debug("request duration %s ms", response.getDuration()); } return EMPTY_LIST; } // The request for the battery elements has failed! private void showRequestError(int statusCode) { Logger.debug("The request for the battery elements has failed! (http status = %s)", statusCode); getMiddlewareHandler() .makeSnackbar(R.string.battery_list_request_error, R.string.battery_list_request_error_action, diagnoseListener) .show(); } @Override protected void onPostExecute(List<BatteryItem> items) { mAdapter.changeData(items); if (mSwipeRefresh.isRefreshing()) { mSwipeRefresh.setRefreshing(false); } } private final List<BatteryItem> EMPTY_LIST = new ArrayList<>(); } private final View.OnClickListener diagnoseListener = new View.OnClickListener() { @Override public void onClick(View v) { Bundle args = new Bundle(); args.putInt(DiagnoseManager.PARAM_FROM, 1); getMiddlewareHandler().onAction(R.string.fragment_diagnose, args); } }; }
mit
saturnflyer/casting
lib/casting/method_consolidator.rb
477
module Casting module MethodConsolidator def methods(all=true) (super + delegated_methods(all)).uniq end def public_methods(include_super=true) (super + delegated_public_methods(include_super)).uniq end def protected_methods(include_super=true) (super + delegated_protected_methods(include_super)).uniq end def private_methods(include_super=true) (super + delegated_private_methods(include_super)).uniq end end end
mit
jbranchaud/rails-routes-math
spec/requests/division_routes_spec.rb
959
require 'rails_helper' RSpec.describe "DivisionRoutes", :type => :request do it "should divide the two values" do visit "/3/by/3" expect(page).to have_content("1") end it "should divide a positive and negative value" do visit "/4/by/-2" expect(page).to have_content("-2") visit "/-4/by/2" expect(page).to have_content("-2") end it "should divide two negative values" do visit "/-10/by/-2" expect(page).to have_content("5") end it "should divide non-evenly-divisible values and round the result" do visit "/5/by/2" expect(page).to have_content("2") end it "should render a 400 Bad Request when the second value is zero" do visit "/4/by/0" expect(page.status_code).to eq(400) end it "should render a 400 Bad Request when a non-number value is given" do visit "/4/by/a" expect(page.status_code).to eq(400) visit "/a/by/4" expect(page.status_code).to eq(400) end end
mit
tangyiyang/v3quick-classic
quick/lib/lua_bindings/auto/api/Hide.lua
780
-------------------------------- -- @module Hide -- @extend ActionInstant -- @parent_module cc -------------------------------- -- Allocates and initializes the action -- @function [parent=#Hide] create -- @param self -- @return Hide#Hide ret (return value: cc.Hide) -------------------------------- -- -- @function [parent=#Hide] clone -- @param self -- @return Hide#Hide ret (return value: cc.Hide) -------------------------------- -- -- @function [parent=#Hide] update -- @param self -- @param #float time -- @return Hide#Hide self (return value: cc.Hide) -------------------------------- -- -- @function [parent=#Hide] reverse -- @param self -- @return ActionInstant#ActionInstant ret (return value: cc.ActionInstant) return nil
mit
FnTm/location-sharing
app/models/user_friendship.rb
1525
class UserFriendship < ActiveRecord::Base belongs_to :user belongs_to :friend, class_name: "User", foreign_key: "friend_id" belongs_to :invited_friend, class_name: "User", foreign_key: "friend_id" belongs_to :inviting_friend, class_name: "User", foreign_key: "friend_id" validates_presence_of :friend_id, :user_id def self.are_friends(user, friend) return false if user == friend return true unless find_by_user_id_and_friend_id(user, friend).nil? return true unless find_by_user_id_and_friend_id(friend, user).nil? false end def self.request(user, friend) return false if are_friends(user, friend) return false if user == friend f1 = new(:user => user, :friend => friend, :accepted => 0) f2 = new(:user => friend, :friend => user, :accepted => 1) transaction do f1.save f2.save end end def self.accept(user, friend) f1 = find_by_user_id_and_friend_id(user, friend) f2 = find_by_user_id_and_friend_id(friend, user) if f1.nil? or f2.nil? or f1.accepted == 0 return false else transaction do f1.update_attributes(:accepted => 2) f2.update_attributes(:accepted => 2) end end return true end def self.reject(user, friend) f1 = find_by_user_id_and_friend_id(user, friend) f2 = find_by_user_id_and_friend_id(friend, user) if f1.nil? or f2.nil? return false else transaction do f1.destroy f2.destroy return true end end end end
mit
lwhitlock/grow-tracker
src/js/SelectFields/SelectField.js
27855
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; import { findDOMNode } from 'react-dom'; import deprecated from 'react-prop-types/lib/deprecated'; import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { UP, DOWN, ESC, ENTER, SPACE, TAB, ZERO, NINE, KEYPAD_ZERO, KEYPAD_NINE } from '../constants/keyCodes'; import getField from '../utils/getField'; import handleKeyboardAccessibility from '../utils/EventUtils/handleKeyboardAccessibility'; import controlled from '../utils/PropTypes/controlled'; import isBetween from '../utils/NumberUtils/isBetween'; import addSuffix from '../utils/StringUtils/addSuffix'; import List from '../Lists/List'; import ListItem from '../Lists/ListItem'; import Menu from '../Menus/Menu'; import Positions from '../Menus/Positions'; import FloatingLabel from '../TextFields/FloatingLabel'; import TextFieldMessage from '../TextFields/TextFieldMessage'; import Field from './Field'; const VALID_LIST_ITEM_PROPS = Object.keys(ListItem.propTypes); const MOBILE_LIST_PADDING = 8; const SelectFieldPositions = Object.assign({}, Positions); delete SelectFieldPositions.BOTTOM_RIGHT; delete SelectFieldPositions.BOTTOM_LEFt; export default class SelectField extends PureComponent { static Positions = SelectFieldPositions; static propTypes = { /** * An id to use for the select field. This is required for a11y. If the `menuId` and * `listId` are not given, this will be used to create their ids for a11y. */ id: isRequiredForA11y(PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ])), /** * An optional name to give the select field's input. */ name: PropTypes.string, /** * An id to give the menu containing the select field. If this is omitted, the `id` prop * will be used to make this id. `${id}Menu`. */ menuId: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * An id to give the list that appears once the menu is open. If this is omitted, the `id` prop * will be used to make this id. `${id}Values`. */ listId: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * An optional style to apply to the select field's container. This is the `Menu` component. */ style: PropTypes.object, /** * An optional style to apply to the select field's container. This is the `Menu` component. */ className: PropTypes.string, /** * An optional style to apply to the select field's list of items that appear when opened. */ listStyle: PropTypes.object, /** * An optional className to apply to the select field's list of items that appear when opened. */ listClassName: PropTypes.string, /** * An optional style to apply to the select field itself. */ inputStyle: PropTypes.object, /** * An optional className to apply to the select field itself. */ inputClassName: PropTypes.string, /** * An optional value for the select field. This will require the `onChange` prop * to be defined since it will be a controlled component. */ value: controlled(PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), 'onChange'), /** * The default value for an uncontrolled select field. */ defaultValue: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]).isRequired, /** * Boolean if the select field is open by default. */ defaultOpen: PropTypes.bool, /** * An optional boolean if the select field is currently open. This will make the component * controlled and require the `onMenuToggle` prop to be defined. */ isOpen: controlled(PropTypes.bool, 'onMenuToggle', 'defaultOpen'), /** * An optional function to call when the menu's open state changes. The callback will include * the next open state and the event that driggered it. * * ```js * onMenuToggle(isOpen, event); * ``` */ onMenuToggle: PropTypes.func, /** * An optional function to call when the value for the select field changes. The callback will * include the new value, the index of the menu item that was selected, and the event that * triggered the change. * * ```js * onChange(newValue, newActiveIndex, event); * ``` */ onChange: PropTypes.func, /** * A list of items to select from. This can be a mixed list of number, string, * or object. If the item is an object, make sure the `itemLabel` and `itemValue` * props match the keys in the object for the label and value. */ menuItems: PropTypes.arrayOf(PropTypes.oneOfType([ PropTypes.number, PropTypes.string, PropTypes.object, ])), /** * An optional floating label to display with the text field. This is invalid * if the `position` is set to `SelectField.Positions.BELOW`. */ label: PropTypes.node, /** * An optional placeholder to display in the select field. */ placeholder: PropTypes.string, /** * Boolean if the select field is disabled. */ disabled: PropTypes.bool, /** * The key to use for extracting a menu item's label if the menu item is an object. * * Example: * * ```js * const item = { something: 'My Label', somethingElse: 'value' }; * const itemLabel = 'something'; * const itemValue = 'somethingElse'; * ``` */ itemLabel: PropTypes.string.isRequired, /** * The key to use for extracting a menu item'value label if the menu item is an object. * * Example: * * ```js * const item = { something: 'My Label', somethingElse: 'value' }; * const itemLabel = 'something'; * const itemValue = 'somethingElse'; * ``` */ itemValue: PropTypes.string.isRequired, /** * Any children used to display the select field's drop down icon. */ iconChildren: PropTypes.node, /** * The icon class name to use to display the select field's drop down icon. */ iconClassName: PropTypes.string, /* * An optional function to call when the menu is clicked. */ onClick: PropTypes.func, /** * The position that the select field's options should appear from. If the position is * set to `BELOW`, the select field will be displayed as a button with ink instead of * a text field. */ position: PropTypes.oneOf([ SelectField.Positions.TOP_LEFT, SelectField.Positions.TOP_RIGHT, SelectField.Positions.BELOW, ]).isRequired, /* * The direction that the select field's focus indicator should grow from. */ lineDirection: PropTypes.oneOf(['left', 'center', 'right']).isRequired, /** * An optional function to call when the select field is focused. */ onFocus: PropTypes.func, /** * An optional function to call when the select field is blurred. This * will also be triggered when a user selects a new item or keyboard navigates * through the list items. */ onBlur: PropTypes.func, /** * The amount of time that a list of letters should be used when finding a menu item * while typing. Since a user can select items by typing multiple letters in a row, * this will be used as the timeout for clearing those letters. * * For example: * - User types `g` * * Full match is now `'g'`. * * - User delays 200ms and types `u` * * Full match is now `'gu'` * * - User delays 1000ms and types `a`. * * Full match is now `'a'` */ keyboardMatchingTimeout: PropTypes.number.isRequired, /** * Boolean if the select field's list of menu items should stretch to at least * be the width of the select field. */ stretchList: PropTypes.bool, /** * Boolean if there has been an error for the select field. This will display * the `errorText`. And style the floating label and focus indicator with the * error color. */ error: PropTypes.bool, /** * An optional error text to display when the `error` prop is true. */ errorText: PropTypes.node, /** * An optional help text to display below the select field. */ helpText: PropTypes.node, /** * Boolean if the help text should only be displayed when the select field * has focus. */ helpOnFocus: PropTypes.bool, /** * Boolean if the select field is required. This will updated the label or placeholder * to include an asterisk. */ required: PropTypes.bool, /** * Boolean if the select field is in a toolbar. This will automatically be injected if the select field * is passed in as the `menuTitle` prop. */ toolbar: PropTypes.bool, /** * Boolean if the menu surrounding the select field should be full width or not. */ fullWidth: PropTypes.bool, menuStyle: deprecated(PropTypes.object, 'Use `style` instead'), menuClassName: deprecated(PropTypes.string, 'Use `className` instead'), initiallyOpen: deprecated(PropTypes.bool, 'Use `defaultOpen` instead'), floatingLabel: deprecated( PropTypes.bool, 'A select field can only have floating labels now. Only provide the `label` prop' ), noAutoAdjust: deprecated(PropTypes.bool, 'No longer valid to use since select fields are no longer text fields'), adjustMinWidth: deprecated(PropTypes.bool, 'No longer valid to use since select fields are no longer text fields'), }; static defaultProps = { defaultValue: '', itemLabel: 'label', itemValue: 'value', iconChildren: 'arrow_drop_down', position: SelectField.Positions.TOP_LEFT, lineDirection: 'left', keyboardMatchingTimeout: 1000, stretchList: true, menuItems: [], }; constructor(props) { super(props); this.state = { active: false, activeIndex: this._getActiveIndex(props, { value: props.defaultValue }), isOpen: typeof props.initiallyOpen !== 'undefined' ? props.initiallyOpen : !!props.defaultOpen, activeLabel: this._getActiveLabel(props, typeof props.value !== 'undefined' ? props.value : props.defaultValue), match: null, lastSearch: null, error: false, }; if (typeof props.value === 'undefined') { this.state.value = props.defaultValue; } this._setMenu = this._setMenu.bind(this); this._setField = this._setField.bind(this); this._positionList = this._positionList.bind(this); this._toggleOpen = this._toggleOpen.bind(this); this._handleBlur = this._handleBlur.bind(this); this._handleFocus = this._handleFocus.bind(this); this._handleOpen = this._handleOpen.bind(this); this._handleClose = this._handleClose.bind(this); this._getActiveLabel = this._getActiveLabel.bind(this); this._mapToListItem = this._mapToListItem.bind(this); this._handleItemSelect = this._handleItemSelect.bind(this); this._handleContainerClick = this._handleContainerClick.bind(this); this._handleKeyDown = this._handleKeyDown.bind(this); this._setMenuItem = this._setMenuItem.bind(this); this._getActiveIndex = this._getActiveIndex.bind(this); this._advanceFocus = this._advanceFocus.bind(this); this._attemptItemFocus = this._attemptItemFocus.bind(this); this._selectItemByLetter = this._selectItemByLetter.bind(this); this._selectFirstMatch = this._selectFirstMatch.bind(this); this._items = []; this._activeItem = null; this._focusedAtLeastOnce = false; } componentWillUpdate(nextProps, nextState) { const prevValue = getField(this.props, this.state, 'value'); const value = getField(nextProps, nextState, 'value'); const error = getField(nextProps, nextState, 'error'); const isOpen = getField(nextProps, nextState, 'isOpen'); const valued = !getField(nextProps, nextState, 'value'); let state; if (prevValue !== value || this.props.menuItems !== nextProps.menuItems) { state = { activeLabel: this._getActiveLabel(nextProps, value), }; } if (this._focusedAtLeastOnce && nextProps.required && !isOpen && error !== valued) { state = state || {}; state.error = valued; } if (state) { this.setState(state); } } componentWillUnmount() { if (this._matchingTimeout) { clearTimeout(this._matchingTimeout); } } _attemptItemFocus(index) { if (index === -1) { return; } const item = this._items[index]; if (item) { item.focus(); } } _getActiveLabel({ menuItems, itemLabel, itemValue }, value) { let activeLabel = ''; menuItems.some(item => { activeLabel = this._getActiveLabelFromItem(item, value, itemLabel, itemValue); return activeLabel; }); return activeLabel; } _getActiveLabelFromItem(item, value, itemLabel, itemValue) { switch (typeof item) { case 'number': case 'string': if (item === value || item === parseInt(value, 10)) { return item; } break; case 'object': if (item[itemValue] === value || item[itemValue] === parseInt(value, 10)) { return item[itemLabel]; } break; default: } return ''; } _getActiveIndex(props, state) { const value = getField(props, state, 'value'); if (!value) { return -1; } const { itemLabel, itemValue, menuItems } = props; let index = -1; menuItems.some((item, i) => { const found = this._getActiveLabelFromItem(item, value, itemLabel, itemValue); if (found) { index = i; } return found; }); return index; } _setMenu(menu) { this._menu = findDOMNode(menu); } _setField(field) { this._field = findDOMNode(field); } _positionList(listRef) { if (listRef === null) { this._items = []; } else if (!this._activeItem) { return; } const list = findDOMNode(listRef); const { position, menuItems, toolbar } = this.props; if (position === SelectField.Positions.BELOW || toolbar) { // only modify scroll distance when below const activeIndex = Math.min(this._activeItem, menuItems.length - 2); const { offsetTop: itemTop } = list.querySelectorAll('.md-list-tile')[activeIndex]; list.scrollTop = itemTop > MOBILE_LIST_PADDING ? itemTop : 0; return; } const { offsetTop: itemTop, offsetHeight: itemHeight } = this._activeItem; const { offsetHeight: menuHeight } = this._menu; const itemPosition = Math.max(0, itemTop - itemHeight); const listPadding = parseInt(window.getComputedStyle(list).getPropertyValue('padding-top'), 10); // Basically calculates where the current item is in the list, and attempts to make the menu // originate from that position. const x = SelectField.Positions.TOP_LEFT === position ? '0' : '100%'; const y = (itemPosition === 0 ? 0 : menuHeight) + (menuHeight / 2) + listPadding; const transformOrigin = `${x} ${y}px`; let top; if (itemPosition > 0) { // close enough. It is off by 4px for floating label on desktop top = -(itemHeight + listPadding - (menuHeight - itemHeight)); } if (itemPosition > 0) { list.scrollTop = itemPosition; } this.setState({ listStyle: { top, transformOrigin, }, }); } _handleFocus(e) { this._focusedAtLeastOnce = true; if (this.props.onFocus) { this.props.onFocus(e); } this.setState({ active: true }); } _handleBlur(e) { if (this.props.onBlur) { this.props.onBlur(e); } const isOpen = getField(this.props, this.state, 'isOpen'); const value = getField(this.props, this.state, 'value'); this.setState({ active: false, error: this.props.required && !isOpen && !value, }); } _handleItemSelect(index, v, e) { const { required, menuItems, itemLabel, itemValue, onChange, position } = this.props; const number = typeof menuItems[index] === 'number' || typeof menuItems[index][itemValue] === 'number'; const value = number ? Number(v) : v; const below = position === SelectField.Positions.BELOW; if (getField(this.props, this.state, 'value') !== value && onChange) { onChange(value, index, e); } const state = { activeIndex: below ? 0 : index, activeLabel: this._getActiveLabelFromItem(menuItems[index], value, itemLabel, itemValue), error: required && !value, }; if (typeof this.props.value === 'undefined') { state.value = value; } if (typeof this.props.isOpen === 'undefined' && e.type !== 'click') { state.isOpen = false; } this.setState(state); } _handleContainerClick(e) { if (this.props.onClick) { this.props.onClick(e); } let { target } = e; while (this._menu && this._menu.contains(target)) { if (target.dataset.id) { this._handleItemSelect(parseInt(target.dataset.id, 10), target.dataset.value, e); return; } target = target.parentNode; } } /** * This function is only called when the user _clicks_ or _touches_ the select field. Since * clicking it can either open or close it, this is actually toggled. */ _toggleOpen(e) { const isOpen = !getField(this.props, this.state, 'isOpen'); if (this.props.onMenuToggle) { this.props.onMenuToggle(isOpen, e); } if (typeof this.props.isOpen === 'undefined') { this.setState({ isOpen }); } } /** * Ths function is used for opening the select field with keyboard input. */ _handleOpen(e) { if (this.props.onMenuToggle) { this.props.onMenuToggle(true, e); } let state; if (!getField(this.props, this.state, 'value') && this.state.activeIndex === -1) { // When there is no value, need to change the default active index to 0 instead of -1 // so that the next DOWN arrow increments correctly state = { activeIndex: 0 }; } if (typeof this.props.isOpen === 'undefined') { state = state || {}; state.isOpen = true; } if (state) { this.setState(state); } } _handleClose(e) { if (this.props.onMenuToggle) { this.props.onMenuToggle(false, e); } let state; if (this.props.position === SelectField.Positions.BELOW) { // Set the active index back to 0 since the active item will be spliced out // of the menu items state = { activeIndex: 0 }; } if (typeof this.props.isOpen === 'undefined') { state = state || {}; state.isOpen = false; } if (state) { this.setState(state); } } _mapToListItem(item, i) { const { id, itemLabel, itemValue: itemValueKey, position } = this.props; const below = position === SelectField.Positions.BELOW; const value = getField(this.props, this.state, 'value'); let primaryText = ''; let itemValue = ''; let props; switch (typeof item) { case 'number': case 'string': primaryText = item; itemValue = item; break; case 'object': primaryText = item[itemLabel]; itemValue = typeof item[itemValueKey] !== 'undefined' ? item[itemValueKey] : item[itemLabel]; props = Object.keys(item).reduce((validProps, key) => { if (key !== itemLabel && key !== itemValueKey && key !== 'primaryText' && VALID_LIST_ITEM_PROPS.indexOf(key) !== -1 ) { validProps[key] = item[key]; } return validProps; }, {}); break; default: } const active = itemValue === value || itemValue === parseInt(value, 10); if (below && active) { return null; } return ( <ListItem {...props} ref={this._setMenuItem} active={active} tabIndex={-1} primaryText={primaryText} key={item.key || i} role="option" id={active ? `${id}Active` : null} data-id={i} data-value={itemValue} tileStyle={below ? { paddingLeft: 24 } : undefined} /> ); } _setMenuItem(item) { if (!item) { return; } if (item.props.active) { this._activeItem = findDOMNode(item); item.focus(); } this._items.push(item); } _handleKeyDown(e) { const key = e.which || e.keyCode; const isOpen = getField(this.props, this.state, 'isOpen'); if (key === UP || key === DOWN) { e.preventDefault(); if (!isOpen) { this._handleOpen(e); return; } } if (!isOpen && handleKeyboardAccessibility(e, this._handleOpen, true, true)) { return; } else if (isOpen && (key === ESC || key === TAB)) { if (this._field && key === ESC) { this._field.focus(); } this._handleClose(e); return; } switch (key) { case UP: case DOWN: this._advanceFocus(key === UP, e); break; case ENTER: case SPACE: if (this._field) { this._field.focus(); } this._handleContainerClick(e); break; default: this._selectItemByLetter(e, key); } } _advanceFocus(decrement) { const { menuItems, position } = this.props; const { activeIndex } = this.state; const below = position === SelectField.Positions.BELOW; // If the select field is positioned below and there is no value, need to increment the last index // by one since this select field removes the active item. Need to account for that here when there // is no value. const lastIndex = menuItems.length - (below && !getField(this.props, this.state, 'value') ? 0 : 1); if ((decrement && activeIndex <= 0) || (!decrement && activeIndex >= lastIndex)) { return; } const nextIndex = Math.max(-1, Math.min(lastIndex, activeIndex + (decrement ? -1 : 1))); if (nextIndex === activeIndex) { return; } this._attemptItemFocus(nextIndex - (below ? 1 : 0)); if (below && decrement && nextIndex === 0) { return; } this.setState({ activeIndex: nextIndex }); } _selectItemByLetter(e, key) { const charCode = String.fromCharCode(key); const isLetter = charCode && charCode.match(/[A-Za-z0-9-_ ]/); const isKeypad = isBetween(key, KEYPAD_ZERO, KEYPAD_NINE); if (!isBetween(key, ZERO, NINE) && !isKeypad && !isLetter) { return; } const letter = isLetter ? charCode : String(key - (isKeypad ? KEYPAD_ZERO : ZERO)); if (this._matchingTimeout) { clearTimeout(this._matchingTimeout); } this._matchingTimeout = setTimeout(() => { this._matchingTimeout = null; this.setState({ match: null, lastSearch: null }); }, this.props.keyboardMatchingTimeout); this._selectFirstMatch(letter, e); } _selectFirstMatch(letter, e) { const { menuItems, itemLabel, itemValue } = this.props; const search = `${this.state.lastSearch || ''}${letter}`; let match = -1; menuItems.some((item, i) => { const value = String(typeof item === 'object' && item ? item[itemLabel] : item); if (value && value.toUpperCase().indexOf(search) === 0) { match = i; } return match > -1; }); const activeItem = menuItems[match]; const state = { match, lastSearch: search, }; if (match === -1) { this.setState(state); return; } state.activeLabel = typeof activeItem === 'object' ? activeItem[itemLabel] : activeItem; state.activeIndex = match; if (getField(this.props, this.state, 'isOpen')) { if (state.match !== this.state.match) { this._attemptItemFocus(state.activeIndex); } } else { const value = typeof activeItem === 'object' ? activeItem[itemValue] : activeItem; state.error = !value; if (getField(this.props, this.state, 'value') !== value && this.props.onChange) { this.props.onChange(value, state.activeIndex, e); } if (typeof this.props.value === 'undefined') { state.value = value; } } this.setState(state); } render() { const { activeLabel, active } = this.state; const { id, style, className, listStyle, listClassName, inputStyle, inputClassName, disabled, menuItems, position, stretchList, errorText, helpText, helpOnFocus, required, fullWidth, ...props } = this.props; delete props.error; delete props.itemLabel; delete props.itemValue; delete props.menuId; delete props.listId; delete props.defaultValue; delete props.value; delete props.isOpen; delete props.defaultOpen; delete props.keyboardMatchingTimeout; delete props.onMenuToggle; // delete deprecated delete props.menuStyle; delete props.menuClassName; delete props.initiallyOpen; delete props.floatingLabel; delete props.noAutoAdjust; delete props.adjustMinWidth; let { menuId, listId, placeholder, label, error } = this.props; error = error || this.state.error; const value = getField(this.props, this.state, 'value'); const isOpen = getField(this.props, this.state, 'isOpen'); const below = position === SelectField.Positions.BELOW; if (!menuId) { menuId = `${id}Menu`; } if (!listId) { listId = `${id}Values`; } if (required) { if (label) { label = addSuffix(label, '*'); } if (placeholder && !label) { placeholder = addSuffix(placeholder, '*'); } } const toggle = [ <FloatingLabel key="floating-label" label={label} htmlFor={id} active={active || isOpen} error={error} floating={!!activeLabel || active || isOpen} disabled={disabled} />, <Field {...props} id={id} ref={this._setField} key="select-field" style={inputStyle} className={inputClassName} activeLabel={activeLabel} required={required} disabled={disabled} active={active || isOpen} below={below} value={value} label={label} error={error} placeholder={placeholder} onClick={this._toggleOpen} onFocus={this._handleFocus} onBlur={this._handleBlur} />, <TextFieldMessage key="message" active={active || isOpen} error={error} errorText={errorText} helpText={helpText} helpOnFocus={helpOnFocus} leftIcon={false} rightIcon={false} />, ]; return ( <Menu id={menuId} position={position} isOpen={isOpen} onClose={this._handleClose} onClick={this._handleContainerClick} onKeyDown={this._handleKeyDown} toggle={toggle} style={style} className={cn('md-select-field-menu', { 'md-select-field-menu--stretch': stretchList, }, className)} ref={this._setMenu} fullWidth={fullWidth} > <List id={listId} role="listbox" ref={this._positionList} aria-activedescendant={value ? `${id}Active` : null} style={{ ...listStyle, ...this.state.listStyle }} className={listClassName} > {menuItems.map(this._mapToListItem).filter(item => item !== null)} </List> </Menu> ); } }
mit
fujiy/FujiyNotepad
src/FujiyNotepad.UI/Model/TextSearcher.cs
4815
using System; using System.Collections.Generic; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace FujiyNotepad.UI.Model { public class TextSearcher { long searchSize = 1024 * 1024; private readonly MemoryMappedFile mFile; public long FileSize { get; } public TextSearcher(MemoryMappedFile file, long fileSize) { this.mFile = file; FileSize = fileSize; } public async IAsyncEnumerable<long> Search(long startOffset, char[] charsToSearch, IProgress<int> progress, CancellationToken token) { int lastReportValue = 0; progress.Report(lastReportValue); //long bytesToRead = Math.Min(searchSize, FileSize - startOffset); var buffer = new byte[charsToSearch.Length - 1]; using (var stream = mFile.CreateViewStream(startOffset, 0, MemoryMappedFileAccess.Read)) using (var streamReader = new StreamReader(stream)) { int byteRead; do { byteRead = stream.ReadByte(); var currentPosition = stream.Position; if (byteRead == charsToSearch[0]) { bool equals = true; await stream.ReadAsync(buffer, 0, charsToSearch.Length - 1); for (int i = 0; i < charsToSearch.Length - 1; i++) { if (buffer[i] != charsToSearch[i + 1])//TODO case insensitive { equals = false; break; } } if (equals) { yield return startOffset + currentPosition - 1;// stream.Position - 1; } else { stream.Position = currentPosition; } } long totalBytes = FileSize - startOffset; long currentProgress = currentPosition - startOffset; int progressValue = (int)(currentProgress * 100 / totalBytes); if (lastReportValue != progressValue) { lastReportValue = progressValue; progress.Report(progressValue); } } while (byteRead > -1 && token.IsCancellationRequested == false); } } //TODO mudar para search backward public IEnumerable<long> SearchBackward(long startOffset, char charToSearch, IProgress<int> progress) { if (startOffset < 0) { throw new ArgumentOutOfRangeException(nameof(startOffset), $"{nameof(startOffset)} cannot be negative"); } int lastReportValue = 0; progress.Report(lastReportValue); long searchBackOffset = startOffset; do { long searchSizePerIteration = Math.Min(searchSize, searchBackOffset); searchBackOffset = searchBackOffset - searchSizePerIteration;// Math.Max(searchBackOffset - searchSizePerIteration, 0); if (searchSizePerIteration > 0) { using (var stream = mFile.CreateViewStream(searchBackOffset, searchSizePerIteration, MemoryMappedFileAccess.Read)) using (var streamReader = new StreamReader(stream)) { stream.Seek(0, SeekOrigin.End); while (stream.Position > 0) { stream.Seek(-1, SeekOrigin.Current); if (stream.ReadByte() == charToSearch) { yield return searchBackOffset + stream.Position - 1; } stream.Seek(-1, SeekOrigin.Current); } } } int progressValue = (int)((FileSize - startOffset) * 100 / FileSize); if (lastReportValue != progressValue) { lastReportValue = progressValue; progress.Report(progressValue); } } while (searchBackOffset > 0); //Implicit new line at file start if (charToSearch == '\n') { yield return -1; } } } }
mit
eaymerich/blaster
src/TexturedSquare.cpp
1413
#include <cstdlib> #include <iostream> #include "TexturedSquare.h" #include "ShaderUtil.h" using std::cerr; using std::endl; GLfloat TexturedSquare::vertices[] = { // Front face -0.5f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f, 0.5f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f }; GLfloat TexturedSquare::textureCoordinates[] = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f }; TexturedSquare::TexturedSquare(GLuint tex) : texture{tex} { ShaderUtil util; program = util.loadProgram("textured"); // Get attribute index positionIndex = glGetAttribLocation(program, "aPosition"); textureCoordinateIndex = glGetAttribLocation(program, "aTextureCoordinate"); // Get Uniform index textureUnitIndex = glGetUniformLocation(program, "uTextureUnit"); } void TexturedSquare::draw() { glUseProgram(program); glVertexAttribPointer(positionIndex, 3, GL_FLOAT, GL_FALSE, 0, vertices); glEnableVertexAttribArray(positionIndex); glVertexAttribPointer(textureCoordinateIndex, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinates); glEnableVertexAttribArray(textureCoordinateIndex); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glUniform1i(textureUnitIndex, 0); glDrawArrays(GL_TRIANGLES, 0, 6); }
mit
leantony/laravel_settings
src/models/SettingObserver.php
461
<?php namespace Leantony\Settings\Models; use Leantony\Settings\SettingsHelper; class SettingObserver { /** * Listen to the Settings updated event. * * @param Settings $setting * @return void */ public function updated(Settings $setting) { $instance = app('settings'); /** @var $instance SettingsHelper */ // clear the settings cache $instance->replaceLoaded($setting->category); } }
mit
diggcoin/diggcoin
src/compat/strnlen.cpp
512
// Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/diggcoin-config.h" #endif #include <cstring> #if HAVE_DECL_STRNLEN == 0 size_t strnlen( const char *start, size_t max_len) { const char *end = (const char *)memchr(start, '\0', max_len); return end ? (size_t)(end - start) : max_len; } #endif // HAVE_DECL_STRNLEN
mit
jvilaplana/langtonsant
javascript/langtonsant.js
5127
var canvasWidth = 800; var canvasHeight = 400; var blockSize = 10; var currentStep = 0; var antPos = [canvasWidth / blockSize / 2, canvasHeight / blockSize / 2]; var antDir = 0; var speed = 1000; var running = false; function grid(w, h, totalW, totalH){ var $this = this; this.blockW = w || blockSize; this.blockH = h || blockSize; this.container; $('#grid').empty(); this.container = document.createElement('div'); this.container.id = 'gridContainer'; var c = document.createElement("canvas"); c.id = 'antCanvas'; c.width = totalW; c.height = totalH; c.className ="antCanvas"; var totalW = totalW || $(document).width(); var totalH = totalH || $(document).height(); var mapGridCanvas = c.getContext("2d"); mapGridCanvas.fillStyle = "#FFFFFF"; mapGridCanvas.fillRect(0, 0, c.width, c.height); mapGridCanvas.globalAlpha = 1; this.container.appendChild(c); document.getElementById('grid').appendChild(this.container); }; function draw(x, y, c) { var canvas = document.getElementById('antCanvas'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.fillStyle = c; ctx.fillRect(blockSize*x, blockSize*y, blockSize, blockSize); } } function nextStep() { var colour = getColour(antPos[0], antPos[1]); if(colour == 0) { draw(antPos[0], antPos[1], "#FFFFFF"); } else { draw(antPos[0], antPos[1], "#000000"); } if(antDir == 0) { antPos[1]--; if(antPos[1] < 0) antPos[1] = canvasHeight / blockSize; } else if(antDir == 1) { antPos[0]++; if(antPos[0] > canvasWidth / blockSize) antPos[0] = 0; } else if(antDir == 2) { antPos[1]++; if(antPos[1] > canvasHeight / blockSize) antPos[1] = 0; } else if(antDir == 3) { antPos[0]--; if(antPos[0] < 0) antPos[0] = canvasWidth / blockSize;; } colour = getColour(antPos[0], antPos[1]); if(colour == 0) { antDir++; if(antDir > 3) antDir = 0; } else { antDir--; if(antDir < 0) antDir = 3; } drawAnt(antPos[0], antPos[1]); currentStep++; $("#currentStep").html(currentStep); } function drawAnt(x, y) { var canvas = document.getElementById('antCanvas'); var ctx = canvas.getContext('2d'); ctx.fillStyle = 'red'; var path=new Path2D(); var initialX = blockSize*x; var initialY = blockSize*y; if(antDir == 0) { path.moveTo(initialX+blockSize/2, initialY); path.lineTo(initialX, initialY+blockSize); path.lineTo(initialX+blockSize, initialY+blockSize); } else if(antDir == 1) { path.moveTo(initialX+blockSize, initialY+blockSize/2); path.lineTo(initialX+2, initialY+2); path.lineTo(initialX+2, initialY+blockSize); } else if(antDir == 2) { path.moveTo(initialX+blockSize/2, initialY+blockSize); path.lineTo(initialX+2, initialY+2); path.lineTo(initialX+blockSize, initialY+2); } else if(antDir == 3) { path.moveTo(initialX, initialY+blockSize/2); path.lineTo(initialX+blockSize, initialY); path.lineTo(initialX+blockSize, initialY+blockSize); } ctx.fill(path); /* var imageObj = new Image(); imageObj.onload = function() { ctx.drawImage(imageObj, 250, 250); }; imageObj.src = 'image/ant.png'; */ } function getColour(x, y) { var canvas = document.getElementById('antCanvas'); var ctx = canvas.getContext('2d'); var p = ctx.getImageData((x*blockSize)+1, (y*blockSize)+1, 1, 1).data; if(p[0] == 0 && p[1] == 0 && p[2] == 0) return 0; else return 1; } function rgbToHex(r, g, b) { if (r > 255 || g > 255 || b > 255) throw "Invalid color component"; return ((r << 16) | (g << 8) | b).toString(16); } function simulate() { setTimeout(function() { nextStep(); if(running) simulate(); }, speed); } $(function() { $('#initializeCanvas').click(function() { blockSize = parseInt($('#blockSize').val()); canvasWidth = parseInt($('#canvasWidth').val()); canvasHeight = parseInt($('#canvasHeight').val()); antPos = [canvasWidth / blockSize / 2, canvasHeight / blockSize / 2]; console.log(blockSize); console.log(canvasWidth); console.log(canvasHeight); grid(blockSize, blockSize, canvasWidth, canvasHeight); draw(antPos[0], antPos[1], "#FFFFFF"); drawAnt(antPos[0], antPos[1]); $('#start').prop('disabled', false); $('#initializeCanvas').prop('disabled', true); }); $('#start').click(function() { if($('#start').is(':disabled')) return; if(!running) { running = true; simulate(); $('#start').html("Pause"); $('#runningSpinner').addClass('is-active'); } else { running = false; $('#start').html("Start"); $('#runningSpinner').removeClass('is-active'); } }); $('#speedDown').click(function() { speed += 50; $('#currentSpeed').html(speed); }); $('#speedUp').click(function() { speed -= 50; if(speed < 0) speed = 0; $('#currentSpeed').html(speed); }); $('#speedSlider').on('input', function() { $('#currentSpeed').html(10000 - $('#speedSlider').val()); speed = 10000 - $('#speedSlider').val(); }); $('#currentSpeed').html(speed); });
mit
mcfedr/youtubelivestreamsbundle
src/Mcfedr/YouTube/LiveStreamsBundle/DependencyInjection/GuzzleClientFactory.php
680
<?php /** * Created by mcfedr on 07/09/2016 22:27 */ namespace Mcfedr\YouTube\LiveStreamsBundle\DependencyInjection; use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\Psr7\Uri; use Psr\Http\Message\RequestInterface; class GuzzleClientFactory { public static function get(array $options, $key) { $stack = HandlerStack::create(); $stack->unshift(Middleware::mapRequest(function (RequestInterface $request) use ($key) { return $request->withUri(Uri::withQueryValue($request->getUri(), 'key', $key)); })); $options['handler'] = $stack; return new Client($options); } }
mit
sejoung/spring-boot-data-jpa-sample
src/main/java/kr/co/killers/sample/controller/WelComeController.java
1786
/* * Copyright 2012-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.co.killers.sample.controller; import java.util.Locale; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import kr.co.killers.sample.security.UserDetailsImpl; import lombok.extern.slf4j.Slf4j; @Slf4j @Controller public class WelComeController { @Value("${application.message}") private String message = "Hello World"; @RequestMapping("/") public String welcome(Map<String, Object> model,Locale locale) { log.info("Welcome home! The client locale is {}.", locale); model.put("message", this.message); return "welcome"; } @RequestMapping("/admin") public String admin(Authentication authentication) { UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); log.debug("admin "+userDetails.getUsername()); return "admin"; } @RequestMapping("/login") public String login(Map<String, Object> model,Locale locale) { log.info("Welcome home! The client locale is {}.", locale); return "login"; } }
mit
innogames/gitlabhq
spec/requests/api/graphql/mutations/merge_requests/accept_spec.rb
1273
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'accepting a merge request', :request_store do include GraphqlHelpers let_it_be(:current_user) { create(:user) } let_it_be(:project) { create(:project, :public, :repository) } let!(:merge_request) { create(:merge_request, source_project: project) } let(:input) do { project_path: project.full_path, iid: merge_request.iid.to_s, sha: merge_request.diff_head_sha } end let(:mutation) { graphql_mutation(:merge_request_accept, input, 'mergeRequest { state }') } let(:mutation_response) { graphql_mutation_response(:merge_request_accept) } context 'when the user is not allowed to accept a merge request' do before do project.add_reporter(current_user) end it_behaves_like 'a mutation that returns a top-level access error' end context 'when user has permissions to create a merge request' do before do project.add_maintainer(current_user) end it 'merges the merge request' do post_graphql_mutation(mutation, current_user: current_user) expect(response).to have_gitlab_http_status(:success) expect(mutation_response['mergeRequest']).to include( 'state' => 'merged' ) end end end
mit
tarquasso/softroboticfish6
fish/pi/ros/catkin_ws/src/rosserial/devel/share/gennodejs/ros/rosserial_arduino/srv/Test.js
2430
// Auto-generated. Do not edit! // (in-package rosserial_arduino.srv) "use strict"; let _serializer = require('../base_serialize.js'); let _deserializer = require('../base_deserialize.js'); let _finder = require('../find.js'); //----------------------------------------------------------- //----------------------------------------------------------- class TestRequest { constructor() { this.input = ''; } static serialize(obj, bufferInfo) { // Serializes a message object of type TestRequest // Serialize message field [input] bufferInfo = _serializer.string(obj.input, bufferInfo); return bufferInfo; } static deserialize(buffer) { //deserializes a message object of type TestRequest let tmp; let len; let data = new TestRequest(); // Deserialize message field [input] tmp = _deserializer.string(buffer); data.input = tmp.data; buffer = tmp.buffer; return { data: data, buffer: buffer } } static datatype() { // Returns string type for a service object return 'rosserial_arduino/TestRequest'; } static md5sum() { //Returns md5sum for a message object return '39e92f1778057359c64c7b8a7d7b19de'; } static messageDefinition() { // Returns full string definition for message return ` string input `; } }; class TestResponse { constructor() { this.output = ''; } static serialize(obj, bufferInfo) { // Serializes a message object of type TestResponse // Serialize message field [output] bufferInfo = _serializer.string(obj.output, bufferInfo); return bufferInfo; } static deserialize(buffer) { //deserializes a message object of type TestResponse let tmp; let len; let data = new TestResponse(); // Deserialize message field [output] tmp = _deserializer.string(buffer); data.output = tmp.data; buffer = tmp.buffer; return { data: data, buffer: buffer } } static datatype() { // Returns string type for a service object return 'rosserial_arduino/TestResponse'; } static md5sum() { //Returns md5sum for a message object return '0825d95fdfa2c8f4bbb4e9c74bccd3fd'; } static messageDefinition() { // Returns full string definition for message return ` string output `; } }; module.exports = { Request: TestRequest, Response: TestResponse };
mit
Pigeoncraft/Aurora
Project-Aurora/Profiles/Overwatch/OverwatchProfileManager.cs
1699
using Aurora.Profiles.Aurora_Wrapper; using Aurora.Settings; using Newtonsoft.Json; using System; using System.IO; using System.Text; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; namespace Aurora.Profiles.Overwatch { public class OverwatchProfileManager : ProfileManager { public OverwatchProfileManager() : base("Overwatch", "overwatch", "overwatch.exe", new OverwatchSettings(), new GameEvent_Overwatch()) { } public override UserControl GetUserControl() { if (Control == null) Control = new Control_Overwatch(); return Control; } public override ImageSource GetIcon() { if (Icon == null) Icon = new BitmapImage(new Uri(@"Resources/overwatch_icon.png", UriKind.Relative)); return Icon; } internal override ProfileSettings LoadProfile(string path) { try { if (File.Exists(path)) { string profile_content = File.ReadAllText(path, Encoding.UTF8); if (!String.IsNullOrWhiteSpace(profile_content)) return JsonConvert.DeserializeObject<OverwatchSettings>(profile_content, new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace }); } } catch (Exception exc) { Global.logger.LogLine(string.Format("Exception Loading Profile: {0}, Exception: {1}", path, exc), Logging_Level.Error); } return null; } } }
mit
devshorts/htf-viewer
src/config.ts
1051
///<reference path='../_all.d.ts'/> ///<reference path='../d.ts/vendor/node.d.ts'/> ///<reference path='../d.ts/vendor/colors.d.ts'/> ///<reference path='../d.ts/interfaces.d.ts'/> var fs = require("fs"); var path = require("path"); var _ = require("underscore")._; var colors = require('colors'); export class Config{ getConfig():ConfigData{ var defaults:ConfigData = { projectSource: process.cwd(), port: 3000 }; var config = defaults; var overrideConfigPath = process.cwd() + "/hconfig.json"; if(fs.existsSync(overrideConfigPath)){ console.log(("found config path @ " + overrideConfigPath).yellow); config = _.defaults(JSON.parse(fs.readFileSync(overrideConfigPath).toString()), defaults); } else{ console.log("using default config".yellow); } console.log(("Source Dir: " + config.projectSource).green); console.log(("Port: " + config.port).green); return config; } }
mit
Nicolas-Constanty/UnityTools
Assets/UnityTools/Collections/NotifyCollectionChangedEventArgs.cs
4379
using System; using System.Collections; using System.Collections.Generic; // ReSharper disable once CheckNamespace namespace UnityTools.Collections { public enum NotifyCollectionChangedAction { Add, Move, Remove, Replace, Reset } public class NotifyCollectionChangedEventArgs : EventArgs { public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action) { //Reset Action = action; } public NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, IList changedItems ) { //Reset || Add || Remove Action = action; NewItems = changedItems; } public NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, IList newItems, IList oldItems ) { //Replace Action = action; NewItems = newItems; OldItems = oldItems; } public NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex ) { //Replace Action = action; NewItems = newItems; OldItems = oldItems; NewStartingIndex = startingIndex; } public NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, IList changedItems, int startingIndex ) { //Reset || Add || Remove Action = action; NewItems = changedItems; NewStartingIndex = startingIndex; } public NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, IList changedItems, int index, int oldIndex ) { //Move Action = action; NewItems = changedItems; NewStartingIndex = index; OldStartingIndex = oldIndex; } public NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, object changedItem ) { //Reset || Add || Remove Action = action; NewItems = new List<object> { changedItem }; } public NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, object changedItem, int index ) { //Reset || Add || Remove Action = action; NewStartingIndex = index; NewItems = new List<object> { changedItem }; } public NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex ) { //Move Action = action; NewStartingIndex = index; NewItems = new List<object> { changedItem }; OldStartingIndex = oldIndex; } public NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, object newItem, object oldItem ) { //Replace Action = action; NewItems = new List<object> { newItem }; OldItems = new List<object> { oldItem }; } public NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, object newItem, object oldItem, int index ) { //Replace Action = action; NewItems = new List<object> { newItem }; OldItems = new List<object> { oldItem }; NewStartingIndex = index; } public NotifyCollectionChangedAction Action { get; private set; } public IList NewItems { get; private set; } public int NewStartingIndex { get; private set; } public IList OldItems { get; private set; } public int OldStartingIndex { get; private set; } } public delegate void NotifyCollectionChangedEventHandler( object sender, NotifyCollectionChangedEventArgs e ); }
mit
dayupu/acme
cqjz/src/main/java/com/manage/base/exception/ActTaskNotFoundException.java
470
package com.manage.base.exception; /** * Created by bert on 2017/10/4. */ public class ActTaskNotFoundException extends RuntimeException { public ActTaskNotFoundException() { } public ActTaskNotFoundException(String message) { super(message); } public ActTaskNotFoundException(String message, Throwable cause) { super(message, cause); } public ActTaskNotFoundException(Throwable cause) { super(cause); } }
mit
runelk/NB_URN_Client_Java
src/main/java/no/clarino/pid/nb/urn/wsdl/InsufficientRightsException.java
1407
package no.clarino.pid.nb.urn.wsdl; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for InsufficientRightsException complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="InsufficientRightsException"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="message" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "InsufficientRightsException", propOrder = { "message" }) public class InsufficientRightsException { protected String message; /** * Gets the value of the message property. * * @return * possible object is * {@link String } * */ public String getMessage() { return message; } /** * Sets the value of the message property. * * @param value * allowed object is * {@link String } * */ public void setMessage(String value) { this.message = value; } }
mit
UsualDeveloper/AssemblyPropertiesViewer
Core/AssemblyPropertiesViewer.Core.Logger/Properties/AssemblyInfo.cs
1409
using System.Reflection; 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("AssemblyPropertiesViewer.Core.Logger")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AssemblyPropertiesViewer.Core.Logger")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("67468eb2-d65d-44f4-b9bf-d45ee562bad7")] // 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
robotex82/itsf_fund_reports
spec/models/itsf/fund_reports/flex_query_spec.rb
2675
require 'spec_helper' module ITSF::FundReports describe FlexQuery do describe '#daily_pending' do before do @daily_recurrence = FactoryGirl.create(:itsf_fund_reports_flex_query_recurrence, :name => 'daily') @weekly_recurrence = FactoryGirl.create(:itsf_fund_reports_flex_query_recurrence, :name => 'weekly') @daily_pending_query = FactoryGirl.create(:itsf_fund_reports_flex_query, :recurrence => @daily_recurrence) @daily_executed_query = FactoryGirl.create(:itsf_fund_reports_flex_query_with_runs, :recurrence => @daily_recurrence) @weekly_pending_query = FactoryGirl.create(:itsf_fund_reports_flex_query, :recurrence => @weekly_recurrence) end # before subject { FlexQuery.daily_pending.all } it 'should include flex queries that have the recurrence daily and no runs' do subject.should include(@daily_pending_query) end # it it 'should not include flex queries that have the recurrence daily and one or more runs' do subject.should_not include(@daily_executed_query) end # it it 'should not include flex queries that have a recurrence other than daily' do subject.should_not include(@weekly_executed_query) subject.should_not include(@weekly_pending_query) end # it end # describe '#pending' describe 'associations' do it { should belong_to :account } it { should belong_to :recurrence } it { should have_many :runs } end # describe 'associations' describe 'public interface' do describe '#account_name' do it { should respond_to(:account_name) } end describe '#run' do subject { FactoryGirl.create(:itsf_fund_reports_flex_query) } it { should respond_to(:run) } it 'should create a new FlexQuery::Run' # it 'should create a new FlexQuery::Run' do # # Stub account name to return a valid entry from the config file # subject.stub(:account_name).and_return('test_account') # subject.run # subject.runs.count.should eq(1) # end # it end # describe '#run' end # describe 'public interface' describe 'validations' do it { should validate_presence_of :account } it { should validate_presence_of :query_identifier } it { should validate_uniqueness_of(:query_identifier).scoped_to(:account_id) } it { should validate_presence_of :format } it { should ensure_inclusion_of(:format).in_array(ITSF::FundReports::Configuration.allowed_flex_query_formats.map(&:to_s)) } end # describe 'validations' end # describe FlexQuery end # module ITSF::FundReports
mit
kasperisager/hemingway
bench/sift.cpp
3381
// Copyright (c) 2016 Kasper Kronborg Isager and Radosław Niemczyk. #include <vector> #include <iostream> #include <fstream> #include <hayai/hayai.hpp> #include <hayai/hayai_posix_main.cpp> #include <hemingway/vector.hpp> #include <hemingway/table.hpp> using namespace lsh; std::vector<vector> parse(std::string path) { std::ifstream stream(path, std::ios::binary); std::vector<vector> vectors; std::vector<char> buffer(1 << 20); while (!stream.eof()) { stream.read(&buffer[0], 1 << 20); int read = stream.gcount(); for (int i = 0; i < read; i += 8) { unsigned long n; for (int j = 0; j < 8; j++) { ((char*) &n)[j] = buffer[i + j]; } std::vector<bool> c(64); for (int j = 0; j < 64; j++) { c[j] = (n >> (63 - j)) & 1; } vectors.push_back(vector(c)); } } return vectors; } std::vector<vector> vs = parse("bench/data/vectors.bin"); std::vector<vector> qs = parse("bench/data/queries.bin"); std::vector<vector> gt; double delta = 0.01; unsigned short r = 4; unsigned short l = (1 << (r + 1)) - 1; unsigned short k = ceil(log2(1 - pow(delta, 1.0 / l)) / log2(1 - r / 64.0)); table t_lin(table::brute({.dimensions = 64})); table t_cla({.dimensions = 64, .samples = k, .partitions = l}); table t_cov({.dimensions = 64, .radius = r}); unsigned int vn = vs.size(); unsigned int qn = qs.size(); unsigned int vi; unsigned int qi; unsigned int runs = 50; void print_stats(const table& t) { table::statistics s = t.stats(); std::cout << " "; std::cout << "Number of buckets: "; std::cout << s.buckets / (1.0 * s.partitions); std::cout << " /partition" << std::endl; std::cout << " "; std::cout << "Number of vectors: "; std::cout << s.vectors / (1.0 * s.buckets); std::cout << " /bucket" << std::endl; } void print_results(const std::vector<vector>& fs) { unsigned int fn = 0; for (unsigned int i = 0; i < qn; i++) { vector q = qs[i]; vector t = gt[i]; if (vector::distance(q, t) <= r) { vector f = fs[i]; if (f.size() == 0 || vector::distance(q, f) > r) { fn++; } } } std::cout << " "; std::cout << "False negatives: "; std::cout << fn / (1.0 * qn); std::cout << " /query" << std::endl; } BENCHMARK(table, insert_linear, runs, vn / runs) { unsigned int i = vi++ % vn; t_lin.insert(vs[i]); } BENCHMARK(table, insert_classic, runs, vn / runs) { unsigned int i = vi++ % vn; t_cla.insert(vs[i]); if (i == vn - 1) { print_stats(t_cla); } } BENCHMARK(table, insert_covering, runs, vn / runs) { unsigned int i = vi++ % vn; t_cov.insert(vs[i]); if (i == vn - 1) { print_stats(t_cov); } } BENCHMARK(table, query_linear, runs, qn / runs) { unsigned int i = qi++ % qn; vector q = qs[i]; vector r = t_lin.query(q); gt.push_back(r); } std::vector<vector> vf_cla; BENCHMARK(table, query_classic, runs, qn / runs) { unsigned int i = qi++ % qn; vector q = qs[i]; vector t = gt[i]; vf_cla.push_back(t_cla.query(q)); if (i == qn - 1) { print_results(vf_cla); } } std::vector<vector> vf_cov; BENCHMARK(table, query_covering, runs, qn / runs) { unsigned int i = qi++ % qn; vector q = qs[i]; vector t = gt[i]; vf_cov.push_back(t_cov.query(q)); if (i == qn - 1) { print_results(vf_cov); } }
mit
curtsheller/BootstrapFourPresenter
src/Pagination/BootstrapFourPresenter.php
3851
<?php namespace CurtSheller\Pagination; use Illuminate\Pagination\BootstrapThreePresenter; /* Based on an article at: http://laravelista.com/laravel-custom-pagination-presenter/ The render() method accepts an Illuminate\Contracts\Pagination\Presenter instance. You can create a custom class that implements that contract and pass it to the render() method. $users = App\User::paginate(15); {!! with(new \App\Services\Pagination\BootstrapFourPresenter($users))->render() !!} */ class BootstrapFourPresenter extends BootstrapThreePresenter { /** * Convert the URL window into Bootstrap HTML. * * @return string */ public function render() { if ($this->hasPages()) { return sprintf( '<nav><ul class="pagination">%s %s %s</ul></nav>', $this->getPreviousButton(), $this->getLinks(), $this->getNextButton() ); } return ''; } /** * Get the previous page pagination element. * * @param string $text * @return string */ public function getPreviousButton($text = '<span aria-hidden="true"><i class="fa fa-arrow-circle-left"></i></span><span class="sr-only">Previous</span>') { // If the current page is less than or equal to one, it means we can't go any // further back in the pages, so we will render a disabled previous button // when that is the case. Otherwise, we will give it an active "status". if ($this->paginator->currentPage() <= 1) { return $this->getDisabledTextWrapper($text); } $url = $this->paginator->url( $this->paginator->currentPage() - 1 ); return $this->getPageLinkWrapper($url, $text, 'prev'); } /** * Get the next page pagination element. * * @param string $text * @return string */ public function getNextButton($text = '<span aria-hidden="true"><i class="fa fa-arrow-circle-right"></i></span><span class="sr-only">Next</span>') { // If the current page is greater than or equal to the last page, it means we // can't go any further into the pages, as we're already on this last page // that is available, so we will make it the "next" link style disabled. if (! $this->paginator->hasMorePages()) { return $this->getDisabledTextWrapper($text); } $url = $this->paginator->url($this->paginator->currentPage() + 1); return $this->getPageLinkWrapper($url, $text, 'next'); } /** * Get HTML wrapper for an available page link. * * @param string $url * @param int $page * @param string|null $rel * @return string */ protected function getAvailablePageWrapper($url, $page, $rel = null) { $rel = is_null($rel) ? '' : ' rel="'.$rel.'"'; return '<li class="page-item"><a class="page-link" href="'.htmlentities($url).'"'.$rel.'>'.$page.'</a></li>'; } /** * Get HTML wrapper for disabled text. * * @param string $text * @return string */ protected function getDisabledTextWrapper($text) { return '<li class="page-item disabled"><a class="page-link" href="#">'.$text.'</a></li>'; } /** * Get HTML wrapper for active text. * * @param string $text * @return string */ protected function getActivePageWrapper($text) { return '<li class="page-item active"><a class="page-link" href="#">'.$text.'</a> <span class="sr-only">(current)</span></li>'; } /** * Get a pagination "dot" element. * * @return string */ protected function getDots() { return $this->getDisabledTextWrapper('&hellip;'); } }
mit
toksaitov/scenario
lib/scenario/objects/rubik.rb
14648
# Scenario is a Ruby domain-specific language for graphics. # Copyright (C) 2010 Dmitrii Toksaitov # # This file is part of Scenario. # # Released under the MIT License. module Scenario class Rubik < Generic Block = Struct.new(:color, :texture) SIDES = {0 => [[:x, :y], [ 0, 0, -1]], 1 => [[:x, :z], [ 0, -1, 0]], 2 => [[:x, :y], [ 0, 0, 3]], 3 => [[:x, :z], [ 0, 3, 0]], 4 => [[:z, :y], [ 3, 0, 0]], 5 => [[:z, :y], [-1, 0, 0]]} meta_accessor :speed meta_accessor :colors, :textures attr_reader :structure, :working def initialize @block = [Cube, lambda { scale 0.4 }] @core = [Cube, lambda { scale 1; color 0, 0, 0 }] @colors = [[1, 0, 0], [0, 0, 1], [0, 1, 0], [1, 1, 1], [0, 1, 1], [1, 1, 0]] @textures = [] @speed = 6 super initialize_structure() initialize_objects() @working = false @container = nil @rotation_specs = [] idle_strategies << method(:update) end def block(*args, &block) unless args.empty? @block = [args.first, block] end @block end def core(*args, &block) unless args.empty? @core = [args.first, block] end @core end def textures(*args) @textures ||= [] if args.size == 1 arg = args.first case arg when Array @textures = arg when Hash rules = {:first => 0, :second => 1, :third => 2, :fourth => 3, :fifth => 4, :sixth => 5} arg.each do |key, texture| (@textures[rules[key]] = texture) rescue nil end when String @textures = extract_textures(arg) end elsif args.size > 1 @textures = args end @textures end def rotate(how, direction, row) result = false unless @working @working = result = true process_move(@structure.rotate(how, direction, row)) end result end def randomize result = false unless @working @working = result = true process_move(@structure.randomize()) end result end def solved? @structure.solved? end def paint apply_color() apply_line_width() apply_pattern() apply_lighting_status() glPushMatrix() apply_position() apply_rotation() apply_scale() notify(:@objects, :on_display_event) glPopMatrix() restore_lighting_status() end private def process_move(blocks) initialize_container(blocks) initialize_objects() end def update if @working and @container and @rotation_specs case @rotation_specs.second when :forward operation = :- when :backward operation = :+ else return end case @rotation_specs.first when :horizontally angle = :y when :vertically case @rotation_specs.third when 0..2 angle = :x when 3..5 angle = :z operation = (operation == :- ? :+ : :-) else return end else return end @container.angle(angle => (@container.angle(angle).send(operation, @speed))) if @container.angle(angle).abs >= 90 @container.angle(angle => 90 * (@container.angle(angle) < 0 ? -1 : 1)) @working = false @container = nil @rotation_specs = nil initialize_objects() @structure.update() end end end def initialize_structure @structure = RubikStructure.new sides = initialize_side_faces() 6.times do |id| 3.times do |i| 3.times do |j| @structure.blocks[id].ids[i][j] = sides[id][i][j] end end end @structure.on_update do |group| 3.times do |i| 3.times do |j| block = group.ids[i][j] group.objects[i][j].color(*block.color) group.objects[i][j].texture(block.texture) end end end 6.times do |id| side = SIDES[id] 3.times do |i| 3.times do |j| block = @block.first.new(&@block.second) if [1, 2].include?(id) block.position(side[0].first => i, side[0].second => 2 - j) else block.position(side[0].first => i, side[0].second => j) end block.position(block.x + side[1].first - 1, block.y + side[1].second - 1, block.z + side[1].third - 1) block.color(*side.third) @structure[id].objects[i][j] = block end end end @structure.update() @structure end #noinspection RubyScope,RubyDynamicConstAssignment def initialize_side_faces result = Array.new(6) 6.times do |id| color = colors[id] texture = textures[id] if texture.is_a?(String) texture = Image.read(texture).first end if texture part_width = texture.columns / 3 part_height = texture.rows / 3 end result[id] = Array.new(3) { Array.new(3) } 3.times do |i| 3.times do |j| texture_part = nil if texture texture_part = Texture2D.new do image(ImageProxy[texture.crop(j * part_width, i * part_height, part_width, part_height)]) end end result[id][i][j] = Block.new(color, texture_part) end end end result end def extract_textures(texture) result = [] if texture.is_a?(String) texture = Image.read(texture).first end if texture part_width = texture.columns / 6 part_height = texture.rows 6.times do |side| texture_part = texture.crop(side * part_width, 0, part_width, part_height, true) result[side] = texture_part if texture_part end end result end def initialize_container(blocks) @container = Container.new @rotation_specs = blocks.first blocks.last.each do |block| side, i, j = block; @container.object(@structure[side].objects[i][j]) end @container end def initialize_objects @objects = [@core.first.new(&@core.second)] if @core 6.times do |side| 3.times do |i| 3.times do |j| object = @structure[side].objects[i][j] unless @container and @container.objects.include?(object) @objects << object end end end end @objects << @container if @container @objects end end class RubikStructure HORIZONTAL_FORWARD_SHIFTS = [[3, 0], [2, 3], [1, 2], [0, 1]] HORIZONTAL_BACKWARD_SHIFTS = [[1, 0], [2, 1], [3, 2], [0, 3]] VERTICAL_FORWARD_SHIFTS = [[5, 0], [2, 5], [4, 2], [0, 4]] VERTICAL_BACKWARD_SHIFTS = [[4, 0], [2, 4], [5, 2], [0, 5]] VERTICAL_FORWARD_SIDE_SHIFTS = [[5, 1], [3, 5], [4, 3], [1, 4]] VERTICAL_BACKWARD_SIDE_SHIFTS = [[4, 1], [3, 4], [5, 3], [1, 5]] RULES = {:horizontally => {:forward => {0 => {:shift => HORIZONTAL_FORWARD_SHIFTS, :rotate => [[5, 3]]}, 1 => {:shift => HORIZONTAL_FORWARD_SHIFTS}, 2 => {:shift => HORIZONTAL_FORWARD_SHIFTS, :rotate => [[4, 3]]}}, :backward => {0 => {:shift => HORIZONTAL_BACKWARD_SHIFTS, :rotate => [[5, 1]]}, 1 => {:shift => HORIZONTAL_BACKWARD_SHIFTS}, 2 => {:shift => HORIZONTAL_BACKWARD_SHIFTS, :rotate => [[4, 1]]}}}, :vertically => {:forward => {0 => {:shift => VERTICAL_FORWARD_SHIFTS, :rotate => [[1, 1]]}, 1 => {:shift => VERTICAL_FORWARD_SHIFTS}, 2 => {:shift => VERTICAL_FORWARD_SHIFTS, :rotate => [[3, 3]]}, 3 => {:shift => VERTICAL_FORWARD_SIDE_SHIFTS, :rotate => [[2, 1]]}, 4 => {:shift => VERTICAL_FORWARD_SIDE_SHIFTS}, 5 => {:shift => VERTICAL_FORWARD_SIDE_SHIFTS, :rotate => [[0, 3]]}}, :backward => {0 => {:shift => VERTICAL_BACKWARD_SHIFTS, :rotate => [[1, 3]]}, 1 => {:shift => VERTICAL_BACKWARD_SHIFTS}, 2 => {:shift => VERTICAL_BACKWARD_SHIFTS, :rotate => [[3, 1]]}, 3 => {:shift => VERTICAL_BACKWARD_SIDE_SHIFTS, :rotate => [[2, 3]]}, 4 => {:shift => VERTICAL_BACKWARD_SIDE_SHIFTS}, 5 => {:shift => VERTICAL_BACKWARD_SIDE_SHIFTS, :rotate => [[0, 1]]}}}} Block = Struct.new(:ids, :objects) attr_accessor :blocks, :update_proc def initialize srand(Time.now.to_i()) @blocks = {} 6.times do |i| @blocks[i] = Block.new(Array.new(3) { Array.new(3, i) }, Array.new(3) { Array.new(3) }) end @update_proc = nil end def [](side) @blocks[side] end def on_update(&block) @update_proc = block if block_given? end def rotate(how, direction, arg) row = arg.is_a?(Hash) ? (arg[:row] || arg[:column]) : arg tasks = RULES[how][direction][row] result = [[how, direction, row], []] result[1] += perform_shift_tasks(tasks[:shift], how, row) result[1] += perform_rotation_tasks(tasks[:rotate]) result end def randomize how = [:horizontally, :vertically].sample direction = [:forward, :backward].sample row = (how == :horizontally ? (0..2).random.round().to_i() : (0..5).random.round().to_i()) rotate(how, direction, row) end def solved? result = true 6.times do |side| ids = @blocks[side].ids first_block = ids[0].first 3.times do |i| 3.times do |j| (result = false; break) if ids[i][j] != first_block end end break unless result end result end def update @blocks.each do |key, group| @update_proc.call(group) if @update_proc end end private def perform_shift_tasks(task, how, row) result = [] task.try(:each) do |shift| 3.times do |i| consumer = @blocks[shift.second].ids producer = @blocks[shift.first].ids case how when :horizontally consumer_column = producer_column = row consumer_row = producer_row = i when :vertically consumer_column = producer_column = i consumer_row = producer_row = row if row > 2 actual_row = row % 3 case shift.second when 3 consumer_column = 2 - i consumer_row = 2 - actual_row when 4 consumer_row = i consumer_column = 2 - actual_row when 5 consumer_row = 2 - i consumer_column = 2 - actual_row else consumer_row = actual_row end case shift.first when 3 producer_column = 2 - i producer_row = 2 - actual_row when 4 producer_row = i producer_column = 2 - actual_row when 5 producer_row = 2 - i producer_column = 2 - actual_row else producer_row = actual_row end else consumer_column = [2, 5].include?(shift.second) ? 2 - i : i producer_column = [2, 5].include?(shift.first) ? 2 - i : i consumer_row = shift.second == 2 ? 2 - row : row producer_row = shift.first == 2 ? 2 - row : row end else return end consumer = consumer[consumer_column] producer = producer[producer_column] if producer[producer_row].is_a?(Array) consumer[consumer_row] = [consumer[consumer_row], producer[producer_row].first] result << [shift.second, consumer_column, consumer_row] else consumer[consumer_row] = [consumer[consumer_row], producer[producer_row]] result << [shift.second, consumer_column, consumer_row] end end end normalize_blocks(result) result end def normalize_blocks(blocks) blocks.each do |block| row = @blocks[block.first].ids[block.second] if row[block.third].is_a?(Array) row[block.third] = row[block.third].last end end end def perform_rotation_tasks(tasks) result = [] tasks.try(:each) do |rotation| rotate_side!(@blocks[rotation.first].ids, rotation.last) 3.times do |i| 3.times do |j| result << [rotation.first, i, j] end end end result end def rotate_side!(container, rotations = 1) result = container rotations.times do helper = [] 3.times do |i| helper[i] = [] 3.times do |j| helper[i][j] = result[result.size - j - 1][i] end end result = helper end 3.times do |i| 3.times do |j| container[i][j] = result[i][j] end end container end end end
mit
eickegao/XamariniOSDemo
FirstXamariniOSDemo/FirstXamariniOSDemo/AppDelegate.cs
1441
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace FirstXamariniOSDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; set; } // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { } } }
mit
Cartman34/MyCraftManager
libs/entitydescriptor/TypeDescriptor.php
2722
<?php abstract class TypeDescriptor { protected $name; protected $writable; protected $nullable; // public function __construct() { // } /** * Get the type name * @return string the type name */ public function getName() { return $this->name; } /** * Get true if field is writable * @return boolean */ public function isWritable() { return $this->writable; } /** * Get true if field is nullable * @return boolean */ public function isNullable() { return $this->nullable; } /** * Get the html input attributes string for the given args * @return string */ public function htmlInputAttr($args) { return ''; } /** * Get the html input attributes array for the given Field descriptor * @return string[] */ public function getHTMLInputAttr($Field) { return array(); } /** * Get true if we consider null an empty input string * @return boolean */ public function emptyIsNull($field) { return true; } /** * Parse args from field declaration * @param string[] $args Arguments * @return stdClass */ public function parseArgs(array $args) { return new stdClass(); } /** * Validate value * * @param FieldDescriptor $field The field to validate * @param string $value The field value to validate * @param array $input The input to validate * @param PermanentEntity $ref The object to update, may be null */ public function validate(FieldDescriptor $field, &$value, $input, &$ref) {} /** * Format value before being validated * * @param FieldDescriptor $field The field to format * @param string $value The field value to format * @param array $input The input to validate * @param PermanentEntity $ref The object to update, may be null */ public function preFormat(FieldDescriptor $field, &$value, $input, &$ref) {} /** * Format value after being validated * * @param FieldDescriptor $field The field to parse * @param string $value The field value to parse */ public function format(FieldDescriptor $field, &$value) {} /** * Parse the value from SQL scalar to PHP type * * @param FieldDescriptor $field The field to parse * @param string $value The field value to parse * @return string The parse $value * @see PermanentObject::formatFieldValue() */ public function parseValue(FieldDescriptor $field, $value) { return $value; } /** * Format the value from PHP type to SQL scalar * * @param FieldDescriptor $field The field to parse * @param string $value The field value to parse * @return string The parse $value * @see PermanentObject::formatFieldValue() */ public function formatValue(FieldDescriptor $field, $value) { return $value; } }
mit
okfde/inkubator
config/routes.rb
2172
OkfIncubator::Application.routes.draw do resources :ideas do get :edit_votes_finance post :update_votes_finance get :edit_finance post :update_finance get :edit_mentor post :update_mentor get 'votes' => 'ideas#edit_votes' post :update_votes resources :comments end devise_for :users devise_scope :user do root :to => "ideas#index" end root :to => "ideas#index" # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root :to => 'welcome#index' # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id))(.:format)' end
mit
imazen/CppSharp
src/Generator/Generators/CSharp/CSharpMarshal.cs
23832
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CppSharp.AST; using CppSharp.AST.Extensions; using CppSharp.Types; using Type = CppSharp.AST.Type; namespace CppSharp.Generators.CSharp { public enum CSharpMarshalKind { Unknown, NativeField } public class CSharpMarshalContext : MarshalContext { public CSharpMarshalContext(Driver driver) : base(driver) { Kind = CSharpMarshalKind.Unknown; ArgumentPrefix = new TextGenerator(); Cleanup = new TextGenerator(); } public CSharpMarshalKind Kind { get; set; } public QualifiedType FullType; public TextGenerator ArgumentPrefix { get; private set; } public TextGenerator Cleanup { get; private set; } } public abstract class CSharpMarshalPrinter : MarshalPrinter { public CSharpMarshalContext CSharpContext { get { return Context as CSharpMarshalContext; } } protected CSharpMarshalPrinter(CSharpMarshalContext context) : base(context) { Options.VisitFunctionParameters = false; Options.VisitTemplateArguments = false; } public override bool VisitMemberPointerType(MemberPointerType member, TypeQualifiers quals) { return false; } } public class CSharpMarshalNativeToManagedPrinter : CSharpMarshalPrinter { public CSharpMarshalNativeToManagedPrinter(CSharpMarshalContext context) : base(context) { Context.MarshalToManaged = this; } public static string QualifiedIdentifier(Declaration decl) { var names = new List<string> { decl.Name }; var ctx = decl.Namespace; while (ctx != null) { if (!string.IsNullOrWhiteSpace(ctx.Name)) names.Add(ctx.Name); ctx = ctx.Namespace; } //if (Options.GenerateLibraryNamespace) // names.Add(Options.OutputNamespace); names.Reverse(); return string.Join(".", names); } public override bool VisitType(Type type, TypeQualifiers quals) { TypeMap typeMap; if (Context.Driver.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) { typeMap.Type = type; typeMap.CSharpMarshalToManaged(Context); return false; } return true; } public override bool VisitDeclaration(Declaration decl) { TypeMap typeMap; if (Context.Driver.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling) { typeMap.Declaration = decl; typeMap.CSharpMarshalToManaged(Context); return false; } return true; } public override bool VisitArrayType(ArrayType array, TypeQualifiers quals) { if (!VisitType(array, quals)) return false; switch (array.SizeType) { case ArrayType.ArraySize.Constant: var supportBefore = Context.SupportBefore; string value = Generator.GeneratedIdentifier("value"); supportBefore.WriteLine("{0}[] {1} = null;", array.Type, value, array.Size); supportBefore.WriteLine("if ({0} != null)", Context.ReturnVarName); supportBefore.WriteStartBraceIndent(); supportBefore.WriteLine("{0} = new {1}[{2}];", value, array.Type, array.Size); supportBefore.WriteLine("for (int i = 0; i < {0}; i++)", array.Size); if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void)) supportBefore.WriteLineIndent("{0}[i] = new global::System.IntPtr({1}[i]);", value, Context.ReturnVarName); else supportBefore.WriteLineIndent("{0}[i] = {1}[i];", value, Context.ReturnVarName); supportBefore.WriteCloseBraceIndent(); Context.Return.Write(value); break; case ArrayType.ArraySize.Variable: Context.Return.Write("null"); break; } return true; } public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals) { if (!VisitType(pointer, quals)) return false; var pointee = pointer.Pointee.Desugar(); if (CSharpTypePrinter.IsConstCharString(pointer)) { Context.Return.Write(MarshalStringToManaged(Context.ReturnVarName, pointer.Pointee.Desugar() as BuiltinType)); return true; } PrimitiveType primitive; if (pointee.IsPrimitiveType(out primitive) || pointee.IsEnumType()) { var param = Context.Parameter; if (param != null && (param.IsOut || param.IsInOut)) { Context.Return.Write("_{0}", param.Name); return true; } Context.Return.Write(Context.ReturnVarName); return true; } return pointer.Pointee.Visit(this, quals); } private string MarshalStringToManaged(string varName, BuiltinType type) { var encoding = type.Type == PrimitiveType.Char ? Encoding.ASCII : Encoding.Unicode; if (Equals(encoding, Encoding.ASCII)) encoding = Context.Driver.Options.Encoding; if (Equals(encoding, Encoding.ASCII)) return string.Format("Marshal.PtrToStringAnsi({0})", varName); if (Equals(encoding, Encoding.Unicode) || Equals(encoding, Encoding.BigEndianUnicode)) return string.Format("Marshal.PtrToStringUni({0})", varName); throw new NotSupportedException(string.Format("{0} is not supported yet.", Context.Driver.Options.Encoding.EncodingName)); } public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals) { switch (primitive) { case PrimitiveType.Void: return true; case PrimitiveType.Bool: case PrimitiveType.Char: case PrimitiveType.UChar: case PrimitiveType.Short: case PrimitiveType.UShort: case PrimitiveType.Int: case PrimitiveType.UInt: case PrimitiveType.Long: case PrimitiveType.ULong: case PrimitiveType.LongLong: case PrimitiveType.ULongLong: case PrimitiveType.Float: case PrimitiveType.Double: case PrimitiveType.WideChar: case PrimitiveType.Null: Context.Return.Write(Context.ReturnVarName); return true; case PrimitiveType.Char16: return false; } throw new NotImplementedException(); } public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals) { if (!VisitType(typedef, quals)) return false; var decl = typedef.Declaration; FunctionType function; if (decl.Type.IsPointerTo(out function)) { var ptrName = Generator.GeneratedIdentifier("ptr") + Context.ParameterIndex; Context.SupportBefore.WriteLine("var {0} = {1};", ptrName, Context.ReturnVarName); Context.Return.Write("({1})Marshal.GetDelegateForFunctionPointer({0}, typeof({1}))", ptrName, typedef.ToString()); return true; } return decl.Type.Visit(this); } public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals) { var ptrName = Generator.GeneratedIdentifier("ptr") + Context.ParameterIndex; Context.SupportBefore.WriteLine("var {0} = {1};", ptrName, Context.ReturnVarName); Context.Return.Write("({1})Marshal.GetDelegateForFunctionPointer({0}, typeof({1}))", ptrName, function.ToString()); return true; } public override bool VisitClassDecl(Class @class) { var instance = Context.ReturnVarName; @class = @class.OriginalClass ?? @class; Type returnType = Context.ReturnType.Type.Desugar(); var type = QualifiedIdentifier(@class) + (Context.Driver.Options.GenerateAbstractImpls && @class.IsAbstract ? "Internal" : ""); if (returnType.IsAddress()) Context.Return.Write("({0} == IntPtr.Zero) ? {1} : {2}.{3}({0})", instance, @class.IsRefType ? "null" : string.Format("new {0}()", type), type, Helpers.CreateInstanceIdentifier); else Context.Return.Write("{0}.{1}({2})", type, Helpers.CreateInstanceIdentifier, instance); return true; } private static bool FindTypeMap(ITypeMapDatabase typeMapDatabase, Class @class, out TypeMap typeMap) { return typeMapDatabase.FindTypeMap(@class, out typeMap) || (@class.HasBase && FindTypeMap(typeMapDatabase, @class.Bases[0].Class, out typeMap)); } public override bool VisitEnumDecl(Enumeration @enum) { Context.Return.Write("{0}", Context.ReturnVarName); return true; } public override bool VisitParameterDecl(Parameter parameter) { if (parameter.Usage == ParameterUsage.Unknown || parameter.IsIn) return base.VisitParameterDecl(parameter); var ctx = new CSharpMarshalContext(base.Context.Driver) { ReturnType = base.Context.ReturnType, ReturnVarName = base.Context.ReturnVarName }; var marshal = new CSharpMarshalNativeToManagedPrinter(ctx); parameter.Type.Visit(marshal); if (!string.IsNullOrWhiteSpace(ctx.SupportBefore)) Context.SupportBefore.WriteLine(ctx.SupportBefore); if (!string.IsNullOrWhiteSpace(ctx.Return)) { Context.SupportBefore.WriteLine("var _{0} = {1};", parameter.Name, ctx.Return); } Context.Return.Write("_{0}", parameter.Name); return true; } } public class CSharpMarshalManagedToNativePrinter : CSharpMarshalPrinter { public CSharpMarshalManagedToNativePrinter(CSharpMarshalContext context) : base(context) { Context.MarshalToNative = this; } public override bool VisitType(Type type, TypeQualifiers quals) { TypeMap typeMap; if (Context.Driver.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) { typeMap.Type = type; typeMap.CSharpMarshalToNative(Context); return false; } return true; } public override bool VisitDeclaration(Declaration decl) { TypeMap typeMap; if (Context.Driver.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling) { typeMap.Declaration = decl; typeMap.CSharpMarshalToNative(Context); return false; } return true; } public override bool VisitArrayType(ArrayType array, TypeQualifiers quals) { if (!VisitType(array, quals)) return false; switch (array.SizeType) { case ArrayType.ArraySize.Constant: var supportBefore = Context.SupportBefore; supportBefore.WriteLine("if ({0} != null)", Context.ArgName); supportBefore.WriteStartBraceIndent(); supportBefore.WriteLine("for (int i = 0; i < {0}; i++)", array.Size); supportBefore.WriteLineIndent("{0}[i] = {1}[i]{2};", Context.ReturnVarName, Context.ArgName, array.Type.IsPointerToPrimitiveType(PrimitiveType.Void) ? ".ToPointer()" : string.Empty); supportBefore.WriteCloseBraceIndent(); break; default: Context.Return.Write("null"); break; } return true; } public bool VisitDelegateType(FunctionType function, string type) { Context.Return.Write("Marshal.GetFunctionPointerForDelegate({0})", Context.Parameter.Name); return true; } public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals) { if (!VisitType(pointer, quals)) return false; var pointee = pointer.Pointee.Desugar(); if ((pointee.IsPrimitiveType(PrimitiveType.Char) || pointee.IsPrimitiveType(PrimitiveType.WideChar)) && pointer.QualifiedPointee.Qualifiers.IsConst) { if (Context.Parameter.IsOut) { Context.Return.Write("IntPtr.Zero"); CSharpContext.ArgumentPrefix.Write("&"); } else if (Context.Parameter.IsInOut) { Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name)); CSharpContext.ArgumentPrefix.Write("&"); } else { Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name)); CSharpContext.Cleanup.WriteLine("Marshal.FreeHGlobal({0});", Context.ArgName); } return true; } if (pointee is FunctionType) { var function = pointee as FunctionType; return VisitDelegateType(function, function.ToString()); } Class @class; if (pointee.TryGetClass(out @class) && @class.IsValueType) { if (Context.Parameter.Usage == ParameterUsage.Out) { Context.SupportBefore.WriteLine("var {0} = new {1}.Internal();", Generator.GeneratedIdentifier(Context.ArgName), @class.Name); } else { Context.SupportBefore.WriteLine("var {0} = {1}.ToInternal();", Generator.GeneratedIdentifier(Context.ArgName), Context.Parameter.Name); } Context.Return.Write("new global::System.IntPtr(&{0})", Generator.GeneratedIdentifier(Context.ArgName)); return true; } PrimitiveType primitive; if (pointee.IsPrimitiveType(out primitive) || pointee.IsEnumType()) { var param = Context.Parameter; // From MSDN: "note that a ref or out parameter is classified as a moveable // variable". This means we must create a local variable to hold the result // and then assign this value to the parameter. if (param.IsOut || param.IsInOut) { var typeName = Type.TypePrinterDelegate(pointee); if (param.IsInOut) Context.SupportBefore.WriteLine("{0} _{1} = {1};", typeName, param.Name); else Context.SupportBefore.WriteLine("{0} _{1};", typeName, param.Name); Context.Return.Write("&_{0}", param.Name); } else Context.Return.Write(Context.Parameter.Name); return true; } return pointer.Pointee.Visit(this, quals); } private string MarshalStringToUnmanaged(string varName) { if (Equals(Context.Driver.Options.Encoding, Encoding.ASCII)) { return string.Format("Marshal.StringToHGlobalAnsi({0})", varName); } if (Equals(Context.Driver.Options.Encoding, Encoding.Unicode) || Equals(Context.Driver.Options.Encoding, Encoding.BigEndianUnicode)) { return string.Format("Marshal.StringToHGlobalUni({0})", varName); } throw new NotSupportedException(string.Format("{0} is not supported yet.", Context.Driver.Options.Encoding.EncodingName)); } public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals) { switch (primitive) { case PrimitiveType.Void: return true; case PrimitiveType.Bool: case PrimitiveType.Char: case PrimitiveType.UChar: case PrimitiveType.Short: case PrimitiveType.UShort: case PrimitiveType.Int: case PrimitiveType.UInt: case PrimitiveType.Long: case PrimitiveType.ULong: case PrimitiveType.LongLong: case PrimitiveType.ULongLong: case PrimitiveType.Float: case PrimitiveType.Double: case PrimitiveType.WideChar: Context.Return.Write(Helpers.SafeIdentifier(Context.Parameter.Name)); return true; case PrimitiveType.Char16: return false; } throw new NotImplementedException(); } public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals) { if (!VisitType(typedef, quals)) return false; var decl = typedef.Declaration; FunctionType func; if (decl.Type.IsPointerTo<FunctionType>(out func)) { VisitDelegateType(func, typedef.Declaration.OriginalName); return true; } return decl.Type.Visit(this); } public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals) { Context.Return.Write(param.Parameter.Name); return true; } public override bool VisitClassDecl(Class @class) { if (!VisitDeclaration(@class)) return false; if (@class.IsValueType) { MarshalValueClass(); } else { MarshalRefClass(@class); } return true; } private void MarshalRefClass(Class @class) { var method = Context.Function as Method; if (method != null && method.Conversion == MethodConversionKind.FunctionToInstanceMethod && Context.ParameterIndex == 0) { Context.Return.Write("{0}", Helpers.InstanceIdentifier); return; } string param = Context.Parameter.Name; Type type = Context.Parameter.Type.Desugar(); if (type.IsAddress()) { Class decl; if (type.TryGetClass(out decl) && decl.IsValueType) Context.Return.Write("{0}.{1}", param, Helpers.InstanceIdentifier); else Context.Return.Write("{0} == ({2}) null ? global::System.IntPtr.Zero : {0}.{1}", param, Helpers.InstanceIdentifier, type); return; } var qualifiedIdentifier = CSharpMarshalNativeToManagedPrinter.QualifiedIdentifier( @class.OriginalClass ?? @class); Context.Return.Write( "ReferenceEquals({0}, null) ? new {1}.Internal() : *({1}.Internal*) ({0}.{2})", param, qualifiedIdentifier, Helpers.InstanceIdentifier); } private void MarshalValueClass() { Context.Return.Write("{0}.ToInternal()", Context.Parameter.Name); } public override bool VisitFieldDecl(Field field) { if (!VisitDeclaration(field)) return false; Context.Parameter = new Parameter { Name = Context.ArgName, QualifiedType = field.QualifiedType }; return field.Type.Visit(this, field.QualifiedType.Qualifiers); } public override bool VisitProperty(Property property) { if (!VisitDeclaration(property)) return false; Context.Parameter = new Parameter { Name = Context.ArgName, QualifiedType = property.QualifiedType }; return base.VisitProperty(property); } public override bool VisitEnumDecl(Enumeration @enum) { Context.Return.Write(Helpers.SafeIdentifier(Context.Parameter.Name)); return true; } public override bool VisitClassTemplateDecl(ClassTemplate template) { return VisitClassDecl(template.TemplatedClass); } public override bool VisitFunctionTemplateDecl(FunctionTemplate template) { return template.TemplatedFunction.Visit(this); } } public static class CSharpMarshalExtensions { public static void CSharpMarshalToNative(this QualifiedType type, CSharpMarshalManagedToNativePrinter printer) { (printer.Context as CSharpMarshalContext).FullType = type; type.Visit(printer); } public static void CSharpMarshalToNative(this Type type, CSharpMarshalManagedToNativePrinter printer) { CSharpMarshalToNative(new QualifiedType(type), printer); } public static void CSharpMarshalToNative(this ITypedDecl decl, CSharpMarshalManagedToNativePrinter printer) { CSharpMarshalToNative(decl.QualifiedType, printer); } public static void CSharpMarshalToManaged(this QualifiedType type, CSharpMarshalNativeToManagedPrinter printer) { (printer.Context as CSharpMarshalContext).FullType = type; type.Visit(printer); } public static void CSharpMarshalToManaged(this Type type, CSharpMarshalNativeToManagedPrinter printer) { CSharpMarshalToManaged(new QualifiedType(type), printer); } public static void CSharpMarshalToManaged(this ITypedDecl decl, CSharpMarshalNativeToManagedPrinter printer) { CSharpMarshalToManaged(decl.QualifiedType, printer); } } }
mit
chadyred/fiscalite
src/Fiscalite/GestionFiscaliteBundle/Admin/ArticleCommuneAdmin.php
1530
<?php // src/Acme/DemoBundle/Admin/PostAdmin.php namespace Fiscalite\GestionFiscaliteBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; class ArticleCommuneAdmin extends Admin { // Fields to be shown on create/edit forms protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('id') ->add('vlmCne') ->add('vlmICO') ->add('vlmDept') ->add('tauxImpositionCommune') ->add('tauxImpositionSyndicats') ->add('tauxImpositionIntercommunalite') ->add('tauxImpositionTSE'); } // Fields to be shown on filter forms protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('id') ->add('vlmCne') ->add('vlmICO') ->add('vlmDept') ->add('tauxImpositionCommune') ->add('tauxImpositionSyndicats') ->add('tauxImpositionIntercommunalite') ->add('tauxImpositionTSE'); } // Fields to be shown on lists protected function configureListFields(ListMapper $listMapper) { $listMapper ->add('id') ->add('vlmCne') ->add('vlmICO') ->add('vlmDept') ->add('tauxImpositionCommune') ->add('tauxImpositionSyndicats') ->add('tauxImpositionIntercommunalite') ->add('tauxImpositionTSE'); } }
mit
oliversalzburg/cbc-kitten-scientists
packages/userscript/source/ui/TimeControlSettingsUi.ts
44877
import { CycleIndices, TimeControlBuildSettingsItem, TimeControlSettings, } from "../options/TimeControlSettings"; import { objectEntries } from "../tools/Entries"; import { ucfirst } from "../tools/Format"; import { isNil, Maybe, mustExist } from "../tools/Maybe"; import { Resource, Season } from "../types"; import { UserScript } from "../UserScript"; import { SettingsSectionUi } from "./SettingsSectionUi"; export class TimeControlSettingsUi extends SettingsSectionUi<TimeControlSettings> { readonly element: JQuery<HTMLElement>; private readonly _options: TimeControlSettings; private _itemsExpanded = false; private _resourcesList: Maybe<JQuery<HTMLElement>>; constructor(host: UserScript, religionOptions: TimeControlSettings = host.options.auto.timeCtrl) { super(host); this._options = religionOptions; const toggleName = "timeCtrl"; const itext = ucfirst(this._host.i18n("ui.timeCtrl")); // Our main element is a list item. const element = this._getSettingsPanel(toggleName, itext); this._options.$enabled = element.checkbox; element.checkbox.on("change", () => { if (element.checkbox.is(":checked") && this._options.enabled === false) { this._host.updateOptions(() => (this._options.enabled = true)); this._host.imessage("status.auto.enable", [itext]); } else if (!element.checkbox.is(":checked") && this._options.enabled === true) { this._host.updateOptions(() => (this._options.enabled = false)); this._host.imessage("status.auto.disable", [itext]); } }); // Create build items. // We create these in a list that is displayed when the user clicks the "items" button. const list = this._getOptionList(toggleName); element.items.on("click", () => { list.toggle(); this._itemsExpanded = !this._itemsExpanded; element.items.text(this._itemsExpanded ? "-" : "+"); element.items.prop( "title", this._itemsExpanded ? this._host.i18n("ui.itemsHide") : this._host.i18n("ui.itemsShow") ); }); const optionButtons = [ this._getOptionAccelerateTime( "accelerateTime", this._options.items.accelerateTime, this._host.i18n("option.accelerate") ), this._getOptionTimeSkip( "timeSkip", this._options.items.timeSkip, this._host.i18n("option.time.skip") ), this._getOptionReset( "reset", this._options.items.reset, this._host.i18n("option.time.reset") ), ]; list.append(...optionButtons); element.panel.append(list); this.element = element.panel; } private _getOptionTimeSkip( name: string, option: TimeControlSettings["items"]["timeSkip"], label: string ): JQuery<HTMLElement> { const element = this._getOption(name, option, label); const triggerButton = $("<div/>", { id: "set-timeSkip-subTrigger", text: this._host.i18n("ui.trigger"), //title: option.subTrigger, css: { cursor: "pointer", display: "inline-block", float: "right", paddingRight: "5px", }, }).data("option", option); option.$subTrigger = triggerButton; triggerButton.on("click", () => { const value = window.prompt( this._host.i18n("time.skip.trigger.set", []), option.subTrigger.toFixed(2) ); if (value !== null) { this._host.updateOptions(() => (option.subTrigger = parseFloat(value))); triggerButton[0].title = option.subTrigger.toFixed(2); } }); const maximunButton = $("<div/>", { id: "set-timeSkip-maximum", text: "⍐", title: this._host.i18n("ui.maximum"), //title: option.max, css: { cursor: "pointer", display: "inline-block", float: "right", paddingRight: "5px", }, }).data("option", option); option.$maximum = maximunButton; maximunButton.on("click", () => { const value = window.prompt( this._host.i18n("ui.max.set", [this._host.i18n("option.time.skip")]), option.maximum.toFixed(0) ); if (value !== null) { this._host.updateOptions(() => (option.maximum = parseFloat(value))); maximunButton[0].title = option.maximum.toFixed(0); } }); const cyclesButton = $("<div/>", { id: `toggle-cycle-${name}`, text: "↻", title: this._host.i18n("ui.cycles"), css: { cursor: "pointer", display: "inline-block", float: "right", paddingRight: "5px", }, }); const cyclesList = $("<ul/>", { id: `cycles-list-${name}`, css: { display: "none", paddingLeft: "20px" }, }); for ( let cycleIndex = 0; cycleIndex < this._host.gamePage.calendar.cycles.length; ++cycleIndex ) { cyclesList.append(this._getCycle(cycleIndex as CycleIndices, option)); } const seasonsButton = $("<div/>", { id: `toggle-seasons-${name}`, text: "🗓", title: this._host.i18n("trade.seasons"), css: { cursor: "pointer", display: "inline-block", float: "right", paddingRight: "5px", }, }); const seasonsList = $("<ul/>", { id: `seasons-list-${name}`, css: { display: "none", paddingLeft: "20px" }, }); // fill out the list with seasons seasonsList.append(this._getSeasonForTimeSkip("spring", option)); seasonsList.append(this._getSeasonForTimeSkip("summer", option)); seasonsList.append(this._getSeasonForTimeSkip("autumn", option)); seasonsList.append(this._getSeasonForTimeSkip("winter", option)); cyclesButton.on("click", function () { cyclesList.toggle(); seasonsList.toggle(false); }); seasonsButton.on("click", function () { cyclesList.toggle(false); seasonsList.toggle(); }); element.append( cyclesButton, seasonsButton, maximunButton, triggerButton, cyclesList, seasonsList ); return element; } private _getOptionReset( name: string, option: TimeControlSettings["items"]["reset"], label: string ): JQuery<HTMLElement> { const element = this._getOption(name, option, label); // Bonfire reset options const resetBuildList = this._getOptionList("reset-build"); resetBuildList.append( this._getResetOption( "hut", "build", this._options.buildItems.hut, this._host.i18n("$buildings.hut.label") ), this._getResetOption( "logHouse", "build", this._options.buildItems.logHouse, this._host.i18n("$buildings.logHouse.label") ), this._getResetOption( "mansion", "build", this._options.buildItems.mansion, this._host.i18n("$buildings.mansion.label"), true ), this._getResetOption( "workshop", "build", this._options.buildItems.workshop, this._host.i18n("$buildings.workshop.label") ), this._getResetOption( "factory", "build", this._options.buildItems.factory, this._host.i18n("$buildings.factory.label"), true ), this._getResetOption( "field", "build", this._options.buildItems.field, this._host.i18n("$buildings.field.label") ), this._getResetOption( "pasture", "build", this._options.buildItems.pasture, this._host.i18n("$buildings.pasture.label") ), this._getResetOption( "solarFarm", "build", this._options.buildItems.solarFarm, this._host.i18n("$buildings.solarfarm.label") ), this._getResetOption( "mine", "build", this._options.buildItems.mine, this._host.i18n("$buildings.mine.label") ), this._getResetOption( "lumberMill", "build", this._options.buildItems.lumberMill, this._host.i18n("$buildings.lumberMill.label") ), this._getResetOption( "aqueduct", "build", this._options.buildItems.aqueduct, this._host.i18n("$buildings.aqueduct.label") ), this._getResetOption( "hydroPlant", "build", this._options.buildItems.hydroPlant, this._host.i18n("$buildings.hydroplant.label") ), this._getResetOption( "oilWell", "build", this._options.buildItems.oilWell, this._host.i18n("$buildings.oilWell.label") ), this._getResetOption( "quarry", "build", this._options.buildItems.quarry, this._host.i18n("$buildings.quarry.label"), true ), this._getResetOption( "smelter", "build", this._options.buildItems.smelter, this._host.i18n("$buildings.smelter.label") ), this._getResetOption( "biolab", "build", this._options.buildItems.biolab, this._host.i18n("$buildings.biolab.label") ), this._getResetOption( "calciner", "build", this._options.buildItems.calciner, this._host.i18n("$buildings.calciner.label") ), this._getResetOption( "reactor", "build", this._options.buildItems.reactor, this._host.i18n("$buildings.reactor.label") ), this._getResetOption( "accelerator", "build", this._options.buildItems.accelerator, this._host.i18n("$buildings.accelerator.label") ), this._getResetOption( "steamworks", "build", this._options.buildItems.steamworks, this._host.i18n("$buildings.steamworks.label") ), this._getResetOption( "magneto", "build", this._options.buildItems.magneto, this._host.i18n("$buildings.magneto.label"), true ), this._getResetOption( "library", "build", this._options.buildItems.library, this._host.i18n("$buildings.library.label") ), this._getResetOption( "dataCenter", "build", this._options.buildItems.dataCenter, this._host.i18n("$buildings.dataCenter.label") ), this._getResetOption( "academy", "build", this._options.buildItems.academy, this._host.i18n("$buildings.academy.label") ), this._getResetOption( "observatory", "build", this._options.buildItems.observatory, this._host.i18n("$buildings.observatory.label"), true ), this._getResetOption( "amphitheatre", "build", this._options.buildItems.amphitheatre, this._host.i18n("$buildings.amphitheatre.label") ), this._getResetOption( "broadcastTower", "build", this._options.buildItems.broadcastTower, this._host.i18n("$buildings.broadcasttower.label") ), this._getResetOption( "tradepost", "build", this._options.buildItems.tradepost, this._host.i18n("$buildings.tradepost.label") ), this._getResetOption( "chapel", "build", this._options.buildItems.chapel, this._host.i18n("$buildings.chapel.label") ), this._getResetOption( "temple", "build", this._options.buildItems.temple, this._host.i18n("$buildings.temple.label") ), this._getResetOption( "mint", "build", this._options.buildItems.mint, this._host.i18n("$buildings.mint.label") ), this._getResetOption( "ziggurat", "build", this._options.buildItems.ziggurat, this._host.i18n("$buildings.ziggurat.label") ), this._getResetOption( "chronosphere", "build", this._options.buildItems.chronosphere, this._host.i18n("$buildings.chronosphere.label") ), this._getResetOption( "aiCore", "build", this._options.buildItems.aiCore, this._host.i18n("$buildings.aicore.label") ), this._getResetOption( "brewery", "build", this._options.buildItems.brewery, this._host.i18n("$buildings.brewery.label"), true ), this._getResetOption( "barn", "build", this._options.buildItems.barn, this._host.i18n("$buildings.barn.label") ), this._getResetOption( "harbor", "build", this._options.buildItems.harbor, this._host.i18n("$buildings.harbor.label") ), this._getResetOption( "warehouse", "build", this._options.buildItems.warehouse, this._host.i18n("$buildings.warehouse.label"), true ), this._getResetOption( "zebraOutpost", "build", this._options.buildItems.zebraOutpost, this._host.i18n("$buildings.zebraOutpost.label") ), this._getResetOption( "zebraWorkshop", "build", this._options.buildItems.zebraWorkshop, this._host.i18n("$buildings.zebraWorkshop.label") ), this._getResetOption( "zebraForge", "build", this._options.buildItems.zebraForge, this._host.i18n("$buildings.zebraForge.label") ) ); // Space reset options const resetSpaceList = this._getOptionList("reset-space"); resetSpaceList.append( this._getResetOption( "spaceElevator", "space", this._options.spaceItems.spaceElevator, this._host.i18n("$space.planet.cath.spaceElevator.label") ), this._getResetOption( "sattelite", "space", this._options.spaceItems.sattelite, this._host.i18n("$space.planet.cath.sattelite.label") ), this._getResetOption( "spaceStation", "space", this._options.spaceItems.spaceStation, this._host.i18n("$space.planet.cath.spaceStation.label"), true ), this._getResetOption( "moonOutpost", "space", this._options.spaceItems.moonOutpost, this._host.i18n("$space.planet.moon.moonOutpost.label") ), this._getResetOption( "moonBase", "space", this._options.spaceItems.moonBase, this._host.i18n("$space.planet.moon.moonBase.label"), true ), this._getResetOption( "planetCracker", "space", this._options.spaceItems.planetCracker, this._host.i18n("$space.planet.dune.planetCracker.label") ), this._getResetOption( "hydrofracturer", "space", this._options.spaceItems.hydrofracturer, this._host.i18n("$space.planet.dune.hydrofracturer.label") ), this._getResetOption( "spiceRefinery", "space", this._options.spaceItems.spiceRefinery, this._host.i18n("$space.planet.dune.spiceRefinery.label"), true ), this._getResetOption( "researchVessel", "space", this._options.spaceItems.researchVessel, this._host.i18n("$space.planet.piscine.researchVessel.label") ), this._getResetOption( "orbitalArray", "space", this._options.spaceItems.orbitalArray, this._host.i18n("$space.planet.piscine.orbitalArray.label"), true ), this._getResetOption( "sunlifter", "space", this._options.spaceItems.sunlifter, this._host.i18n("$space.planet.helios.sunlifter.label") ), this._getResetOption( "containmentChamber", "space", this._options.spaceItems.containmentChamber, this._host.i18n("$space.planet.helios.containmentChamber.label") ), this._getResetOption( "heatsink", "space", this._options.spaceItems.heatsink, this._host.i18n("$space.planet.helios.heatsink.label") ), this._getResetOption( "sunforge", "space", this._options.spaceItems.sunforge, this._host.i18n("$space.planet.helios.sunforge.label"), true ), this._getResetOption( "cryostation", "space", this._options.spaceItems.cryostation, this._host.i18n("$space.planet.terminus.cryostation.label"), true ), this._getResetOption( "spaceBeacon", "space", this._options.spaceItems.spaceBeacon, this._host.i18n("$space.planet.kairo.spaceBeacon.label"), true ), this._getResetOption( "terraformingStation", "space", this._options.spaceItems.terraformingStation, this._host.i18n("$space.planet.yarn.terraformingStation.label") ), this._getResetOption( "hydroponics", "space", this._options.spaceItems.hydroponics, this._host.i18n("$space.planet.yarn.hydroponics.label"), true ), this._getResetOption( "hrHarvester", "space", this._options.spaceItems.hrHarvester, this._host.i18n("$space.planet.umbra.hrHarvester.label"), true ), this._getResetOption( "entangler", "space", this._options.spaceItems.entangler, this._host.i18n("$space.planet.charon.entangler.label"), true ), this._getResetOption( "tectonic", "space", this._options.spaceItems.tectonic, this._host.i18n("$space.planet.centaurusSystem.tectonic.label") ), this._getResetOption( "moltenCore", "space", this._options.spaceItems.moltenCore, this._host.i18n("$space.planet.centaurusSystem.moltenCore.label") ) ); // Resources list const resetResourcesList = this._getResourceOptions(); for (const [item, resource] of objectEntries(this._options.resources)) { resetResourcesList.append( this._addNewResourceOptionForReset(item, item, resource, (_name, _resource) => { delete this._options.resources[_name]; }) ); this._setStockValue(item, resource.stockForReset, true); } // Religion reset options. const resetReligionList = this._getOptionList("reset-religion"); resetReligionList.append( this._getResetOption( "unicornPasture", "faith", this._options.religionItems.unicornPasture, this._host.i18n("$buildings.unicornPasture.label") ), this._getResetOption( "unicornTomb", "faith", this._options.religionItems.unicornTomb, this._host.i18n("$religion.zu.unicornTomb.label") ), this._getResetOption( "ivoryTower", "faith", this._options.religionItems.ivoryTower, this._host.i18n("$religion.zu.ivoryTower.label") ), this._getResetOption( "ivoryCitadel", "faith", this._options.religionItems.ivoryCitadel, this._host.i18n("$religion.zu.ivoryCitadel.label") ), this._getResetOption( "skyPalace", "faith", this._options.religionItems.skyPalace, this._host.i18n("$religion.zu.skyPalace.label") ), this._getResetOption( "unicornUtopia", "faith", this._options.religionItems.unicornUtopia, this._host.i18n("$religion.zu.unicornUtopia.label") ), this._getResetOption( "sunspire", "faith", this._options.religionItems.sunspire, this._host.i18n("$religion.zu.sunspire.label"), true ), this._getResetOption( "marker", "faith", this._options.religionItems.marker, this._host.i18n("$religion.zu.marker.label") ), this._getResetOption( "unicornGraveyard", "faith", this._options.religionItems.unicornGraveyard, this._host.i18n("$religion.zu.unicornGraveyard.label") ), this._getResetOption( "unicornNecropolis", "faith", this._options.religionItems.unicornNecropolis, this._host.i18n("$religion.zu.unicornNecropolis.label") ), this._getResetOption( "blackPyramid", "faith", this._options.religionItems.blackPyramid, this._host.i18n("$religion.zu.blackPyramid.label"), true ), this._getResetOption( "solarchant", "faith", this._options.religionItems.solarchant, this._host.i18n("$religion.ru.solarchant.label") ), this._getResetOption( "scholasticism", "faith", this._options.religionItems.scholasticism, this._host.i18n("$religion.ru.scholasticism.label") ), this._getResetOption( "goldenSpire", "faith", this._options.religionItems.goldenSpire, this._host.i18n("$religion.ru.goldenSpire.label") ), this._getResetOption( "sunAltar", "faith", this._options.religionItems.sunAltar, this._host.i18n("$religion.ru.sunAltar.label") ), this._getResetOption( "stainedGlass", "faith", this._options.religionItems.stainedGlass, this._host.i18n("$religion.ru.stainedGlass.label") ), this._getResetOption( "solarRevolution", "faith", this._options.religionItems.solarRevolution, this._host.i18n("$religion.ru.solarRevolution.label") ), this._getResetOption( "basilica", "faith", this._options.religionItems.basilica, this._host.i18n("$religion.ru.basilica.label") ), this._getResetOption( "templars", "faith", this._options.religionItems.templars, this._host.i18n("$religion.ru.templars.label") ), this._getResetOption( "apocripha", "faith", this._options.religionItems.apocripha, this._host.i18n("$religion.ru.apocripha.label") ), this._getResetOption( "transcendence", "faith", this._options.religionItems.transcendence, this._host.i18n("$religion.ru.transcendence.label"), true ), this._getResetOption( "blackObelisk", "faith", this._options.religionItems.blackObelisk, this._host.i18n("$religion.tu.blackObelisk.label") ), this._getResetOption( "blackNexus", "faith", this._options.religionItems.blackNexus, this._host.i18n("$religion.tu.blackNexus.label") ), this._getResetOption( "blackCore", "faith", this._options.religionItems.blackCore, this._host.i18n("$religion.tu.blackCore.label") ), this._getResetOption( "singularity", "faith", this._options.religionItems.singularity, this._host.i18n("$religion.tu.singularity.label") ), this._getResetOption( "blackLibrary", "faith", this._options.religionItems.blackLibrary, this._host.i18n("$religion.tu.blackLibrary.label") ), this._getResetOption( "blackRadiance", "faith", this._options.religionItems.blackRadiance, this._host.i18n("$religion.tu.blackRadiance.label") ), this._getResetOption( "blazar", "faith", this._options.religionItems.blazar, this._host.i18n("$religion.tu.blazar.label") ), this._getResetOption( "darkNova", "faith", this._options.religionItems.darkNova, this._host.i18n("$religion.tu.darkNova.label") ), this._getResetOption( "holyGenocide", "faith", this._options.religionItems.holyGenocide, this._host.i18n("$religion.tu.holyGenocide.label") ) ); const resetTimeList = this._getOptionList("reset-time"); resetTimeList.append( this._getResetOption( "temporalBattery", "time", this._options.timeItems.temporalBattery, this._host.i18n("$time.cfu.temporalBattery.label") ), this._getResetOption( "blastFurnace", "time", this._options.timeItems.blastFurnace, this._host.i18n("$time.cfu.blastFurnace.label") ), this._getResetOption( "timeBoiler", "time", this._options.timeItems.timeBoiler, this._host.i18n("$time.cfu.timeBoiler.label") ), this._getResetOption( "temporalAccelerator", "time", this._options.timeItems.temporalAccelerator, this._host.i18n("$time.cfu.temporalAccelerator.label") ), this._getResetOption( "temporalImpedance", "time", this._options.timeItems.temporalImpedance, this._host.i18n("$time.cfu.temporalImpedance.label") ), this._getResetOption( "ressourceRetrieval", "time", this._options.timeItems.ressourceRetrieval, this._host.i18n("$time.cfu.ressourceRetrieval.label"), true ), this._getResetOption( "cryochambers", "time", this._options.timeItems.cryochambers, this._host.i18n("$time.vsu.cryochambers.label") ), this._getResetOption( "voidHoover", "time", this._options.timeItems.voidHoover, this._host.i18n("$time.vsu.voidHoover.label") ), this._getResetOption( "voidRift", "time", this._options.timeItems.voidRift, this._host.i18n("$time.vsu.voidRift.label") ), this._getResetOption( "chronocontrol", "time", this._options.timeItems.chronocontrol, this._host.i18n("$time.vsu.chronocontrol.label") ), this._getResetOption( "voidResonator", "time", this._options.timeItems.voidResonator, this._host.i18n("$time.vsu.voidResonator.label") ) ); const buildButton = $("<div/>", { id: "toggle-reset-build", text: "🔥", title: this._host.i18n("ui.build"), css: { cursor: "pointer", display: "inline-block", filter: "grayscale(100%)", float: "right", paddingRight: "5px", }, }); const spaceButton = $("<div/>", { id: "toggle-reset-space", text: "🚀", title: this._host.i18n("ui.space"), css: { cursor: "pointer", display: "inline-block", filter: "grayscale(100%)", float: "right", paddingRight: "5px", }, }); const resourcesButton = $("<div/>", { id: "toggle-reset-resources", text: "🛠", title: this._host.i18n("ui.craft.resources"), css: { cursor: "pointer", display: "inline-block", float: "right", paddingRight: "5px", }, }); const religionButton = $("<div/>", { id: "toggle-reset-religion", text: "🐈", title: this._host.i18n("ui.faith"), css: { cursor: "pointer", display: "inline-block", filter: "grayscale(100%)", float: "right", paddingRight: "5px", }, }); const timeButton = $("<div/>", { id: "toggle-reset-time", text: "🕙", title: this._host.i18n("ui.time"), css: { cursor: "pointer", display: "inline-block", filter: "grayscale(100%)", float: "right", paddingRight: "5px", }, }); buildButton.on("click", () => { resetBuildList.toggle(); resetSpaceList.toggle(false); resetResourcesList.toggle(false); resetReligionList.toggle(false); resetTimeList.toggle(false); }); spaceButton.on("click", () => { resetBuildList.toggle(false); resetSpaceList.toggle(); resetResourcesList.toggle(false); resetReligionList.toggle(false); resetTimeList.toggle(false); }); resourcesButton.on("click", () => { resetBuildList.toggle(false); resetSpaceList.toggle(false); resetResourcesList.toggle(); resetReligionList.toggle(false); resetTimeList.toggle(false); }); religionButton.on("click", () => { resetBuildList.toggle(false); resetSpaceList.toggle(false); resetResourcesList.toggle(false); resetReligionList.toggle(); resetTimeList.toggle(false); }); timeButton.on("click", () => { resetBuildList.toggle(false); resetSpaceList.toggle(false); resetResourcesList.toggle(false); resetReligionList.toggle(false); resetTimeList.toggle(); }); element.append( buildButton, spaceButton, resourcesButton, religionButton, timeButton, resetBuildList, resetSpaceList, resetResourcesList, resetReligionList, resetTimeList ); return element; } private _getOptionAccelerateTime( name: string, option: TimeControlSettings["items"]["accelerateTime"], label: string ): JQuery<HTMLElement> { const element = this._getOption(name, option, label); const triggerButton = $("<div/>", { id: `set-${name}-subTrigger`, text: this._host.i18n("ui.trigger"), //title: option.subTrigger, css: { cursor: "pointer", display: "inline-block", float: "right", paddingRight: "5px", }, }).data("option", option); option.$subTrigger = triggerButton; triggerButton.on("click", () => { const value = window.prompt( this._host.i18n("ui.trigger.set", [label]), option.subTrigger.toFixed(2) ); if (value !== null) { this._host.updateOptions(() => (option.subTrigger = parseFloat(value))); triggerButton[0].title = option.subTrigger.toFixed(2); } }); element.append(triggerButton); return element; } private _getCycle( index: CycleIndices, option: TimeControlSettings["items"]["timeSkip"] ): JQuery<HTMLElement> { const cycle = this._host.gamePage.calendar.cycles[index]; const element = $("<li/>"); const label = $("<label/>", { for: `toggle-timeSkip-${index}`, text: cycle.title, }); const input = $("<input/>", { id: `toggle-timeSkip-${index}`, type: "checkbox", }).data("option", option); option[`$${index}` as const] = input; input.on("change", () => { if (input.is(":checked") && option[index] === false) { this._host.updateOptions(() => (option[index] = true)); this._host.imessage("time.skip.cycle.enable", [cycle.title]); } else if (!input.is(":checked") && option[index] === true) { this._host.updateOptions(() => (option[index] = false)); this._host.imessage("time.skip.cycle.disable", [cycle.title]); } }); element.append(input, label); return element; } // Ideally, this was replaced by using `getOption()`. private _getResetOption( name: string, type: "build" | "faith" | "space" | "time", option: TimeControlBuildSettingsItem, i18nName: string, delimiter = false ): JQuery<HTMLElement> { const element = $("<li/>"); const elementLabel = i18nName; const label = $("<label/>", { for: `toggle-reset-${type}-${name}`, text: elementLabel, css: { display: "inline-block", marginBottom: delimiter ? "10px" : undefined, minWidth: "100px", }, }); const input = $("<input/>", { id: `toggle-reset-${type}-${name}`, type: "checkbox", }).data("option", option); option.$checkForReset = input; input.on("change", () => { if (input.is(":checked") && option.checkForReset === false) { this._host.updateOptions(() => (option.checkForReset = true)); this._host.imessage("status.reset.check.enable", [elementLabel]); } else if (!input.is(":checked") && option.checkForReset === true) { this._host.updateOptions(() => (option.checkForReset = false)); this._host.imessage("status.reset.check.disable", [elementLabel]); } }); const minButton = $("<div/>", { id: `set-reset-${type}-${name}-min`, text: this._host.i18n("ui.min", [option.triggerForReset]), //title: option.triggerForReset, css: { cursor: "pointer", display: "inline-block", float: "right", paddingRight: "5px", }, }).data("option", option); option.$triggerForReset = minButton; minButton.on("click", () => { const value = window.prompt( this._host.i18n("reset.check.trigger.set", [i18nName]), option.triggerForReset.toFixed(2) ); if (value !== null) { this._host.updateOptions(() => (option.triggerForReset = parseInt(value))); minButton.text(this._host.i18n("ui.min", [option.triggerForReset])); } }); element.append(input, label, minButton); return element; } private _getSeasonForTimeSkip( season: Season, option: TimeControlSettings["items"]["timeSkip"] ): JQuery<HTMLElement> { const iseason = ucfirst(this._host.i18n(`$calendar.season.${season}` as const)); const element = $("<li/>"); const label = $("<label/>", { for: `toggle-timeSkip-${season}`, text: ucfirst(iseason), }); const input = $("<input/>", { id: `toggle-timeSkip-${season}`, type: "checkbox", }).data("option", option); option[`$${season}` as const] = input; input.on("change", () => { if (input.is(":checked") && option[season] === false) { this._host.updateOptions(() => (option[season] = true)); this._host.imessage("time.skip.season.enable", [iseason]); } else if (!input.is(":checked") && option[season] === true) { this._host.updateOptions(() => (option[season] = false)); this._host.imessage("time.skip.season.disable", [iseason]); } }); element.append(input, label); return element; } private _getResourceOptions(): JQuery<HTMLElement> { this._resourcesList = $("<ul/>", { id: "toggle-reset-list-resources", css: { display: "none", paddingLeft: "20px" }, }); const add = $("<div/>", { id: "resources-add", text: this._host.i18n("resources.add"), css: { border: "1px solid grey", cursor: "pointer", display: "inline-block", padding: "1px 2px", }, }); const clearunused = $("<div/>", { id: "resources-clear-unused", text: this._host.i18n("resources.clear.unused"), css: { cursor: "pointer", display: "inline-block", float: "right", paddingRight: "5px", }, }); clearunused.on("click", () => { for (const name in this._host.options.auto.craft.resources) { // Only delete resources with unmodified values. Require manual // removal of resources with non-standard values. const resource = mustExist(this._host.options.auto.craft.resources[name as Resource]); if ( (!resource.stock && resource.consume === this._host.options.consume) || resource.consume === undefined ) { $(`#resource-${name}`).remove(); } } }); const allresources = $("<ul/>", { id: "available-resources-list", css: { display: "none", paddingLeft: "20px" }, }); add.on("click", () => { allresources.toggle(); allresources.empty(); allresources.append( this._getAllAvailableResourceOptions(true, res => { if (!this._options.resources[res.name]) { const option = { checkForReset: true, stockForReset: Infinity, }; this._host.updateOptions(() => (this._options.resources[res.name] = option)); $("#toggle-reset-list-resources").append( this._addNewResourceOptionForReset( res.name, res.title, option, (_name, _resource) => { delete this._options.resources[_name]; } ) ); } }) ); }); this._resourcesList.append(add, allresources); return this._resourcesList; } getState(): TimeControlSettings { return { enabled: this._options.enabled, items: this._options.items, buildItems: this._options.buildItems, religionItems: this._options.religionItems, resources: this._options.resources, spaceItems: this._options.spaceItems, timeItems: this._options.timeItems, }; } setState(state: TimeControlSettings): void { this._options.enabled = state.enabled; this._options.items.accelerateTime.enabled = state.items.accelerateTime.enabled; this._options.items.accelerateTime.subTrigger = state.items.accelerateTime.subTrigger; this._options.items.reset.enabled = state.items.reset.enabled; this._options.items.timeSkip.enabled = state.items.timeSkip.enabled; this._options.items.timeSkip.subTrigger = state.items.timeSkip.subTrigger; this._options.items.timeSkip.autumn = state.items.timeSkip.autumn; this._options.items.timeSkip.spring = state.items.timeSkip.spring; this._options.items.timeSkip.summer = state.items.timeSkip.summer; this._options.items.timeSkip.winter = state.items.timeSkip.winter; this._options.items.timeSkip[0] = state.items.timeSkip[0]; this._options.items.timeSkip[1] = state.items.timeSkip[1]; this._options.items.timeSkip[2] = state.items.timeSkip[2]; this._options.items.timeSkip[3] = state.items.timeSkip[3]; this._options.items.timeSkip[4] = state.items.timeSkip[4]; this._options.items.timeSkip[5] = state.items.timeSkip[5]; this._options.items.timeSkip[6] = state.items.timeSkip[6]; this._options.items.timeSkip[7] = state.items.timeSkip[7]; this._options.items.timeSkip[8] = state.items.timeSkip[8]; this._options.items.timeSkip[9] = state.items.timeSkip[9]; for (const [name, option] of objectEntries(this._options.buildItems)) { option.checkForReset = state.buildItems[name].checkForReset; option.triggerForReset = state.buildItems[name].triggerForReset; } for (const [name, option] of objectEntries(this._options.religionItems)) { option.checkForReset = state.religionItems[name].checkForReset; option.triggerForReset = state.religionItems[name].triggerForReset; } for (const [name, option] of objectEntries(this._options.spaceItems)) { option.checkForReset = state.spaceItems[name].checkForReset; option.triggerForReset = state.spaceItems[name].triggerForReset; } for (const [name, option] of objectEntries(this._options.timeItems)) { option.checkForReset = state.timeItems[name].checkForReset; option.triggerForReset = state.timeItems[name].triggerForReset; } // Resources are a dynamic list. We first do a primitive dirty check, // then simply replace our entire stored list, if the state is dirty. if ( Object.keys(this._options.resources).length !== Object.keys(state.resources).length || objectEntries(this._options.resources).some( ([name, resource]) => resource.checkForReset !== state.resources[name]?.checkForReset || resource.stockForReset !== state.resources[name]?.stockForReset ) ) { // Remove existing elements. for (const [name, resource] of objectEntries(this._options.resources)) { if (!isNil(resource.$checkForReset)) { resource.$checkForReset.remove(); resource.$checkForReset = undefined; } if (!isNil(resource.$stockForReset)) { resource.$stockForReset.remove(); resource.$stockForReset = undefined; } } // Replace state. this._options.resources = { ...state.resources }; // Add all the current resources for (const [name, res] of objectEntries(this._options.resources)) { mustExist(this._resourcesList).append( this._addNewResourceOptionForReset(name, name, res, (_name, _resource) => { delete this._options.resources[_name]; }) ); } } else { // If both lists are the same, just copy the state. for (const [name, option] of objectEntries(this._options.resources)) { const stateResource = mustExist(state.resources[name]); option.checkForReset = stateResource.checkForReset; option.stockForReset = stateResource.stockForReset; } } } refreshUi(): void { mustExist(this._options.$enabled).prop("checked", this._options.enabled); mustExist(this._options.items.accelerateTime.$enabled).prop( "checked", this._options.items.accelerateTime.enabled ); mustExist(this._options.items.accelerateTime.$subTrigger)[0].title = this._options.items.accelerateTime.subTrigger.toFixed(2); mustExist(this._options.items.reset.$enabled).prop( "checked", this._options.items.reset.enabled ); mustExist(this._options.items.timeSkip.$enabled).prop( "checked", this._options.items.timeSkip.enabled ); mustExist(this._options.items.timeSkip.$subTrigger)[0].title = this._options.items.timeSkip.subTrigger.toFixed(2); mustExist(this._options.items.timeSkip.$autumn).prop( "checked", this._options.items.timeSkip.autumn ); mustExist(this._options.items.timeSkip.$spring).prop( "checked", this._options.items.timeSkip.spring ); mustExist(this._options.items.timeSkip.$summer).prop( "checked", this._options.items.timeSkip.summer ); mustExist(this._options.items.timeSkip.$winter).prop( "checked", this._options.items.timeSkip.winter ); mustExist(this._options.items.timeSkip.$0).prop("checked", this._options.items.timeSkip[0]); mustExist(this._options.items.timeSkip.$1).prop("checked", this._options.items.timeSkip[1]); mustExist(this._options.items.timeSkip.$2).prop("checked", this._options.items.timeSkip[2]); mustExist(this._options.items.timeSkip.$3).prop("checked", this._options.items.timeSkip[3]); mustExist(this._options.items.timeSkip.$4).prop("checked", this._options.items.timeSkip[4]); mustExist(this._options.items.timeSkip.$5).prop("checked", this._options.items.timeSkip[5]); mustExist(this._options.items.timeSkip.$6).prop("checked", this._options.items.timeSkip[6]); mustExist(this._options.items.timeSkip.$7).prop("checked", this._options.items.timeSkip[7]); mustExist(this._options.items.timeSkip.$8).prop("checked", this._options.items.timeSkip[8]); mustExist(this._options.items.timeSkip.$9).prop("checked", this._options.items.timeSkip[9]); for (const [name, option] of objectEntries(this._options.buildItems)) { mustExist(option.$checkForReset).prop( "checked", this._options.buildItems[name].checkForReset ); mustExist(option.$triggerForReset).text( this._host.i18n("ui.min", [this._options.buildItems[name].triggerForReset]) ); } for (const [name, option] of objectEntries(this._options.religionItems)) { mustExist(option.$checkForReset).prop( "checked", this._options.religionItems[name].checkForReset ); mustExist(option.$triggerForReset).text( this._host.i18n("ui.min", [this._options.religionItems[name].triggerForReset]) ); } for (const [name, option] of objectEntries(this._options.spaceItems)) { mustExist(option.$checkForReset).prop( "checked", this._options.spaceItems[name].checkForReset ); mustExist(option.$triggerForReset).text( this._host.i18n("ui.min", [this._options.spaceItems[name].triggerForReset]) ); } for (const [name, option] of objectEntries(this._options.timeItems)) { mustExist(option.$checkForReset).prop("checked", this._options.timeItems[name].checkForReset); mustExist(option.$triggerForReset).text( this._host.i18n("ui.min", [this._options.timeItems[name].triggerForReset]) ); } for (const [name, option] of objectEntries(this._options.resources)) { mustExist(option.$stockForReset).text( this._host.i18n("resources.stock", [ option.stockForReset === Infinity ? "∞" : this._host.gamePage.getDisplayValueExt( mustExist(this._options.resources[name]).stockForReset ), ]) ); } } }
mit
lob/lob-java
src/main/java/com/lob/exception/AuthenticationException.java
261
package com.lob.exception; public class AuthenticationException extends LobException { private static final long serialVersionUID = 1L; public AuthenticationException(String message, Integer statusCode) { super(message, statusCode); } }
mit
wei0831/fileorganizer
setup.py
1529
#!/usr/bin/env python """ setup.py """ from setuptools import setup, find_packages import fileorganizer setup( name="fileorganizer", version=fileorganizer.VERSION, packages=find_packages(), include_package_data=True, install_requires=['click>=6.0', 'yapf>=0.17', 'PyYAML'], entry_points={ 'console_scripts': [ 'folderin=fileorganizer.cli:cli_folderin', 'folderout=fileorganizer.cli:cli_folderout', 'moveintofolder=fileorganizer.cli:cli_moveintofolder', 'replacename=fileorganizer.cli:cli_replacename', 'fanhaorename=fileorganizer.cli:cli_fanhaorename', 'fanhaofolderin=fileorganizer.cli:cli_fanhaofolderin', 'renameafterfolder=fileorganizer.cli:cli_renameafterfolder', ], }, package_data={ '': ['*.txt', '*.rst', '*.sh', 'LICENSE', '*md'], 'fileorganizer': ['conf/*.yaml'], }, # metadata author="Jack Chang", author_email="[email protected]", description="batch file organizer", license="MIT", keywords="file organizer", url="https://github.com/wei0831/fileorganizer", classifiers=[ 'Development Status :: 1 - Planning Development', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
mit