code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using LevelEditor.Extensibility.ReadOnlyViewModels; namespace LevelEditor.ViewModels { public class ElementToolBoxViewModel : RootedViewModel, IReadOnlyElementToolBoxViewModel { public IEnumerable<ElementToolBoxCategoryViewModel> Categories { get; private set; } private string searchText; public string SearchText { get { return searchText; } set { if (SetValue(ref searchText, value)) { foreach (var element in Categories.SelectMany(x => x.Elements)) element.SearchTextChanged(SearchText); } } } public ElementToolBoxViewModel(RootViewModel root) : base(root) { var dic = new Dictionary<string, List<ElementToolBoxElementViewModel>>(); foreach (var element in Root.Settings.GameElements.Elements) { var categories = SplitCategories(element.Categories); foreach (var categ in categories) { List<ElementToolBoxElementViewModel> itemList; if (dic.TryGetValue(categ, out itemList) == false) { itemList = new List<ElementToolBoxElementViewModel>(); dic[categ] = itemList; } itemList.Add(new ElementToolBoxElementViewModel(root, element)); } } var result = new ElementToolBoxCategoryViewModel[dic.Keys.Count]; var n = 0; foreach (var kv in dic) result[n++] = new ElementToolBoxCategoryViewModel(root, kv.Key, kv.Value.ToArray()); Categories = new ReadOnlyCollection<ElementToolBoxCategoryViewModel>(result); } private IEnumerable<string> SplitCategories(string categories) { return categories .Split(',', ';', ':') .Select(s => s.Trim()) .Where(s => s.Length > 0); } IEnumerable<IReadOnlyElementToolBoxCategoryViewModel> IReadOnlyElementToolBoxViewModel.Categories { get { return Categories; } } } }
bitcraftCoLtd/level-editor
LevelEditor/ViewModels/ElementToolBoxViewModel.cs
C#
mit
2,511
package com.fragmobile; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
Pinablink/FragMobile
FragMobile/app/src/test/java/com/fragmobile/ExampleUnitTest.java
Java
mit
408
#include "log/logger.h" #include "log/stdoutlog.h" //#include <windows.h> //void SetColor(unsigned short forecolor = 4, unsigned short backgroudcolor = 0) //{ // HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE); //»ñÈ¡»º³åÇø¾ä±ú // SetConsoleTextAttribute(hCon, forecolor | backgroudcolor); //ÉèÖÃÎı¾¼°±³¾°É« //} int main(){ Logger l; StdoutLogSink cl; l.Trace("trace ....."); l.Debug("debug --- %d", 11); l.Info("info --- %d", 11); l.Warn("warn ..yellow"); l.Error("error --- %d", 11); l.Fatal("fatal--------------"); return 0; }
tamzr/code-snippet
code_cpp/common/main.cc
C++
mit
572
<?php namespace InfinityGames\InfinityBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ReponseTopicForumType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder //->add('titre') ->add('contenu', 'textarea', array('label'=>'Votre texte')) //->add('date') //->add('statut') //->add('utilisateur') //->add('forum') //->add('idParent') ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'InfinityGames\InfinityBundle\Entity\MessageForum' )); } public function getName() { return 'infinitygames_infinitybundle_reponsetopictype'; } }
thomaschvt/Infinity-Games
src/InfinityGames/InfinityBundle/Form/ReponseTopicForumType.php
PHP
mit
955
using System; using System.Collections.Generic; using AssemblyLine.DAL.Entities; namespace AssemblyLine.Models { public class ProjectModel { public int Id { get; set; } public string Name { get; set; } public ProjectStatus Status { get; set; } public DateTime Created { get; set; } public List<ProjectLineListModel> AssemblyLines { get; set; } } }
alexey-ernest/assembly-line
AssemblyLine/Models/ProjectModel.cs
C#
mit
407
class LinkedList { public static void main(String[] a) { System.out.println(new LL().Start()); } } class Element { int Age; int Salary; boolean Married; public boolean Init(int v_Age, int v_Salary, boolean v_Married) { Age = v_Age; Salary = v_Salary; Married = v_Married; return true; } public int GetAge() { return Age; } public int GetSalary() { return Salary; } public boolean GetMarried() { return Married; } public boolean Equal(Element other) { boolean ret_val; int aux01; int aux02; int nt; ret_val = true; aux01 = other.GetAge(); if (!(this.Compare(aux01, Age))) ret_val = false; else { aux02 = other.GetSalary(); if (!(this.Compare(aux02, Salary))) ret_val = false; else if (Married) if (!(other.GetMarried())) ret_val = false; else nt = 0; else if (other.GetMarried()) ret_val = false; else nt = 0; } return ret_val; } public boolean Compare(int num1, int num2) { boolean retval; int aux02; retval = false; aux02 = num2 + 1; if (num1 < num2) retval = false; else if (!(num1 < aux02)) retval = false; else retval = true; return retval; } } class List { Element elem; List next; boolean end; public boolean Init() { end = true; return true; } public boolean InitNew(Element v_elem, List v_next, boolean v_end) { end = v_end; elem = v_elem; next = v_next; return true; } public List Insert(Element new_elem) { boolean ret_val; List aux03; List aux02; aux03 = this; aux02 = new List(); ret_val = aux02.InitNew(new_elem, aux03, false); return aux02; } public boolean SetNext(List v_next) { next = v_next; return true; } public List Delete(Element e) { List my_head; boolean ret_val; boolean aux05; List aux01; List prev; boolean var_end; Element var_elem; int aux04; int nt; my_head = this; ret_val = false; aux04 = 0 - 1; aux01 = this; prev = this; var_end = end; var_elem = elem; while (!(var_end) && !(ret_val)) { if (e.Equal(var_elem)) { ret_val = true; if (aux04 < 0) { my_head = aux01.GetNext(); } else { System.out.println(0 - 555); aux05 = prev.SetNext(aux01.GetNext()); System.out.println(0 - 555); } } else nt = 0; if (!(ret_val)) { prev = aux01; aux01 = aux01.GetNext(); var_end = aux01.GetEnd(); var_elem = aux01.GetElem(); aux04 = 1; } else nt = 0; } return my_head; } public int Search(Element e) { int int_ret_val; List aux01; Element var_elem; boolean var_end; int nt; int_ret_val = 0; aux01 = this; var_end = end; var_elem = elem; while (!(var_end)) { if (e.Equal(var_elem)) { int_ret_val = 1; } else nt = 0; aux01 = aux01.GetNext(); var_end = aux01.GetEnd(); var_elem = aux01.GetElem(); } return int_ret_val; } public boolean GetEnd() { return end; } public Element GetElem() { return elem; } public List GetNext() { return next; } public boolean Print() { List aux01; boolean var_end; Element var_elem; aux01 = this; var_end = end; var_elem = elem; while (!(var_end)) { System.out.println(var_elem.GetAge()); aux01 = aux01.GetNext(); var_end = aux01.GetEnd(); var_elem = aux01.GetElem(); } return true; } } class LL { public int Start() { List head; List last_elem; boolean aux01; Element el01; Element el02; Element el03; last_elem = new List(); aux01 = last_elem.Init(); head = last_elem; aux01 = head.Init(); aux01 = head.Print(); el01 = new Element(); aux01 = el01.Init(25, 37000, false); head = head.Insert(el01); aux01 = head.Print(); System.out.println(10000000); el01 = new Element(); aux01 = el01.Init(39, 42000, true); el02 = el01; head = head.Insert(el01); aux01 = head.Print(); System.out.println(10000000); el01 = new Element(); aux01 = el01.Init(22, 34000, false); head = head.Insert(el01); aux01 = head.Print(); el03 = new Element(); aux01 = el03.Init(27, 34000, false); System.out.println(head.Search(el02)); System.out.println(head.Search(el03)); System.out.println(10000000); el01 = new Element(); aux01 = el01.Init(28, 35000, false); head = head.Insert(el01); aux01 = head.Print(); System.out.println(2220000); head = head.Delete(el02); aux01 = head.Print(); System.out.println(33300000); head = head.Delete(el01); aux01 = head.Print(); System.out.println(44440000); return 0; } }
team-compilers/compilers
MiniJava/results/SamplesCorrect/LinkedList/code.java
Java
mit
6,548
class CreateRoles < ActiveRecord::Migration def change create_table :roles do |t| t.string :name t.text :comment t.boolean :is_active t.timestamps end end end
hex337/quantum-attendance
db/migrate/20150321222054_create_roles.rb
Ruby
mit
196
<?php namespace Rotor\DB; class DbSchema { public static function Update($table,$definition) { //_gc($table, 'Schema Update'); $definition = static::flattenDefinition($definition); if (!self::Table_exists($table)) { self::Create_Table($table,$definition); } else { $currentQuery = 'SHOW FULL COLUMNS FROM `'.$table.'`'; $cols = DB::get($currentQuery); //_d($cols,'columns from DB'); $currCols = []; foreach ($cols as $col) { $fieldObj = new DbSchemaField(); $fieldObj->setFromQuery($col); $currCols[$col->Field] = $fieldObj; } //_d($currCols,'current columns'); $defCols = []; foreach ($definition as $fieldName=>$def){ $fieldObj = new DbSchemaField; $fieldObj->setFromDefinition($fieldName, $def); $defCols[$fieldName] = $fieldObj; } //_d($defCols,'definition columns'); $operations = []; //_g('checking fields'); foreach ($defCols as $fieldName=>$def) { //_gc('defcol'); //_d($defCols); //_d($fieldName); //_d($def); //_u(); if (!array_key_exists($fieldName, $currCols)){ //_d($fieldName, 'does not exist in currcols'); $op = $def->getAddField(); //_d($op); $operations[] = $op; } else { //_d($fieldName, 'exists in currcols'); if ($def->differsFrom($currCols[$fieldName])){ //_d($fieldName,'DIFFERS'); $operations[] = $def->getAlterField($currCols[$fieldName]); } else { //_d($fieldName,'does not differ'); } } } //_u(); //if (Config::get('db.schema.update.delete')) { foreach ($currCols as $fieldName=>$def){ if (!array_key_exists($fieldName,$defCols)) { $operations[] = $currCols[$fieldName]->getDrop(); } } //} //_d($operations,"operations"); if (count($operations) > 0) { $sql = 'ALTER TABLE `'.$table.'` '.implode(', ',$operations); //_d($sql); DB::query($sql); } } //_u(); } private static function Table_exists($tableName) { $query = 'SHOW TABLES LIKE "' . $tableName . '"'; $result = DB::get($query); return (bool)$result; } private static function Create_Table($tableName,$definition){ $fields = []; $definition = static::flattenDefinition($definition); foreach ($definition as $fieldName => $def) { $field = new DbSchemaField(); $field->setFromDefinition($fieldName,$def); $fields[] = $field; } $fieldDefs = []; foreach ($fields as $field){ $fieldDefs[] = $field->getCreateField(); } $query = 'CREATE TABLE `' . $tableName . '` (' . implode(' , ', $fieldDefs) . ')'; DB::query($query); } private static function flattenDefinition($definition){ //_g('flattenDefinition'); //_d($definition); $result = array_merge($definition); foreach ($definition as $fieldName=>$def){ if (substr($def,0,1) == '@') { $className = substr($def,1).'Repository'; $vars = get_class_vars($className); $fdef = $vars['Fields'][$vars['PrimaryKey']]; $fdefParts = explode(',',$fdef); $result[$fieldName] = $fdefParts[0]; } } //_d($result); //_u(); return $result; } }
andrixh/rotor
Rotor/DB/DbSchema.php
PHP
mit
4,044
using System.Collections; using System.Collections.Generic; using UnityEngine; using WaveVR_Log; using wvr; public class WaveVR_PointerCameraTracker : MonoBehaviour { private const string LOG_TAG = "WaveVR_PointerCameraTracker"; public GameObject reticleObject = null; public WVR_DeviceType type; private WaveVR_ControllerPointer reticle; private Vector3 pointer_location; private void PrintDebugLog(string msg) { #if UNITY_EDITOR Debug.Log(LOG_TAG + " " + msg); #endif Log.d (LOG_TAG, msg); } // Use this for initialization void Start() { if (reticleObject != null) { reticle = reticleObject.GetComponent<WaveVR_ControllerPointer>(); } } // Update is called once per frame void Update() { if (reticleObject != null && reticle == null) { reticle = reticleObject.GetComponent<WaveVR_ControllerPointer>(); } if (reticleObject != null && reticle != null) { pointer_location = reticleObject.transform.position + reticleObject.transform.forward * reticle.getPointerCurrentDistance(); transform.rotation = Quaternion.LookRotation(pointer_location - transform.position); } } public void setDeviceType(WVR_DeviceType value) { type = value; } }
demonixis/TESUnity
Assets/Vendors/WaveVR/Scripts/WaveVR_PointerCameraTracker.cs
C#
mit
1,377
<?php namespace Kunstmaan\MediaBundle\Helper\RemoteSlide; use Kunstmaan\MediaBundle\Form\RemoteSlide\RemoteSlideType; use Kunstmaan\MediaBundle\Helper\Media\AbstractMediaHandler; use Kunstmaan\MediaBundle\Entity\Media; /** * RemoteSlideStrategy */ class RemoteSlideHandler extends AbstractMediaHandler { /** * @var string */ const CONTENT_TYPE = 'remote/slide'; const TYPE = 'slide'; /** * @return string */ public function getName() { return 'Remote Slide Handler'; } /** * @return string */ public function getType() { return RemoteSlideHandler::TYPE; } /** * @return RemoteSlideType */ public function getFormType() { return new RemoteSlideType(); } /** * @param mixed $object * * @return bool */ public function canHandle($object) { if ( (is_string($object)) || ($object instanceof Media && $object->getContentType() == RemoteSlideHandler::CONTENT_TYPE) ) { return true; } return false; } /** * @param Media $media * * @return RemoteSlideHelper */ public function getFormHelper(Media $media) { return new RemoteSlideHelper($media); } /** * @param Media $media * * @throws \RuntimeException when the file does not exist */ public function prepareMedia(Media $media) { if (null == $media->getUuid()) { $uuid = uniqid(); $media->setUuid($uuid); } $slide = new RemoteSlideHelper($media); $code = $slide->getCode(); // update thumbnail switch ($slide->getType()) { case 'slideshare': try { $json = json_decode( file_get_contents( 'http://www.slideshare.net/api/oembed/2?url=http://www.slideshare.net/slideshow/embed_code/' . $code . '&format=json' ) ); $slide->setThumbnailUrl($json->thumbnail); } catch (\ErrorException $e) { // Silent exception - should not bubble up since failure to create a thumbnail is not a fatal error } break; } } /** * @param Media $media */ public function saveMedia(Media $media) { } /** * @param Media $media */ public function removeMedia(Media $media) { } /** * {@inheritDoc} */ public function updateMedia(Media $media) { } /** * @param array $params * * @return array */ public function getAddUrlFor(array $params = array()) { return array( 'slide' => array( 'path' => 'KunstmaanMediaBundle_folder_slidecreate', 'params' => array( 'folderId' => $params['folderId'] ) ) ); } /** * @param mixed $data * * @return Media */ public function createNew($data) { $result = null; if (is_string($data)) { if (strpos($data, 'http') !== 0) { $data = 'http://' . $data; } $parsedUrl = parse_url($data); switch ($parsedUrl['host']) { case 'www.slideshare.net': case 'slideshare.net': $result = new Media(); $slide = new RemoteSlideHelper($result); $slide->setType('slideshare'); $json = json_decode( file_get_contents('http://www.slideshare.net/api/oembed/2?url=' . $data . '&format=json') ); $slide->setCode($json->{"slideshow_id"}); $result = $slide->getMedia(); $result->setName('SlideShare ' . $data); break; } } return $result; } /** * {@inheritDoc} */ public function getShowTemplate(Media $media) { return 'KunstmaanMediaBundle:Media\RemoteSlide:show.html.twig'; } /** * @param Media $media The media entity * @param string $basepath The base path * * @return string */ public function getImageUrl(Media $media, $basepath) { $helper = new RemoteSlideHelper($media); return $helper->getThumbnailUrl(); } /** * @return array */ public function getAddFolderActions() { return array( RemoteSlideHandler::TYPE => array( 'type' => RemoteSlideHandler::TYPE, 'name' => 'media.slide.add' ) ); } }
WouterJ/KunstmaanBundlesCMS
src/Kunstmaan/MediaBundle/Helper/RemoteSlide/RemoteSlideHandler.php
PHP
mit
4,857
'use strict'; $(function() { $.material.init(); $('#libraries').btsListFilter('#searcher', { itemChild: 'h3', resetOnBlur: false }); $('#searcher').focus(); });
jerone/PackageSize
public/js/script.js
JavaScript
mit
171
package com.binaryedu.web.controllers; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class SignUpSuccessController implements Controller { protected final Log logger = LogFactory.getLog(this.getClass()); public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("Returning Sign Up Success View"); return new ModelAndView("signupSuccess"); } }
parambirs/binaryedu
src/main/java/com/binaryedu/web/controllers/SignUpSuccessController.java
Java
mit
782
/** * Copyright 2016 aixigo AG * Released under the MIT license. * http://laxarjs.org/license */ /** * Allows to instantiate a mock implementations of {@link AxStorage}, compatible to the "axStorage" injection. * * @module widget_services_storage_mock */ import { create as createGlobalStorageMock } from './storage_mock'; /** * Creates a mock for the `axStorage` injection of a widget. * * @return {AxStorageMock} * a mock of `axStorage` that can be spied and/or mocked with additional items */ export function create() { const globalStorageMock = createGlobalStorageMock(); const namespace = 'mock'; const local = globalStorageMock.getLocalStorage( namespace ); const session = globalStorageMock.getSessionStorage( namespace ); /** * The AxStorageMock provides the same API as AxStorage, with the additional property * {@link #mockBackends} to inspect and/or simulate mock values in the storage backend. * * @name AxStorageMock * @constructor * @extends AxStorage */ return { local, session, /** * Provides access to the backing stores for `local` and `session` storage. * * Contains `local` and `session` store properties. The stores are plain objects whose properties * reflect any setItem/removeItem operations. When properties are set on a store, they are observed * by `getItem` calls on the corresponding axStorage API. * * @memberof AxStorageMock */ mockBackends: { local: globalStorageMock.mockBackends.local[ namespace ].store, session: globalStorageMock.mockBackends.session[ namespace ].store } }; }
LaxarJS/laxar
lib/testing/widget_services_storage_mock.js
JavaScript
mit
1,690
import {appendHtml, combine} from './../util'; const ELEMENT_NAMES = { frameName: 'text-frame', messageName: 'text-message', indicatorName: 'text-indicator' }; let createElements = (container, names) => { const elements = '\ <div class="text-frame" id="' + names.frameName + '">\ <span class="text-message" id="' + names.messageName + '"></span>\ <span id="' + names.indicatorName + '">▼</span>\ </div>'; appendHtml(container, elements); } export default class TextOutput { constructor(parent, engine) { let elementNames = Object.assign(ELEMENT_NAMES, engine.overrides.customElementNames); if (!engine.overrides.useCustomElements) { createElements(parent, elementNames); } this._textMessages = []; this.engine = engine; this.textMessageFrame = document.getElementById(elementNames.frameName); this.textMessage = document.getElementById(elementNames.messageName); this.textIndicator = document.getElementById(elementNames.indicatorName) this.textMessageFrame.onclick = () => engine.drawMessages(); engine.clearText = combine(engine.clearText, this.clearText.bind(this)); engine.displayText = combine(engine.displayText, this.displayText.bind(this)); engine.drawMessages = combine(engine.drawMessages, this.drawMessages.bind(this)); engine.actionExecutor.registerAction("text", (options, engine, player, callback) => { engine.displayText(options.text.split("\n")); }, false, true); } clearText () { this._textMessages = []; this.textMessageFrame.classList.remove("in"); this.textMessage.innerHTML = ""; this.textIndicator.classList.remove("in"); this.engine.unpause(); } displayText (text) { this._textMessages = this._textMessages.concat(text); } drawMessages () { if (this._textMessages.length > 0) { this.engine.pause(); const text = this._textMessages.splice(0, 1)[0]; this.textMessage.innerHTML = text; if (!("in" in this.textMessageFrame.classList)) { this.textMessageFrame.classList.add("in"); } if (this._textMessages.length >= 1) { this.textIndicator.classList.add("in"); } else { this.textIndicator.classList.remove("in"); } } else { this.clearText(); } } }
Parnswir/tie
src/extensions/TextOutput.js
JavaScript
mit
2,308
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace ARRO.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult Error() { ViewData["RequestId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier; return View(); } } }
CliXiD/ARRO
Controllers/HomeController.cs
C#
mit
525
<?php namespace Nutricion\EmpresasBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * PermisosRole * * @ORM\Table(name="permisos_role", uniqueConstraints={@ORM\UniqueConstraint(name="role", columns={"role", "permiso"})}) * @ORM\Entity */ class PermisosRole { /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var integer * * @ORM\Column(name="role", type="integer", nullable=false) */ private $role; /** * @var integer * * @ORM\Column(name="permiso", type="integer", nullable=false) */ private $permiso; /** * @var boolean * * @ORM\Column(name="valor", type="boolean", nullable=false) */ private $valor; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set role * * @param integer $role * @return PermisosRole */ public function setRole($role) { $this->role = $role; return $this; } /** * Get role * * @return integer */ public function getRole() { return $this->role; } /** * Set permiso * * @param integer $permiso * @return PermisosRole */ public function setPermiso($permiso) { $this->permiso = $permiso; return $this; } /** * Get permiso * * @return integer */ public function getPermiso() { return $this->permiso; } /** * Set valor * * @param boolean $valor * @return PermisosRole */ public function setValor($valor) { $this->valor = $valor; return $this; } /** * Get valor * * @return boolean */ public function getValor() { return $this->valor; } }
cristianangulo/nutricion_sy
src/Nutricion/EmpresasBundle/Entity/PermisosRole.php
PHP
mit
1,998
require "rails_helper" RSpec.describe AnswersMailer, type: :mailer do describe "notify_subscriber" do let!(:subscription) { create(:subscription) } let(:mail) { AnswersMailer.notify_subscriber(subscription) } it "renders the headers" do expect(mail.subject).to eq("Notify subscriber") expect(mail.to).to eq([subscription.user.email]) end it "renders the body" do expect(mail.body.encoded).to match(subscription.question.title) end end end
bdisney/stackoverflow
spec/mailers/answers_mailer_spec.rb
Ruby
mit
497
//= require sencha_touch/sencha-touch //= require_directory ./sencha_touch/app //= require_tree ./sencha_touch/app/models //= require_tree ./sencha_touch/app/stores //= require_tree ./sencha_touch/app/controllers //= require_tree ./sencha_touch/app/views
AlexanderFlatscher/bakk1todo
app/assets/javascripts/sencha_touch.js
JavaScript
mit
261
;(function() { function ToerismeApp(id, parentContainer) { this.API_URL = 'https://datatank.stad.gent/4/toerisme/visitgentevents.json'; this.id = id; this.parentContainer = parentContainer; this.loadData = function() { var that = this; var xhr = new XMLHttpRequest(); xhr.open('get', this.API_URL, true); xhr.responseType = 'json'; xhr.onload = function() { if(xhr.status == 200) { var data = (!xhr.responseType)?JSON.parse(xhr.response):xhr.response; var id = 1; var tempStr = ''; for(i=0; i<20; i++) { var title = data[i].title; var contact = data[i].contact[0]; //var website = contact.website[0]; //var weburl = website.url; var images = data[i].images[0]; var language = data[i].language; var website = ''; if(contact.website){ website = contact.website[0].url; //console.log(website); } if(language == 'nl'){ tempStr += '<div class="row row_events">'; tempStr += '<a href="http://' + website +'" target="_blank";>'; tempStr += '<div class="col-xs-6"><div class="div_image" style="background: url(' + images +') no-repeat center ;background-size:cover;"></div></div>'; tempStr += '<div class="col-xs-6"><h4>' + title + '</h4>'; tempStr += '<p>Adres: ' + contact.street + ' nr ' + contact.number + '<br> Stad: ' + contact.city +'</p>'; tempStr += '</div>'; /* einde adres */ tempStr += '</a>'; tempStr += '<a class="link_heart" id="myDIV'+[i]+'" alt="Add to favorites" title="Add to favorites" onclick="myFunction('+[i]+')" ><span class="glyphicon glyphicon-heart-empty"></span></a>'; tempStr += '</div>';/* einde row */ }else{}; } that.parentContainer.innerHTML = tempStr; } else { console.log('xhr.status'); } } xhr.onerror = function() { console.log('Error'); } xhr.send(); }; this.updateUI = function() { }; this.toString = function() { return `ToerismeApp with id: ${this.id}`; }; }; var ww1 = new ToerismeApp(1, document.querySelector('.sidebar')); ww1.loadData(); console.log(ww1.toString()); })(); function myFunction(id){ document.getElementById("myDIV"+id).classList.toggle("link_heart-select"); }
dwievane/dwievane.github.io
js/events.js
JavaScript
mit
2,650
package raft import ( "github.com/iketheadore/raft/comm" "github.com/iketheadore/raft/logic" ) type Raft struct { localServ logic.Server listener comm.Listener sender comm.Sender logic *logic.Logic } func New(addr string) *Raft { r := &Raft{localServ: logic.Server{Addr: addr, Role: logic.Follower}, listener: comm.NewListener(addr)} r.listener.Run() r.logic = logic.New(r.localServ) r.logic.Subscribe(r.listener) return r } func (r *Raft) Connect(addr string) error { return r.logic.Connect(logic.Server{Addr: addr, Role: logic.Follower}) } func (r *Raft) Run() { r.logic.Run() } func (r *Raft) ReplicateCmd(cmd comm.Command) { r.logic.ReplicateCmd(cmd) }
iketheadore/raft
raft.go
GO
mit
685
package main import "time" import "fmt" import "os" import "io/ioutil" import "math/rand" import "github.com/antonholmquist/jason" var LOADED *jason.Object // global var to hold the entire json object from file // loads from file into the jason.Object pointer. func LoadRollTables() (err error) { fi, err := os.Open("./rolltables.json") // hardcoded input file if err != nil { panic(err) } defer fi.Close() r, err := ioutil.ReadAll(fi) // read entire file at once, may need to change if files get large if err != nil { panic(err) } LOADED, err = jason.NewObjectFromBytes(r) // take the bytes object and turn into the jason object if err != nil { panic(err) } return err } // rolls all the tables in the jason.Object pointer LOADED. func RollAllTables() (err error) { rtables, err := LOADED.GetObjectArray("rolltables") for _, value := range rtables { err = RollOneTable(value) if err != nil { fmt.Println(err) // just want to print, not panic so it keeps going through other rolls } } return } func RollOneTable(rt *jason.Object) (err error) { // initialize vars var i int64 // counter for the loop of rolls var rolls []int64 // holds a list of all rolls if needed later for debugging var total int64 // result amount var dnum int64 // how many dice to roll var dmod int64 // this is to add a single fixed modifier amount to the roll if you desire dnum, err = rt.GetInt64("Dicenum") if err != nil { panic(err) } dmod, err = rt.GetInt64("Dicemod") if err != nil { panic(err) } // generates a roll based off of dnum and dsize for i = 0; i < dnum; i++ { var dsize int64 // number of sides of dice, 1 being the lowest always dsize, err = rt.GetInt64("Dicesize") if err != nil { panic(err) } roll := rand.Int63n(dsize) + 1 // + 1 makes it 1-100 instead of 0-99 rolls = append(rolls, roll) total += roll } // adds dmod to total from the rolls total += dmod rollsarray, err := rt.GetObjectArray("Rolls") if err != nil { panic(err) } // this portion of the function loads the inidividual rolls and then checks if the generated roll matches for _, individRolls := range rollsarray { var themin int64 // "Min" in json var themax int64 // "Max" in json themin, err = individRolls.GetInt64("Min") if err != nil { panic(err) } themax, err = individRolls.GetInt64("Max") if err != nil { panic(err) } if total >= themin && total <= themax { var result string result, err = individRolls.GetString("Result") if err != nil { panic(err) } var name string name, err = rt.GetString("Name") if err != nil { panic(err) } fmt.Printf("%s: %s\n", name, result) var subrolls *jason.Object // place to store any subrolls subrolls, err = individRolls.GetObject("rolltable") if err != nil { // idea is if there's an error, there's no subrolls so just pass } else { // but, if err is nil, we call ourselves recursively err = RollOneTable(subrolls) if err != nil { fmt.Println(err) // don't panic as their might be a non-nil error with further sub rolls return } } } } err = nil return } func main() { rand.Seed(time.Now().UnixNano()) // sets a unique seed for the random number generator LoadRollTables() // loads the json into a *jason.Object global RollAllTables() // rolls it all }
jrmiller82/dm-roller
main.go
GO
mit
3,379
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\CoreBundle\Entity; use PHPSpec2\ObjectBehavior; /** * Cart spec. * * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ class Cart extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\CoreBundle\Entity\Cart'); } function it_implements_Sylius_cart_interface() { $this->shouldImplement('Sylius\Bundle\CoreBundle\Model\CartInterface'); } function it_extends_Sylius_cart_mapped_superclass() { $this->shouldHaveType('Sylius\Bundle\CartBundle\Entity\Cart'); } function it_implements_shippables_aware_interface() { $this->shouldImplement('Sylius\Bundle\ShippingBundle\Model\ShippablesAwareInterface'); } function it_has_no_shipping_address_by_default() { $this->getShippingAddress()->shouldReturn(null); } /** * @param Sylius\Bundle\AddressingBundle\Model\AddressInterface $address */ function its_shipping_address_is_mutable($address) { $this->setShippingAddress($address); $this->getShippingAddress()->shouldReturn($address); } function it_has_no_billing_address_by_default() { $this->getBillingAddress()->shouldReturn(null); } /** * @param Sylius\Bundle\AddressingBundle\Model\AddressInterface $address */ function its_billing_address_is_mutable($address) { $this->setBillingAddress($address); $this->getBillingAddress()->shouldReturn($address); } function it_has_no_shipping_method_by_default() { $this->getShippingMethod()->shouldReturn(null); } function its_shipping_method_is_mutable($method) { $this->setShippingMethod($method); $this->getShippingMethod()->shouldReturn($method); } function it_has_no_payment_method_by_default() { $this->getPaymentMethod()->shouldReturn(null); } function its_payment_method_is_mutable($method) { $this->setPaymentMethod($method); $this->getPaymentMethod()->shouldReturn($method); } }
formapro-forks/Sylius
src/Sylius/Bundle/CoreBundle/spec/Sylius/Bundle/CoreBundle/Entity/Cart.php
PHP
mit
2,333
module.exports = "module-one-A-model";
sekko27/node-wire-helper
tests/loader/module-one/lib/domain/models/A.js
JavaScript
mit
39
$(function () { 'use strict'; const notificationType = { success: 'Success', error: 'Error', info: 'Info' }, notificationTypeClass = { success: 'toast-success', info: 'toast-info', error: 'toast-error' }; function initSignalR() { let connection = $.connection, hub = connection.notificationHub; hub.client.toast = (message, dellay, type) => { console.log('CALLEEEEEEEEEEEED') if (type === notificationType.success) { Materialize.toast(message, dellay, notificationTypeClass.success) } else if (type === notificationType.info) { Materialize.toast(message, dellay, notificationTypeClass.info) } else { Materialize.toast(message, dellay, notificationTypeClass.error) } }; connection.hub.start().done(() => hub.server.init()); } initSignalR(); }());
SuchTeam-NoJoro-MuchSad/Doge-News
DogeNews/Src/Web/DogeNews.Web/Scripts/Common/notificator.js
JavaScript
mit
1,006
/** * Ensures that the callback pattern is followed properly * with an Error object (or undefined or null) in the first position. */ 'use strict' // ------------------------------------------------------------------------------ // Helpers // ------------------------------------------------------------------------------ /** * Determine if a node has a possiblity to be an Error object * @param {ASTNode} node ASTNode to check * @returns {boolean} True if there is a chance it contains an Error obj */ function couldBeError (node) { let exprs switch (node.type) { case 'Identifier': case 'CallExpression': case 'NewExpression': case 'MemberExpression': case 'TaggedTemplateExpression': case 'YieldExpression': return true // possibly an error object. case 'AssignmentExpression': return couldBeError(node.right) case 'SequenceExpression': exprs = node.expressions return exprs.length !== 0 && couldBeError(exprs[exprs.length - 1]) case 'LogicalExpression': return couldBeError(node.left) || couldBeError(node.right) case 'ConditionalExpression': return couldBeError(node.consequent) || couldBeError(node.alternate) default: return node.value === null } } // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ module.exports = { meta: { type: 'suggestion', docs: { url: 'https://github.com/standard/eslint-plugin-standard#rules-explanations' } }, create: function (context) { const callbackNames = context.options[0] || ['callback', 'cb'] function isCallback (name) { return callbackNames.indexOf(name) > -1 } return { CallExpression: function (node) { const errorArg = node.arguments[0] const calleeName = node.callee.name if (errorArg && !couldBeError(errorArg) && isCallback(calleeName)) { context.report(node, 'Unexpected literal in error position of callback.') } } } } }
xjamundx/eslint-plugin-standard
rules/no-callback-literal.js
JavaScript
mit
2,134
package com.github.mikhailerofeev.scholarm.local.services; import android.app.Application; import com.github.mikhailerofeev.scholarm.api.entities.Question; import com.github.mikhailerofeev.scholarm.local.entities.QuestionImpl; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.inject.Inject; import java.io.*; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @author m-erofeev * @since 22.08.14 */ public class QuestionsManager { private final Application application; private List<QuestionImpl> questions; private Long maxId; @Inject public QuestionsManager(Application application) { this.application = application; } public List<Question> getQuestions(Set<String> questionThemesAndSubthemesNames) { List<Question> ret = new ArrayList<>(); for (QuestionImpl question : questions) { if (questionThemesAndSubthemesNames.contains(question.getThemeName())) { ret.add(question); } } return ret; } @Inject public synchronized void init() { System.out.println("init QuestionsManager"); System.out.println("our dir: " + application.getApplicationContext().getFilesDir()); maxId = 0L; File dataFile = getDataFile(); if (!dataFile.exists()) { System.out.println(dataFile.getAbsolutePath() + " not exists"); if (!tryToLoadAssets()) { questions = new ArrayList<>(); } return; } FileReader fileReader; try { fileReader = new FileReader(dataFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } readQuestions(fileReader); } private void readQuestions(Reader fileReader) { Type type = new TypeToken<List<QuestionImpl>>() { }.getType(); questions = new Gson().fromJson(fileReader, type); for (QuestionImpl question : questions) { if (maxId < question.getId()) { maxId = question.getId(); } } } private boolean tryToLoadAssets() { if (application.getAssets() == null) { return false; } try { Reader inputStreamReader = new InputStreamReader(application.getAssets().open("database.json")); readQuestions(inputStreamReader); } catch (IOException e) { e.printStackTrace(); return false; } return true; } public synchronized void addQuestions(List<QuestionImpl> questionsToAdd) { for (QuestionImpl question : questionsToAdd) { question.setId(maxId++); this.questions.add(question); } File dataFile = getDataFile(); dataFile.delete(); try { if (!dataFile.createNewFile()) { throw new RuntimeException("can't create file"); } String questionsStr = new Gson().toJson(this.questions); FileWriter writer = new FileWriter(dataFile); writer.append(questionsStr); writer.close(); } catch (IOException e) { throw new RuntimeException(e); } } private File getDataFile() { File filesDir = application.getApplicationContext().getFilesDir(); return new File(filesDir.getAbsolutePath() + "database.json"); } }
Whoosh/schalarm
localdb/src/main/java/com/github/mikhailerofeev/scholarm/local/services/QuestionsManager.java
Java
mit
3,530
/* * Copyright (C) 2011-2012 Dr. John Lindsay <jlindsay@uoguelph.ca> * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package plugins; import java.util.Date; import whitebox.geospatialfiles.WhiteboxRaster; import whitebox.interfaces.WhiteboxPlugin; import whitebox.interfaces.WhiteboxPluginHost; /** * This tool calculates the average slope gradient (i.e., slope steepness in degrees) of the flowpaths that run through each grid cell in an input digital elevation model (DEM) to the upslope divide cells. * * @author Dr. John Lindsay email: jlindsay@uoguelph.ca */ public class AverageSlopeToDivide implements WhiteboxPlugin { private WhiteboxPluginHost myHost = null; private String[] args; // Constants private static final double LnOf2 = 0.693147180559945; /** * Used to retrieve the plugin tool's name. This is a short, unique name * containing no spaces. * * @return String containing plugin name. */ @Override public String getName() { return "AverageSlopeToDivide"; } /** * Used to retrieve the plugin tool's descriptive name. This can be a longer * name (containing spaces) and is used in the interface to list the tool. * * @return String containing the plugin descriptive name. */ @Override public String getDescriptiveName() { return "Average Flowpath Slope From Cell To Divide"; } /** * Used to retrieve a short description of what the plugin tool does. * * @return String containing the plugin's description. */ @Override public String getToolDescription() { return "Measures the average slope gradient from each grid cell to all " + "upslope divide cells."; } /** * Used to identify which toolboxes this plugin tool should be listed in. * * @return Array of Strings. */ @Override public String[] getToolbox() { String[] ret = {"FlowpathTAs"}; return ret; } /** * Sets the WhiteboxPluginHost to which the plugin tool is tied. This is the * class that the plugin will send all feedback messages, progress updates, * and return objects. * * @param host The WhiteboxPluginHost that called the plugin tool. */ @Override public void setPluginHost(WhiteboxPluginHost host) { myHost = host; } /** * Used to communicate feedback pop-up messages between a plugin tool and * the main Whitebox user-interface. * * @param feedback String containing the text to display. */ private void showFeedback(String message) { if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } } /** * Used to communicate a return object from a plugin tool to the main * Whitebox user-interface. * * @return Object, such as an output WhiteboxRaster. */ private void returnData(Object ret) { if (myHost != null) { myHost.returnData(ret); } } private int previousProgress = 0; private String previousProgressLabel = ""; /** * Used to communicate a progress update between a plugin tool and the main * Whitebox user interface. * * @param progressLabel A String to use for the progress label. * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(String progressLabel, int progress) { if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel, progress); } previousProgress = progress; previousProgressLabel = progressLabel; } /** * Used to communicate a progress update between a plugin tool and the main * Whitebox user interface. * * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(int progress) { if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress = progress; } /** * Sets the arguments (parameters) used by the plugin. * * @param args An array of string arguments. */ @Override public void setArgs(String[] args) { this.args = args.clone(); } private boolean cancelOp = false; /** * Used to communicate a cancel operation from the Whitebox GUI. * * @param cancel Set to true if the plugin should be canceled. */ @Override public void setCancelOp(boolean cancel) { cancelOp = cancel; } private void cancelOperation() { showFeedback("Operation cancelled."); updateProgress("Progress: ", 0); } private boolean amIActive = false; /** * Used by the Whitebox GUI to tell if this plugin is still running. * * @return a boolean describing whether or not the plugin is actively being * used. */ @Override public boolean isActive() { return amIActive; } /** * Used to execute this plugin tool. */ @Override public void run() { amIActive = true; String inputHeader = null; String outputHeader = null; String DEMHeader = null; int row, col, x, y; int progress = 0; double z, val, val2, val3; int i, c; int[] dX = new int[]{1, 1, 1, 0, -1, -1, -1, 0}; int[] dY = new int[]{-1, 0, 1, 1, 1, 0, -1, -1}; double[] inflowingVals = new double[]{16, 32, 64, 128, 1, 2, 4, 8}; boolean flag = false; double flowDir = 0; double flowLength = 0; double numUpslopeFlowpaths = 0; double flowpathLengthToAdd = 0; double conversionFactor = 1; double divideElevToAdd = 0; double radToDeg = 180 / Math.PI; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputHeader = args[0]; DEMHeader = args[1]; outputHeader = args[2]; conversionFactor = Double.parseDouble(args[3]); // check to see that the inputHeader and outputHeader are not null. if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster pntr = new WhiteboxRaster(inputHeader, "r"); int rows = pntr.getNumberRows(); int cols = pntr.getNumberColumns(); double noData = pntr.getNoDataValue(); double gridResX = pntr.getCellSizeX(); double gridResY = pntr.getCellSizeY(); double diagGridRes = Math.sqrt(gridResX * gridResX + gridResY * gridResY); double[] gridLengths = new double[]{diagGridRes, gridResX, diagGridRes, gridResY, diagGridRes, gridResX, diagGridRes, gridResY}; WhiteboxRaster DEM = new WhiteboxRaster(DEMHeader, "r"); if (DEM.getNumberRows() != rows || DEM.getNumberColumns() != cols) { showFeedback("The input files must have the same dimensions, i.e. number of " + "rows and columns."); return; } WhiteboxRaster output = new WhiteboxRaster(outputHeader, "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, -999); output.setPreferredPalette("blueyellow.pal"); output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS); output.setZUnits(pntr.getXYUnits()); WhiteboxRaster numInflowingNeighbours = new WhiteboxRaster(outputHeader.replace(".dep", "_temp1.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0); numInflowingNeighbours.isTemporaryFile = true; WhiteboxRaster numUpslopeDivideCells = new WhiteboxRaster(outputHeader.replace(".dep", "_temp2.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0); numUpslopeDivideCells.isTemporaryFile = true; WhiteboxRaster totalFlowpathLength = new WhiteboxRaster(outputHeader.replace(".dep", "_temp3.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0); totalFlowpathLength.isTemporaryFile = true; WhiteboxRaster totalUpslopeDivideElev = new WhiteboxRaster(outputHeader.replace(".dep", "_temp4.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0); totalUpslopeDivideElev.isTemporaryFile = true; updateProgress("Loop 1 of 3:", 0); for (row = 0; row < rows; row++) { for (col = 0; col < cols; col++) { if (pntr.getValue(row, col) != noData) { z = 0; for (i = 0; i < 8; i++) { if (pntr.getValue(row + dY[i], col + dX[i]) == inflowingVals[i]) { z++; } } if (z > 0) { numInflowingNeighbours.setValue(row, col, z); } else { numInflowingNeighbours.setValue(row, col, -1); } } else { output.setValue(row, col, noData); } } if (cancelOp) { cancelOperation(); return; } progress = (int) (100f * row / (rows - 1)); updateProgress("Loop 1 of 3:", progress); } updateProgress("Loop 2 of 3:", 0); for (row = 0; row < rows; row++) { for (col = 0; col < cols; col++) { val = numInflowingNeighbours.getValue(row, col); if (val <= 0 && val != noData) { flag = false; x = col; y = row; do { val = numInflowingNeighbours.getValue(y, x); if (val <= 0 && val != noData) { //there are no more inflowing neighbours to visit; carry on downslope if (val == -1) { //it's the start of a flowpath numUpslopeDivideCells.setValue(y, x, 0); numUpslopeFlowpaths = 1; divideElevToAdd = DEM.getValue(y, x); } else { numUpslopeFlowpaths = numUpslopeDivideCells.getValue(y, x); divideElevToAdd = totalUpslopeDivideElev.getValue(y, x); } numInflowingNeighbours.setValue(y, x, noData); // find it's downslope neighbour flowDir = pntr.getValue(y, x); if (flowDir > 0) { // what's the flow direction as an int? c = (int) (Math.log(flowDir) / LnOf2); flowLength = gridLengths[c]; val2 = totalFlowpathLength.getValue(y, x); flowpathLengthToAdd = val2 + numUpslopeFlowpaths * flowLength; //move x and y accordingly x += dX[c]; y += dY[c]; numUpslopeDivideCells.setValue(y, x, numUpslopeDivideCells.getValue(y, x) + numUpslopeFlowpaths); totalFlowpathLength.setValue(y, x, totalFlowpathLength.getValue(y, x) + flowpathLengthToAdd); totalUpslopeDivideElev.setValue(y, x, totalUpslopeDivideElev.getValue(y, x) + divideElevToAdd); numInflowingNeighbours.setValue(y, x, numInflowingNeighbours.getValue(y, x) - 1); } else { // you've hit the edge or a pit cell. flag = true; } } else { flag = true; } } while (!flag); } } if (cancelOp) { cancelOperation(); return; } progress = (int) (100f * row / (rows - 1)); updateProgress("Loop 2 of 3:", progress); } numUpslopeDivideCells.flush(); totalFlowpathLength.flush(); totalUpslopeDivideElev.flush(); numInflowingNeighbours.close(); updateProgress("Loop 3 of 3:", 0); double[] data1 = null; double[] data2 = null; double[] data3 = null; double[] data4 = null; double[] data5 = null; for (row = 0; row < rows; row++) { data1 = numUpslopeDivideCells.getRowValues(row); data2 = totalFlowpathLength.getRowValues(row); data3 = pntr.getRowValues(row); data4 = totalUpslopeDivideElev.getRowValues(row); data5 = DEM.getRowValues(row); for (col = 0; col < cols; col++) { if (data3[col] != noData) { if (data1[col] > 0) { val = data2[col] / data1[col]; val2 = (data4[col] / data1[col] - data5[col]) * conversionFactor; val3 = Math.atan(val2 / val) * radToDeg; output.setValue(row, col, val3); } else { output.setValue(row, col, 0); } } else { output.setValue(row, col, noData); } } if (cancelOp) { cancelOperation(); return; } progress = (int) (100f * row / (rows - 1)); updateProgress("Loop 3 of 3:", progress); } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); pntr.close(); DEM.close(); numUpslopeDivideCells.close(); totalFlowpathLength.close(); totalUpslopeDivideElev.close(); output.close(); // returning a header file string displays the image. returnData(outputHeader); } catch (OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch (Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(), e); } finally { updateProgress("Progress: ", 0); // tells the main application that this process is completed. amIActive = false; myHost.pluginComplete(); } } }
jblindsay/jblindsay.github.io
ghrg/Whitebox/WhiteboxGAT-linux/resources/plugins/source_files/AverageSlopeToDivide.java
Java
mit
16,874
#-*- coding: utf-8 -*- from .grant import Grant from ..endpoint import AuthorizationEndpoint class ImplicitGrant(Grant): """ The implicit grant type is used to obtain access tokens (it does not support the issuance of refresh tokens) and is optimized for public clients known to operate a particular redirection URI. These clients are typically implemented in a browser using a scripting language such as JavaScript. +----------+ | Resource | | Owner | | | +----------+ ^ | (B) +----|-----+ Client Identifier +---------------+ | -+----(A)-- & Redirection URI --->| | | User- | | Authorization | | Agent -|----(B)-- User authenticates -->| Server | | | | | | |<---(C)--- Redirection URI ----<| | | | with Access Token +---------------+ | | in Fragment | | +---------------+ | |----(D)--- Redirection URI ---->| Web-Hosted | | | without Fragment | Client | | | | Resource | | (F) |<---(E)------- Script ---------<| | | | +---------------+ +-|--------+ | | (A) (G) Access Token | | ^ v +---------+ | | | Client | | | +---------+ Note: The lines illustrating steps (A) and (B) are broken into two parts as they pass through the user-agent. Figure 4: Implicit Grant Flow """ def get_redirection_uri(self, expires_in): self._authorization_endpoint = AuthorizationEndpoint(self._server, self._request, self._client) return self._authorization_endpoint.implicit(expires_in)
uptown/django-town
django_town/oauth2/grant/implicitgrant.py
Python
mit
2,061
using System; using System.Collections.Generic; using System.Linq; using System.Text; class MessagesInABottle { static void GetMessage(string input, int start, Dictionary<string, char> cipher, List<string> answers) { if (start >= input.Length) { answers.Add(input); return; } StringBuilder newMess = new StringBuilder(); for (int i = start; i < input.Length; i++) { newMess.Append(input[i]); char newChar; if (cipher.TryGetValue(newMess.ToString(), out newChar)) { StringBuilder newMessMod = new StringBuilder(); if (start > 0) { newMessMod.Append(input.Substring(0, start)); } newMessMod.Append(newChar); if(i <= input.Length - 2) { newMessMod.Append(input.Substring(i + 1)); } GetMessage(newMessMod.ToString(), start + 1, cipher, answers); } else if (i == input.Length - 1) { return; } } } static void Main() { List<string> answers = new List<string>(); Dictionary<string, char> cipher = new Dictionary<string,char>(); string input = Console.ReadLine(); string cipherInput = Console.ReadLine(); for (int i = 0; i < cipherInput.Length;) { StringBuilder key = new StringBuilder(); char value = cipherInput[i++]; while(!Char.IsLetter(cipherInput[i])) { key.Append(cipherInput[i]); i++; if (i == cipherInput.Length) { break; } } cipher.Add(key.ToString(), value); } GetMessage(input, 0, cipher, answers); Console.WriteLine(answers.Count); answers.Sort(); foreach (string answer in answers) { Console.WriteLine(answer); } } }
kalinalazarova1/TelerikAcademy
Programming/2. CSharpPartTwo/ExamCS2_07.02.2012/2. MessagesInABottle/MessagesInABottle.cs
C#
mit
2,116
<?xml version="1.0" ?><!DOCTYPE TS><TS language="hi_IN" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About HazeCoin</source> <translation>बिटकोइन के संबंध में</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;HazeCoin&lt;/b&gt; version</source> <translation>बिटकोइन वर्सन</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>कापीराइट</translation> </message> <message> <location line="+0"/> <source>The HazeCoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>पता पुस्तक</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>दो बार क्लिक करे पता या लेबल संपादन करने के लिए !</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>नया पता लिखिए !</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;नया पता</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your HazeCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;पता कॉपी करे</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a HazeCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified HazeCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;मिटाए !!</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your HazeCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>&amp;लेबल कॉपी करे </translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;एडिट</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>पता पुस्तक का डेटा एक्सपोर्ट (निर्यात) करे !</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>ग़लतियाँ एक्सपोर्ट (निर्यात) करे!</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>फाइल में लिख नही सके %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>लेबल</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>नया पहचान शब्द/अक्षर वॉलेट मे डालिए ! &lt;br/&gt; कृपा करके पहचान शब्द में &lt;br&gt; 10 से ज़्यादा अक्षॉरों का इस्तेमाल करे &lt;/b&gt;,या &lt;b&gt;आठ या उससे से ज़्यादा शब्दो का इस्तेमाल करे&lt;/b&gt; !</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>एनक्रिप्ट वॉलेट !</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>वॉलेट खोलने के आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>वॉलेट खोलिए</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>वॉलेट डीक्रिप्ट( विकोड) करने के लिए आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation> डीक्रिप्ट वॉलेट</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>पहचान शब्द/अक्षर बदलिये !</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>कृपा करके पुराना एवं नया पहचान शब्द/अक्षर वॉलेट में डालिए !</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>वॉलेट एनक्रिपशन को प्रमाणित कीजिए !</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR HAZECOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>वॉलेट एनक्रिप्ट हो गया !</translation> </message> <message> <location line="-56"/> <source>HazeCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your hazecoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>वॉलेट एनक्रिप्ट नही हुआ!</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>वॉलेट एनक्रिपशन नाकाम हो गया इंटर्नल एरर की वजह से! आपका वॉलेट एनक्रीपत नही हुआ है!</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>आपके द्वारा डाले गये पहचान शब्द/अक्षर मिलते नही है !</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>वॉलेट का लॉक नही खुला !</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>वॉलेट डीक्रिप्ट करने के लिए जो पहचान शब्द/अक्षर डाले गये है वो सही नही है!</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>वॉलेट का डीक्रिप्ट-ष्ण असफल !</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>नेटवर्क से समकालिक (मिल) रहा है ...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;विवरण</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>वॉलेट का सामानया विवरण दिखाए !</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp; लेन-देन </translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>देखिए पुराने लेन-देन के विवरण !</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>स्टोर किए हुए पते और लेबलओ को बदलिए !</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>पते की सूची दिखाए जिन्हे भुगतान करना है !</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>बाहर जायें</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>अप्लिकेशन से बाहर निकलना !</translation> </message> <message> <location line="+4"/> <source>Show information about HazeCoin</source> <translation>बीटकोइन के बारे में जानकारी !</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;विकल्प</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;बैकप वॉलेट</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a HazeCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for HazeCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>HazeCoin</source> <translation>बीटकोइन</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About HazeCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your HazeCoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified HazeCoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;फाइल</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;सेट्टिंग्स</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;मदद</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>टैबस टूलबार</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[टेस्टनेट]</translation> </message> <message> <location line="+47"/> <source>HazeCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to HazeCoin network</source> <translation><numerusform>%n सक्रिया संपर्क बीटकोइन नेटवर्क से</numerusform><numerusform>%n सक्रिया संपर्क बीटकोइन नेटवर्क से</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n घंटा</numerusform><numerusform>%n घंटे</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n दिन</numerusform><numerusform>%n दिनो</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n हफ़्ता</numerusform><numerusform>%n हफ्ते</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 पीछे</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>भूल</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>जानकारी</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>नवीनतम</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>भेजी ट्रांजक्शन</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>प्राप्त हुई ट्रांजक्शन</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>तारीख: %1\n राशि: %2\n टाइप: %3\n पता:%4\n</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid HazeCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. HazeCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>पता एडिट करना</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;लेबल</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>इस एड्रेस बुक से जुड़ा एड्रेस</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;पता</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>इस एड्रेस बुक से जुड़ी प्रविष्टि केवल भेजने वाले addresses के लिए बदली जा सकती है|</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>नया स्वीकार्य पता</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>नया भेजने वाला पता</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>एडिट स्वीकार्य पता </translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>एडिट भेजने वाला पता</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>डाला गया पता &quot;%1&quot; एड्रेस बुक में पहले से ही मोजूद है|</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid HazeCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>वॉलेट को unlock नहीं किया जा सकता|</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>नयी कुंजी का निर्माण असफल रहा|</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>HazeCoin-Qt</source> <translation>बीटकोइन-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>संस्करण</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>खपत :</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>विकल्प</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start HazeCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start HazeCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the HazeCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the HazeCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting HazeCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show HazeCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;ओके</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;कैन्सल</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting HazeCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>फार्म</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the HazeCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>बाकी रकम :</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>अपुष्ट :</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;हाल का लेन-देन&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>आपका चालू बॅलेन्स</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>लेन देन की पुष्टि अभी नहीं हुई है, इसलिए इन्हें अभी मोजुदा बैलेंस में गिना नहीं गया है|</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start hazecoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>भुगतान का अनुरोध</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>लेबल :</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>लागू नही </translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the HazeCoin-Qt help message to get a list with possible HazeCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>HazeCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>HazeCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the HazeCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the HazeCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>सिक्के भेजें|</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>बाकी रकम :</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>भेजने की पुष्टि करें</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; से %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>सिक्के भेजने की पुष्टि करें</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>क्या आप %1 भेजना चाहते हैं?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>और</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>भेजा गया अमाउंट शुन्य से अधिक होना चाहिए|</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>फार्म</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>अमाउंट:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>प्राप्तकर्ता:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>आपकी एड्रेस बुक में इस एड्रेस के लिए एक लेबल लिखें</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>लेबल:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>प्राप्तकर्ता हटायें</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a HazeCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>HazeCoin एड्रेस लिखें (उदाहरण: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation>हस्ताक्षर</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this HazeCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified HazeCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a HazeCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>HazeCoin एड्रेस लिखें (उदाहरण: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter HazeCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The HazeCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/अपुष्ट</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 पुष्टियाँ</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 20 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>राशि</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>सही</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>ग़लत</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, अभी तक सफलतापूर्वक प्रसारित नहीं किया गया है</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>अज्ञात</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>लेन-देन का विवरण</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>टाइप</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>राशि</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>ऑफलाइन ( %1 पक्का करना)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>अपुष्ट ( %1 मे %2 पक्के )</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>पक्के ( %1 पक्का करना)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>यह ब्लॉक किसी भी और नोड को मिला नही है ! शायद यह ब्लॉक कोई भी नोड स्वीकारे गा नही !</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>जेनरेट किया गया किंतु स्वीकारा नही गया !</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>स्वीकारा गया</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>स्वीकार्य ओर से</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>भेजा खुद को भुगतान</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>माइंड</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(लागू नहीं)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>ट्रांसेक्शन स्तिथि| पुष्टियों की संख्या जानने के लिए इस जगह पर माउस लायें|</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>तारीख तथा समय जब ये ट्रांसेक्शन प्राप्त हुई थी|</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>ट्रांसेक्शन का प्रकार|</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>ट्रांसेक्शन की मंजिल का पता|</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>अमाउंट बैलेंस से निकला या जमा किया गया |</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>सभी</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>आज</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>इस हफ्ते</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>इस महीने</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>पिछले महीने</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>इस साल</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>विस्तार...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>स्वीकार करना</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>अपनेआप को</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>माइंड</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>अन्य</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>ढूँदने के लिए कृपा करके पता या लेबल टाइप करे !</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>लघुत्तम राशि</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>पता कॉपी करे</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>एडिट लेबल</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>लेन-देन का डेटा निर्यात करे !</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>पक्का</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>टाइप</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>लेबल</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>राशि</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>ग़लतियाँ एक्सपोर्ट (निर्यात) करे!</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>फाइल में लिख नही सके %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>विस्तार:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>तक</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>बैकप वॉलेट</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>वॉलेट डेटा (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>बैकप असफल</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>बैकप सफल</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>HazeCoin version</source> <translation>बीटकोइन संस्करण</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>खपत :</translation> </message> <message> <location line="-29"/> <source>Send command to -server or hazecoind</source> <translation>-server या hazecoind को कमांड भेजें</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>commands की लिस्ट बनाएं</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>किसी command के लिए मदद लें</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>विकल्प:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: hazecoin.conf)</source> <translation>configuraion की फाइल का विवरण दें (default: hazecoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: hazecoind.pid)</source> <translation>pid फाइल का विवरण दें (default: hazecoin.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 4369 or testnet: 14369)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 4370 or testnet: 14370)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=hazecoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;HazeCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. HazeCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong HazeCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>ब्लॉक्स जाँचे जा रहा है...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>वॉलेट जाँचा जा रहा है...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>जानकारी</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the HazeCoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>पता पुस्तक आ रही है...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of HazeCoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart HazeCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>राशि ग़लत है</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>ब्लॉक इंडेक्स आ रहा है...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. HazeCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>वॉलेट आ रहा है...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>रि-स्केनी-इंग...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>लोड हो गया|</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>भूल</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
HazeDev/Hazecoin
src/qt/locale/bitcoin_hi_IN.ts
TypeScript
mit
106,336
#include "bond/api/libio.h" #include "bond/io/outputstream.h" #include "bond/io/outputstreamadaptor.h" #include <cstdio> namespace Bond { void OutputStreamAdaptor::Print(const char *str) { const char *format = ((mFlags & IO::Left) != 0) ? "%-*s" : "%*s"; mStream->Print(format, mWidth, str); mWidth = 0; } void OutputStreamAdaptor::Print(bool value) { if ((mFlags & IO::BoolAlpha) != 0) { Print(value ? "true" : "false"); } else { Print(value ? int32_t(1) : int32_t(0)); } } void OutputStreamAdaptor::Print(char value) { const char *format = ((mFlags & IO::Left) != 0) ? "%-*c" : "%*c"; mStream->Print(format, mWidth, value); mWidth = 0; } void OutputStreamAdaptor::Print(int32_t value) { char format[16]; FormatInteger(format, BOND_PRId32, BOND_PRIx32, BOND_PRIo32); mStream->Print(format, mWidth, value); mWidth = 0; } void OutputStreamAdaptor::Print(uint32_t value) { char format[16]; FormatInteger(format, BOND_PRIu32, BOND_PRIx32, BOND_PRIo32); mStream->Print(format, mWidth, value); mWidth = 0; } void OutputStreamAdaptor::Print(int64_t value) { char format[16]; FormatInteger(format, BOND_PRId64, BOND_PRIx64, BOND_PRIo64); mStream->Print(format, mWidth, value); mWidth = 0; } void OutputStreamAdaptor::Print(uint64_t value) { char format[16]; FormatInteger(format, BOND_PRIu64, BOND_PRIx64, BOND_PRIo64); mStream->Print(format, mWidth, value); mWidth = 0; } void OutputStreamAdaptor::Print(double value) { char format[16]; FormatFloat(format); mStream->Print(format, mWidth, mPrecision, value); mWidth = 0; } void OutputStreamAdaptor::FormatInteger(char *format, const char *dec, const char *hex, const char *oct) const { *format++ = '%'; if ((mFlags & IO::Left) != 0) { *format++ = '-'; } if (((mFlags & IO::ShowBase) != 0) && ((mFlags & (IO::Hex | IO::Oct)) != 0)) { *format++ = '#'; } if ((mFlags & IO::Zero) != 0) { *format++ = '0'; } *format++ = '*'; const char *specifier = ((mFlags & IO::Hex) != 0) ? hex : ((mFlags & IO::Oct) != 0) ? oct : dec; while (*specifier) { *format++ = *specifier++; } *format++ = '\0'; } void OutputStreamAdaptor::FormatFloat(char *format) const { *format++ = '%'; if ((mFlags & IO::Left) != 0) { *format++ = '-'; } if ((mFlags & IO::ShowPoint) != 0) { *format++ = '#'; } if ((mFlags & IO::Zero) != 0) { *format++ = '0'; } *format++ = '*'; *format++ = '.'; *format++ = '*'; if ((mFlags & IO::Fixed) != 0) { *format++ = 'f'; } else if ((mFlags & IO::Scientific) != 0) { *format++ = 'e'; } else { *format++ = 'g'; } *format++ = '\0'; } }
bondscripting/bond
source/outputstreamadaptor.cpp
C++
mit
2,600
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("DateDifference")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DateDifference")] [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("8760b94e-74e6-43c8-9d2b-74a074a02c18")] // 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")]
DJBuro/Telerik
C#2/Strings and Text Processing/DateDifference/Properties/AssemblyInfo.cs
C#
mit
1,404
# Include this module in the base class of a class cluster to handle swizzling # of ::new module ClusterFactory def self.included(parent) class << parent alias :original_new :new def inherited(subclass) class << subclass alias :new :original_new end end end end end
jrmyward/euclidean
lib/euclidean/cluster_factory.rb
Ruby
mit
323
<?php namespace Twit\AppBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class WallControllerTest extends WebTestCase { /* public function testCompleteScenario() { // Create a new client to browse the application $client = static::createClient(); // Create a new entry in the database $crawler = $client->request('GET', '/wall/'); $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /wall/"); $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); // Fill in the form and submit it $form = $crawler->selectButton('Create')->form(array( 'twit_appbundle_wall[field_name]' => 'Test', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check data in the show view $this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")'); // Edit the entity $crawler = $client->click($crawler->selectLink('Edit')->link()); $form = $crawler->selectButton('Update')->form(array( 'twit_appbundle_wall[field_name]' => 'Foo', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check the element contains an attribute with value equals "Foo" $this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]'); // Delete the entity $client->submit($crawler->selectButton('Delete')->form()); $crawler = $client->followRedirect(); // Check the entity has been delete on the list $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); } */ }
villers/PHP_Avance_SymfoTweet
src/Twit/AppBundle/Tests/Controller/WallControllerTest.php
PHP
mit
1,913
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > The Date.prototype.getMinutes property "length" has { ReadOnly, DontDelete, DontEnum } attributes es5id: 15.9.5.20_A3_T1 description: Checking ReadOnly attribute ---*/ x = Date.prototype.getMinutes.length; Date.prototype.getMinutes.length = 1; if (Date.prototype.getMinutes.length !== x) { $ERROR('#1: The Date.prototype.getMinutes.length has the attribute ReadOnly'); }
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/Date/prototype/getMinutes/S15.9.5.20_A3_T1.js
JavaScript
mit
529
require 'test_helper' class RegistrationCustomControllerTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end end
IsaiasAntonio/PI
test/controllers/registration_custom_controller_test.rb
Ruby
mit
150
class Beer < ActiveRecord::Base SORTABLE_COLUMNS = %w(id name created_at updated_at).freeze include SearchableModel belongs_to :brewery belongs_to :user validates :brewery_id, presence: true validates :name, presence: true, length: { maximum: 255 } validates :description, presence: true, length: { maximum: 4096 } validates :abv, presence: true, numericality: true attr_accessible :name, :description, :abv def self.filter_by_brewery_id(brewery_id) if brewery_id.present? where(brewery_id: brewery_id) else where("") end end def self.search(options = {}) includes(:brewery) .for_token(options[:token]) .filter_by_name(options[:query]) .filter_by_brewery_id(options[:brewery_id]) .page(options[:page]) .per_page(options[:per_page] || 50) .order_by(options[:order]) end def public? user_id.nil? end end
openbeerdatabase/openbeerdatabase
app/models/beer.rb
Ruby
mit
923
package nl.rmokveld.wearcast.phone; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v7.app.NotificationCompat; import nl.rmokveld.wearcast.shared.C; public class WearCastService extends Service { private static final String ACTION_DISCOVERY = "discovery"; private static final String ACTION_START_CAST = "start_cast"; public static void startDiscovery(Context context) { context.startService(new Intent(context, WearCastService.class).setAction(ACTION_DISCOVERY).putExtra("start", true)); } public static void stopDiscovery(Context context) { context.startService(new Intent(context, WearCastService.class).setAction(ACTION_DISCOVERY).putExtra("start", false)); } public static void startCast(Context context, String requestNode, String deviceId, String mediaJson) { context.startService(new Intent(context, WearCastService.class) .setAction(ACTION_START_CAST) .putExtra(C.REQUEST_NODE_ID, requestNode) .putExtra(C.ARG_MEDIA_INFO, mediaJson) .putExtra(C.DEVICE_ID, deviceId)); } private WearCastDiscoveryHelper mCastDiscoveryHelper; private AbstractStartCastHelper mStartCastHelper; private Runnable mTimeout = new Runnable() { @Override public void run() { stopForeground(true); mCastDiscoveryHelper.stopDiscovery(); } }; @Override public void onCreate() { super.onCreate(); mCastDiscoveryHelper = new WearCastDiscoveryHelper(this); if (WearCastNotificationManager.getExtension() != null) mStartCastHelper = WearCastNotificationManager.getExtension().newStartCastHelper(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { if (ACTION_DISCOVERY.equals(intent.getAction())) { if (intent.getBooleanExtra("start", false)) { mCastDiscoveryHelper.startDiscovery(); } else { mCastDiscoveryHelper.stopDiscovery(); } } else if (ACTION_START_CAST.equals(intent.getAction())) { mStartCastHelper.startCastFromWear( intent.getStringExtra(C.DEVICE_ID), intent.getStringExtra(C.ARG_MEDIA_INFO), intent.getStringExtra(C.REQUEST_NODE_ID), null); } } return START_NOT_STICKY; } @Override public void onDestroy() { super.onDestroy(); mCastDiscoveryHelper.release(); mStartCastHelper.release(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
remcomokveld/WearCast
library-app/src/main/java/nl/rmokveld/wearcast/phone/WearCastService.java
Java
mit
2,916
module LogStasher VERSION = "0.6.1" end
rockaBe/logstasher
lib/logstasher/version.rb
Ruby
mit
42
export class NewForm { update() { } }
sergemazille/gextion
src/AppBundle/Resources/js/New/NewForm.js
JavaScript
mit
48
<?php namespace Vexilo\Utilities\Models\Traits; trait SortableTrait { /** * Return an array with the sortable columns * * @param array $sort the current sort array * @return array */ public static function getSortableColums($sort = null) { $instance = new static; $sortable = $instance->sortable; // Sort the array based on the input if (is_array($sort)&&count($sort)) { foreach ($sort as $item) { if (isset($sortable[$item])) { $sortable_aux[$item] = $sortable[$item]; } } $sortable = array_merge($sortable_aux, $sortable); } return $sortable; } /** * Return an array with the searchable columns * * @return array */ public static function getSearchableColums() { $instance = new static; return $instance->searchable; } /** * Allow to filter results by the search form * * @param Illuminate\Database\Query $query [description] * @param string $string The search query * @return lluminate\Database\Query [description] */ public function scopeSearchByInput($query, $string = '') { if ($string) { $searchable = self::getSearchableColums(); $query->where(function ($query) use ($searchable, $string) { $string_parts = explode(" ", $string); foreach ($string_parts as $part) { $query->where(function ($query) use ($searchable, $part) { foreach ($searchable as $column => $value) { $query->orWhere($column, 'like', '%'.$part.'%'); } }); } }); } return $query; } /** * Sort the results by the order form input * * @param Illuminate\Database\Query $query * @param array $sortBy Order by columns * @param array $sortByOrder Order by sort colums * @return Illuminate\Database\Query\Builder */ public function scopeSortByInput($query, $sortBy = array(), $sortByOrder = array()) { if (is_array($sortBy)&&count($sortBy)) { foreach ($sortBy as $column) { $query->orderBy($column, ($sortByOrder && in_array($column, $sortByOrder))?'desc':'asc'); } } return $query; } }
vexilo/utilities
src/Models/Traits/SortableTrait.php
PHP
mit
2,500
using Radical.Validation; using System; using System.Windows.Data; using System.Windows.Markup; namespace Radical.Windows.Converters { [MarkupExtensionReturnType(typeof(NotConverter))] [ValueConversion(typeof(bool), typeof(bool))] public sealed class NotConverter : AbstractSingletonConverter { //static WeakReference singleton = new WeakReference( null ); //public override object ProvideValue( IServiceProvider serviceProvider ) //{ // IValueConverter converter = ( IValueConverter )singleton.Target; // if( converter == null ) // { // converter = this; // singleton.Target = converter; // } // return converter; //} public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Ensure.That(value).Named("value") .IsNotNull() .IsTrue(v => v is bool); Ensure.That(targetType).Is<bool>(); return !((bool)value); } public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Ensure.That(value).Named("value").IsNotNull(); Ensure.That(targetType).Is(typeof(bool)); return !((bool)value); } } }
RadicalFx/Radical.Windows
src/Radical.Windows/Converters/NotConverter.cs
C#
mit
1,421
require 'ebay_trading/types/shipment' require 'ebay_trading/types/variation' module EbayTrading # :nodoc: module Types # :nodoc: # == Attributes # text_node :invoice_number, 'InvoiceNumber', :optional => true # numeric_node :transaction_id, 'TransactionID', :optional => true # numeric_node :sale_record_id, 'SaleRecordID', :optional => true # text_node :item_id, 'ItemID', :optional => true # numeric_node :quantity_sold, 'QuantitySold', :optional => true # money_node :item_price, 'ItemPrice', :optional => true # money_node :subtotal_amount, 'SubtotalAmount', :optional => true # text_node :item_title, 'ItemTitle', :optional => true # text_node :listing_type, 'ListingType', :optional => true # boolean_node :relisted, 'Relisted', 'true', 'false', :optional => true # numeric_node :watch_count, 'WatchCount', :optional => true # money_node :start_price, 'StartPrice', :optional => true # money_node :reserve_price, 'ReservePrice', :optional => true # boolean_node :second_chance_offer_sent, 'SecondChanceOfferSent', 'true', 'false', :optional => true # text_node :custom_label, 'CustomLabel', :optional => true # text_node :sold_on, 'SoldOn', :optional => true # value_array_node :listed_ons, 'ListedOn', :default_value => [] # object_node :shipment, 'Shipment', :class => Shipment, :optional => true # boolean_node :charity_listing, 'CharityListing', 'true', 'false', :optional => true # object_node :variation, 'Variation', :class => Variation, :optional => true # text_node :order_line_item_id, 'OrderLineItemID', :optional => true class SellingManagerSoldTransaction include XML::Mapping include Initializer root_element_name 'SellingManagerSoldTransaction' text_node :invoice_number, 'InvoiceNumber', :optional => true numeric_node :transaction_id, 'TransactionID', :optional => true numeric_node :sale_record_id, 'SaleRecordID', :optional => true text_node :item_id, 'ItemID', :optional => true numeric_node :quantity_sold, 'QuantitySold', :optional => true money_node :item_price, 'ItemPrice', :optional => true money_node :subtotal_amount, 'SubtotalAmount', :optional => true text_node :item_title, 'ItemTitle', :optional => true text_node :listing_type, 'ListingType', :optional => true boolean_node :relisted, 'Relisted', 'true', 'false', :optional => true numeric_node :watch_count, 'WatchCount', :optional => true money_node :start_price, 'StartPrice', :optional => true money_node :reserve_price, 'ReservePrice', :optional => true boolean_node :second_chance_offer_sent, 'SecondChanceOfferSent', 'true', 'false', :optional => true text_node :custom_label, 'CustomLabel', :optional => true text_node :sold_on, 'SoldOn', :optional => true value_array_node :listed_ons, 'ListedOn', :default_value => [] object_node :shipment, 'Shipment', :class => Shipment, :optional => true boolean_node :charity_listing, 'CharityListing', 'true', 'false', :optional => true object_node :variation, 'Variation', :class => Variation, :optional => true text_node :order_line_item_id, 'OrderLineItemID', :optional => true end end end
plzen/ebay
lib/ebay_trading/types/selling_manager_sold_transaction.rb
Ruby
mit
3,298
module TokyoMetro::Modules::ToFactory::Api::Convert::Patch::TrainTimetable::YurakuchoLine::Generate::List def generate( max = nil ) ary = super( max ) return ::TokyoMetro::Factory::Convert::Patch::Api::TrainTimetable::YurakuchoLine::Generate::List.updated( ary ) end end
osorubeki-fujita/odpt_tokyo_metro
lib/tokyo_metro/modules/to_factory/api/convert/patch/train_timetable/yurakucho_line/generate/list.rb
Ruby
mit
285
module DeviseSslSessionVerifiable VERSION = "3.0.4".freeze end
mobalean/devise_ssl_session_verifiable
lib/devise_ssl_session_verifiable/version.rb
Ruby
mit
65
package org.github.sriki77.edgesh.command; public class CommandException extends RuntimeException { public CommandException(String message) { super(message); } }
sriki77/edgesh
src/main/java/org/github/sriki77/edgesh/command/CommandException.java
Java
mit
180
<?php include ('clases/User.php'); include ('clases/Rss.php'); session_start(); if(!isset($_SESSION['user'])) { header ("location: index.php"); exit; } $usuarios = USER::TraerTodosLosUsersSP(); ?> <!DOCTYPE html> <html> <head> <?php include('modules/headContent.html'); ?> <title>Casita</title> <?php include('modules/style.html'); ?> </head> <body> <div class='container-fluid'> <div class'row'> <?php include ('modules/navbar.php'); ?> </div> <main id='main' class='main container-fluid center-block row text-center'> <div id='presentacion ' class="wrapper "> <h1>Casita dulce casita</h1> </div> <div class="container-fluid form-group center-block"> <label for="ingresoNuevo">Agrega una fuente rss nueva</label> <input id="ingresoNuevo" type="text" class="form-control" > <button id="agregar" type='submit'class="btn btn-default" > Agregar </button> </div> <!-- when clicked, it will load the create product form --> <div id='load-product' class='btn btn-primary pull-right'> <span class='glyphicon glyphicon-load'></span> Cargar productos </div> <section id='stream' class='row container center-block'> <!-- this is where the contents will be shown. --> <div id='page-content'> </div> <?php //include ('modules/generarRss.php'); ?> </section> </main> </div> <?php include ('modules/footer.html'); ?> <?php include ('modules/script.html'); ?> <script src="https://code.highcharts.com/stock/highstock.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> <script type="text/javascript" src="js/CRUD.js"></script> </body> </html>
AlvarezElias/Consuministisismo
home.php
PHP
mit
1,712
var sourceFolder = 'src', destFolder = 'public', configFolder = 'config'; module.exports = { folders: { source: sourceFolder, dest: destFolder }, files: { scripts: [ `${sourceFolder}/js/utils.js`, `${sourceFolder}/js/sprites/weapon.js`, `${sourceFolder}/js/sprites/hook.js`, `${sourceFolder}/js/sprites/enemy.js`, `${sourceFolder}/js/sprites/**/*.js`, `${sourceFolder}/js/map.js`, `${sourceFolder}/js/ui/**/*.js`, `${sourceFolder}/js/states/**/*.js`, `${sourceFolder}/js/**/*.js` ], templates: `${sourceFolder}/templates/**/*.html`, libs: [ 'node_modules/phaser/dist/phaser.js', 'node_modules/stats.js/build/stats.min.js' ], styles: `${sourceFolder}/styles/**/*.css`, images: `${sourceFolder}/images/**/*.*`, sounds: `${sourceFolder}/sounds/**/*.*`, json: `${sourceFolder}/json/**/*.*`, fonts: `${sourceFolder}/fonts/**/*.*`, cname: `${configFolder}/CNAME` }, scripts: { destFolder: `${destFolder}/js`, outFile: 'index.js' }, libs: { destFolder: `${destFolder}/js`, outFile: 'libs.js' }, styles: { destFolder: `${destFolder}/css`, outFile: 'index.css' }, images: { destFolder: `${destFolder}/images` }, sounds: { destFolder: `${destFolder}/sounds` }, json: { destFolder: `${destFolder}/json` }, fonts: { destFolder: `${destFolder}/fonts` }, server: { root: destFolder, livereload: true } };
themadknights/wellofeternity
config/gulp.config.js
JavaScript
mit
1,714
using Newtonsoft.Json.Linq; using Skybrud.Essentials.Json.Extensions; using Skybrud.Essentials.Time; namespace Skybrud.Social.Slack.Models.Conversations { /// <summary> /// Class representing the topic a Slack conversation. /// </summary> public class SlackConversationTopic : SlackObject { #region Properties /// <summary> /// Gets the value representing the topic. /// </summary> public string Value { get; } /// <summary> /// Gets the user who set the topic. /// </summary> public string Creator { get; } /// <summary> /// Gets a timestamp for when the topic was last updated. /// </summary> public EssentialsTime LastSet { get; } #endregion #region Constructors /// <summary> /// Initializes a new instance based on the specified <paramref name="json"/> object. /// </summary> /// <param name="json">An instance of <see cref="JObject"/> representing the jsonect.</param> protected SlackConversationTopic(JObject json) : base(json) { Value = json.GetString("value"); Creator = json.GetString("creator"); LastSet = json.GetInt64("last_set", ParseUnixTimestamp); } #endregion #region Static methods /// <summary> /// Parses the specified <paramref name="json"/> object into an instance of <see cref="SlackConversationTopic"/>. /// </summary> /// <param name="json">The instance of <see cref="JObject"/> to parse.</param> /// <returns>An instance of <see cref="SlackConversationTopic"/>.</returns> public static SlackConversationTopic Parse(JObject json) { return json == null ? null : new SlackConversationTopic(json); } #endregion } }
abjerner/Skybrud.Social.Slack
src/Skybrud.Social.Slack/Models/Conversations/SlackConversationTopic.cs
C#
mit
1,870
package storageapi // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2021-08-01/storage" "github.com/Azure/go-autorest/autorest" ) // OperationsClientAPI contains the set of methods on the OperationsClient type. type OperationsClientAPI interface { List(ctx context.Context) (result storage.OperationListResult, err error) } var _ OperationsClientAPI = (*storage.OperationsClient)(nil) // SkusClientAPI contains the set of methods on the SkusClient type. type SkusClientAPI interface { List(ctx context.Context) (result storage.SkuListResult, err error) } var _ SkusClientAPI = (*storage.SkusClient)(nil) // AccountsClientAPI contains the set of methods on the AccountsClient type. type AccountsClientAPI interface { AbortHierarchicalNamespaceMigration(ctx context.Context, resourceGroupName string, accountName string) (result storage.AccountsAbortHierarchicalNamespaceMigrationFuture, err error) CheckNameAvailability(ctx context.Context, accountName storage.AccountCheckNameAvailabilityParameters) (result storage.CheckNameAvailabilityResult, err error) Create(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountCreateParameters) (result storage.AccountsCreateFuture, err error) Delete(ctx context.Context, resourceGroupName string, accountName string) (result autorest.Response, err error) Failover(ctx context.Context, resourceGroupName string, accountName string) (result storage.AccountsFailoverFuture, err error) GetProperties(ctx context.Context, resourceGroupName string, accountName string, expand storage.AccountExpand) (result storage.Account, err error) HierarchicalNamespaceMigration(ctx context.Context, resourceGroupName string, accountName string, requestType string) (result storage.AccountsHierarchicalNamespaceMigrationFuture, err error) List(ctx context.Context) (result storage.AccountListResultPage, err error) ListComplete(ctx context.Context) (result storage.AccountListResultIterator, err error) ListAccountSAS(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountSasParameters) (result storage.ListAccountSasResponse, err error) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result storage.AccountListResultPage, err error) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result storage.AccountListResultIterator, err error) ListKeys(ctx context.Context, resourceGroupName string, accountName string, expand storage.ListKeyExpand) (result storage.AccountListKeysResult, err error) ListServiceSAS(ctx context.Context, resourceGroupName string, accountName string, parameters storage.ServiceSasParameters) (result storage.ListServiceSasResponse, err error) RegenerateKey(ctx context.Context, resourceGroupName string, accountName string, regenerateKey storage.AccountRegenerateKeyParameters) (result storage.AccountListKeysResult, err error) RestoreBlobRanges(ctx context.Context, resourceGroupName string, accountName string, parameters storage.BlobRestoreParameters) (result storage.AccountsRestoreBlobRangesFuture, err error) RevokeUserDelegationKeys(ctx context.Context, resourceGroupName string, accountName string) (result autorest.Response, err error) Update(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountUpdateParameters) (result storage.Account, err error) } var _ AccountsClientAPI = (*storage.AccountsClient)(nil) // DeletedAccountsClientAPI contains the set of methods on the DeletedAccountsClient type. type DeletedAccountsClientAPI interface { Get(ctx context.Context, deletedAccountName string, location string) (result storage.DeletedAccount, err error) List(ctx context.Context) (result storage.DeletedAccountListResultPage, err error) ListComplete(ctx context.Context) (result storage.DeletedAccountListResultIterator, err error) } var _ DeletedAccountsClientAPI = (*storage.DeletedAccountsClient)(nil) // UsagesClientAPI contains the set of methods on the UsagesClient type. type UsagesClientAPI interface { ListByLocation(ctx context.Context, location string) (result storage.UsageListResult, err error) } var _ UsagesClientAPI = (*storage.UsagesClient)(nil) // ManagementPoliciesClientAPI contains the set of methods on the ManagementPoliciesClient type. type ManagementPoliciesClientAPI interface { CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, properties storage.ManagementPolicy) (result storage.ManagementPolicy, err error) Delete(ctx context.Context, resourceGroupName string, accountName string) (result autorest.Response, err error) Get(ctx context.Context, resourceGroupName string, accountName string) (result storage.ManagementPolicy, err error) } var _ ManagementPoliciesClientAPI = (*storage.ManagementPoliciesClient)(nil) // BlobInventoryPoliciesClientAPI contains the set of methods on the BlobInventoryPoliciesClient type. type BlobInventoryPoliciesClientAPI interface { CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, properties storage.BlobInventoryPolicy) (result storage.BlobInventoryPolicy, err error) Delete(ctx context.Context, resourceGroupName string, accountName string) (result autorest.Response, err error) Get(ctx context.Context, resourceGroupName string, accountName string) (result storage.BlobInventoryPolicy, err error) List(ctx context.Context, resourceGroupName string, accountName string) (result storage.ListBlobInventoryPolicy, err error) } var _ BlobInventoryPoliciesClientAPI = (*storage.BlobInventoryPoliciesClient)(nil) // PrivateEndpointConnectionsClientAPI contains the set of methods on the PrivateEndpointConnectionsClient type. type PrivateEndpointConnectionsClientAPI interface { Delete(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string) (result autorest.Response, err error) Get(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string) (result storage.PrivateEndpointConnection, err error) List(ctx context.Context, resourceGroupName string, accountName string) (result storage.PrivateEndpointConnectionListResult, err error) Put(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, properties storage.PrivateEndpointConnection) (result storage.PrivateEndpointConnection, err error) } var _ PrivateEndpointConnectionsClientAPI = (*storage.PrivateEndpointConnectionsClient)(nil) // PrivateLinkResourcesClientAPI contains the set of methods on the PrivateLinkResourcesClient type. type PrivateLinkResourcesClientAPI interface { ListByStorageAccount(ctx context.Context, resourceGroupName string, accountName string) (result storage.PrivateLinkResourceListResult, err error) } var _ PrivateLinkResourcesClientAPI = (*storage.PrivateLinkResourcesClient)(nil) // ObjectReplicationPoliciesClientAPI contains the set of methods on the ObjectReplicationPoliciesClient type. type ObjectReplicationPoliciesClientAPI interface { CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, objectReplicationPolicyID string, properties storage.ObjectReplicationPolicy) (result storage.ObjectReplicationPolicy, err error) Delete(ctx context.Context, resourceGroupName string, accountName string, objectReplicationPolicyID string) (result autorest.Response, err error) Get(ctx context.Context, resourceGroupName string, accountName string, objectReplicationPolicyID string) (result storage.ObjectReplicationPolicy, err error) List(ctx context.Context, resourceGroupName string, accountName string) (result storage.ObjectReplicationPolicies, err error) } var _ ObjectReplicationPoliciesClientAPI = (*storage.ObjectReplicationPoliciesClient)(nil) // LocalUsersClientAPI contains the set of methods on the LocalUsersClient type. type LocalUsersClientAPI interface { CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, username string, properties storage.LocalUser) (result storage.LocalUser, err error) Delete(ctx context.Context, resourceGroupName string, accountName string, username string) (result autorest.Response, err error) Get(ctx context.Context, resourceGroupName string, accountName string, username string) (result storage.LocalUser, err error) List(ctx context.Context, resourceGroupName string, accountName string) (result storage.LocalUsers, err error) ListKeys(ctx context.Context, resourceGroupName string, accountName string, username string) (result storage.LocalUserKeys, err error) RegeneratePassword(ctx context.Context, resourceGroupName string, accountName string, username string) (result storage.LocalUserRegeneratePasswordResult, err error) } var _ LocalUsersClientAPI = (*storage.LocalUsersClient)(nil) // EncryptionScopesClientAPI contains the set of methods on the EncryptionScopesClient type. type EncryptionScopesClientAPI interface { Get(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string) (result storage.EncryptionScope, err error) List(ctx context.Context, resourceGroupName string, accountName string) (result storage.EncryptionScopeListResultPage, err error) ListComplete(ctx context.Context, resourceGroupName string, accountName string) (result storage.EncryptionScopeListResultIterator, err error) Patch(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, encryptionScope storage.EncryptionScope) (result storage.EncryptionScope, err error) Put(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, encryptionScope storage.EncryptionScope) (result storage.EncryptionScope, err error) } var _ EncryptionScopesClientAPI = (*storage.EncryptionScopesClient)(nil) // BlobServicesClientAPI contains the set of methods on the BlobServicesClient type. type BlobServicesClientAPI interface { GetServiceProperties(ctx context.Context, resourceGroupName string, accountName string) (result storage.BlobServiceProperties, err error) List(ctx context.Context, resourceGroupName string, accountName string) (result storage.BlobServiceItems, err error) SetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, parameters storage.BlobServiceProperties) (result storage.BlobServiceProperties, err error) } var _ BlobServicesClientAPI = (*storage.BlobServicesClient)(nil) // BlobContainersClientAPI contains the set of methods on the BlobContainersClient type. type BlobContainersClientAPI interface { ClearLegalHold(ctx context.Context, resourceGroupName string, accountName string, containerName string, legalHold storage.LegalHold) (result storage.LegalHold, err error) Create(ctx context.Context, resourceGroupName string, accountName string, containerName string, blobContainer storage.BlobContainer) (result storage.BlobContainer, err error) CreateOrUpdateImmutabilityPolicy(ctx context.Context, resourceGroupName string, accountName string, containerName string, parameters *storage.ImmutabilityPolicy, ifMatch string) (result storage.ImmutabilityPolicy, err error) Delete(ctx context.Context, resourceGroupName string, accountName string, containerName string) (result autorest.Response, err error) DeleteImmutabilityPolicy(ctx context.Context, resourceGroupName string, accountName string, containerName string, ifMatch string) (result storage.ImmutabilityPolicy, err error) ExtendImmutabilityPolicy(ctx context.Context, resourceGroupName string, accountName string, containerName string, ifMatch string, parameters *storage.ImmutabilityPolicy) (result storage.ImmutabilityPolicy, err error) Get(ctx context.Context, resourceGroupName string, accountName string, containerName string) (result storage.BlobContainer, err error) GetImmutabilityPolicy(ctx context.Context, resourceGroupName string, accountName string, containerName string, ifMatch string) (result storage.ImmutabilityPolicy, err error) Lease(ctx context.Context, resourceGroupName string, accountName string, containerName string, parameters *storage.LeaseContainerRequest) (result storage.LeaseContainerResponse, err error) List(ctx context.Context, resourceGroupName string, accountName string, maxpagesize string, filter string, include storage.ListContainersInclude) (result storage.ListContainerItemsPage, err error) ListComplete(ctx context.Context, resourceGroupName string, accountName string, maxpagesize string, filter string, include storage.ListContainersInclude) (result storage.ListContainerItemsIterator, err error) LockImmutabilityPolicy(ctx context.Context, resourceGroupName string, accountName string, containerName string, ifMatch string) (result storage.ImmutabilityPolicy, err error) ObjectLevelWorm(ctx context.Context, resourceGroupName string, accountName string, containerName string) (result storage.BlobContainersObjectLevelWormFuture, err error) SetLegalHold(ctx context.Context, resourceGroupName string, accountName string, containerName string, legalHold storage.LegalHold) (result storage.LegalHold, err error) Update(ctx context.Context, resourceGroupName string, accountName string, containerName string, blobContainer storage.BlobContainer) (result storage.BlobContainer, err error) } var _ BlobContainersClientAPI = (*storage.BlobContainersClient)(nil) // FileServicesClientAPI contains the set of methods on the FileServicesClient type. type FileServicesClientAPI interface { GetServiceProperties(ctx context.Context, resourceGroupName string, accountName string) (result storage.FileServiceProperties, err error) List(ctx context.Context, resourceGroupName string, accountName string) (result storage.FileServiceItems, err error) SetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, parameters storage.FileServiceProperties) (result storage.FileServiceProperties, err error) } var _ FileServicesClientAPI = (*storage.FileServicesClient)(nil) // FileSharesClientAPI contains the set of methods on the FileSharesClient type. type FileSharesClientAPI interface { Create(ctx context.Context, resourceGroupName string, accountName string, shareName string, fileShare storage.FileShare, expand string) (result storage.FileShare, err error) Delete(ctx context.Context, resourceGroupName string, accountName string, shareName string, xMsSnapshot string, include string) (result autorest.Response, err error) Get(ctx context.Context, resourceGroupName string, accountName string, shareName string, expand string, xMsSnapshot string) (result storage.FileShare, err error) Lease(ctx context.Context, resourceGroupName string, accountName string, shareName string, parameters *storage.LeaseShareRequest, xMsSnapshot string) (result storage.LeaseShareResponse, err error) List(ctx context.Context, resourceGroupName string, accountName string, maxpagesize string, filter string, expand string) (result storage.FileShareItemsPage, err error) ListComplete(ctx context.Context, resourceGroupName string, accountName string, maxpagesize string, filter string, expand string) (result storage.FileShareItemsIterator, err error) Restore(ctx context.Context, resourceGroupName string, accountName string, shareName string, deletedShare storage.DeletedShare) (result autorest.Response, err error) Update(ctx context.Context, resourceGroupName string, accountName string, shareName string, fileShare storage.FileShare) (result storage.FileShare, err error) } var _ FileSharesClientAPI = (*storage.FileSharesClient)(nil) // QueueServicesClientAPI contains the set of methods on the QueueServicesClient type. type QueueServicesClientAPI interface { GetServiceProperties(ctx context.Context, resourceGroupName string, accountName string) (result storage.QueueServiceProperties, err error) List(ctx context.Context, resourceGroupName string, accountName string) (result storage.ListQueueServices, err error) SetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, parameters storage.QueueServiceProperties) (result storage.QueueServiceProperties, err error) } var _ QueueServicesClientAPI = (*storage.QueueServicesClient)(nil) // QueueClientAPI contains the set of methods on the QueueClient type. type QueueClientAPI interface { Create(ctx context.Context, resourceGroupName string, accountName string, queueName string, queue storage.Queue) (result storage.Queue, err error) Delete(ctx context.Context, resourceGroupName string, accountName string, queueName string) (result autorest.Response, err error) Get(ctx context.Context, resourceGroupName string, accountName string, queueName string) (result storage.Queue, err error) List(ctx context.Context, resourceGroupName string, accountName string, maxpagesize string, filter string) (result storage.ListQueueResourcePage, err error) ListComplete(ctx context.Context, resourceGroupName string, accountName string, maxpagesize string, filter string) (result storage.ListQueueResourceIterator, err error) Update(ctx context.Context, resourceGroupName string, accountName string, queueName string, queue storage.Queue) (result storage.Queue, err error) } var _ QueueClientAPI = (*storage.QueueClient)(nil) // TableServicesClientAPI contains the set of methods on the TableServicesClient type. type TableServicesClientAPI interface { GetServiceProperties(ctx context.Context, resourceGroupName string, accountName string) (result storage.TableServiceProperties, err error) List(ctx context.Context, resourceGroupName string, accountName string) (result storage.ListTableServices, err error) SetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, parameters storage.TableServiceProperties) (result storage.TableServiceProperties, err error) } var _ TableServicesClientAPI = (*storage.TableServicesClient)(nil) // TableClientAPI contains the set of methods on the TableClient type. type TableClientAPI interface { Create(ctx context.Context, resourceGroupName string, accountName string, tableName string) (result storage.Table, err error) Delete(ctx context.Context, resourceGroupName string, accountName string, tableName string) (result autorest.Response, err error) Get(ctx context.Context, resourceGroupName string, accountName string, tableName string) (result storage.Table, err error) List(ctx context.Context, resourceGroupName string, accountName string) (result storage.ListTableResourcePage, err error) ListComplete(ctx context.Context, resourceGroupName string, accountName string) (result storage.ListTableResourceIterator, err error) Update(ctx context.Context, resourceGroupName string, accountName string, tableName string) (result storage.Table, err error) } var _ TableClientAPI = (*storage.TableClient)(nil)
Azure/azure-sdk-for-go
services/storage/mgmt/2021-08-01/storage/storageapi/interfaces.go
GO
mit
19,150
module.exports = { server: { host: '0.0.0.0', port: 3000 }, database: { host: '158.85.190.240', port: 27017, db: 'hackathon', username: 'administrator', password: 'hunenokGaribaldi9' } };
esmoreit-hack/hackathon
src/server/config.js
JavaScript
mit
259
'use strict'; /* istanbul ignore next */ /* eslint-disable no-console */ /** * Handle failures in the application by terminating. * @param {Exception} err - Exception to handle. */ module.exports = (err) => { console.log(err); console.log(err.stack); process.exit(-1); };
steve-gray/swagger-codegen
src/failure-handler.js
JavaScript
mit
290
<?php namespace Bostick\Stocker; /** * The plugin.php file (called the plugin initialization script) defines the plugin information class. */ use System\Classes\PluginBase; class Plugin extends PluginBase { public function pluginDetails() { return [ 'name' => 'Stocker', 'description' => 'Provides stock quote information.', 'author' => 'Bill Bostick', 'icon' => 'icon-sun-o' ]; } public function registerComponents() { return [ '\Bostick\Stocker\Components\Stocker' => 'stocker', ]; } }
billbostick/Stocker
Plugin.php
PHP
mit
629
import Omi from 'omi/dist/omi' import { CellsTitle, Cells, CellHeader, CellBody, CellFooter } from '../cell' Omi.makeHTML('CellsTitle', CellsTitle); Omi.makeHTML('Cells', Cells); Omi.makeHTML('CellHeader', CellHeader); Omi.makeHTML('CellBody', CellBody); Omi.makeHTML('CellFooter', CellFooter); export default class List extends Omi.Component{ constructor(data) { super(data); } render(){ return ` <div> <CellsTitle data-title={{title}} /> <Cells slot-index="0"> <div> {{#items}} <{{#link}}a href={{link}} {{/link}}{{^link}}div{{/link}} class="weui-cell {{#link}}weui-cell_access{{/link}}"> {{#imageUrl}} <CellHeader> <img style="width:20px;margin-right:5px;display:block" src={{imageUrl}} /> </CellHeader> {{/imageUrl}} <CellBody slot-index="0" > <p>{{{title}}}</p> </CellBody> <CellFooter slot-index="1"> <span>{{value}}</span> </CellFooter> </{{#link}}a{{/link}}{{^link}}div{{/link}}> {{/items}} </div> </Cells> </div> `; } }
omijs/omi-weui
src/components/list/list.js
JavaScript
mit
1,425
package spaceinvaders.command.client; import static spaceinvaders.command.ProtocolEnum.UDP; import spaceinvaders.client.mvc.Controller; import spaceinvaders.client.mvc.View; import spaceinvaders.command.Command; /** Flush the screen. */ public class FlushScreenCommand extends Command { private transient Controller executor; public FlushScreenCommand() { super(FlushScreenCommand.class.getName(),UDP); } @Override public void execute() { for (View view : executor.getViews()) { view.flush(); } } @Override public void setExecutor(Object executor) { if (executor instanceof Controller) { this.executor = (Controller) executor; } else { // This should never happen. throw new AssertionError(); } } }
apetenchea/SpaceInvaders
src/main/java/spaceinvaders/command/client/FlushScreenCommand.java
Java
mit
771
/** @module ember-flexberry-gis */ import Ember from 'ember'; /** Class implementing base stylization for markers. @class BaseMarkerStyle */ export default Ember.Object.extend({ /** Gets default style settings. @method getDefaultStyleSettings @return {Object} Hash containing default style settings. */ getDefaultStyleSettings() { return null; }, /** Applies layer-style to the specified leaflet layer. @method renderOnLeafletMarker @param {Object} options Method options. @param {<a =ref="http://leafletjs.com/reference-1.2.0.html#marker">L.Marker</a>} options.marker Leaflet marker to which marker-style must be applied. @param {Object} options.style Hash containing style settings. */ renderOnLeafletMarker({ marker, style }) { throw `Method 'renderOnLeafletMarker' isn't implemented in 'base' marker-style`; }, /** Renderes layer-style preview on the specified canvas element. @method renderOnCanvas @param {Object} options Method options. @param {<a =ref="https://developer.mozilla.org/ru/docs/Web/HTML/Element/canvas">Canvas</a>} options.canvas Canvas element on which marker-style preview must be rendered. @param {Object} options.style Hash containing style settings. @param {Object} [options.target = 'preview'] Render target ('preview' or 'legend'). */ renderOnCanvas({ canvas, style, target }) { throw `Method 'renderOnCanvas' isn't implemented in 'base' marker-style`; } });
Flexberry/ember-flexberry-gis
addon/markers-styles/-private/base.js
JavaScript
mit
1,493
namespace live.asp.net.Models { public enum ShowStatus { OffAir = 1, OnAir = 2, Standby = 3 } }
matsprea/live.asp.net
src/live.asp.net/Models/ShowStatus.cs
C#
mit
131
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Build.Framework { public delegate void AnyEventHandler(object sender, Microsoft.Build.Framework.BuildEventArgs e); [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BuildEngineResult { private object _dummy; private int _dummyPrimitive; public BuildEngineResult(bool result, System.Collections.Generic.List<System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.ITaskItem[]>> targetOutputsPerProject) { throw null; } public bool Result { get { throw null; } } public System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.ITaskItem[]>> TargetOutputsPerProject { get { throw null; } } } public partial class BuildErrorEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs { protected BuildErrorEventArgs() { } public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName) { } public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { } public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { } public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, string helpLink, System.DateTime eventTimestamp, params object[] messageArgs) { } public string Code { get { throw null; } } public int ColumnNumber { get { throw null; } } public int EndColumnNumber { get { throw null; } } public int EndLineNumber { get { throw null; } } public string File { get { throw null; } } public string HelpLink { get { throw null; } } public int LineNumber { get { throw null; } } public string ProjectFile { get { throw null; } set { } } public string Subcategory { get { throw null; } } } public delegate void BuildErrorEventHandler(object sender, Microsoft.Build.Framework.BuildErrorEventArgs e); public abstract partial class BuildEventArgs : System.EventArgs { protected BuildEventArgs() { } protected BuildEventArgs(string message, string helpKeyword, string senderName) { } protected BuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { } public Microsoft.Build.Framework.BuildEventContext BuildEventContext { get { throw null; } set { } } public string HelpKeyword { get { throw null; } } public virtual string Message { get { throw null; } protected set { } } protected internal string RawMessage { get { throw null; } set { } } protected internal System.DateTime RawTimestamp { get { throw null; } set { } } public string SenderName { get { throw null; } } public int ThreadId { get { throw null; } } public System.DateTime Timestamp { get { throw null; } } } public partial class BuildEventContext { public const int InvalidEvaluationId = -1; public const int InvalidNodeId = -2; public const int InvalidProjectContextId = -2; public const int InvalidProjectInstanceId = -1; public const int InvalidSubmissionId = -1; public const int InvalidTargetId = -1; public const int InvalidTaskId = -1; public BuildEventContext(int nodeId, int targetId, int projectContextId, int taskId) { } public BuildEventContext(int nodeId, int projectInstanceId, int projectContextId, int targetId, int taskId) { } public BuildEventContext(int submissionId, int nodeId, int projectInstanceId, int projectContextId, int targetId, int taskId) { } public BuildEventContext(int submissionId, int nodeId, int evaluationId, int projectInstanceId, int projectContextId, int targetId, int taskId) { } public long BuildRequestId { get { throw null; } } public int EvaluationId { get { throw null; } } public static Microsoft.Build.Framework.BuildEventContext Invalid { get { throw null; } } public int NodeId { get { throw null; } } public int ProjectContextId { get { throw null; } } public int ProjectInstanceId { get { throw null; } } public int SubmissionId { get { throw null; } } public int TargetId { get { throw null; } } public int TaskId { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(Microsoft.Build.Framework.BuildEventContext left, Microsoft.Build.Framework.BuildEventContext right) { throw null; } public static bool operator !=(Microsoft.Build.Framework.BuildEventContext left, Microsoft.Build.Framework.BuildEventContext right) { throw null; } public override string ToString() { throw null; } } public partial class BuildFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs { protected BuildFinishedEventArgs() { } public BuildFinishedEventArgs(string message, string helpKeyword, bool succeeded) { } public BuildFinishedEventArgs(string message, string helpKeyword, bool succeeded, System.DateTime eventTimestamp) { } public BuildFinishedEventArgs(string message, string helpKeyword, bool succeeded, System.DateTime eventTimestamp, params object[] messageArgs) { } public bool Succeeded { get { throw null; } } } public delegate void BuildFinishedEventHandler(object sender, Microsoft.Build.Framework.BuildFinishedEventArgs e); public partial class BuildMessageEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs { protected BuildMessageEventArgs() { } public BuildMessageEventArgs(string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance) { } public BuildMessageEventArgs(string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp) { } public BuildMessageEventArgs(string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp, params object[] messageArgs) { } public BuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance) { } public BuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp) { } public BuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp, params object[] messageArgs) { } public string Code { get { throw null; } } public int ColumnNumber { get { throw null; } } public int EndColumnNumber { get { throw null; } } public int EndLineNumber { get { throw null; } } public string File { get { throw null; } } public Microsoft.Build.Framework.MessageImportance Importance { get { throw null; } } public int LineNumber { get { throw null; } } public string ProjectFile { get { throw null; } set { } } public string Subcategory { get { throw null; } } } public delegate void BuildMessageEventHandler(object sender, Microsoft.Build.Framework.BuildMessageEventArgs e); public partial class BuildStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs { protected BuildStartedEventArgs() { } public BuildStartedEventArgs(string message, string helpKeyword) { } public BuildStartedEventArgs(string message, string helpKeyword, System.Collections.Generic.IDictionary<string, string> environmentOfBuild) { } public BuildStartedEventArgs(string message, string helpKeyword, System.DateTime eventTimestamp) { } public BuildStartedEventArgs(string message, string helpKeyword, System.DateTime eventTimestamp, params object[] messageArgs) { } public System.Collections.Generic.IDictionary<string, string> BuildEnvironment { get { throw null; } } } public delegate void BuildStartedEventHandler(object sender, Microsoft.Build.Framework.BuildStartedEventArgs e); public abstract partial class BuildStatusEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs { protected BuildStatusEventArgs() { } protected BuildStatusEventArgs(string message, string helpKeyword, string senderName) { } protected BuildStatusEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { } protected BuildStatusEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { } } public delegate void BuildStatusEventHandler(object sender, Microsoft.Build.Framework.BuildStatusEventArgs e); public partial class BuildWarningEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs { protected BuildWarningEventArgs() { } public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName) { } public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { } public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { } public BuildWarningEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, string helpLink, System.DateTime eventTimestamp, params object[] messageArgs) { } public string Code { get { throw null; } } public int ColumnNumber { get { throw null; } } public int EndColumnNumber { get { throw null; } } public int EndLineNumber { get { throw null; } } public string File { get { throw null; } } public string HelpLink { get { throw null; } } public int LineNumber { get { throw null; } } public string ProjectFile { get { throw null; } set { } } public string Subcategory { get { throw null; } } } public delegate void BuildWarningEventHandler(object sender, Microsoft.Build.Framework.BuildWarningEventArgs e); public partial class CriticalBuildMessageEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs { protected CriticalBuildMessageEventArgs() { } public CriticalBuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName) { } public CriticalBuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { } public CriticalBuildMessageEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { } } public abstract partial class CustomBuildEventArgs : Microsoft.Build.Framework.LazyFormattedBuildEventArgs { protected CustomBuildEventArgs() { } protected CustomBuildEventArgs(string message, string helpKeyword, string senderName) { } protected CustomBuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp) { } protected CustomBuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { } } public delegate void CustomBuildEventHandler(object sender, Microsoft.Build.Framework.CustomBuildEventArgs e); public abstract partial class EngineServices { public const int Version1 = 1; protected EngineServices() { } public virtual bool IsTaskInputLoggingEnabled { get { throw null; } } public virtual int Version { get { throw null; } } public virtual bool LogsMessagesOfImportance(Microsoft.Build.Framework.MessageImportance importance) { throw null; } } public partial class EnvironmentVariableReadEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs { public EnvironmentVariableReadEventArgs() { } public EnvironmentVariableReadEventArgs(string environmentVariableName, string message, string helpKeyword = null, string senderName = null, Microsoft.Build.Framework.MessageImportance importance = Microsoft.Build.Framework.MessageImportance.Low) { } public string EnvironmentVariableName { get { throw null; } set { } } } public partial class ExternalProjectFinishedEventArgs : Microsoft.Build.Framework.CustomBuildEventArgs { protected ExternalProjectFinishedEventArgs() { } public ExternalProjectFinishedEventArgs(string message, string helpKeyword, string senderName, string projectFile, bool succeeded) { } public ExternalProjectFinishedEventArgs(string message, string helpKeyword, string senderName, string projectFile, bool succeeded, System.DateTime eventTimestamp) { } public string ProjectFile { get { throw null; } } public bool Succeeded { get { throw null; } } } public partial class ExternalProjectStartedEventArgs : Microsoft.Build.Framework.CustomBuildEventArgs { protected ExternalProjectStartedEventArgs() { } public ExternalProjectStartedEventArgs(string message, string helpKeyword, string senderName, string projectFile, string targetNames) { } public ExternalProjectStartedEventArgs(string message, string helpKeyword, string senderName, string projectFile, string targetNames, System.DateTime eventTimestamp) { } public string ProjectFile { get { throw null; } } public string TargetNames { get { throw null; } } } public partial interface IBuildEngine { int ColumnNumberOfTaskNode { get; } bool ContinueOnError { get; } int LineNumberOfTaskNode { get; } string ProjectFileOfTaskNode { get; } bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs); void LogCustomEvent(Microsoft.Build.Framework.CustomBuildEventArgs e); void LogErrorEvent(Microsoft.Build.Framework.BuildErrorEventArgs e); void LogMessageEvent(Microsoft.Build.Framework.BuildMessageEventArgs e); void LogWarningEvent(Microsoft.Build.Framework.BuildWarningEventArgs e); } public partial interface IBuildEngine10 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5, Microsoft.Build.Framework.IBuildEngine6, Microsoft.Build.Framework.IBuildEngine7, Microsoft.Build.Framework.IBuildEngine8, Microsoft.Build.Framework.IBuildEngine9 { Microsoft.Build.Framework.EngineServices EngineServices { get; } } public partial interface IBuildEngine2 : Microsoft.Build.Framework.IBuildEngine { bool IsRunningMultipleNodes { get; } bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs, string toolsVersion); bool BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, System.Collections.IDictionary[] globalProperties, System.Collections.IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion); } public partial interface IBuildEngine3 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2 { Microsoft.Build.Framework.BuildEngineResult BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, System.Collections.IDictionary[] globalProperties, System.Collections.Generic.IList<string>[] removeGlobalProperties, string[] toolsVersion, bool returnTargetOutputs); void Reacquire(); void Yield(); } public partial interface IBuildEngine4 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3 { object GetRegisteredTaskObject(object key, Microsoft.Build.Framework.RegisteredTaskObjectLifetime lifetime); void RegisterTaskObject(object key, object obj, Microsoft.Build.Framework.RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection); object UnregisterTaskObject(object key, Microsoft.Build.Framework.RegisteredTaskObjectLifetime lifetime); } public partial interface IBuildEngine5 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4 { void LogTelemetry(string eventName, System.Collections.Generic.IDictionary<string, string> properties); } public partial interface IBuildEngine6 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5 { System.Collections.Generic.IReadOnlyDictionary<string, string> GetGlobalProperties(); } public partial interface IBuildEngine7 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5, Microsoft.Build.Framework.IBuildEngine6 { bool AllowFailureWithoutError { get; set; } } public partial interface IBuildEngine8 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5, Microsoft.Build.Framework.IBuildEngine6, Microsoft.Build.Framework.IBuildEngine7 { bool ShouldTreatWarningAsError(string warningCode); } public partial interface IBuildEngine9 : Microsoft.Build.Framework.IBuildEngine, Microsoft.Build.Framework.IBuildEngine2, Microsoft.Build.Framework.IBuildEngine3, Microsoft.Build.Framework.IBuildEngine4, Microsoft.Build.Framework.IBuildEngine5, Microsoft.Build.Framework.IBuildEngine6, Microsoft.Build.Framework.IBuildEngine7, Microsoft.Build.Framework.IBuildEngine8 { void ReleaseCores(int coresToRelease); int RequestCores(int requestedCores); } public partial interface ICancelableTask : Microsoft.Build.Framework.ITask { void Cancel(); } public partial interface IEventRedirector { void ForwardEvent(Microsoft.Build.Framework.BuildEventArgs buildEvent); } public partial interface IEventSource { event Microsoft.Build.Framework.AnyEventHandler AnyEventRaised; event Microsoft.Build.Framework.BuildFinishedEventHandler BuildFinished; event Microsoft.Build.Framework.BuildStartedEventHandler BuildStarted; event Microsoft.Build.Framework.CustomBuildEventHandler CustomEventRaised; event Microsoft.Build.Framework.BuildErrorEventHandler ErrorRaised; event Microsoft.Build.Framework.BuildMessageEventHandler MessageRaised; event Microsoft.Build.Framework.ProjectFinishedEventHandler ProjectFinished; event Microsoft.Build.Framework.ProjectStartedEventHandler ProjectStarted; event Microsoft.Build.Framework.BuildStatusEventHandler StatusEventRaised; event Microsoft.Build.Framework.TargetFinishedEventHandler TargetFinished; event Microsoft.Build.Framework.TargetStartedEventHandler TargetStarted; event Microsoft.Build.Framework.TaskFinishedEventHandler TaskFinished; event Microsoft.Build.Framework.TaskStartedEventHandler TaskStarted; event Microsoft.Build.Framework.BuildWarningEventHandler WarningRaised; } public partial interface IEventSource2 : Microsoft.Build.Framework.IEventSource { event Microsoft.Build.Framework.TelemetryEventHandler TelemetryLogged; } public partial interface IEventSource3 : Microsoft.Build.Framework.IEventSource, Microsoft.Build.Framework.IEventSource2 { void IncludeEvaluationMetaprojects(); void IncludeEvaluationProfiles(); void IncludeTaskInputs(); } public partial interface IEventSource4 : Microsoft.Build.Framework.IEventSource, Microsoft.Build.Framework.IEventSource2, Microsoft.Build.Framework.IEventSource3 { void IncludeEvaluationPropertiesAndItems(); } public partial interface IForwardingLogger : Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger { Microsoft.Build.Framework.IEventRedirector BuildEventRedirector { get; set; } int NodeId { get; set; } } public partial interface IGeneratedTask : Microsoft.Build.Framework.ITask { object GetPropertyValue(Microsoft.Build.Framework.TaskPropertyInfo property); void SetPropertyValue(Microsoft.Build.Framework.TaskPropertyInfo property, object value); } [System.Runtime.InteropServices.ComVisibleAttribute(true)] public partial interface ILogger { string Parameters { get; set; } Microsoft.Build.Framework.LoggerVerbosity Verbosity { get; set; } void Initialize(Microsoft.Build.Framework.IEventSource eventSource); void Shutdown(); } [System.Runtime.InteropServices.ComVisibleAttribute(true)] public partial interface INodeLogger : Microsoft.Build.Framework.ILogger { void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount); } public partial interface IProjectElement { string ElementName { get; } string OuterElement { get; } } public partial interface ITask { Microsoft.Build.Framework.IBuildEngine BuildEngine { get; set; } Microsoft.Build.Framework.ITaskHost HostObject { get; set; } bool Execute(); } public partial interface ITaskFactory { string FactoryName { get; } System.Type TaskType { get; } void CleanupTask(Microsoft.Build.Framework.ITask task); Microsoft.Build.Framework.ITask CreateTask(Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost); Microsoft.Build.Framework.TaskPropertyInfo[] GetTaskParameters(); bool Initialize(string taskName, System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.TaskPropertyInfo> parameterGroup, string taskBody, Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost); } public partial interface ITaskFactory2 : Microsoft.Build.Framework.ITaskFactory { Microsoft.Build.Framework.ITask CreateTask(Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost, System.Collections.Generic.IDictionary<string, string> taskIdentityParameters); bool Initialize(string taskName, System.Collections.Generic.IDictionary<string, string> factoryIdentityParameters, System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.TaskPropertyInfo> parameterGroup, string taskBody, Microsoft.Build.Framework.IBuildEngine taskFactoryLoggingHost); } [System.Runtime.InteropServices.ComVisibleAttribute(true)] [System.Runtime.InteropServices.GuidAttribute("9049A481-D0E9-414f-8F92-D4F67A0359A6")] [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public partial interface ITaskHost { } [System.Runtime.InteropServices.ComVisibleAttribute(true)] [System.Runtime.InteropServices.GuidAttribute("8661674F-2148-4F71-A92A-49875511C528")] public partial interface ITaskItem { string ItemSpec { get; set; } int MetadataCount { get; } System.Collections.ICollection MetadataNames { get; } System.Collections.IDictionary CloneCustomMetadata(); void CopyMetadataTo(Microsoft.Build.Framework.ITaskItem destinationItem); string GetMetadata(string metadataName); void RemoveMetadata(string metadataName); void SetMetadata(string metadataName, string metadataValue); } [System.Runtime.InteropServices.ComVisibleAttribute(true)] [System.Runtime.InteropServices.GuidAttribute("ac6d5a59-f877-461b-88e3-b2f06fce0cb9")] public partial interface ITaskItem2 : Microsoft.Build.Framework.ITaskItem { string EvaluatedIncludeEscaped { get; set; } System.Collections.IDictionary CloneCustomMetadataEscaped(); string GetMetadataValueEscaped(string metadataName); void SetMetadataValueLiteral(string metadataName, string metadataValue); } public partial class LazyFormattedBuildEventArgs : Microsoft.Build.Framework.BuildEventArgs { [System.NonSerializedAttribute] protected object locker; protected LazyFormattedBuildEventArgs() { } public LazyFormattedBuildEventArgs(string message, string helpKeyword, string senderName) { } public LazyFormattedBuildEventArgs(string message, string helpKeyword, string senderName, System.DateTime eventTimestamp, params object[] messageArgs) { } public override string Message { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class LoadInSeparateAppDomainAttribute : System.Attribute { public LoadInSeparateAppDomainAttribute() { } } public partial class LoggerException : System.Exception { public LoggerException() { } protected LoggerException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public LoggerException(string message) { } public LoggerException(string message, System.Exception innerException) { } public LoggerException(string message, System.Exception innerException, string errorCode, string helpKeyword) { } public string ErrorCode { get { throw null; } } public string HelpKeyword { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } [System.Runtime.InteropServices.ComVisibleAttribute(true)] public enum LoggerVerbosity { Quiet = 0, Minimal = 1, Normal = 2, Detailed = 3, Diagnostic = 4, } public enum MessageImportance { High = 0, Normal = 1, Low = 2, } public partial class MetaprojectGeneratedEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs { public string metaprojectXml; public MetaprojectGeneratedEventArgs(string metaprojectXml, string metaprojectPath, string message) { } } [System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] public sealed partial class OutputAttribute : System.Attribute { public OutputAttribute() { } } public sealed partial class ProjectEvaluationFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs { public ProjectEvaluationFinishedEventArgs() { } public ProjectEvaluationFinishedEventArgs(string message, params object[] messageArgs) { } public System.Collections.IEnumerable GlobalProperties { get { throw null; } set { } } public System.Collections.IEnumerable Items { get { throw null; } set { } } public Microsoft.Build.Framework.Profiler.ProfilerResult? ProfilerResult { get { throw null; } set { } } public string ProjectFile { get { throw null; } set { } } public System.Collections.IEnumerable Properties { get { throw null; } set { } } } public partial class ProjectEvaluationStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs { public ProjectEvaluationStartedEventArgs() { } public ProjectEvaluationStartedEventArgs(string message, params object[] messageArgs) { } public string ProjectFile { get { throw null; } set { } } } public partial class ProjectFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs { protected ProjectFinishedEventArgs() { } public ProjectFinishedEventArgs(string message, string helpKeyword, string projectFile, bool succeeded) { } public ProjectFinishedEventArgs(string message, string helpKeyword, string projectFile, bool succeeded, System.DateTime eventTimestamp) { } public override string Message { get { throw null; } } public string ProjectFile { get { throw null; } } public bool Succeeded { get { throw null; } } } public delegate void ProjectFinishedEventHandler(object sender, Microsoft.Build.Framework.ProjectFinishedEventArgs e); public partial class ProjectImportedEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs { public ProjectImportedEventArgs() { } public ProjectImportedEventArgs(int lineNumber, int columnNumber, string message, params object[] messageArgs) { } public string ImportedProjectFile { get { throw null; } set { } } public bool ImportIgnored { get { throw null; } set { } } public string UnexpandedProject { get { throw null; } set { } } } public partial class ProjectStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs { public const int InvalidProjectId = -1; protected ProjectStartedEventArgs() { } public ProjectStartedEventArgs(int projectId, string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, Microsoft.Build.Framework.BuildEventContext parentBuildEventContext) { } public ProjectStartedEventArgs(int projectId, string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, Microsoft.Build.Framework.BuildEventContext parentBuildEventContext, System.Collections.Generic.IDictionary<string, string> globalProperties, string toolsVersion) { } public ProjectStartedEventArgs(int projectId, string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, Microsoft.Build.Framework.BuildEventContext parentBuildEventContext, System.DateTime eventTimestamp) { } public ProjectStartedEventArgs(string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items) { } public ProjectStartedEventArgs(string message, string helpKeyword, string projectFile, string targetNames, System.Collections.IEnumerable properties, System.Collections.IEnumerable items, System.DateTime eventTimestamp) { } public System.Collections.Generic.IDictionary<string, string> GlobalProperties { get { throw null; } } public System.Collections.IEnumerable Items { get { throw null; } } public override string Message { get { throw null; } } public Microsoft.Build.Framework.BuildEventContext ParentProjectBuildEventContext { get { throw null; } } public string ProjectFile { get { throw null; } } public int ProjectId { get { throw null; } } public System.Collections.IEnumerable Properties { get { throw null; } } public string TargetNames { get { throw null; } } public string ToolsVersion { get { throw null; } } } public delegate void ProjectStartedEventHandler(object sender, Microsoft.Build.Framework.ProjectStartedEventArgs e); public partial class PropertyInitialValueSetEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs { public PropertyInitialValueSetEventArgs() { } public PropertyInitialValueSetEventArgs(string propertyName, string propertyValue, string propertySource, string message, string helpKeyword = null, string senderName = null, Microsoft.Build.Framework.MessageImportance importance = Microsoft.Build.Framework.MessageImportance.Low) { } public string PropertyName { get { throw null; } set { } } public string PropertySource { get { throw null; } set { } } public string PropertyValue { get { throw null; } set { } } } public partial class PropertyReassignmentEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs { public PropertyReassignmentEventArgs() { } public PropertyReassignmentEventArgs(string propertyName, string previousValue, string newValue, string location, string message, string helpKeyword = null, string senderName = null, Microsoft.Build.Framework.MessageImportance importance = Microsoft.Build.Framework.MessageImportance.Low) { } public string Location { get { throw null; } set { } } public override string Message { get { throw null; } } public string NewValue { get { throw null; } set { } } public string PreviousValue { get { throw null; } set { } } public string PropertyName { get { throw null; } set { } } } public enum RegisteredTaskObjectLifetime { Build = 0, AppDomain = 1, } [System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] public sealed partial class RequiredAttribute : System.Attribute { public RequiredAttribute() { } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class RequiredRuntimeAttribute : System.Attribute { public RequiredRuntimeAttribute(string runtimeVersion) { } public string RuntimeVersion { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class RunInMTAAttribute : System.Attribute { public RunInMTAAttribute() { } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class RunInSTAAttribute : System.Attribute { public RunInSTAAttribute() { } } public abstract partial class SdkLogger { protected SdkLogger() { } public abstract void LogMessage(string message, Microsoft.Build.Framework.MessageImportance messageImportance = Microsoft.Build.Framework.MessageImportance.Low); } public sealed partial class SdkReference : System.IEquatable<Microsoft.Build.Framework.SdkReference> { public SdkReference(string name, string version, string minimumVersion) { } public string MinimumVersion { get { throw null; } } public string Name { get { throw null; } } public string Version { get { throw null; } } public bool Equals(Microsoft.Build.Framework.SdkReference other) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } public static bool TryParse(string sdk, out Microsoft.Build.Framework.SdkReference sdkReference) { throw null; } } public abstract partial class SdkResolver { protected SdkResolver() { } public abstract string Name { get; } public abstract int Priority { get; } public abstract Microsoft.Build.Framework.SdkResult Resolve(Microsoft.Build.Framework.SdkReference sdkReference, Microsoft.Build.Framework.SdkResolverContext resolverContext, Microsoft.Build.Framework.SdkResultFactory factory); } public abstract partial class SdkResolverContext { protected SdkResolverContext() { } public virtual bool Interactive { get { throw null; } protected set { } } public virtual bool IsRunningInVisualStudio { get { throw null; } protected set { } } public virtual Microsoft.Build.Framework.SdkLogger Logger { get { throw null; } protected set { } } public virtual System.Version MSBuildVersion { get { throw null; } protected set { } } public virtual string ProjectFilePath { get { throw null; } protected set { } } public virtual string SolutionFilePath { get { throw null; } protected set { } } public virtual object State { get { throw null; } set { } } } public abstract partial class SdkResult { protected SdkResult() { } public virtual System.Collections.Generic.IList<string> AdditionalPaths { get { throw null; } set { } } public virtual System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.SdkResultItem> ItemsToAdd { get { throw null; } protected set { } } public virtual string Path { get { throw null; } protected set { } } public virtual System.Collections.Generic.IDictionary<string, string> PropertiesToAdd { get { throw null; } protected set { } } public virtual Microsoft.Build.Framework.SdkReference SdkReference { get { throw null; } protected set { } } public virtual bool Success { get { throw null; } protected set { } } public virtual string Version { get { throw null; } protected set { } } } public abstract partial class SdkResultFactory { protected SdkResultFactory() { } public abstract Microsoft.Build.Framework.SdkResult IndicateFailure(System.Collections.Generic.IEnumerable<string> errors, System.Collections.Generic.IEnumerable<string> warnings = null); public virtual Microsoft.Build.Framework.SdkResult IndicateSuccess(System.Collections.Generic.IEnumerable<string> paths, string version, System.Collections.Generic.IDictionary<string, string> propertiesToAdd = null, System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.SdkResultItem> itemsToAdd = null, System.Collections.Generic.IEnumerable<string> warnings = null) { throw null; } public virtual Microsoft.Build.Framework.SdkResult IndicateSuccess(string path, string version, System.Collections.Generic.IDictionary<string, string> propertiesToAdd, System.Collections.Generic.IDictionary<string, Microsoft.Build.Framework.SdkResultItem> itemsToAdd, System.Collections.Generic.IEnumerable<string> warnings = null) { throw null; } public abstract Microsoft.Build.Framework.SdkResult IndicateSuccess(string path, string version, System.Collections.Generic.IEnumerable<string> warnings = null); } public partial class SdkResultItem { public SdkResultItem() { } public SdkResultItem(string itemSpec, System.Collections.Generic.Dictionary<string, string> metadata) { } public string ItemSpec { get { throw null; } set { } } public System.Collections.Generic.Dictionary<string, string> Metadata { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } } public enum TargetBuiltReason { None = 0, BeforeTargets = 1, DependsOn = 2, AfterTargets = 3, } public partial class TargetFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs { protected TargetFinishedEventArgs() { } public TargetFinishedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, bool succeeded) { } public TargetFinishedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, bool succeeded, System.Collections.IEnumerable targetOutputs) { } public TargetFinishedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, bool succeeded, System.DateTime eventTimestamp, System.Collections.IEnumerable targetOutputs) { } public override string Message { get { throw null; } } public string ProjectFile { get { throw null; } } public bool Succeeded { get { throw null; } } public string TargetFile { get { throw null; } } public string TargetName { get { throw null; } } public System.Collections.IEnumerable TargetOutputs { get { throw null; } set { } } } public delegate void TargetFinishedEventHandler(object sender, Microsoft.Build.Framework.TargetFinishedEventArgs e); public partial class TargetSkippedEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs { public TargetSkippedEventArgs() { } public TargetSkippedEventArgs(string message, params object[] messageArgs) { } public Microsoft.Build.Framework.TargetBuiltReason BuildReason { get { throw null; } set { } } public string Condition { get { throw null; } set { } } public string EvaluatedCondition { get { throw null; } set { } } public override string Message { get { throw null; } } public Microsoft.Build.Framework.BuildEventContext OriginalBuildEventContext { get { throw null; } set { } } public bool OriginallySucceeded { get { throw null; } set { } } public string ParentTarget { get { throw null; } set { } } public Microsoft.Build.Framework.TargetSkipReason SkipReason { get { throw null; } set { } } public string TargetFile { get { throw null; } set { } } public string TargetName { get { throw null; } set { } } } public enum TargetSkipReason { None = 0, PreviouslyBuiltSuccessfully = 1, PreviouslyBuiltUnsuccessfully = 2, OutputsUpToDate = 3, ConditionWasFalse = 4, } public partial class TargetStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs { protected TargetStartedEventArgs() { } public TargetStartedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile) { } public TargetStartedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, string parentTarget, Microsoft.Build.Framework.TargetBuiltReason buildReason, System.DateTime eventTimestamp) { } public TargetStartedEventArgs(string message, string helpKeyword, string targetName, string projectFile, string targetFile, string parentTarget, System.DateTime eventTimestamp) { } public Microsoft.Build.Framework.TargetBuiltReason BuildReason { get { throw null; } } public override string Message { get { throw null; } } public string ParentTarget { get { throw null; } } public string ProjectFile { get { throw null; } } public string TargetFile { get { throw null; } } public string TargetName { get { throw null; } } } public delegate void TargetStartedEventHandler(object sender, Microsoft.Build.Framework.TargetStartedEventArgs e); public partial class TaskCommandLineEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs { protected TaskCommandLineEventArgs() { } public TaskCommandLineEventArgs(string commandLine, string taskName, Microsoft.Build.Framework.MessageImportance importance) { } public TaskCommandLineEventArgs(string commandLine, string taskName, Microsoft.Build.Framework.MessageImportance importance, System.DateTime eventTimestamp) { } public string CommandLine { get { throw null; } } public string TaskName { get { throw null; } } } public partial class TaskFinishedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs { protected TaskFinishedEventArgs() { } public TaskFinishedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName, bool succeeded) { } public TaskFinishedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName, bool succeeded, System.DateTime eventTimestamp) { } public override string Message { get { throw null; } } public string ProjectFile { get { throw null; } } public bool Succeeded { get { throw null; } } public string TaskFile { get { throw null; } } public string TaskName { get { throw null; } } } public delegate void TaskFinishedEventHandler(object sender, Microsoft.Build.Framework.TaskFinishedEventArgs e); public partial class TaskParameterEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs { public TaskParameterEventArgs(Microsoft.Build.Framework.TaskParameterMessageKind kind, string itemType, System.Collections.IList items, bool logItemMetadata, System.DateTime eventTimestamp) { } public System.Collections.IList Items { get { throw null; } } public string ItemType { get { throw null; } } public Microsoft.Build.Framework.TaskParameterMessageKind Kind { get { throw null; } } public bool LogItemMetadata { get { throw null; } } public override string Message { get { throw null; } } } public enum TaskParameterMessageKind { TaskInput = 0, TaskOutput = 1, AddItem = 2, RemoveItem = 3, SkippedTargetInputs = 4, SkippedTargetOutputs = 5, } public partial class TaskPropertyInfo { public TaskPropertyInfo(string name, System.Type typeOfParameter, bool output, bool required) { } public bool Log { get { throw null; } set { } } public bool LogItemMetadata { get { throw null; } set { } } public string Name { get { throw null; } } public bool Output { get { throw null; } } public System.Type PropertyType { get { throw null; } } public bool Required { get { throw null; } } } public partial class TaskStartedEventArgs : Microsoft.Build.Framework.BuildStatusEventArgs { protected TaskStartedEventArgs() { } public TaskStartedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName) { } public TaskStartedEventArgs(string message, string helpKeyword, string projectFile, string taskFile, string taskName, System.DateTime eventTimestamp) { } public int ColumnNumber { get { throw null; } } public int LineNumber { get { throw null; } } public override string Message { get { throw null; } } public string ProjectFile { get { throw null; } } public string TaskFile { get { throw null; } } public string TaskName { get { throw null; } } } public delegate void TaskStartedEventHandler(object sender, Microsoft.Build.Framework.TaskStartedEventArgs e); public sealed partial class TelemetryEventArgs : Microsoft.Build.Framework.BuildEventArgs { public TelemetryEventArgs() { } public string EventName { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, string> Properties { get { throw null; } set { } } } public delegate void TelemetryEventHandler(object sender, Microsoft.Build.Framework.TelemetryEventArgs e); public partial class UninitializedPropertyReadEventArgs : Microsoft.Build.Framework.BuildMessageEventArgs { public UninitializedPropertyReadEventArgs() { } public UninitializedPropertyReadEventArgs(string propertyName, string message, string helpKeyword = null, string senderName = null, Microsoft.Build.Framework.MessageImportance importance = Microsoft.Build.Framework.MessageImportance.Low) { } public string PropertyName { get { throw null; } set { } } } } namespace Microsoft.Build.Framework.Profiler { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EvaluationLocation { private object _dummy; private int _dummyPrimitive; public EvaluationLocation(Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationPassDescription, string file, int? line, string elementName, string elementDescription, Microsoft.Build.Framework.Profiler.EvaluationLocationKind kind) { throw null; } public EvaluationLocation(long id, long? parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationPassDescription, string file, int? line, string elementName, string elementDescription, Microsoft.Build.Framework.Profiler.EvaluationLocationKind kind) { throw null; } public EvaluationLocation(long? parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationPassDescription, string file, int? line, string elementName, string elementDescription, Microsoft.Build.Framework.Profiler.EvaluationLocationKind kind) { throw null; } public string ElementDescription { get { throw null; } } public string ElementName { get { throw null; } } public static Microsoft.Build.Framework.Profiler.EvaluationLocation EmptyLocation { get { throw null; } } public Microsoft.Build.Framework.Profiler.EvaluationPass EvaluationPass { get { throw null; } } public string EvaluationPassDescription { get { throw null; } } public string File { get { throw null; } } public long Id { get { throw null; } } public bool IsEvaluationPass { get { throw null; } } public Microsoft.Build.Framework.Profiler.EvaluationLocationKind Kind { get { throw null; } } public int? Line { get { throw null; } } public long? ParentId { get { throw null; } } public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForAggregatedGlob() { throw null; } public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForCondition(long? parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationDescription, string file, int? line, string condition) { throw null; } public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForGlob(long? parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationDescription, string file, int? line, string globDescription) { throw null; } public static Microsoft.Build.Framework.Profiler.EvaluationLocation CreateLocationForProject(long? parentId, Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string evaluationDescription, string file, int? line, Microsoft.Build.Framework.IProjectElement element) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } public Microsoft.Build.Framework.Profiler.EvaluationLocation WithEvaluationPass(Microsoft.Build.Framework.Profiler.EvaluationPass evaluationPass, string passDescription = null) { throw null; } public Microsoft.Build.Framework.Profiler.EvaluationLocation WithFile(string file) { throw null; } public Microsoft.Build.Framework.Profiler.EvaluationLocation WithFileLineAndCondition(string file, int? line, string condition) { throw null; } public Microsoft.Build.Framework.Profiler.EvaluationLocation WithFileLineAndElement(string file, int? line, Microsoft.Build.Framework.IProjectElement element) { throw null; } public Microsoft.Build.Framework.Profiler.EvaluationLocation WithGlob(string globDescription) { throw null; } public Microsoft.Build.Framework.Profiler.EvaluationLocation WithParentId(long? parentId) { throw null; } } public enum EvaluationLocationKind : byte { Element = (byte)0, Condition = (byte)1, Glob = (byte)2, } public enum EvaluationPass : byte { TotalEvaluation = (byte)0, TotalGlobbing = (byte)1, InitialProperties = (byte)2, Properties = (byte)3, ItemDefinitionGroups = (byte)4, Items = (byte)5, LazyItems = (byte)6, UsingTasks = (byte)7, Targets = (byte)8, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ProfiledLocation { private int _dummyPrimitive; public ProfiledLocation(System.TimeSpan inclusiveTime, System.TimeSpan exclusiveTime, int numberOfHits) { throw null; } public System.TimeSpan ExclusiveTime { get { throw null; } } public System.TimeSpan InclusiveTime { get { throw null; } } public int NumberOfHits { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ProfilerResult { private object _dummy; public ProfilerResult(System.Collections.Generic.IDictionary<Microsoft.Build.Framework.Profiler.EvaluationLocation, Microsoft.Build.Framework.Profiler.ProfiledLocation> profiledLocations) { throw null; } public System.Collections.Generic.IReadOnlyDictionary<Microsoft.Build.Framework.Profiler.EvaluationLocation, Microsoft.Build.Framework.Profiler.ProfiledLocation> ProfiledLocations { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } } }
rainersigwald/msbuild
ref/Microsoft.Build.Framework/netstandard/Microsoft.Build.Framework.cs
C#
mit
55,579
using System; using System.Diagnostics.Contracts; namespace Graph { public class Edge<TVertex> : IEdge<TVertex> { public Edge (TVertex source, TVertex target) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (target == null) { throw new ArgumentNullException(nameof(target)); } Contract.EndContractBlock(); Source = source; Target = target; } public TVertex Source { get; private set; } public TVertex Target { get; private set; } } }
EGrun/Grun.Math
src/Graph/Edge.cs
C#
mit
663
import { NgModule, Component, ElementRef, AfterContentInit, AfterViewInit, AfterViewChecked, OnInit, OnDestroy, DoCheck, Input, ViewContainerRef, ViewChild, Output, SimpleChange, EventEmitter, ContentChild, ContentChildren, Renderer, IterableDiffers, QueryList, TemplateRef, ChangeDetectorRef, Inject, forwardRef, NgZone } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms' import { SharedModule } from '../common/shared'; import { PaginatorModule } from '../paginator/paginator'; import { Column, Header, Footer, HeaderColumnGroup, FooterColumnGroup, PrimeTemplate } from '../common/shared'; import { LazyLoadEvent, FilterMetadata, SortMeta } from '../common/api'; import { DomHandler } from '../dom/domhandler'; import { ObjectUtils } from '../utils/ObjectUtils'; import { Subscription } from 'rxjs/Subscription'; import { BlockableUI } from '../common/api'; import { GlobalEventsManager } from '../common/globalevent'; import * as FileSaver from 'file-saver'; import * as XLSX from 'xlsx-style'; @Component({ selector: 'p-dtRadioButton', template: ` <div class="ui-radiobutton ui-widget"> <div class="ui-helper-hidden-accessible"> <input type="radio" [checked]="checked"> </div> <div class="ui-radiobutton-box ui-widget ui-radiobutton-relative ui-state-default" (click)="handleClick($event)" (mouseenter)="hover=true" (mouseleave)="hover=false" [ngClass]="{'ui-state-hover':hover,'ui-state-active':checked}"> <span class="ui-radiobutton-icon" [ngClass]="{'fa fa-circle':checked}"></span> </div> </div> ` }) export class DTRadioButton { @Input() checked: boolean; @Output() onClick: EventEmitter<any> = new EventEmitter(); public hover: boolean; handleClick(event) { this.onClick.emit(event); } } @Component({ selector: 'p-dtCheckbox', template: ` <div class="ui-chkbox ui-widget"> <div class="ui-helper-hidden-accessible"> <input type="checkbox" [checked]="checked"> </div> <div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default" (click)="handleClick($event)" (mouseover)="hover=true" (mouseout)="hover=false" [ngClass]="{'ui-state-hover':hover&&!disabled,'ui-state-active':checked&&!disabled,'ui-state-disabled':disabled}"> <span class="ui-chkbox-icon ui-c" [ngClass]="{'fa fa-check':checked}"></span> </div> </div> ` }) export class DTCheckbox { @Input() checked: boolean; @Input() disabled: boolean; @Output() onChange: EventEmitter<any> = new EventEmitter(); public hover: boolean; handleClick(event) { if (!this.disabled) { this.onChange.emit({ originalEvent: event, checked: !this.checked }); } } } @Component({ selector: 'p-rowExpansionLoader', template: `` }) export class RowExpansionLoader { @Input() template: TemplateRef<any>; @Input() rowData: any; constructor(public viewContainer: ViewContainerRef) { } ngOnInit() { let view = this.viewContainer.createEmbeddedView(this.template, { '\$implicit': this.rowData }); } } @Component({ selector: '[pColumnHeaders]', template: ` <ng-template ngFor let-col [ngForOf]="columns" let-lastCol="last"> <th #headerCell [ngStyle]="col.style" [class]="col.styleClass" [style.display]="col.hidden ? 'none' : 'table-cell'" (click)="dt.sort($event,col)" [attr.colspan]="col.colspan" [attr.rowspan]="col.rowspan" [ngClass]="{'ui-state-default ui-unselectable-text':true, 'ui-sortable-column': col.sortable, 'ui-state-active': dt.isSorted(col), 'ui-resizable-column': dt.resizableColumns, 'ui-selection-column':col.selectionMode}" (dragstart)="dt.onColumnDragStart($event)" (dragover)="dt.onColumnDragover($event)" (dragleave)="dt.onColumnDragleave($event)" (drop)="dt.onColumnDrop($event)" (mousedown)="dt.onHeaderMousedown($event,headerCell)" [attr.tabindex]="col.sortable ? tabindex : null" (keydown)="dt.onHeaderKeydown($event,col)"> <span class="ui-column-resizer" *ngIf="dt.resizableColumns && ((dt.columnResizeMode == 'fit' && !lastCol) || dt.columnResizeMode == 'expand')" (mousedown)="dt.initColumnResize($event)"></span> <span class="ui-column-title" *ngIf="!col.selectionMode&&!col.headerTemplate">{{col.header}}</span> <span class="ui-column-title" *ngIf="col.headerTemplate"> <p-columnHeaderTemplateLoader [column]="col"></p-columnHeaderTemplateLoader> </span> <span class="ui-sortable-column-icon fa fa-fw fa-sort" *ngIf="col.sortable" [ngClass]="{'fa-sort-desc': (dt.getSortOrder(col) == -1),'fa-sort-asc': (dt.getSortOrder(col) == 1)}"></span> <input type="text" class="ui-column-filter ui-inputtext ui-widget ui-state-default ui-corner-all" [attr.placeholder]="col.filterPlaceholder" *ngIf="col.filter&&!col.filterTemplate" [value]="dt.filters[col.field] ? dt.filters[col.field].value : ''" (click)="dt.onFilterInputClick($event)" (blur)="dt.onFilterKeyup($event,$event.target.value, col.field, col.filterMatchMode)" (keyup)="dt.onFilterKeyup($event,$event.target.value, col.field, col.filterMatchMode)"/> <p-columnFilterTemplateLoader [column]="col" *ngIf="col.filterTemplate"></p-columnFilterTemplateLoader> <p-dtCheckbox *ngIf="col.selectionMode=='multiple'" (onChange)="dt.toggleRowsWithCheckbox($event)" [checked]="dt.allSelected" [disabled]="dt.isEmpty()"></p-dtCheckbox> </th> </ng-template> ` }) export class ColumnHeaders { constructor( @Inject(forwardRef(() => DataTable)) public dt: DataTable) { } @Input("pColumnHeaders") columns: Column[]; } @Component({ selector: '[pColumnFooters]', template: ` <td *ngFor="let col of columns" [ngStyle]="col.style" [class]="col.styleClass" [attr.colspan]="col.colspan" [attr.rowspan]="col.rowspan" [ngClass]="{'ui-state-default':true}" [style.display]="col.hidden ? 'none' : 'table-cell'"> <span class="ui-column-footer" *ngIf="!col.footerTemplate">{{col.footer}}</span> <span class="ui-column-footer" *ngIf="col.footerTemplate"> <p-columnFooterTemplateLoader [column]="col"></p-columnFooterTemplateLoader> </span> </td> ` }) export class ColumnFooters { constructor( @Inject(forwardRef(() => DataTable)) public dt: DataTable) { } @Input("pColumnFooters") columns: Column[]; } @Component({ selector: '[pTableBody]', template: ` <ng-template ngFor let-rowData [ngForOf]="dt.dataToRender" let-even="even" let-odd="odd" let-rowIndex="index"> <tr #rowGroupElement class="ui-widget-header ui-rowgroup-header" *ngIf="dt.rowGroupMode=='subheader' && (rowIndex === 0||(dt.resolveFieldData(rowData,dt.groupField) !== dt.resolveFieldData(dt.dataToRender[rowIndex - 1], dt.groupField)))" (click)="dt.onRowGroupClick($event)" [ngStyle]="{'cursor': dt.sortableRowGroup ? 'pointer' : 'auto'}"> <td [attr.colspan]="columns.length"> <a href="#" *ngIf="dt.expandableRowGroups" (click)="dt.toggleRowGroup($event,rowData)"> <span class="fa fa-fw" [ngClass]="{'fa-chevron-circle-down':dt.isRowGroupExpanded(rowData), 'fa-chevron-circle-right': !dt.isRowGroupExpanded(rowData)}"></span> </a> <span class="ui-rowgroup-header-name"> <p-templateLoader [template]="dt.rowGroupHeaderTemplate" [data]="rowData"></p-templateLoader> </span> </td> </tr> <tr #rowElement *ngIf="!dt.expandableRowGroups||dt.isRowGroupExpanded(rowData)" [class]="dt.getRowStyleClass(rowData,rowIndex)" (click)="dt.handleRowClick($event, rowData)" (dblclick)="dt.rowDblclick($event,rowData)" (contextmenu)="dt.onRowRightClick($event,rowData)" (touchend)="dt.handleRowTouchEnd($event)" [ngClass]="{'ui-datatable-even':even&&dt.rowGroupMode!='rowspan','ui-datatable-odd':odd&&dt.rowGroupMode!='rowspan','ui-state-highlight': dt.isSelected(rowData)}"> <ng-template ngFor let-col [ngForOf]="columns" let-colIndex="index"> <td #cell *ngIf="!dt.rowGroupMode || (dt.rowGroupMode == 'subheader') || (dt.rowGroupMode=='rowspan' && ((dt.sortField==col.field && dt.rowGroupMetadata[dt.resolveFieldData(rowData,dt.sortField)].index == rowIndex) || (dt.sortField!=col.field)))" [ngStyle]="col.style" [class]="col.styleClass" [style.display]="col.hidden ? 'none' : 'table-cell'" [ngClass]="{'ui-editable-column':col.editable,'ui-selection-column':col.selectionMode}" (click)="dt.switchCellToEditMode(cell,col,rowData)" [attr.rowspan]="(dt.rowGroupMode=='rowspan' && dt.sortField == col.field && dt.rowGroupMetadata[dt.resolveFieldData(rowData,dt.sortField)].index == rowIndex) ? dt.rowGroupMetadata[dt.resolveFieldData(rowData,dt.sortField)].size : null"> <span class="ui-column-title" *ngIf="dt.responsive">{{col.header}}</span> <span class="ui-cell-data" *ngIf="!col.bodyTemplate && !col.expander && !col.selectionMode">{{dt.resolveFieldData(rowData,col.field)}}</span> <span class="ui-cell-data" *ngIf="col.bodyTemplate"> <p-columnBodyTemplateLoader [column]="col" [rowData]="rowData" [rowIndex]="rowIndex + dt.first"></p-columnBodyTemplateLoader> </span> <div class="ui-cell-editor" *ngIf="col.editable"> <input *ngIf="!col.editorTemplate" type="text" [(ngModel)]="rowData[col.field]" required="true" (keydown)="dt.onCellEditorKeydown($event, col, rowData, rowIndex)" class="ui-inputtext ui-widget ui-state-default ui-corner-all"/> <a *ngIf="col.editorTemplate" class="ui-cell-editor-proxy-focus" href="#" (focus)="dt.onCustomEditorFocusPrev($event, colIndex)"></a> <p-columnEditorTemplateLoader *ngIf="col.editorTemplate" [column]="col" [rowData]="rowData" [rowIndex]="rowIndex"></p-columnEditorTemplateLoader> <a *ngIf="col.editorTemplate" class="ui-cell-editor-proxy-focus" href="#" (focus)="dt.onCustomEditorFocusNext($event, colIndex)"></a> </div> <a href="#" *ngIf="col.expander" (click)="dt.toggleRow(rowData,$event)"> <span class="ui-row-toggler fa fa-fw ui-c" [ngClass]="{'fa-chevron-circle-down':dt.isRowExpanded(rowData), 'fa-chevron-circle-right': !dt.isRowExpanded(rowData)}"></span> </a> <p-dtRadioButton *ngIf="col.selectionMode=='single'" (onClick)="dt.selectRowWithRadio($event, rowData)" [checked]="dt.isSelected(rowData)"></p-dtRadioButton> <p-dtCheckbox *ngIf="col.selectionMode=='multiple'" (onChange)="dt.toggleRowWithCheckbox($event,rowData)" [checked]="dt.isSelected(rowData)"></p-dtCheckbox> </td> </ng-template> </tr> <tr class="ui-widget-header" *ngIf="dt.rowGroupFooterTemplate && dt.rowGroupMode=='subheader' && ((rowIndex === dt.dataToRender.length - 1)||(dt.resolveFieldData(rowData,dt.groupField) !== dt.resolveFieldData(dt.dataToRender[rowIndex + 1],dt.groupField))) && (!dt.expandableRowGroups || dt.isRowGroupExpanded(rowData))"> <p-templateLoader class="ui-helper-hidden" [data]="rowData" [template]="dt.rowGroupFooterTemplate"></p-templateLoader> </tr> <tr *ngIf="dt.expandableRows && dt.isRowExpanded(rowData)"> <td [attr.colspan]="dt.visibleColumns().length"> <p-rowExpansionLoader [rowData]="rowData" [template]="dt.rowExpansionTemplate"></p-rowExpansionLoader> </td> </tr> </ng-template> <tr *ngIf="dt.isEmpty()" class="ui-widget-content"> <td [attr.colspan]="dt.visibleColumns().length" class="ui-datatable-emptymessage">{{dt.emptyMessage}}</td> </tr> ` }) export class TableBody { constructor( @Inject(forwardRef(() => DataTable)) public dt: DataTable) { } @Input("pTableBody") columns: Column[]; visibleColumns() { return this.columns ? this.columns.filter(c => !c.hidden) : []; } } @Component({ selector: '[pScrollableView]', template: ` <div #scrollHeader class="ui-widget-header ui-datatable-scrollable-header" [ngStyle]="{'width': width}" > <div #scrollHeaderBox class="ui-datatable-scrollable-header-box"> <table [class]="dt.tableStyleClass" [ngStyle]="dt.tableStyle"> <thead class="ui-datatable-thead"> <tr *ngIf="!dt.headerColumnGroup" class="ui-state-default" [pColumnHeaders]="columns"></tr> <ng-template [ngIf]="dt.headerColumnGroup"> <tr *ngFor="let headerRow of dt.headerColumnGroup.rows" class="ui-state-default" [pColumnHeaders]="initpcolumnHeader(headerRow.columns)"></tr> </ng-template> </thead> </table> </div> </div> <div #scrollBody class="ui-datatable-scrollable-body" [ngStyle]="{'width': width,'max-height':dt.scrollHeight}"> <div #scrollTableWrapper style="position:relative" [ngStyle]="{'height':virtualTableHeight}"> <table #scrollTable [class]="dt.tableStyleClass" [ngStyle]="dt.tableStyle" [ngClass]="{'ui-datatable-virtual-table':virtualScroll}" style="top:0px"> <!--<colgroup class="ui-datatable-scrollable-colgroup"> <col *ngFor="let col of dt.visibleColumns()" /> </colgroup>--> <tbody [ngClass]="{'ui-datatable-data ui-widget-content': true, 'ui-datatable-hoverable-rows': (dt.rowHover||dt.selectionMode)}" [pTableBody]="columns"></tbody> </table> </div> </div> <div #scrollFooter class="ui-widget-header ui-datatable-scrollable-footer" [ngStyle]="{'width': width}" *ngIf="dt.hasFooter()"> <div #scrollFooterBox class="ui-datatable-scrollable-footer-box"> <table [class]="dt.tableStyleClass" [ngStyle]="dt.tableStyle"> <tfoot class="ui-datatable-tfoot"> <tr *ngIf="!footerColumnGroup" [pColumnFooters]="columns" class="ui-state-default"></tr> <ng-template [ngIf]="footerColumnGroup"> <tr *ngFor="let footerRow of footerColumnGroup.rows" [pColumnFooters]="footerRow.columns"></tr> </ng-template> </tfoot> </table> </div> </div> ` }) export class ScrollableView implements AfterViewInit, AfterViewChecked, OnDestroy { constructor( @Inject(forwardRef(() => DataTable)) public dt: DataTable, public domHandler: DomHandler, public el: ElementRef, public renderer: Renderer) { } @Input("pScrollableView") columns: Column[]; @ViewChild('scrollHeader') scrollHeaderViewChild: ElementRef; @ViewChild('scrollHeaderBox') scrollHeaderBoxViewChild: ElementRef; @ViewChild('scrollBody') scrollBodyViewChild: ElementRef; @ViewChild('scrollTable') scrollTableViewChild: ElementRef; @ViewChild('scrollTableWrapper') scrollTableWrapperViewChild: ElementRef; @ViewChild('scrollFooter') scrollFooterViewChild: ElementRef; @ViewChild('scrollFooterBox') scrollFooterBoxViewChild: ElementRef; @Input() frozen: boolean; @Input() width: string; @Input() virtualScroll: boolean; @Output() onVirtualScroll: EventEmitter<any> = new EventEmitter(); @Input() loading: boolean; public scrollBody: HTMLDivElement; public scrollHeader: HTMLDivElement; public scrollHeaderBox: HTMLDivElement; public scrollTable: HTMLDivElement; public scrollTableWrapper: HTMLDivElement; public scrollFooter: HTMLDivElement; public scrollFooterBox: HTMLDivElement; public bodyScrollListener: Function; public headerScrollListener: Function; public scrollBodyMouseWheelListener: Function; public scrollFunction: Function; public rowHeight: number; public scrollTimeout: any; ngAfterViewInit() { this.initScrolling(); } initpcolumnHeader(columns: Column[]): Column[] { if (!this.frozen) { columns = columns.filter(f => !f.frozen); } else { columns = columns.filter(f => f.frozen); } return columns; } ngAfterViewChecked() { if (this.virtualScroll && !this.rowHeight) { let row = this.domHandler.findSingle(this.scrollTable, 'tr.ui-widget-content'); if (row) { this.rowHeight = this.domHandler.getOuterHeight(row); } } } initScrolling() { this.scrollHeader = <HTMLDivElement>this.scrollHeaderViewChild.nativeElement; this.scrollHeaderBox = <HTMLDivElement>this.scrollHeaderBoxViewChild.nativeElement; this.scrollBody = <HTMLDivElement>this.scrollBodyViewChild.nativeElement; this.scrollTable = <HTMLDivElement>this.scrollTableViewChild.nativeElement; this.scrollTableWrapper = <HTMLDivElement>this.scrollTableWrapperViewChild.nativeElement; this.scrollFooter = this.scrollFooterViewChild ? <HTMLDivElement>this.scrollFooterViewChild.nativeElement : null; this.scrollFooterBox = this.scrollFooterBoxViewChild ? <HTMLDivElement>this.scrollFooterBoxViewChild.nativeElement : null; if (!this.frozen) { let frozenView = this.el.nativeElement.previousElementSibling; if (frozenView) { var frozenScrollBody = this.domHandler.findSingle(frozenView, '.ui-datatable-scrollable-body'); } this.bodyScrollListener = this.renderer.listen(this.scrollBody, 'scroll', (event) => { GlobalEventsManager.onDatatableScrollEvent.emit(true); // var dropdownFilterContainer=document.getElementsByClassName('ui-dropdown-panel'); // // for(let i=0;i<dropdownFilterContainer.length;i++){ // dropdownFilterContainer[i].style.display='none'; // } this.scrollHeaderBox.style.marginLeft = -1 * this.scrollBody.scrollLeft + 'px'; if (this.scrollFooterBox) { this.scrollFooterBox.style.marginLeft = -1 * this.scrollBody.scrollLeft + 'px'; } if (frozenScrollBody) { frozenScrollBody.scrollTop = this.scrollBody.scrollTop; } if (this.virtualScroll) { clearTimeout(this.scrollTimeout); this.scrollTimeout = setTimeout(() => { let viewport = this.domHandler.getOuterHeight(this.scrollBody); let tableHeight = this.domHandler.getOuterHeight(this.scrollTable); let pageHeight = this.rowHeight * this.dt.rows; let virtualTableHeight = parseFloat(this.virtualTableHeight); let pageCount = (virtualTableHeight / pageHeight) || 1; if (this.scrollBody.scrollTop + viewport > parseFloat(this.scrollTable.style.top) + tableHeight || this.scrollBody.scrollTop < parseFloat(this.scrollTable.style.top)) { let page = Math.floor((this.scrollBody.scrollTop * pageCount) / (this.scrollBody.scrollHeight)) + 1; this.onVirtualScroll.emit({ page: page }); this.scrollTable.style.top = ((page - 1) * pageHeight) + 'px'; } }, 200); } }); //to trigger change detection this.scrollBodyMouseWheelListener = this.renderer.listen(this.scrollBody, 'mousewheel', (event) => { }); this.headerScrollListener = this.renderer.listen(this.scrollHeader, 'scroll', () => { this.scrollHeader.scrollLeft = 0; }); } let scrollBarWidth = this.domHandler.calculateScrollbarWidth(); if (!this.frozen) { this.scrollHeaderBox.style.marginRight = scrollBarWidth + 'px'; if (this.scrollFooterBox) { this.scrollFooterBox.style.marginRight = scrollBarWidth + 'px'; } } else { this.scrollBody.style.paddingBottom = scrollBarWidth + 'px'; } } get virtualTableHeight(): string { let totalRecords = this.dt.lazy ? this.dt.totalRecords : (this.dt.value ? this.dt.value.length : 0); return (totalRecords * this.rowHeight) + 'px'; } ngOnDestroy() { if (this.bodyScrollListener) { this.bodyScrollListener(); } if (this.scrollBodyMouseWheelListener) { this.scrollBodyMouseWheelListener(); } if (this.headerScrollListener) { this.headerScrollListener(); } } } @Component({ selector: 'p-dataTable', template: ` <div [ngStyle]="style" [class]="styleClass" [style.width]="containerWidth" [ngClass]="{'ui-datatable ui-widget':true,'ui-datatable-reflow':responsive,'ui-datatable-stacked':stacked,'ui-datatable-resizable':resizableColumns,'ui-datatable-scrollable':scrollable}"> <div class="ui-datatable-loading ui-widget-overlay" *ngIf="loading"></div> <div class="ui-datatable-loading-content" *ngIf="loading"> <i class="fa fa-circle-o-notch fa-spin fa-2x"></i> </div> <div class="ui-datatable-header ui-widget-header" *ngIf="header"> <ng-content select="p-header"></ng-content> </div> <p-paginator [rows]="rows" [first]="first" [totalRecords]="totalRecords" [pageLinkSize]="pageLinks" styleClass="ui-paginator-bottom" (onPageChange)="paginate($event)" [rowsPerPageOptions]="rowsPerPageOptions" *ngIf="paginator && paginatorPosition!='bottom' || paginatorPosition =='both'"></p-paginator> <div class="ui-datatable-tablewrapper" *ngIf="!scrollable"> <table [class]="tableStyleClass" [ngStyle]="tableStyle"> <thead class="ui-datatable-thead"> <tr *ngIf="!headerColumnGroup" class="ui-state-default" [pColumnHeaders]="columns"></tr> <ng-template [ngIf]="headerColumnGroup"> <tr *ngFor="let headerRow of headerColumnGroup.rows" class="ui-state-default" [pColumnHeaders]="headerRow.columns"></tr> </ng-template> </thead> <tfoot *ngIf="hasFooter()" class="ui-datatable-tfoot"> <tr *ngIf="!footerColumnGroup" class="ui-state-default" [pColumnFooters]="columns"></tr> <ng-template [ngIf]="footerColumnGroup"> <tr *ngFor="let footerRow of footerColumnGroup.rows" class="ui-state-default" [pColumnFooters]="footerRow.columns"></tr> </ng-template> </tfoot> <tbody [ngClass]="{'ui-datatable-data ui-widget-content': true, 'ui-datatable-hoverable-rows': (rowHover||selectionMode)}" [pTableBody]="columns"></tbody> </table> </div> <ng-template [ngIf]="scrollable"> <div class="ui-datatable-scrollable-wrapper ui-helper-clearfix" [ngClass]="{'max-height':scrollHeight}"> <div *ngIf="frozenColumns" [pScrollableView]="frozenColumns" frozen="true" [ngStyle]="{'width':this.frozenWidth}" class="ui-datatable-scrollable-view ui-datatable-frozen-view"></div> <div [pScrollableView]="scrollableColumns" [ngStyle]="{'width':this.unfrozenWidth, 'left': this.frozenWidth}" class="ui-datatable-scrollable-view" [virtualScroll]="virtualScroll" (onVirtualScroll)="onVirtualScroll($event)" [ngClass]="{'ui-datatable-unfrozen-view': frozenColumns}"></div> </div> </ng-template> <p-paginator [rows]="rows" [first]="first" [totalRecords]="totalRecords" [pageLinkSize]="pageLinks" styleClass="ui-paginator-bottom" (onPageChange)="paginate($event)" [rowsPerPageOptions]="rowsPerPageOptions" *ngIf="paginator && paginatorPosition!='top' || paginatorPosition =='both'"></p-paginator> <div class="ui-datatable-footer ui-widget-header" *ngIf="footer"> <ng-content select="p-footer"></ng-content> </div> <div class="ui-column-resizer-helper ui-state-highlight" style="display:none"></div> <span class="fa fa-arrow-down ui-datatable-reorder-indicator-up" style="position: absolute; display: none;"></span> <span class="fa fa-arrow-up ui-datatable-reorder-indicator-down" style="position: absolute; display: none;"></span> </div> `, providers: [DomHandler, ObjectUtils] }) export class DataTable implements AfterViewChecked, AfterViewInit, AfterContentInit, OnInit, DoCheck, OnDestroy, BlockableUI { @Input() paginator: boolean; @Input() rows: number; @Input() totalRecords: number; @Input() pageLinks: number = 5; @Input() rowsPerPageOptions: number[]; @Input() responsive: boolean; @Input() stacked: boolean; @Input() selectionMode: string; @Input() selection: any; @Output() selectionChange: EventEmitter<any> = new EventEmitter(); @Input() editable: boolean; @Output() onRowClick: EventEmitter<any> = new EventEmitter(); @Output() onRowSelect: EventEmitter<any> = new EventEmitter(); @Output() onRowUnselect: EventEmitter<any> = new EventEmitter(); @Output() onRowDblclick: EventEmitter<any> = new EventEmitter(); @Output() onHeaderCheckboxToggle: EventEmitter<any> = new EventEmitter(); @Output() onContextMenuSelect: EventEmitter<any> = new EventEmitter(); @Input() filterDelay: number = 300; @Input() lazy: boolean; @Output() onLazyLoad: EventEmitter<any> = new EventEmitter(); @Input() resizableColumns: boolean; @Input() columnResizeMode: string = 'fit'; @Output() onColResize: EventEmitter<any> = new EventEmitter(); @Input() reorderableColumns: boolean; @Output() onColReorder: EventEmitter<any> = new EventEmitter(); @Input() scrollable: boolean; @Input() virtualScroll: boolean; @Input() scrollHeight: any; @Input() scrollWidth: any; @Input() frozenWidth: any; @Input() unfrozenWidth: any; @Input() style: any; @Input() styleClass: string; @Input() tableStyle: any; @Input() tableStyleClass: string; @Input() globalFilter: any; @Input() sortMode: string = 'single'; @Input() sortField: string; @Input() sortOrder: number = -1; @Input() groupField: string; @Input() multiSortMeta: SortMeta[]; @Input() contextMenu: any; @Input() csvSeparator: string = ','; @Input() exportFilename: string = 'download'; @Input() emptyMessage: string = 'No records found'; @Input() paginatorPosition: string = 'bottom'; @Input() metaKeySelection: boolean = true; @Input() immutable: boolean; @Output() onEditInit: EventEmitter<any> = new EventEmitter(); @Output() onEditComplete: EventEmitter<any> = new EventEmitter(); @Output() onEdit: EventEmitter<any> = new EventEmitter(); @Output() onEditCancel: EventEmitter<any> = new EventEmitter(); @Output() onPage: EventEmitter<any> = new EventEmitter(); @Output() onSort: EventEmitter<any> = new EventEmitter(); @Output() onFilter: EventEmitter<any> = new EventEmitter(); @ContentChild(Header) header; @ContentChild(Footer) footer; @Input() expandableRows: boolean; @Input() expandedRows: any[]; @Input() expandableRowGroups: boolean; @Input() rowExpandMode: string = 'multiple'; @Input() public expandedRowsGroups: any[]; @Input() tabindex: number = 1; @Input() rowStyleClass: Function; @Input() rowGroupMode: string; @Input() sortableRowGroup: boolean = true; @Input() sortFile: string; @Input() rowHover: boolean; @Input() first: number = 0; @Input() public filters: { [s: string]: FilterMetadata; } = {}; @Input() dataKey: string; @Input() loading: boolean; @Input() displaysum: boolean; @Output() onRowExpand: EventEmitter<any> = new EventEmitter(); @Output() onRowCollapse: EventEmitter<any> = new EventEmitter(); @Output() onRowGroupExpand: EventEmitter<any> = new EventEmitter(); @Output() onRowGroupCollapse: EventEmitter<any> = new EventEmitter(); @ContentChildren(PrimeTemplate) templates: QueryList<PrimeTemplate>; @ContentChildren(Column) cols: QueryList<Column>; @ContentChild(HeaderColumnGroup) headerColumnGroup: HeaderColumnGroup; @ContentChild(FooterColumnGroup) footerColumnGroup: FooterColumnGroup; public _value: any[]; public dataToRender: any[]; public page: number = 0; public filterTimeout: any; public filteredValue: any[]; public columns: Column[]; public frozenColumns: Column[]; public scrollableColumns: Column[]; public columnsChanged: boolean = false; public dataChanged: boolean = false; public stopSortPropagation: boolean; public sortColumn: Column; public columnResizing: boolean; public lastResizerHelperX: number; public documentClickListener: Function; public documentColumnResizeListener: Function; public documentColumnResizeEndListener: Function; public resizerHelper: any; public resizeColumn: any; public reorderIndicatorUp: any; public reorderIndicatorDown: any; public draggedColumn: any; public dropPosition: number; public tbody: any; public rowTouched: boolean; public rowGroupToggleClick: boolean; public editingCell: any; public stopFilterPropagation: boolean; public rowGroupMetadata: any; public rowGroupHeaderTemplate: TemplateRef<any>; public rowGroupFooterTemplate: TemplateRef<any>; public rowExpansionTemplate: TemplateRef<any>; public scrollBarWidth: number; public editorClick: boolean; differ: any; globalFilterFunction: any; columnsSubscription: Subscription; resizeTimeout: any; datatableHeaderWidth: number; rowGroupScrollableWidthFix: boolean; // public emptyMessageAlignmentTimeout:any; constructor(public el: ElementRef, public domHandler: DomHandler, public differs: IterableDiffers, public renderer: Renderer, public changeDetector: ChangeDetectorRef, public objectUtils: ObjectUtils, private ngZone: NgZone) { window.onresize = (e) => { ngZone.run(() => { this.calculateUnforzenWidth(); }) } } ngOnInit() { if (this.lazy) { this.onLazyLoad.emit(this.createLazyLoadMetadata()); } if (!this.immutable) { this.differ = this.differs.find([]).create(null); } this.calculateUnforzenWidth(); } ngAfterContentInit() { this.initColumns(); this.columnsSubscription = this.cols.changes.subscribe(_ => { this.initColumns(); this.changeDetector.markForCheck(); }); this.templates.forEach((item) => { switch (item.getType()) { case 'rowexpansion': this.rowExpansionTemplate = item.template; break; case 'rowgroupheader': this.rowGroupHeaderTemplate = item.template; break; case 'rowgroupfooter': this.rowGroupFooterTemplate = item.template; break; } }); } ngAfterViewChecked() { if (this.columnsChanged && this.el.nativeElement.offsetParent) { if (this.resizableColumns) { this.initResizableColumns(); } if (this.reorderableColumns) { this.initColumnReordering(); } this.columnsChanged = false; } if (this.dataChanged) { this.dataChanged = false; } if (this.calculateRowHeight && this.dataToRender && this.dataToRender.length > 0) { //resize row height based on unfrozen columns this.initFrozenRows(); } this.scrollableBodytableAlignment(); } ngAfterViewInit() { if (this.globalFilter) { this.globalFilterFunction = this.renderer.listen(this.globalFilter, 'keyup', () => { this.filterTimeout = setTimeout(() => { this._filter(); this.filterTimeout = null; }, this.filterDelay); }); } if (this.editable) { this.documentClickListener = this.renderer.listenGlobal('body', 'click', (event) => { if (!this.editorClick) { this.closeCell(); } this.editorClick = false; }); } } ngDoCheck() { if (!this.immutable) { let changes = this.differ.diff(this.value); if (changes) { this.handleDataChange(); } } } @Input() get value(): any[] { return this._value; } set value(val: any[]) { this._value = val; this.handleDataChange(); } currentscrollY: number; calculateRowHeight: boolean = true; initFrozenRows() { if (this.unfrozenWidth) { //getting scroll height // let rowcount=this.rows; // let renderedRowCount=document.querySelectorAll('.ui-datatable-unfrozen-view .ui-datatable-scrollable-body table tr').length; // if(rowcount==renderedRowCount){ this.calculateRowHeight = false; // } let unfrozenRows = document.querySelectorAll('.ui-datatable-unfrozen-view .ui-datatable-scrollable-body table tr'); let frozenRows = document.querySelectorAll('.ui-datatable-frozen-view .ui-datatable-scrollable-body table tr'); //reset rows height to there actuals for (var i = 0; i < unfrozenRows.length; i++) { let frozenRowsHeight = frozenRows[i]['style']['height'] = 'auto'; let unfrozenRowHeight = unfrozenRows[i]['style']['height'] = 'auto'; } for (var i = 0; i < unfrozenRows.length; i++) { let frozenRowsHeight = frozenRows[i]['offsetHeight']; let unfrozenRowHeight = unfrozenRows[i]['offsetHeight']; if (frozenRowsHeight > unfrozenRowHeight) { unfrozenRows[i]['style']['height'] = frozenRowsHeight + 'px'; } else { frozenRows[i]['style']['height'] = unfrozenRowHeight + 'px'; } } if (this.headerColumnGroup) { let frozenHeaderRows = document.querySelectorAll('.ui-datatable-frozen-view .ui-datatable-thead .ui-column-title')[0].parentElement; let unfrozenHeaderRows = document.querySelectorAll('.ui-datatable-unfrozen-view .ui-datatable-thead')[0]; frozenHeaderRows['style']['height'] = unfrozenHeaderRows['offsetHeight'] + 'px'; } //set scroll position to original -- work around for firfox //when we set rows height scroll bar position get lost in case of firfox if (this.currentscrollY) { window.scrollTo(0, this.currentscrollY); } } } handleDataChange() { this.dataChanged = true; if (this.paginator) { this.updatePaginator(); } if (this.hasFilter()) { if (this.lazy) { //prevent loop if (this.stopFilterPropagation) this.stopFilterPropagation = false; else this._filter(); } else { this._filter(); } } if (this.stopSortPropagation) { this.stopSortPropagation = false; } else if (!this.lazy && (this.sortField || this.multiSortMeta)) { if (!this.sortColumn && this.columns) { this.sortColumn = this.columns.find(col => col.field === this.sortField && col.sortable === 'custom'); } if (this.sortMode == 'single') this.sortSingle(); else if (this.sortMode == 'multiple') this.sortMultiple(); } this.updateDataToRender(this.filteredValue || this.value); } initColumns(): void { this.columns = this.cols.toArray(); if (this.scrollable) { this.scrollableColumns = []; this.cols.forEach((col) => { if (col.frozen) { this.frozenColumns = this.frozenColumns || []; this.frozenColumns.push(col); } else { this.scrollableColumns.push(col); } }); //Rohit Sindhu Customization for Global Filter on scrollable grid if (this.hasFilter()) { this._filter(); } } this.columnsChanged = true; } resolveFieldData(data: any, field: string): any { if (data && field) { if (field.indexOf('.') == -1) { if (data[field] == null) { return ' '; } return data[field]; } else { let fields: string[] = field.split('.'); let value = data; for (var i = 0, len = fields.length; i < len; ++i) { if (value == null) { return ' '; } value = value[fields[i]]; } return value; } } else { return ' '; } } updateRowGroupMetadata() { this.rowGroupMetadata = {}; if (this.dataToRender) { for (let i = 0; i < this.dataToRender.length; i++) { let rowData = this.dataToRender[i]; let group = this.resolveFieldData(rowData, this.sortField); if (i == 0) { this.rowGroupMetadata[group] = { index: 0, size: 1 }; } else { let previousRowData = this.dataToRender[i - 1]; let previousRowGroup = this.resolveFieldData(previousRowData, this.sortField); if (group === previousRowGroup) { this.rowGroupMetadata[group].size++; } else { this.rowGroupMetadata[group] = { index: i, size: 1 }; } } } } } updatePaginator() { //total records this.totalRecords = this.lazy ? this.totalRecords : (this.value ? this.value.length : 0); //first if (this.totalRecords && this.first >= this.totalRecords) { let numberOfPages = Math.ceil(this.totalRecords / this.rows); this.first = Math.max((numberOfPages - 1) * this.rows, 0); } } paginate(event) { this.first = event.first; this.rows = event.rows; if (this.lazy) { this.stopFilterPropagation = true; this.onLazyLoad.emit(this.createLazyLoadMetadata()); } else { this.updateDataToRender(this.filteredValue || this.value); } this.onPage.emit({ first: this.first, rows: this.rows }); } scrollableBodytableAlignment() { let unfrozenclass = ""; let frozenWidth: number = 0; if (this.unfrozenWidth && this.frozenWidth && parseInt(this.frozenWidth) > 0) { unfrozenclass = ".ui-datatable-unfrozen-view"; if (document.querySelectorAll('.ui-datatable-unfrozen-view table tr th.col-group-header')[0]) frozenWidth = parseInt(this.frozenWidth) - (parseInt(this.frozenWidth) - 150) } if (this.isEmpty() || (!this.rowGroupScrollableWidthFix && this.rowGroupMode)) { let ele = this.el.nativeElement.querySelectorAll(unfrozenclass + ' .ui-datatable-scrollable-header-box > table'); if (ele.length > 0) { if (this.datatableHeaderWidth != ele[0].clientWidth) { this.datatableHeaderWidth = ele[0].clientWidth; let emptyContentWidth = this.el.nativeElement.querySelectorAll(unfrozenclass + " .ui-datatable-scrollable-body table")[0].clientWidth; if (this.datatableHeaderWidth > 0 && emptyContentWidth > 0 && emptyContentWidth != this.datatableHeaderWidth) { this.setScrollableBodyTableWidth(unfrozenclass, (this.datatableHeaderWidth - frozenWidth)); } if ((!this.rowGroupScrollableWidthFix && this.rowGroupMode)) { this.rowGroupScrollableWidthFix = true; } } } } if (!this.isEmpty() && this.datatableHeaderWidth && !this.rowGroupScrollableWidthFix) { this.datatableHeaderWidth = undefined; this.setScrollableBodyTableWidth(unfrozenclass, this.datatableHeaderWidth); } } setScrollableBodyTableWidth(classname: string, width: number) { let msgcontainer = this.el.nativeElement.querySelectorAll(classname + " .ui-datatable-scrollable-body table")[0]; if (msgcontainer) { msgcontainer.style.width = width ? width + 'px' : ''; } } updateDataToRender(datasource) { //setting current scroll position before rendering data this.currentscrollY = window.scrollY; if ((this.paginator || this.virtualScroll) && datasource) { this.dataToRender = []; let startIndex: number = this.lazy ? 0 : this.first; let endIndex: number = this.virtualScroll ? this.first + this.rows * 2 : startIndex + this.rows; for (let i = startIndex; i < endIndex; i++) { if (i >= datasource.length) { break; } this.dataToRender.push(datasource[i]); } } else { this.dataToRender = datasource; } if (this.rowGroupMode) { this.updateRowGroupMetadata(); } //setting flag to true so row height is being calculated for new data //as well on ngAfterViewChecked this.calculateRowHeight = true; } onVirtualScroll(event) { this.first = (event.page - 1) * this.rows; if (this.lazy) { this.stopFilterPropagation = true; this.onLazyLoad.emit(this.createLazyLoadMetadata()); } else { this.updateDataToRender(this.filteredValue || this.value); } } onHeaderKeydown(event, column: Column) { if (event.keyCode == 13) { this.sort(event, column); event.preventDefault(); } } onHeaderMousedown(event, header: any) { if (this.reorderableColumns) { if (event.target.nodeName !== 'INPUT') { header.draggable = true; } else if (event.target.nodeName === 'INPUT') { header.draggable = false; } } } sort(event, column: Column) { if (!column.sortable) { return; } let targetNode = event.target.nodeName; if (targetNode == 'TH' || (targetNode == 'SPAN' && !this.domHandler.hasClass(event.target, 'ui-c'))) { let columnSortField = column.sortField || column.field; this.sortOrder = (this.sortField === columnSortField) ? this.sortOrder * -1 : -1; this.sortField = columnSortField; this.sortColumn = column; let metaKey = event.metaKey || event.ctrlKey; if (this.sortMode == 'multiple') { if (!this.multiSortMeta || !metaKey) { this.multiSortMeta = []; } this.addSortMeta({ field: this.sortField, order: this.sortOrder }); } if (this.lazy) { this.first = 0; this.stopFilterPropagation = true; this.onLazyLoad.emit(this.createLazyLoadMetadata()); } else { if (this.sortMode == 'multiple') this.sortMultiple(); else this.sortSingle(); } this.onSort.emit({ field: this.sortField, order: this.sortOrder, multisortmeta: this.multiSortMeta }); } } sortSingle() { if (this.value) { if (this.sortColumn && this.sortColumn.sortable === 'custom') { this.sortColumn.sortFunction.emit({ field: this.sortField, order: this.sortOrder }); } else { this.value.sort((data1, data2) => { let value1 = this.resolveFieldData(data1, this.sortField); let value2 = this.resolveFieldData(data2, this.sortField); let result = null; if (value1 == null && value2 != null) result = -1; else if (value1 != null && value2 == null) result = 1; else if (value1 == null && value2 == null) result = 0; else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2); else result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0; return (this.sortOrder * result); }); } this.first = 0; if (this.hasFilter()) { this._filter(); } } //prevent resort at ngDoCheck this.stopSortPropagation = true; } sortMultiple() { if (this.value) { this.value.sort((data1, data2) => { return this.multisortField(data1, data2, this.multiSortMeta, 0); }); if (this.hasFilter()) { this._filter(); } } //prevent resort at ngDoCheck this.stopSortPropagation = true; } multisortField(data1, data2, multiSortMeta, index) { let value1 = this.resolveFieldData(data1, multiSortMeta[index].field); let value2 = this.resolveFieldData(data2, multiSortMeta[index].field); let result = null; if (typeof value1 == 'string' || value1 instanceof String) { if (value1.localeCompare && (value1 != value2)) { return (multiSortMeta[index].order * value1.localeCompare(value2)); } } else { result = (value1 < value2) ? -1 : 1; } if (value1 == value2) { return (multiSortMeta.length - 1) > (index) ? (this.multisortField(data1, data2, multiSortMeta, index + 1)) : 0; } return (multiSortMeta[index].order * result); } addSortMeta(meta) { var index = -1; for (var i = 0; i < this.multiSortMeta.length; i++) { if (this.multiSortMeta[i].field === meta.field) { index = i; break; } } if (index >= 0) this.multiSortMeta[index] = meta; else this.multiSortMeta.push(meta); } isSorted(column: Column) { if (!column.sortable) { return false; } let columnSortField = column.sortField || column.field; if (this.sortMode === 'single') { return (this.sortField && columnSortField === this.sortField); } else if (this.sortMode === 'multiple') { let sorted = false; if (this.multiSortMeta) { for (let i = 0; i < this.multiSortMeta.length; i++) { if (this.multiSortMeta[i].field == columnSortField) { sorted = true; break; } } } return sorted; } } getSortOrder(column: Column) { let order = 0; let columnSortField = column.sortField || column.field; if (this.sortMode === 'single') { if (this.sortField && columnSortField === this.sortField) { order = this.sortOrder; } } else if (this.sortMode === 'multiple') { if (this.multiSortMeta) { for (let i = 0; i < this.multiSortMeta.length; i++) { if (this.multiSortMeta[i].field == columnSortField) { order = this.multiSortMeta[i].order; break; } } } } return order; } onRowGroupClick(event) { if (this.rowGroupToggleClick) { this.rowGroupToggleClick = false; return; } if (this.sortableRowGroup) { let targetNode = event.target.nodeName; if ((targetNode == 'TD' || (targetNode == 'SPAN' && !this.domHandler.hasClass(event.target, 'ui-c')))) { if (this.sortField != this.groupField) { this.sortField = this.groupField; this.sortSingle(); } else { this.sortOrder = -1 * this.sortOrder; this.sortSingle(); } } } } handleRowClick(event, rowData) { let targetNode = event.target.nodeName; if (targetNode == 'TD' || (targetNode == 'SPAN' && !this.domHandler.hasClass(event.target, 'ui-c'))) { this.onRowClick.next({ originalEvent: event, data: rowData }); if (!this.selectionMode) { return; } let selected = this.isSelected(rowData); let metaSelection = this.rowTouched ? false : this.metaKeySelection; if (metaSelection) { let metaKey = event.metaKey || event.ctrlKey; if (selected && metaKey) { if (this.isSingleSelectionMode()) { this.selection = null; this.selectionChange.emit(null); } else { let selectionIndex = this.findIndexInSelection(rowData); this.selection = this.selection.filter((val, i) => i != selectionIndex); this.selectionChange.emit(this.selection); } this.onRowUnselect.emit({ originalEvent: event, data: rowData, type: 'row' }); } else { if (this.isSingleSelectionMode()) { this.selection = rowData; this.selectionChange.emit(rowData); } else if (this.isMultipleSelectionMode()) { if (metaKey) this.selection = this.selection || []; else this.selection = []; this.selection = [...this.selection, rowData]; this.selectionChange.emit(this.selection); } this.onRowSelect.emit({ originalEvent: event, data: rowData, type: 'row' }); } } else { if (this.isSingleSelectionMode()) { if (selected) { this.selection = null; this.onRowUnselect.emit({ originalEvent: event, data: rowData, type: 'row' }); } else { this.selection = rowData; this.onRowSelect.emit({ originalEvent: event, data: rowData, type: 'row' }); } } else { if (selected) { let selectionIndex = this.findIndexInSelection(rowData); this.selection = this.selection.filter((val, i) => i != selectionIndex); this.onRowUnselect.emit({ originalEvent: event, data: rowData, type: 'row' }); } else { this.selection = [...this.selection || [], rowData]; this.onRowSelect.emit({ originalEvent: event, data: rowData, type: 'row' }); } } this.selectionChange.emit(this.selection); } } this.rowTouched = false; } handleRowTouchEnd(event) { this.rowTouched = true; } selectRowWithRadio(event, rowData: any) { if (this.selection != rowData) { this.selection = rowData; this.selectionChange.emit(this.selection); this.onRowSelect.emit({ originalEvent: event, data: rowData, type: 'radiobutton' }); } } toggleRowWithCheckbox(event, rowData) { let selectionIndex = this.findIndexInSelection(rowData); this.selection = this.selection || []; if (selectionIndex != -1) { this.selection = this.selection.filter((val, i) => i != selectionIndex); this.onRowUnselect.emit({ originalEvent: event, data: rowData, type: 'checkbox' }); } else { this.selection = [...this.selection, rowData]; this.onRowSelect.emit({ originalEvent: event, data: rowData, type: 'checkbox' }); } this.selectionChange.emit(this.selection); } toggleRowsWithCheckbox(event) { if (event.checked) this.selection = this.dataToRender.slice(0); else this.selection = []; this.selectionChange.emit(this.selection); this.onHeaderCheckboxToggle.emit({ originalEvent: event, checked: event.checked }); } onRowRightClick(event, rowData) { if (this.contextMenu) { let selectionIndex = this.findIndexInSelection(rowData); let selected = selectionIndex != -1; if (!selected) { if (this.isSingleSelectionMode()) { this.selection = rowData; this.selectionChange.emit(rowData); } else if (this.isMultipleSelectionMode()) { this.selection = [rowData]; this.selectionChange.emit(this.selection); } } this.contextMenu.show(event); this.onContextMenuSelect.emit({ originalEvent: event, data: rowData }); } } rowDblclick(event, rowData) { this.onRowDblclick.emit({ originalEvent: event, data: rowData }); } isSingleSelectionMode() { return this.selectionMode === 'single'; } isMultipleSelectionMode() { return this.selectionMode === 'multiple'; } findIndexInSelection(rowData: any) { let index: number = -1; if (this.selection) { for (let i = 0; i < this.selection.length; i++) { if (this.objectUtils.equals(rowData, this.selection[i], this.dataKey)) { index = i; break; } } } return index; } isSelected(rowData) { return ((rowData && this.objectUtils.equals(rowData, this.selection, this.dataKey)) || this.findIndexInSelection(rowData) != -1); } get allSelected() { let val = true; if (this.dataToRender && this.selection && (this.dataToRender.length <= this.selection.length)) { for (let data of this.dataToRender) { if (!this.isSelected(data)) { val = false; break; } } } else { val = false; } return val; } onFilterKeyup(event, value, field, matchMode) { if (event.keyCode === 13 || (event.type === 'blur')) { if (this.filterTimeout) { clearTimeout(this.filterTimeout); } this.filterTimeout = setTimeout(() => { this.filter(value, field, matchMode); this.filterTimeout = null; }, this.filterDelay); } } filter(value, field, matchMode) { if (!this.isFilterBlank(value)) { this.filters[field] = { value: value, matchMode: matchMode }; } else if (this.filters[field]) { delete this.filters[field]; } this._filter(); } isFilterBlank(filter: any): boolean { if (filter !== null && filter !== undefined) { if ((typeof filter === 'string' && filter.trim().length == 0) || (filter instanceof Array && filter.length == 0)) return true; else return false; } return true; } _filter() { this.first = 0; if (this.lazy) { this.stopFilterPropagation = true; this.onLazyLoad.emit(this.createLazyLoadMetadata()); } else { this.filteredValue = []; for (let i = 0; i < this.value.length; i++) { let localMatch = true; let globalMatch = false; if (this.columns) { for (let j = 0; j < this.columns.length; j++) { let col = this.columns[j], filterMeta = this.filters[col.field]; //local if (filterMeta) { let filterValue = filterMeta.value, filterField = col.field, filterMatchMode = filterMeta.matchMode || 'startsWith', dataFieldValue = this.resolveFieldData(this.value[i], filterField); let filterConstraint = this.filterConstraints[filterMatchMode]; if (!filterConstraint(dataFieldValue, filterValue.toString())) { localMatch = false; } if (!localMatch) { break; } } //global if (this.globalFilter && !globalMatch) { globalMatch = this.filterConstraints['contains'](this.resolveFieldData(this.value[i], col.field), this.globalFilter.value); } } } let matches = localMatch; if (this.globalFilter) { matches = localMatch && globalMatch; } if (matches) { this.filteredValue.push(this.value[i]); } } if (this.filteredValue.length === this.value.length) { this.filteredValue = null; } if (this.paginator) { this.totalRecords = this.filteredValue ? this.filteredValue.length : this.value ? this.value.length : 0; } this.updateDataToRender(this.filteredValue || this.value); } this.onFilter.emit({ filters: this.filters }); } hasFilter() { let empty = true; for (let prop in this.filters) { if (this.filters.hasOwnProperty(prop)) { empty = false; break; } } return !empty || (this.globalFilter && this.globalFilter.value && this.globalFilter.value.trim().length); } onFilterInputClick(event) { event.stopPropagation(); } filterConstraints = { startsWith(value, filter): boolean { if (filter === undefined || filter === null || filter.trim() === '') { return true; } if (value === undefined || value === null) { return false; } let filterValue = filter.toLowerCase(); return value.toString().toLowerCase().slice(0, filterValue.length) === filterValue; }, contains(value, filter): boolean { if (filter === undefined || filter === null || (typeof filter === 'string' && filter.trim() === '')) { return true; } if (value === undefined || value === null) { return false; } return value.toString().toLowerCase().indexOf(filter.toLowerCase()) !== -1; }, endsWith(value, filter): boolean { if (filter === undefined || filter === null || filter.trim() === '') { return true; } if (value === undefined || value === null) { return false; } let filterValue = filter.toString().toLowerCase(); return value.toString().toLowerCase().indexOf(filterValue, value.toString().length - filterValue.length) !== -1; }, equals(value, filter): boolean { if (filter === undefined || filter === null || (typeof filter === 'string' && filter.trim() === '')) { return true; } if (value === undefined || value === null) { return false; } return value.toString().toLowerCase() == filter.toString().toLowerCase(); }, in(value, filter: any[]): boolean { if (filter === undefined || filter === null || filter.length === 0) { return true; } if (value === undefined || value === null) { return false; } for (let i = 0; i < filter.length; i++) { if (filter[i] === value) return true; } return false; } } switchCellToEditMode(cell: any, column: Column, rowData: any) { if (!this.selectionMode && this.editable && column.editable) { this.editorClick = true; if (cell != this.editingCell) { if (this.editingCell && this.domHandler.find(this.editingCell, '.ng-invalid.ng-dirty').length == 0) { this.domHandler.removeClass(this.editingCell, 'ui-cell-editing'); } this.editingCell = cell; this.onEditInit.emit({ column: column, data: rowData }); this.domHandler.addClass(cell, 'ui-cell-editing'); let focusable = this.domHandler.findSingle(cell, '.ui-cell-editor input'); if (focusable) { setTimeout(() => this.renderer.invokeElementMethod(focusable, 'focus'), 50); } } } } switchCellToViewMode(element: any) { this.editingCell = null; let cell = this.findCell(element); this.domHandler.removeClass(cell, 'ui-cell-editing'); } closeCell() { if (this.editingCell) { this.domHandler.removeClass(this.editingCell, 'ui-cell-editing'); this.editingCell = null; } } onCellEditorKeydown(event, column: Column, rowData: any, rowIndex: number) { if (this.editable) { this.onEdit.emit({ originalEvent: event, column: column, data: rowData, index: rowIndex }); //enter if (event.keyCode == 13) { this.onEditComplete.emit({ column: column, data: rowData, index: rowIndex }); this.renderer.invokeElementMethod(event.target, 'blur'); this.switchCellToViewMode(event.target); event.preventDefault(); } //escape else if (event.keyCode == 27) { this.onEditCancel.emit({ column: column, data: rowData, index: rowIndex }); this.renderer.invokeElementMethod(event.target, 'blur'); this.switchCellToViewMode(event.target); event.preventDefault(); } //tab else if (event.keyCode == 9) { if (event.shiftKey) this.moveToPreviousCell(event); else this.moveToNextCell(event); } } } moveToPreviousCell(event: KeyboardEvent) { let currentCell = this.findCell(event.target); let row = currentCell.parentElement; let targetCell = this.findPreviousEditableColumn(currentCell); if (targetCell) { this.renderer.invokeElementMethod(targetCell, 'click'); event.preventDefault(); } } moveToNextCell(event: KeyboardEvent) { let currentCell = this.findCell(event.target); let row = currentCell.parentElement; let targetCell = this.findNextEditableColumn(currentCell); if (targetCell) { this.renderer.invokeElementMethod(targetCell, 'click'); event.preventDefault(); } } findPreviousEditableColumn(cell: Element) { let prevCell = cell.previousElementSibling; if (!prevCell) { let previousRow = cell.parentElement.previousElementSibling; if (previousRow) { prevCell = previousRow.lastElementChild; } } if (this.domHandler.hasClass(prevCell, 'ui-editable-column')) return prevCell; else return this.findPreviousEditableColumn(prevCell); } findNextEditableColumn(cell: Element) { let nextCell = cell.nextElementSibling; if (!nextCell) { let nextRow = cell.parentElement.nextElementSibling; if (nextRow) { nextCell = nextRow.firstElementChild; } } if (this.domHandler.hasClass(nextCell, 'ui-editable-column')) return nextCell; else return this.findNextEditableColumn(nextCell); } onCustomEditorFocusPrev(event: KeyboardEvent) { this.moveToPreviousCell(event); } onCustomEditorFocusNext(event: KeyboardEvent) { this.moveToNextCell(event); } findCell(element) { let cell = element; while (cell.tagName != 'TD') { cell = cell.parentElement; } return cell; } initResizableColumns() { this.tbody = this.domHandler.findSingle(this.el.nativeElement, 'tbody.ui-datatable-data'); this.resizerHelper = this.domHandler.findSingle(this.el.nativeElement, 'div.ui-column-resizer-helper'); this.fixColumnWidths(); this.documentColumnResizeListener = this.renderer.listenGlobal('body', 'mousemove', (event) => { if (this.columnResizing) { this.onColumnResize(event); } }); this.documentColumnResizeEndListener = this.renderer.listenGlobal('body', 'mouseup', (event) => { if (this.columnResizing) { this.columnResizing = false; this.onColumnResizeEnd(event); } }); } initColumnResize(event) { let container = this.el.nativeElement.children[0]; let containerLeft = this.domHandler.getOffset(container).left; this.resizeColumn = event.target.parentElement; this.columnResizing = true; this.lastResizerHelperX = (event.pageX - containerLeft); } onColumnResize(event) { let container = this.el.nativeElement.children[0]; let containerLeft = this.domHandler.getOffset(container).left; this.domHandler.addClass(container, 'ui-unselectable-text'); this.resizerHelper.style.height = container.offsetHeight + 'px'; this.resizerHelper.style.top = 0 + 'px'; if (event.pageX > containerLeft && event.pageX < (containerLeft + container.offsetWidth)) { this.resizerHelper.style.left = (event.pageX - containerLeft) + 'px'; } this.resizerHelper.style.display = 'block'; } onColumnResizeEnd(event) { let delta = this.resizerHelper.offsetLeft - this.lastResizerHelperX; let columnWidth = this.resizeColumn.offsetWidth; let newColumnWidth = columnWidth + delta; let minWidth = this.resizeColumn.style.minWidth || 15; if (columnWidth + delta > parseInt(minWidth)) { if (this.columnResizeMode === 'fit') { let nextColumn = this.resizeColumn.nextElementSibling; let nextColumnWidth = nextColumn.offsetWidth - delta; if (newColumnWidth > 15 && nextColumnWidth > 15) { this.resizeColumn.style.width = newColumnWidth + 'px'; if (nextColumn) { nextColumn.style.width = nextColumnWidth + 'px'; } if (this.scrollable) { let colGroup = this.domHandler.findSingle(this.el.nativeElement, 'colgroup.ui-datatable-scrollable-colgroup'); let resizeColumnIndex = this.domHandler.index(this.resizeColumn); colGroup.children[resizeColumnIndex].style.width = newColumnWidth + 'px'; if (nextColumn) { colGroup.children[resizeColumnIndex + 1].style.width = nextColumnWidth + 'px'; } } } } else if (this.columnResizeMode === 'expand') { this.tbody.parentElement.style.width = this.tbody.parentElement.offsetWidth + delta + 'px'; this.resizeColumn.style.width = newColumnWidth + 'px'; let containerWidth = this.tbody.parentElement.style.width; if (this.scrollable) { this.scrollBarWidth = this.scrollBarWidth || this.domHandler.calculateScrollbarWidth(); this.el.nativeElement.children[0].style.width = parseFloat(containerWidth) + this.scrollBarWidth + 'px'; let colGroup = this.domHandler.findSingle(this.el.nativeElement, 'colgroup.ui-datatable-scrollable-colgroup'); let resizeColumnIndex = this.domHandler.index(this.resizeColumn); colGroup.children[resizeColumnIndex].style.width = newColumnWidth + 'px'; } else { this.el.nativeElement.children[0].style.width = containerWidth; } } this.onColResize.emit({ element: this.resizeColumn, delta: delta }); } this.resizerHelper.style.display = 'none'; this.resizeColumn = null; this.domHandler.removeClass(this.el.nativeElement.children[0], 'ui-unselectable-text'); } fixColumnWidths() { let columns = this.domHandler.find(this.el.nativeElement, 'th.ui-resizable-column'); for (let col of columns) { col.style.width = col.offsetWidth + 'px'; } } onColumnDragStart(event) { if (this.columnResizing) { event.preventDefault(); return; } this.draggedColumn = this.findParentHeader(event.target); event.dataTransfer.setData('text', 'b'); // Firefox requires this to make dragging possible } onColumnDragover(event) { if (this.reorderableColumns && this.draggedColumn) { event.preventDefault(); let iconWidth = this.domHandler.getHiddenElementOuterWidth(this.reorderIndicatorUp); let iconHeight = this.domHandler.getHiddenElementOuterHeight(this.reorderIndicatorUp); let dropHeader = this.findParentHeader(event.target); let container = this.el.nativeElement.children[0]; let containerOffset = this.domHandler.getOffset(container); let dropHeaderOffset = this.domHandler.getOffset(dropHeader); if (this.draggedColumn != dropHeader) { let targetLeft = dropHeaderOffset.left - containerOffset.left; let targetTop = containerOffset.top - dropHeaderOffset.top; let columnCenter = dropHeaderOffset.left + dropHeader.offsetWidth / 2; this.reorderIndicatorUp.style.top = dropHeaderOffset.top - containerOffset.top - (iconHeight - 1) + 'px'; this.reorderIndicatorDown.style.top = dropHeaderOffset.top - containerOffset.top + dropHeader.offsetHeight + 'px'; if (event.pageX > columnCenter) { this.reorderIndicatorUp.style.left = (targetLeft + dropHeader.offsetWidth - Math.ceil(iconWidth / 2)) + 'px'; this.reorderIndicatorDown.style.left = (targetLeft + dropHeader.offsetWidth - Math.ceil(iconWidth / 2)) + 'px'; this.dropPosition = 1; } else { this.reorderIndicatorUp.style.left = (targetLeft - Math.ceil(iconWidth / 2)) + 'px'; this.reorderIndicatorDown.style.left = (targetLeft - Math.ceil(iconWidth / 2)) + 'px'; this.dropPosition = -1; } this.reorderIndicatorUp.style.display = 'block'; this.reorderIndicatorDown.style.display = 'block'; } else { event.dataTransfer.dropEffect = 'none'; } } } onColumnDragleave(event) { if (this.reorderableColumns && this.draggedColumn) { event.preventDefault(); this.reorderIndicatorUp.style.display = 'none'; this.reorderIndicatorDown.style.display = 'none'; } } onColumnDrop(event) { event.preventDefault(); if (this.draggedColumn) { let dragIndex = this.domHandler.index(this.draggedColumn); let dropIndex = this.domHandler.index(this.findParentHeader(event.target)); let allowDrop = (dragIndex != dropIndex); if (allowDrop && ((dropIndex - dragIndex == 1 && this.dropPosition === -1) || (dragIndex - dropIndex == 1 && this.dropPosition === 1))) { allowDrop = false; } if (allowDrop) { this.columns.splice(dropIndex, 0, this.columns.splice(dragIndex, 1)[0]); this.onColReorder.emit({ dragIndex: dragIndex, dropIndex: dropIndex, columns: this.columns }); } this.reorderIndicatorUp.style.display = 'none'; this.reorderIndicatorDown.style.display = 'none'; this.draggedColumn.draggable = false; this.draggedColumn = null; this.dropPosition = null; } } initColumnReordering() { this.reorderIndicatorUp = this.domHandler.findSingle(this.el.nativeElement.children[0], 'span.ui-datatable-reorder-indicator-up'); this.reorderIndicatorDown = this.domHandler.findSingle(this.el.nativeElement.children[0], 'span.ui-datatable-reorder-indicator-down'); } findParentHeader(element) { if (element.nodeName == 'TH') { return element; } else { let parent = element.parentElement; while (parent.nodeName != 'TH') { parent = parent.parentElement; } return parent; } } hasFooter() { if (this.footerColumnGroup) { return true; } else { if (this.columns) { for (let i = 0; i < this.columns.length; i++) { if (this.columns[i].footer) { return true; } } } } return false; } isEmpty() { return !this.dataToRender || (this.dataToRender.length == 0); } createLazyLoadMetadata(): LazyLoadEvent { return { first: this.first, rows: this.virtualScroll ? this.rows * 2 : this.rows, sortField: this.sortField, sortOrder: this.sortOrder, filters: this.filters, globalFilter: this.globalFilter ? this.globalFilter.value : null, multiSortMeta: this.multiSortMeta }; } toggleRow(row: any, event?: Event) { if (!this.expandedRows) { this.expandedRows = []; } let expandedRowIndex = this.findExpandedRowIndex(row); if (expandedRowIndex != -1) { this.expandedRows.splice(expandedRowIndex, 1); this.onRowCollapse.emit({ originalEvent: event, data: row }); } else { if (this.rowExpandMode === 'single') { this.expandedRows = []; } this.expandedRows.push(row); this.onRowExpand.emit({ originalEvent: event, data: row }); } if (event) { event.preventDefault(); } } findExpandedRowIndex(row: any): number { let index = -1 if (this.expandedRows) { for (let i = 0; i < this.expandedRows.length; i++) { if (this.expandedRows[i] == row) { index = i; break; } } } return index; } isRowExpanded(row: any): boolean { return this.findExpandedRowIndex(row) != -1; } findExpandedRowGroupIndex(row: any): number { let index = -1; if (this.expandedRowsGroups && this.expandedRowsGroups.length) { for (let i = 0; i < this.expandedRowsGroups.length; i++) { let group = this.expandedRowsGroups[i]; let rowGroupField = this.resolveFieldData(row, this.groupField); if (rowGroupField === group) { index = i; break; } } } return index; } isRowGroupExpanded(row: any): boolean { return this.findExpandedRowGroupIndex(row) != -1; } toggleAllRowGroup(event: Event, expand: boolean): void { if (this.rowGroupMetadata) { let groups = Object.keys(this.rowGroupMetadata); this.expandedRowsGroups = []; if (expand) { groups.forEach(row => { this.expandedRowsGroups.push(row); }); } } } toggleRowGroup(event: Event, row: any): void { this.rowGroupToggleClick = true; let index = this.findExpandedRowGroupIndex(row); let rowGroupField = this.resolveFieldData(row, this.groupField); if (index >= 0) { this.expandedRowsGroups.splice(index, 1); //this.onRowGroupCollapse.emit({ // originalEvent: event, // group: rowGroupField //}); } else { this.expandedRowsGroups = this.expandedRowsGroups || [], this.expandedRowsGroups.push(rowGroupField); // this.onRowGroupExpand.emit({ // originalEvent: event, // group: rowGroupField // }); } event.preventDefault(); } public reset() { this.sortField = null; this.sortOrder = 1; this.filteredValue = null; this.filters = {}; if (this.paginator) { this.paginate({ first: 0, rows: this.rows }); } else { this.updateDataToRender(this.value); } } public exportCSV(filter?: any) { let data = ((typeof (this.filteredValue) != "undefined" && this.filteredValue != null) && filter == true) ? this.filteredValue : this.value; let csv = '\ufeff'; let exportColumns = this.columns.filter(c => c.exportColumn != false); //headers for (let i = 0; i < exportColumns.length; i++) { if (exportColumns[i].field) { csv += exportColumns[i].header || exportColumns[i].field; if (i < (exportColumns.length - 1)) { csv += this.csvSeparator; } } } //body data.forEach((record, i) => { csv += '\n'; for (let i = 0; i < exportColumns.length; i++) { if (exportColumns[i].field) { csv += '"' + this.resolveFieldData(record, exportColumns[i].field) + '"'; if (i < (exportColumns.length - 1)) { csv += this.csvSeparator; } } } }); let blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveOrOpenBlob(blob, this.exportFilename + '.csv'); } else { let link = document.createElement("a"); link.style.display = 'none'; document.body.appendChild(link); if (link.download !== undefined) { link.setAttribute('href', URL.createObjectURL(blob)); link.setAttribute('download', this.exportFilename + '.csv'); document.body.appendChild(link); link.click(); } else { csv = 'data:text/csv;charset=utf-8,' + csv; window.open(encodeURI(csv)); } document.body.removeChild(link); } } getBlockableElement(): HTMLElement { return this.el.nativeElement.children[0]; } getRowStyleClass(rowData: any, rowIndex: number) { let styleClass = 'ui-widget-content'; if (this.rowStyleClass) { let rowClass = this.rowStyleClass.call(this, rowData, rowIndex); if (rowClass) { styleClass += ' ' + rowClass; } } return styleClass; } // Excel Export transformData(filter?: any): Array<any> { let data = ((typeof (this.filteredValue) != "undefined" && this.filteredValue != null) && filter == true) ? this.filteredValue : this.value; let exportColumns = this.columns.filter(c => c.exportColumn != false); let data_array: any[] = []; let result_array: any[] = []; //headers for (let i = 0; i < exportColumns.length; i++) { if (exportColumns[i].field) { result_array.push(exportColumns[i].header || exportColumns[i].field); if (i == (exportColumns.length - 1)) { data_array.push(result_array); result_array = []; } } } //body data.forEach((record, j) => { let result_arr: any[] = []; for (let i = 0; i < exportColumns.length; i++) { if (exportColumns[i].field) { result_arr.push(this.resolveFieldData(record, exportColumns[i].field)); if (i == (exportColumns.length - 1)) { data_array.push(result_arr); } } } }); let res_columnsum: any = []; for (let j = 0; j < exportColumns.length; j++) { if (exportColumns[j].displaysum) { if (!this.displaysum) { this.displaysum = true; } let hours: number = 0; let minutes: number = 0; let seconds: number = 0; // console.log('sum column'); let columnsum: number = 0; let isNumber: boolean; for (let i = 1; i < data_array.length; i++) { let value = data_array[i][j]; if (!isNaN(Number(value))) { if (!isNumber) { isNumber = true; } if (!columnsum) { columnsum = 0; } columnsum = columnsum + parseFloat(value); } else if (this.durationvalue(value)) { var duration: any = value.split(":"); hours = hours + parseInt(duration[0]); minutes = minutes + parseInt(duration[1]); seconds = seconds + parseInt(duration[2]); // Convert each 60 minutes to an hour if (minutes >= 60) { hours++; minutes -= 60; } // Convert each 60 seconds to a minute if (seconds >= 60) { minutes++; seconds -= 60; } } } if (isNumber) { if (columnsum % 1 != 0) { res_columnsum.push(columnsum.toFixed(2)); } else { res_columnsum.push(columnsum); } } else if (hours || minutes || seconds) { res_columnsum.push(hours + ":" + minutes + ":" + seconds); } else { res_columnsum.push(0); } } else { res_columnsum.push(""); } if (j == (exportColumns.length - 1) && this.displaysum) { let indexOfFirstFilledcolumn = res_columnsum.findIndex(c => c || c === 0); if (indexOfFirstFilledcolumn > 0 && res_columnsum[indexOfFirstFilledcolumn - 1].length == 0) { res_columnsum[indexOfFirstFilledcolumn - 1] = 'Total'; } data_array.push(res_columnsum); } } // let headerData: Array<any> = []; // let dataNew: Array<any> = []; // var keys_arr: any = []; // let excel_data: any; // if (data instanceof DataTable) { // excel_data = data.value; // } // else { // excel_data = data; // } //_.forEach(this.data.headerColumnGroup.rows._results, function (value: any, index: any) { // console.log(value.columns._results); // value.columns._results.forEach((c:any) => { // headerData.push({ colspan: c['colspan'], header: c['header'], rowspan: c['rowspan']}); // }) //}); //console.log(headerData); // debugger; // _.forEach(data, function(json) { // var arr = _.filter(json, function(value: any, index: any) { // if (typeof value !== "object") { // keys_arr.push(_.startCase(index)); // return value; // } // }); // dataNew.push(arr); // }); // dataNew.unshift(_.uniq(keys_arr)); return data_array; } sheet_from_array_of_arrays(data: any) { var ws = {}; var endCell = { c: 10000000, r: 10000000 }; var startCell = { c: 0, r: 0 }; var range = { s: endCell, e: startCell }; var wscols = []; var sumormaulcellRange: {} for (var R = 0; R != data.length; ++R) { for (var C = 0; C != data[R].length; ++C) { wscols.push({ wch: 20 }); if (range.s.r > R) range.s.r = R; if (range.s.c > C) range.s.c = C; if (range.e.r < R) range.e.r = R; if (range.e.c < C) range.e.c = C; var cell = { v: data[R][C], t: 's', s: {} }; if (R === 0) { cell.s = { fill: { fgColor: { rgb: "00BFFF" } }, font: { bold: true, sz: '11' }, border: { bottom: { style: 'thin', color: { rgb: "000000" } }, top: { style: 'thin', color: { rgb: "000000" } }, left: { style: 'thin', color: { rgb: "000000" } }, right: { style: 'thin', color: { rgb: "000000" } } } }; } else if (this.displaysum && R === (data.length - 1)) { cell.t = 'n'; cell.s = { font: { bold: true, sz: '11' }, border: { bottom: { style: 'thin', color: { rgb: "000000" } }, top: { style: 'thin', color: { rgb: "000000" } }, left: { style: 'thin', color: { rgb: "000000" } }, right: { style: 'thin', color: { rgb: "000000" } } } }; } else if ((R === (data.length - 1) && !this.displaysum) || (R === (data.length - 2) && this.displaysum)) { cell.s = { border: { bottom: { style: 'thin', color: { rgb: "000000" } }, top: { style: 'thin', color: { rgb: "000000" } }, left: { style: 'thin', color: { rgb: "000000" } }, right: { style: 'thin', color: { rgb: "000000" } } } }; } else if (cell.v && cell.v.toString().toLowerCase().indexOf('\n') !== -1) { cell.s = { alignment: { wrapText: true }, border: { bottom: { style: 'thin', color: { rgb: "000000" } }, top: { style: 'thin', color: { rgb: "000000" } }, left: { style: 'thin', color: { rgb: "000000" } }, right: { style: 'thin', color: { rgb: "000000" } } } }; } else { cell.s = { border: { bottom: { style: 'thin', color: { rgb: "000000" } }, top: { style: 'thin', color: { rgb: "000000" } }, left: { style: 'thin', color: { rgb: "000000" } }, right: { style: 'thin', color: { rgb: "000000" } } } }; } //convert null value to empty string if (cell.v == null) cell.v = " "; var cell_ref = XLSX.utils.encode_cell({ c: C, r: R }); if (typeof cell.v === 'number') cell.t = 'n'; else if (typeof cell.v === 'boolean') cell.t = 'b'; else if (cell.t === 'n' && !isNaN(Number(cell.v))) cell.t = 'n'; else cell.t = 's'; ws[cell_ref] = cell; } } // ws['!cols'] = wscols; // console.log("Worksheet goes here", ws); if (range.s.c < 10000000) { ws['!ref'] = XLSX.utils.encode_range(endCell, startCell); } return ws; } datenum(v: any, date1904?: any): any { if (date1904) v += 1462; var epoch = Date.parse(v); var dt: any = new Date(Date.UTC(1899, 11, 30)); return (epoch - dt) / (24 * 60 * 60 * 1000); } durationvalue(v: any) { var patt = new RegExp("\d+:\d{2}:\d{2}$"); return patt.compile().test(v); } generateExcelFile(filter?: any): any { var dstyle = { font: { name: 'arial', sz: '10' } }; let sheetName: string = this.exportFilename; let workbook: { Sheets: {}, SheetNames: any[], Props: {} } = { Sheets: {}, SheetNames: [], Props: {} }; let ws: any; let wbout: any; ws = this.sheet_from_array_of_arrays(this.transformData(filter)); workbook.SheetNames.push(sheetName); workbook.Sheets[sheetName] = ws; wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary', showGridLines: false, defaultCellStyle: dstyle }); return wbout; } s2ab(s: any): ArrayBuffer { var buf = new ArrayBuffer(s.length); var view = new Uint8Array(buf); for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } exportExcel(filter?: any): void { FileSaver.saveAs(new Blob([this.s2ab(this.generateExcelFile(filter))], { type: "application/octet-stream" }), this.exportFilename + ".xlsx"); } visibleColumns() { return this.columns ? this.columns.filter(c => !c.hidden) : []; } initialPerUnfrozenWidth: number; calculateUnforzenWidth() { if (this.resizeTimeout) { clearTimeout(this.resizeTimeout); } this.resizeTimeout = setTimeout(() => { if (this.unfrozenWidth && this.isWidthinPercentage(this.unfrozenWidth)) { this.initialPerUnfrozenWidth = this.initialPerUnfrozenWidth > 0 ? this.initialPerUnfrozenWidth : parseFloat(this.unfrozenWidth); let actualWidth = this.calculatePerWidth(this.initialPerUnfrozenWidth, true); let widthDifference = (parseFloat(this.frozenWidth) / parseFloat(actualWidth)) * 100; let calWidth = (this.initialPerUnfrozenWidth - widthDifference); this.unfrozenWidth = calWidth + '%'; } }, 200); } // get containerWidth() { // // if(this.scrollable) { // if(this.scrollWidth) { // // /*Custom Code Added to calculate width in %*/ // var width=this.scrollWidth; // var hasPx = width.indexOf('px') >= 0; // var hasPct = width.indexOf('%') >= 0; // if(hasPct){ // var gridwidth= document.getElementsByClassName("ui-datatable-scrollable-header-box")[0].clientWidth; // if(gridwidth) // { // width=width.replace('%',''); // width=Math.ceil(gridwidth*width/100); // width=width+'px'; // } // } // return width; // } // else if(this.frozenWidth && this.unfrozenWidth) { // debugger; // return parseFloat(this.frozenWidth) + parseFloat(this.unfrozenWidth) + 'px'; // } // } // else { // return this.style ? this.style.width : null; // } // } // isforzenWidthInit:boolean; // get containerWidth() { // if (this.scrollable) { // if (this.scrollWidth) { // return this.scrollWidth; // } // else if (this.frozenWidth && this.unfrozenWidth) { // if(!this.isforzenWidthInit){ // debugger // this.calculateUnforzenWidth(); // } // // let actualWidth=this.calculatePerWidth(this.unfrozenWidth,true); // // this.unfrozenWidth=(this.frozenWidth/actualWidth)*100; // // // if (this.isWidthinPercentage(this.unfrozenWidth)) { // // // this.unfrozenWidth = this.calculatePerWidth(this.unfrozenWidth, true);// - parseFloat(this.frozenWidth); // // return parseFloat(this.unfrozenWidth); // // } // // return parseFloat(this.frozenWidth) + parseFloat(actualWidth) + 'px'; // } // } // else { // return this.style ? this.style.width : null; // } // } isWidthinPercentage(width: any) { return typeof width == 'string' ? width.indexOf('%') >= 0 : true; } calculatePerWidth(width: any, forzen: boolean) { if (this.isWidthinPercentage(width)) { let element: any; let gridwidth = this.el.nativeElement.firstElementChild.clientWidth; if (gridwidth) { width = typeof width == 'string' ? width.replace('%', '') : width; width = Math.ceil(gridwidth * width / 100); width = (width - 19) + 'px'; } } return width; } ngOnDestroy() { //remove event listener if (this.globalFilterFunction) { this.globalFilterFunction(); } if (this.resizableColumns && this.documentColumnResizeListener && this.documentColumnResizeEndListener) { this.documentColumnResizeListener(); this.documentColumnResizeEndListener(); } if (this.documentClickListener) { this.documentClickListener(); } if (this.columnsSubscription) { this.columnsSubscription.unsubscribe(); } } } @NgModule({ imports: [CommonModule, SharedModule, PaginatorModule, FormsModule], exports: [DataTable, SharedModule], declarations: [DataTable, DTRadioButton, DTCheckbox, ColumnHeaders, ColumnFooters, TableBody, ScrollableView, RowExpansionLoader] }) export class DataTableModule { }
rohitsindhu90/Primeng-custom-4.0.0.0-rc3
components/datatable/datatable.ts
TypeScript
mit
101,388
/* * * The MIT License * * Copyright (c) 2015, Sebastian Sdorra * * 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. */ 'use strict'; angular.module('sample-01', ['adf', 'LocalStorageModule']) .controller('sample01Ctrl', function($scope, localStorageService){ var name = 'sample-01'; var model;// = localStorageService.get(name); if (!model) { // set default model for demo purposes model = { title: "Sample 01", structure: "4-4-4", rows: [{ columns: [{ styleClass: "col-md-4", widgets: [{ type: "Pie" }] }, { styleClass: "col-md-4", widgets: [{ type: "Pie" }] },{ styleClass: "col-md-4", widgets: [{ type: "Pie" }] }] }] }; } $scope.name = name; $scope.model = model; $scope.collapsible = false; $scope.maximizable = false; $scope.$on('adfDashboardChanged', function (event, name, model) { localStorageService.set(name, model); }); });
AjithVas/ACP
sample/scripts/sample-01.js
JavaScript
mit
2,096
module VirusGame { export const enum CellState { Empty, Alive, Dead }; export class BoardCell extends Phaser.Image { state: CellState = CellState.Empty; player: BoardPlayer; isPossibleToMoveTo: boolean = false; constructor(public row: number, public col: number, public board_game: BoardGame) { super(board_game.game, 0, 0, 'board_cells', 'grey_box'); this.inputEnabled = true; this.input.useHandCursor = true; this.events.onInputOver.add(this.drawUnderPointer, this); this.events.onInputOut.add(this.drawNormal, this); this.events.onInputUp.add(function() { if (this.board_game.current_player.is_local_player) this.cellPlayed(); }, this); } setState(state, player) { this.state = state; this.player = player; switch (this.state) { case CellState.Alive: this.frameName = this.player.color + '_boxCross'; break; case CellState.Dead: this.frameName = this.player.color + '_boxCheckmark'; break; } } cellPlayed(opponentTurn?) { if (this.board_game.isTurnLegal(this.row, this.col)) { switch (this.state) { case CellState.Empty: this.frameName = this.board_game.current_player_color + '_boxCross'; this.state = CellState.Alive; this.player = this.board_game.current_player; this.board_game.endTurn(); if (!opponentTurn) client.player_move(this.board_game.id,this.row,this.col,1,this.board_game.left_turn_cells,this.board_game.current_player_number,this.player.state,0); break; case CellState.Alive: this.frameName = this.board_game.current_player_color + '_boxCheckmark'; this.state = CellState.Dead; this.player = this.board_game.current_player; this.board_game.endTurn(); if (!opponentTurn) client.player_move(this.board_game.id,this.row,this.col,2,this.board_game.left_turn_cells,this.board_game.current_player_number,this.player.state,0); break; case CellState.Dead: break; } } } drawNormal() { if(this.isPossibleToMoveTo) this.tint = 0xabcdef; else this.tint = 0xffffff; } drawUnderPointer() { this.tint = 0xaaaaaa; } makePossibleToMoveTo() { this.isPossibleToMoveTo = true; this.drawNormal(); } disablePossibleToMoveTo() { this.isPossibleToMoveTo = false; this.drawNormal(); } } }
asyler/virus-game
game/BoardCell.ts
TypeScript
mit
3,199
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # 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. # __revision__ = "test/Execute.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" """ Test the Execute() function for executing actions directly. """ import TestSCons _python_ = TestSCons._python_ test = TestSCons.TestSCons() test.write('my_copy.py', """\ import sys open(sys.argv[2], 'wb').write(open(sys.argv[1], 'rb').read()) try: exitval = int(sys.argv[3]) except IndexError: exitval = 0 sys.exit(exitval) """) test.write('SConstruct', """\ Execute(r'%(_python_)s my_copy.py a.in a.out') Execute(Action(r'%(_python_)s my_copy.py b.in b.out')) env = Environment(COPY = 'my_copy.py') env.Execute(r'%(_python_)s my_copy.py c.in c.out') env.Execute(Action(r'%(_python_)s my_copy.py d.in d.out')) v = env.Execute(r'%(_python_)s $COPY e.in e.out') assert v == 0, v v = env.Execute(Action(r'%(_python_)s $COPY f.in f.out')) assert v == 0, v v = env.Execute(r'%(_python_)s $COPY g.in g.out 1') assert v == 1, v v = env.Execute(Action(r'%(_python_)s $COPY h.in h.out 2')) assert v == 2, v import shutil Execute(lambda target, source, env: shutil.copy('i.in', 'i.out')) Execute(Action(lambda target, source, env: shutil.copy('j.in', 'j.out'))) env.Execute(lambda target, source, env: shutil.copy('k.in', 'k.out')) env.Execute(Action(lambda target, source, env: shutil.copy('l.in', 'l.out'))) Execute(Copy('m.out', 'm.in')) Execute(Copy('nonexistent.out', 'nonexistent.in')) """ % locals()) test.write('a.in', "a.in\n") test.write('b.in', "b.in\n") test.write('c.in', "c.in\n") test.write('d.in', "d.in\n") test.write('e.in', "e.in\n") test.write('f.in', "f.in\n") test.write('g.in', "g.in\n") test.write('h.in', "h.in\n") test.write('i.in', "i.in\n") test.write('j.in', "j.in\n") test.write('k.in', "k.in\n") test.write('l.in', "l.in\n") test.write('m.in', "m.in\n") import sys if sys.platform == 'win32': expect = r"""scons: \*\*\* Error 1 scons: \*\*\* Error 2 scons: \*\*\* nonexistent.in/\*\.\*: (The system cannot find the path specified|Das System kann den angegebenen Pfad nicht finden)""" else: expect = r"""scons: \*\*\* Error 1 scons: \*\*\* Error 2 scons: \*\*\* nonexistent\.in: No such file or directory""" test.run(arguments = '.', stdout = None, stderr = None) test.must_contain_all_lines(test.stderr(), expect.splitlines(), find=TestSCons.search_re) test.must_match('a.out', "a.in\n") test.must_match('b.out', "b.in\n") test.must_match('c.out', "c.in\n") test.must_match('d.out', "d.in\n") test.must_match('e.out', "e.in\n") test.must_match('f.out', "f.in\n") test.must_match('g.out', "g.in\n") test.must_match('h.out', "h.in\n") test.must_match('i.out', "i.in\n") test.must_match('j.out', "j.in\n") test.must_match('k.out', "k.in\n") test.must_match('l.out', "l.in\n") test.must_match('m.out', "m.in\n") test.pass_test() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
EmanueleCannizzaro/scons
test/Execute.py
Python
mit
4,013
using System; 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("ModelGraph")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ModelGraph")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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")] [assembly: ComVisible(false)]
davetz/ModelGraph
ModelGraph/ModelGraph/Properties/AssemblyInfo.cs
C#
mit
1,052
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var app = new EmberApp(); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/modernizr/modernizr.js'); module.exports = app.toTree();
surreymagpie/club
client/Brocfile.js
JavaScript
mit
763
"use strict"; var CropTouch = (function () { function CropTouch(x, y, id) { this.id = id || 0; this.x = x || 0; this.y = y || 0; this.dragHandle = null; } return CropTouch; }()); exports.CropTouch = CropTouch; //# sourceMappingURL=cropTouch.js.map
ToruHyuga/angular2-img-cropper-v2
src/model/cropTouch.js
JavaScript
mit
291
(function () { 'use strict'; angular .module('Debug', ['pullrefresh']); })();
stomt/angular-pullrefresh
debug/debug-app.js
JavaScript
mit
87
<?php namespace Yadakhov; use mikehaertl\shellcommand\Command; /** * A simple wrapper class for Tor * @package Yadakhov */ class Tor { public function __construct() { if (!$this->isRunning()) { $this->command('start'); } } /** * Execute tor command * * @param $command * @return Command|string */ public function command($command) { if (!in_array($command, ['start', 'stop', 'restart', 'reload', 'force-reload', 'status'])) { throw new \InvalidArgumentException($command); } $command = 'sudo /etc/init.d/tor '.$command; $command = new Command($command); $command->execute(); return $command; } /** * Start * * @return Command|string */ public function start() { $command = $this->command('start'); return $command; } /** * Stop * * @return Command|string */ public function stop() { $command = $this->command('stop'); return $command; } /** * Restart * * @return Command|string */ public function restart() { $command = $this->command('restart'); return $command; } /** * Reload * * @return Command|string */ public function reload() { $command = $this->command('reload'); return $command; } /** * Force Reload * @return Command|string */ public function forceReload() { $command = $this->command('force-reload'); return $command; } /** * Status * @return Command|string */ public function status() { $command = $this->command('status'); return $command; } /** * Return true if tor is running * * @return bool */ public function isRunning() { $command = $this->command('status'); return $command->getOutput() === '* tor is running'; } /** * Reload for a new ip number * * @return bool */ public function newIp() { $command = $this->command('reload'); return $command->getExitCode() === 0; } /** * Tor curl wrapper * @param $url * @return bool|mixed */ public function curl($url) { $ip = '127.0.0.1'; $port = '9051'; $auth = 'PASSWORD'; $command = 'signal NEWNYM'; $fp = fsockopen($ip, $port, $error_number, $err_string, 2); if (!$fp) { echo "ERROR: $error_number : $err_string"; return false; } else { fwrite($fp, "AUTHENTICATE \"".$auth."\"\n"); fread($fp, 512); fwrite($fp, $command."\n"); fread($fp, 512); } fclose($fp); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:9050'); curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent()); // $this->getUserAgent(true) for random); curl_setopt($ch, CURLOPT_ENCODING , 'gzip'); $response = curl_exec($ch); return [$response, $ch]; } /** * Get a user agent * * @param bool $random * @return string */ public function getUserAgent($random = false) { if ($random === false) { return 'Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0'; } $headers = [ 'Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20120101 Firefox/29.0', ]; $randomKey = array_rand($headers); return $headers[$randomKey]; } }
yadakhov/tor
src/Tor.php
PHP
mit
4,631
module.exports = function(knex) { describe('Transactions', function() { it('should be able to commit transactions', function(ok) { var id = null; return knex.transaction(function(t) { knex('accounts') .transacting(t) .returning('id') .insert({ first_name: 'Transacting', last_name: 'User', email:'transaction-test@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date() }).then(function(resp) { return knex('test_table_two').transacting(t).insert({ account_id: (id = resp[0]), details: '', status: 1 }); }).then(function() { t.commit('Hello world'); }); }).then(function(commitMessage) { expect(commitMessage).to.equal('Hello world'); return knex('accounts').where('id', id).select('first_name'); }).then(function(resp) { expect(resp).to.have.length(1); }).otherwise(function(err) { console.log(err); }); }); it('should be able to rollback transactions', function(ok) { var id = null; var err = new Error('error message'); return knex.transaction(function(t) { knex('accounts') .transacting(t) .returning('id') .insert({ first_name: 'Transacting', last_name: 'User2', email:'transaction-test2@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date() }).then(function(resp) { return knex('test_table_two').transacting(t).insert({ account_id: (id = resp[0]), details: '', status: 1 }); }).then(function() { t.rollback(err); }); }).otherwise(function(msg) { expect(msg).to.equal(err); return knex('accounts').where('id', id).select('first_name'); }).then(function(resp) { expect(resp).to.be.empty; }); }); }); };
viniborges/designizando
node_modules/knex/test/integration/builder/transaction.js
JavaScript
mit
2,294
<?php namespace PhpParser\Node\Scalar; use PhpParser\Node\Scalar; /** * @property array $parts Encaps list */ class Encapsed extends Scalar { /** * Constructs an encapsed string node. * * @param array $parts Encaps list * @param array $attributes Additional attributes */ public function __construct(array $parts = array(), array $attributes = array()) { parent::__construct( array( 'parts' => $parts ), $attributes ); } }
Amaire/filmy
vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Encapsed.php
PHP
mit
532
// Source file for alignment utility functions // Include files #include "R3Shapes.h" // Namespace namespace gaps { R3Box R3BoundingBox(const RNArray<R3Point *>& points) { // Compute bounding box R3Box bbox = R3null_box; for (int i = 0; i < points.NEntries(); i++) { bbox.Union(*points[i]); } // Return bounding box return bbox; } R3Point R3Centroid(const RNArray<R3Point *>& points, const RNScalar *weights) { // Compute center of mass R3Point centroid(0.0, 0.0, 0.0); RNScalar total_weight = 0; for (int i = 0; i < points.NEntries(); i++) { RNScalar weight = (weights) ? weights[i] : 1; R3Point *point = points[i]; centroid += *point * weight; total_weight += weight; } // Compute average if (total_weight > 0) centroid /= total_weight; // Return center of mass return centroid; } R3Triad R3PrincipleAxes(const R3Point& centroid, const RNArray<R3Point *>& points, const RNScalar *weights, RNScalar *variances) { // Compute covariance matrix RNScalar m[9] = { 0 }; RNScalar total_weight = 0; for (int i = 0; i < points.NEntries(); i++) { RNScalar weight = (weights) ? weights[i] : 1; RNScalar x = points[i]->X() - centroid[0]; RNScalar y = points[i]->Y() - centroid[1]; RNScalar z = points[i]->Z() - centroid[2]; m[0] += weight * x*x; m[1] += weight * x*y; m[2] += weight * x*z; m[3] += weight * y*x; m[4] += weight * y*y; m[5] += weight * y*z; m[6] += weight * z*x; m[7] += weight * z*y; m[8] += weight * z*z; total_weight += weight; } // Normalize covariance matrix if (total_weight == 0) return R3xyz_triad; for (int i = 0; i < 9; i++) { m[i] /= total_weight; } // Calculate SVD of second order moments RNScalar U[9]; RNScalar W[3]; RNScalar Vt[9]; RNSvdDecompose(3, 3, m, U, W, Vt); // m == U . DiagonalMatrix(W) . Vt // Principle axes are in Vt R3Vector axes[3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { axes[i][j] = Vt[3*i+j]; } } // Normalize all axis vectors (probably not necessary) RNLength length0 = axes[0].Length(); RNLength length1 = axes[1].Length(); RNLength length2 = axes[2].Length(); if (RNIsPositive(length0)) axes[0] /= length0; if (RNIsPositive(length1)) axes[1] /= length1; if (RNIsPositive(length2)) axes[2] /= length2; // Flip axes so that "heavier" on positive side int positive_count[3] = { 0, 0, 0 }; int negative_count[3] = { 0, 0, 0 }; for (int i = 0; i < points.NEntries(); i++) { R3Point *point = points[i]; for (int j = 0; j < 3; j++) { RNScalar dot = axes[j].Dot(point->Vector()); if (dot > 0.0) positive_count[j]++; else negative_count[j]++; } } for (int j =0; j < 3; j++) { if (positive_count[j] < negative_count[j]) { axes[j].Flip(); } } // Compute orthonormal triad of axes axes[2] = axes[0] % axes[1]; // Just checking assert(RNIsEqual(axes[0].Length(), 1.0, RN_BIG_EPSILON)); assert(RNIsEqual(axes[1].Length(), 1.0, RN_BIG_EPSILON)); assert(RNIsEqual(axes[2].Length(), 1.0, RN_BIG_EPSILON)); assert(RNIsZero(axes[0].Dot(axes[1]), RN_BIG_EPSILON)); assert(RNIsZero(axes[1].Dot(axes[2]), RN_BIG_EPSILON)); assert(RNIsZero(axes[0].Dot(axes[2]), RN_BIG_EPSILON)); // Return variances (eigenvalues) if (variances) { variances[0] = W[0]; variances[1] = W[1]; variances[2] = W[2]; } // Return triad of axes return R3Triad(axes[0], axes[1], axes[2]); } RNLength R3AverageDistance(const R3Point& center, const RNArray<R3Point *>& points, const RNScalar *weights) { // Compute sum of distances between a position on the surface and a center point RNScalar distance = 0.0; RNScalar total_weight = 0; for (int i = 0; i < points.NEntries(); i++) { RNScalar weight = (weights) ? weights[i] : 1; R3Point *point = points[i]; distance += weight * R3Distance(*point, center); total_weight += weight; } // Compute average distance if (total_weight > 0) distance /= total_weight; // Return average distance return distance; } R3Affine R3NormalizationTransformation(const RNArray<R3Point *>& points, RNBoolean translate, RNBoolean rotate, int scale) { // Initialize transformation R3Affine affine(R3identity_affine); // Compute center of mass R3Point centroid = R3Centroid(points); // Translate center of mass back to original (if not translating) if (!translate) { affine.Translate(centroid.Vector()); } // Scale by inverse of radius if ((scale != 0) && (scale != 2)) { RNScalar radius = R3AverageDistance(centroid, points); if (RNIsPositive(radius)) affine.Scale(1.0 / radius); } // Rotate to align principal axes with XYZ if (rotate || (scale == 2)) { RNScalar variances[3] = { 0 }; R3Triad triad = R3PrincipleAxes(centroid, points, variances); if (!rotate) affine.Transform(R3Affine(triad.InverseMatrix())); if (scale == 2) { if (variances[0] > 0) affine.XScale(1.0 / variances[0]); if (variances[1] > 0) affine.YScale(1.0 / variances[1]); if (variances[2] > 0) affine.ZScale(1.0 / variances[2]); } affine.Transform(R3Affine(triad.InverseMatrix())); } // Translate center of mass to origin affine.Translate(-(centroid.Vector())); // Return normalization transformation return affine; } static R4Matrix SetQuaternion(RNScalar p[4]) { R4Matrix m(R4identity_matrix); RNScalar l; if(p[0]<0){ p[0]=-p[0]; p[1]=-p[1]; p[2]=-p[2]; p[3]=-p[3]; } l=p[0]*p[0]+p[1]*p[1]+p[2]*p[2]+p[3]*p[3]; if(l<.000001){return R4identity_matrix;} l=sqrt(l); p[0]/=l; p[1]/=l; p[2]/=l; p[3]/=l; m[0][0]=p[0]*p[0]+p[1]*p[1]-p[2]*p[2]-p[3]*p[3]; m[0][1]=2*(p[1]*p[2]+p[0]*p[3]); m[0][2]=2*(p[1]*p[3]-p[0]*p[2]); m[1][0]=2*(p[1]*p[2]-p[0]*p[3]); m[1][1]=p[0]*p[0]+p[2]*p[2]-p[1]*p[1]-p[3]*p[3]; m[1][2]=2*(p[2]*p[3]+p[0]*p[1]); m[2][0]=2*(p[1]*p[3]+p[0]*p[2]); m[2][1]=2*(p[2]*p[3]-p[0]*p[1]); m[2][2]=p[0]*p[0]+p[3]*p[3]-p[1]*p[1]-p[2]*p[2]; return m; } RNScalar R3AlignError(const RNArray<R3Point *>& points1, const RNArray<R3Point *>& points2, const R4Matrix& rotation, const R3Point& center1, const R3Point& center2, RNScalar s1, RNScalar s2, const RNScalar* weights) { // Get number of points int count = points1.NEntries(); if (points2.NEntries() < count) count = points2.NEntries(); if (count == 0) return -1; // Compute sum of squared distances RNScalar ssd = 0; RNScalar total_weight = 0; for(int i = 0; i < count; i++) { RNScalar weight = (weights) ? weights[i] : 1; R3Point *point1 = points1[i]; R3Point *point2 = points2[i]; R3Vector v1 = (*point1 - center1) / s1; R3Vector v2 = (*point2 - center2) / s2; R3Vector v = v1 - rotation * v2; ssd += weight * v.Dot(v); total_weight += weight; } // Return RMSD if (total_weight == 0) return -1; return sqrt(ssd / total_weight); } RNScalar R3AlignError(const RNArray<R3Point *>& points1, const RNArray<R3Point *>& points2, const R4Matrix& matrix, const RNScalar* weights) { // Get number of points int count = points1.NEntries(); if (points2.NEntries() < count) count = points2.NEntries(); if (count == 0) return -1; // Compute sum of squared distances RNScalar ssd = 0; RNScalar total_weight = 0; for (int i = 0; i < count; i++) { RNScalar weight = (weights) ? weights[i] : 1; R3Point *point1 = points1[i]; R3Point point2 = *(points2[i]); point2 = matrix * point2; R3Vector v = *point1 - point2; ssd += weight * v.Dot(v); total_weight += weight; } // Return RMSD if (total_weight == 0) return -1; return sqrt(ssd / total_weight); } R4Matrix R3AlignPoints(const RNArray<R3Point *>& points1, const RNArray<R3Point *>& points2, const RNScalar* weights, RNBoolean align_center, RNBoolean align_rotation, int align_scale) { int i,j,k; // Get count of points int count = points1.NEntries(); if (points2.NEntries() < count) count = points2.NEntries(); // Check number of points if (count < 1) align_center = 0; if (count < 2) align_scale = 0; if (count < 3) align_rotation = 0; // Compute centers R3Point center1(0.0, 0.0, 0.0); R3Point center2(0.0, 0.0, 0.0); if (align_center){ center1 = R3Centroid(points1, weights); center2 = R3Centroid(points2, weights); } // Compute scales RNScalar s1 = 1; RNScalar s2 = 1; if (align_scale){ s1 = R3AverageDistance(center1, points1, weights); s2 = R3AverageDistance(center2, points2, weights); } // Compute cross-covariance of two point sets R4Matrix rotation = R4identity_matrix; if (align_rotation) { R4Matrix m = R4identity_matrix; m[0][0] = m[1][1] = m[2][2] = 0; RNScalar total_weight = 0; for (i=0; i< count; i++){ RNScalar weight = (weights) ? weights[i] : 1; total_weight += weight; R3Point *point1 = points1[i]; R3Point *point2 = points2[i]; R3Vector p1 = (*point1 - center1) / s1; R3Vector p2 = (*point2 - center2) / s2; for(j=0;j<3;j++){ for(k=0;k<3;k++){ m[j][k] += weight * p1[j]*p2[k]; } } } // Normalize cross-covariance matrix if (total_weight == 0) return R4identity_matrix; for(j=0;j<3;j++){for(k=0;k<3;k++){ m[j][k] /= total_weight; } } // Make cross-covariance matrix skew-symmetric R4Matrix a = R4identity_matrix; for(j=0;j<3;j++){for(k=0;k<3;k++){a[j][k]=m[j][k]-m[k][j];}} // Compute trace of cross-covariance matrix RNScalar trace=m[0][0]+m[1][1]+m[2][2]; // Setup symmetric matrix whose eigenvectors give quaternion terms of optimal rotation RNScalar M[16]; M[0]=trace; M[1]=M[4]=a[1][2]; M[2]=M[8]=a[2][0]; M[3]=M[12]=a[0][1]; for(j=0;j<3;j++){ for(k=0;k<3;k++){M[4*(j+1)+(k+1)]=m[j][k]+m[k][j];} M[4*(j+1)+(j+1)]-=trace; } // Perform SVD to get eigenvectors (quaternion terms of optimal rotation) RNScalar U[16]; RNScalar W[4]; RNScalar Vt[16]; RNSvdDecompose(4, 4, M, U, W, Vt); // Look at error using all eigenvectors and keep best int minI=0; R4Matrix temp[4]; RNScalar e[4]; for(i=0;i<4;i++){ RNScalar p[4]; for(j=0;j<4;j++){p[j]=U[4*j+i];} if(p[0]<0){for(j=0;j<4;j++){p[j]=-p[j];}} temp[i] = SetQuaternion(p); e[i]= R3AlignError(points1, points2, temp[i], center1, center2, s1, s2, weights); if (e[i]<e[minI]) minI=i; } rotation = temp[minI]; } // Compute result R4Matrix result = R4identity_matrix; if (align_center) result.Translate(center1.Vector()); if (align_scale) result.Scale(s1/s2); if (align_rotation) result.Transform(rotation); if (align_center) result.Translate(-(center2.Vector())); // Return resulting matrix that takes points2 to points1 return result; } R3Plane R3EstimatePlaneWithPCA(const RNArray<R3Point *>& points, const RNScalar *weights) { // Return best fitting plane RNScalar variances[3]; R3Point centroid = R3Centroid(points); R3Triad axes = R3PrincipleAxes(centroid, points, weights, variances); if (RNIsZero(variances[1])) return R3null_plane; return R3Plane(centroid, axes[2]); } R3Plane R3EstimatePlaneWithRansac(const RNArray<R3Point *>& points, const RNScalar *weights, RNScalar tolerance, int max_iterations, RNScalar *max_inlier_fraction, RNScalar *avg_inlier_fraction) { // Check number of points if (points.NEntries() < 3) return R3null_plane; // Try PCA plane RNScalar variances[3]; RNArray<R3Point *> inliers; RNScalar *w = (weights) ? new RNScalar [ points.NEntries() ] : NULL; R3Point centroid = R3Centroid(points); R3Triad axes = R3PrincipleAxes(centroid, points, weights, variances); if (RNIsZero(variances[1])) return R3null_plane; R3Plane plane(centroid, axes[2]); if (tolerance == 0) tolerance = sqrt(variances[2]); for (int i = 0; i < points.NEntries(); i++) { R3Point *point = points[i]; RNScalar d = R3Distance(plane, *point); if (d > tolerance) continue; if (w) w[inliers.NEntries()] = weights[i]; inliers.Insert(point); } // Initialize best score R3Plane best_plane = plane; RNScalar score = (RNScalar) inliers.NEntries() / (RNScalar) points.NEntries(); RNScalar best_score = score; RNScalar total_score = score; int nscores = 1; // Search for a best normal for (int i = 0; i < max_iterations; i++) { // Guess normal by selecting three random points R3Point *p0 = points[(int) (RNRandomScalar() * points.NEntries()) ]; R3Point *p1 = points[(int) (RNRandomScalar() * points.NEntries()) ]; R3Point *p2 = points[(int) (RNRandomScalar() * points.NEntries()) ]; if (R3Contains(*p0, *p1) || R3Contains(*p1, *p2) || R3Contains(*p2, *p0)) continue; R3Plane plane(*p0, *p1, *p2); // Find inliers inliers.Empty(); for (int i = 0; i < points.NEntries(); i++) { R3Point *point = points[i]; RNScalar d = R3Distance(plane, *point); if (d > tolerance) continue; if (w) w[inliers.NEntries()] = weights[i]; inliers.Insert(point); } // Compute score RNScalar score = (RNScalar) inliers.NEntries() / (RNScalar) points.NEntries(); total_score += score; nscores++; // Check score if (score <= best_score) continue; // Recompute plane with just inliers plane = R3EstimatePlaneWithPCA(inliers, w); if (plane == R3null_plane) continue; // Update best stuff best_plane = plane; best_score = score; } // Update returned results if (max_inlier_fraction) *max_inlier_fraction = best_score; if (avg_inlier_fraction) *avg_inlier_fraction = total_score / nscores; // Return best plane return best_plane; } //////////////////////////////////////////////////////////////////////// R3Box R3BoundingBox(int npoints, R3Point *points) { RNArray<R3Point *> array; for (int i = 0; i < npoints; i++) array.Insert(&points[i]); return R3BoundingBox(array); } R3Point R3Centroid(int npoints, R3Point *points, const RNScalar *weights) { RNArray<R3Point *> array; for (int i = 0; i < npoints; i++) array.Insert(&points[i]); return R3Centroid(array, weights); } R3Triad R3PrincipleAxes(const R3Point& centroid, int npoints, R3Point *points, const RNScalar *weights, RNScalar *variances) { RNArray<R3Point *> array; for (int i = 0; i < npoints; i++) array.Insert(&points[i]); return R3PrincipleAxes(centroid, array, weights, variances); } RNLength R3AverageDistance(const R3Point& center, int npoints, R3Point *points, const RNScalar *weights) { RNArray<R3Point *> array; for (int i = 0; i < npoints; i++) array.Insert(&points[i]); return R3AverageDistance(center, array, weights); } R3Affine R3NormalizationTransformation(int npoints, R3Point *points, RNBoolean translate, RNBoolean rotate, int scale) { RNArray<R3Point *> array; for (int i = 0; i < npoints; i++) array.Insert(&points[i]); return R3NormalizationTransformation(array, translate, rotate, scale); } RNScalar R3AlignError(int npoints, R3Point *points1, R3Point *points2, const R4Matrix& matrix, const RNScalar *weights) { RNArray<R3Point *> array1, array2; for (int i = 0; i < npoints; i++) { array1.Insert(&points1[i]); array2.Insert(&points2[i]); } return R3AlignError(array1, array2, matrix, weights); } R4Matrix R3AlignPoints(int npoints, R3Point *points1, R3Point *points2, const RNScalar *weights, RNBoolean align_center, RNBoolean align_rotation, int align_scale) { RNArray<R3Point *> array1, array2; for (int i = 0; i < npoints; i++) { array1.Insert(&points1[i]); array2.Insert(&points2[i]); } return R3AlignPoints(array1, array2, weights, align_center, align_rotation, align_scale); } R3Plane R3EstimatePlaneWithPCA(int npoints, R3Point *points, const RNScalar *weights) { RNArray<R3Point *> array; for (int i = 0; i < npoints; i++) array.Insert(&points[i]); return R3EstimatePlaneWithPCA(array, weights); } R3Plane R3EstimatePlaneWithRansac(int npoints, R3Point *points, const RNScalar *weights, RNScalar tolerance, int max_iterations, RNScalar *max_inlier_fraction, RNScalar *avg_inlier_fraction) { RNArray<R3Point *> array; for (int i = 0; i < npoints; i++) array.Insert(&points[i]); return R3EstimatePlaneWithRansac(array, weights, tolerance, max_iterations, max_inlier_fraction, avg_inlier_fraction); } } // namespace gaps
tomfunkhouser/gaps
pkgs/R3Shapes/R3Align.cpp
C++
mit
16,484
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <policy/feerate.h> #include <tinyformat.h> const std::string CURRENCY_UNIT = "UFO"; CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nBytes_) { assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max())); int64_t nSize = int64_t(nBytes_); if (nSize > 0) nSatoshisPerK = nFeePaid * 1000 / nSize; else nSatoshisPerK = 0; } CAmount CFeeRate::GetFee(size_t nBytes_) const { assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max())); int64_t nSize = int64_t(nBytes_); CAmount nFee = nSatoshisPerK * nSize / 1000; if (nFee == 0 && nSize != 0) { if (nSatoshisPerK > 0) nFee = CAmount(1); if (nSatoshisPerK < 0) nFee = CAmount(-1); } return nFee; } std::string CFeeRate::ToString() const { return strprintf("%d.%08d %s/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN, CURRENCY_UNIT); }
Bushstar/UFO-Project
src/policy/feerate.cpp
C++
mit
1,149
var util = require("util"); var choreography = require("temboo/core/choreography"); /* CreateDeployment Create a RightScale Deployment. */ var CreateDeployment = function(session) { /* Create a new instance of the CreateDeployment Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/CreateDeployment" CreateDeployment.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new CreateDeploymentResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new CreateDeploymentInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the CreateDeployment Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var CreateDeploymentInputSet = function() { CreateDeploymentInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, integer) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the DeploymentDefaultEC2AvailabilityZone input for this Choreo. ((optional, string) The default EC2 availability zone for this deployment.) */ this.set_DeploymentDefaultEC2AvailabilityZone = function(value) { this.setInput("DeploymentDefaultEC2AvailabilityZone", value); } /* Set the value of the DeploymentDefaultVPCSubnetHref input for this Choreo. ((optional, string) The href of the vpc subnet.) */ this.set_DeploymentDefaultVPCSubnetHref = function(value) { this.setInput("DeploymentDefaultVPCSubnetHref", value); } /* Set the value of the DeploymentDescription input for this Choreo. ((optional, string) The deployment being created.) */ this.set_DeploymentDescription = function(value) { this.setInput("DeploymentDescription", value); } /* Set the value of the DeploymentNickname input for this Choreo. ((required, string) The nickname of the deployment being created.) */ this.set_DeploymentNickname = function(value) { this.setInput("DeploymentNickname", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the CreateDeployment Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var CreateDeploymentResultSet = function(resultStream) { CreateDeploymentResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(CreateDeployment, choreography.Choreography); util.inherits(CreateDeploymentInputSet, choreography.InputSet); util.inherits(CreateDeploymentResultSet, choreography.ResultSet); exports.CreateDeployment = CreateDeployment; /* CreateServer Creates a RightScale server instance. */ var CreateServer = function(session) { /* Create a new instance of the CreateServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/CreateServer" CreateServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new CreateServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new CreateServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the CreateServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var CreateServerInputSet = function() { CreateServerInputSet.super_.call(this); /* Set the value of the AKIImage input for this Choreo. ((optional, string) The URL to the AKI image.) */ this.set_AKIImage = function(value) { this.setInput("AKIImage", value); } /* Set the value of the ARIImage input for this Choreo. ((optional, string) The URL to the ARI Image.) */ this.set_ARIImage = function(value) { this.setInput("ARIImage", value); } /* Set the value of the AccountID input for this Choreo. ((required, integer) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the CloudID input for this Choreo. ((optional, integer) The cloud region identifier. If undefined, the default is 1 (us-east).) */ this.set_CloudID = function(value) { this.setInput("CloudID", value); } /* Set the value of the EC2AvailabilityZone input for this Choreo. ((optional, string) The EC2 availablity zone, for example: us-east-1a, or any. Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2AvailabilityZone = function(value) { this.setInput("EC2AvailabilityZone", value); } /* Set the value of the EC2Image input for this Choreo. ((optional, string) The URL to AMI image.) */ this.set_EC2Image = function(value) { this.setInput("EC2Image", value); } /* Set the value of the EC2SSHKeyHref input for this Choreo. ((optional, string) The URL to the SSH Key.) */ this.set_EC2SSHKeyHref = function(value) { this.setInput("EC2SSHKeyHref", value); } /* Set the value of the EC2SecurityGroupsHref input for this Choreo. ((optional, string) The URL(s) to security group(s). Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2SecurityGroupsHref = function(value) { this.setInput("EC2SecurityGroupsHref", value); } /* Set the value of the InstanceType input for this Choreo. ((optional, string) The AWS instance type: small, medium, etc.) */ this.set_InstanceType = function(value) { this.setInput("InstanceType", value); } /* Set the value of the MaxSpotPrice input for this Choreo. ((optional, integer) The maximum price (a dollar value) dollars) per hour for the spot server.) */ this.set_MaxSpotPrice = function(value) { this.setInput("MaxSpotPrice", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the Pricing input for this Choreo. ((optional, string) AWS pricing. Specify on_demand, or spot.) */ this.set_Pricing = function(value) { this.setInput("Pricing", value); } /* Set the value of the ServerDeployment input for this Choreo. ((required, string) The URL of the deployment that this server wil be added to.) */ this.set_ServerDeployment = function(value) { this.setInput("ServerDeployment", value); } /* Set the value of the ServerNickname input for this Choreo. ((required, string) The nickname for the server being created.) */ this.set_ServerNickname = function(value) { this.setInput("ServerNickname", value); } /* Set the value of the ServerTemplate input for this Choreo. ((required, string) The URL to a server template.) */ this.set_ServerTemplate = function(value) { this.setInput("ServerTemplate", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The username obtained from RightScale.) */ this.set_Username = function(value) { this.setInput("Username", value); } /* Set the value of the VPCSubnet input for this Choreo. ((optional, string) The href to the VPC subnet.) */ this.set_VPCSubnet = function(value) { this.setInput("VPCSubnet", value); } } /* A ResultSet with methods tailored to the values returned by the CreateServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var CreateServerResultSet = function(resultStream) { CreateServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(CreateServer, choreography.Choreography); util.inherits(CreateServerInputSet, choreography.InputSet); util.inherits(CreateServerResultSet, choreography.ResultSet); exports.CreateServer = CreateServer; /* CreateServerXMLInput Creates a RightScale server instance using a given XML template. */ var CreateServerXMLInput = function(session) { /* Create a new instance of the CreateServerXMLInput Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/CreateServerXMLInput" CreateServerXMLInput.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new CreateServerXMLInputResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new CreateServerXMLInputInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the CreateServerXMLInput Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var CreateServerXMLInputInputSet = function() { CreateServerXMLInputInputSet.super_.call(this); /* Set the value of the ServerParameters input for this Choreo. ((required, xml) The XML file containing the required parameters for the server creation. See documentation for XML schema.) */ this.set_ServerParameters = function(value) { this.setInput("ServerParameters", value); } /* Set the value of the ARIImage input for this Choreo. ((required, string) The URL to the ARI Image.) */ this.set_ARIImage = function(value) { this.setInput("ARIImage", value); } /* Set the value of the AccountID input for this Choreo. ((required, integer) The Account ID obtained from RightScale.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the CloudID input for this Choreo. ((required, integer) The cloud region identifier. If undefined, the default is: 1 (us-east).) */ this.set_CloudID = function(value) { this.setInput("CloudID", value); } /* Set the value of the EC2AvailabilityZone input for this Choreo. ((optional, any) The EC2 availablity zone, for example: us-east-1a, or any. Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2AvailabilityZone = function(value) { this.setInput("EC2AvailabilityZone", value); } /* Set the value of the EC2Image input for this Choreo. ((required, string) The URL to AMI image.) */ this.set_EC2Image = function(value) { this.setInput("EC2Image", value); } /* Set the value of the EC2SSHKeyHref input for this Choreo. ((optional, any) The URL to the SSH Key.) */ this.set_EC2SSHKeyHref = function(value) { this.setInput("EC2SSHKeyHref", value); } /* Set the value of the EC2SecurityGroupsHref input for this Choreo. ((optional, any) The URL(s) to security group(s). Do not set, if also passing the vpc_subnet_href parameter.) */ this.set_EC2SecurityGroupsHref = function(value) { this.setInput("EC2SecurityGroupsHref", value); } /* Set the value of the InstanceType input for this Choreo. ((optional, any) The AWS instance type: small, medium, etc.) */ this.set_InstanceType = function(value) { this.setInput("InstanceType", value); } /* Set the value of the MaxSpotPrice input for this Choreo. ((required, integer) The maximum price (a dollar value) dollars) per hour for the spot server.) */ this.set_MaxSpotPrice = function(value) { this.setInput("MaxSpotPrice", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the Pricing input for this Choreo. ((required, string) AWS pricing. Specify on_demand, or spot.) */ this.set_Pricing = function(value) { this.setInput("Pricing", value); } /* Set the value of the ServerDeployment input for this Choreo. ((optional, any) The URL of the deployment that this server wil be added to.) */ this.set_ServerDeployment = function(value) { this.setInput("ServerDeployment", value); } /* Set the value of the ServerNickname input for this Choreo. ((optional, any) The nickname for the server being created.) */ this.set_ServerNickname = function(value) { this.setInput("ServerNickname", value); } /* Set the value of the ServerTemplate input for this Choreo. ((optional, any) The URL to a server template.) */ this.set_ServerTemplate = function(value) { this.setInput("ServerTemplate", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } /* Set the value of the VPCSubnet input for this Choreo. ((required, string) The href to the VPC subnet) */ this.set_VPCSubnet = function(value) { this.setInput("VPCSubnet", value); } } /* A ResultSet with methods tailored to the values returned by the CreateServerXMLInput Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var CreateServerXMLInputResultSet = function(resultStream) { CreateServerXMLInputResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. (The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(CreateServerXMLInput, choreography.Choreography); util.inherits(CreateServerXMLInputInputSet, choreography.InputSet); util.inherits(CreateServerXMLInputResultSet, choreography.ResultSet); exports.CreateServerXMLInput = CreateServerXMLInput; /* GetArrayIndex Retrieve a list of server assets grouped within a particular RightScale Array. */ var GetArrayIndex = function(session) { /* Create a new instance of the GetArrayIndex Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/GetArrayIndex" GetArrayIndex.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetArrayIndexResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetArrayIndexInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetArrayIndex Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetArrayIndexInputSet = function() { GetArrayIndexInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the GetArrayIndex Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetArrayIndexResultSet = function(resultStream) { GetArrayIndexResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetArrayIndex, choreography.Choreography); util.inherits(GetArrayIndexInputSet, choreography.InputSet); util.inherits(GetArrayIndexResultSet, choreography.ResultSet); exports.GetArrayIndex = GetArrayIndex; /* GetServerSettings Retrieve server settings for a specified RightScale Server ID. */ var GetServerSettings = function(session) { /* Create a new instance of the GetServerSettings Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/GetServerSettings" GetServerSettings.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetServerSettingsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetServerSettingsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetServerSettings Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetServerSettingsInputSet = function() { GetServerSettingsInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the GetServerSettings Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetServerSettingsResultSet = function(resultStream) { GetServerSettingsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetServerSettings, choreography.Choreography); util.inherits(GetServerSettingsInputSet, choreography.InputSet); util.inherits(GetServerSettingsResultSet, choreography.ResultSet); exports.GetServerSettings = GetServerSettings; /* IndexDeployments Retrieve a list of server assets grouped within a particular RightScale Deployment. */ var IndexDeployments = function(session) { /* Create a new instance of the IndexDeployments Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/IndexDeployments" IndexDeployments.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new IndexDeploymentsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new IndexDeploymentsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the IndexDeployments Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var IndexDeploymentsInputSet = function() { IndexDeploymentsInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Filter input for this Choreo. ((optional, string) An attributeName=AttributeValue filter pair. For example: nickname=mynick; OR description<>mydesc) */ this.set_Filter = function(value) { this.setInput("Filter", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } /* Set the value of the inputFile input for this Choreo. () */ } /* A ResultSet with methods tailored to the values returned by the IndexDeployments Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var IndexDeploymentsResultSet = function(resultStream) { IndexDeploymentsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(IndexDeployments, choreography.Choreography); util.inherits(IndexDeploymentsInputSet, choreography.InputSet); util.inherits(IndexDeploymentsResultSet, choreography.ResultSet); exports.IndexDeployments = IndexDeployments; /* LaunchArrayInstance Start an array instance. */ var LaunchArrayInstance = function(session) { /* Create a new instance of the LaunchArrayInstance Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/LaunchArrayInstance" LaunchArrayInstance.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new LaunchArrayInstanceResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new LaunchArrayInstanceInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the LaunchArrayInstance Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var LaunchArrayInstanceInputSet = function() { LaunchArrayInstanceInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the LaunchArrayInstance Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var LaunchArrayInstanceResultSet = function(resultStream) { LaunchArrayInstanceResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(LaunchArrayInstance, choreography.Choreography); util.inherits(LaunchArrayInstanceInputSet, choreography.InputSet); util.inherits(LaunchArrayInstanceResultSet, choreography.ResultSet); exports.LaunchArrayInstance = LaunchArrayInstance; /* ListAllOperationalArrayInstances List all operational instances in an array. */ var ListAllOperationalArrayInstances = function(session) { /* Create a new instance of the ListAllOperationalArrayInstances Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ListAllOperationalArrayInstances" ListAllOperationalArrayInstances.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ListAllOperationalArrayInstancesResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ListAllOperationalArrayInstancesInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ListAllOperationalArrayInstances Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ListAllOperationalArrayInstancesInputSet = function() { ListAllOperationalArrayInstancesInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ListAllOperationalArrayInstances Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ListAllOperationalArrayInstancesResultSet = function(resultStream) { ListAllOperationalArrayInstancesResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ListAllOperationalArrayInstances, choreography.Choreography); util.inherits(ListAllOperationalArrayInstancesInputSet, choreography.InputSet); util.inherits(ListAllOperationalArrayInstancesResultSet, choreography.ResultSet); exports.ListAllOperationalArrayInstances = ListAllOperationalArrayInstances; /* RunRightScript Executes a specified RightScript. */ var RunRightScript = function(session) { /* Create a new instance of the RunRightScript Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/RunRightScript" RunRightScript.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new RunRightScriptResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new RunRightScriptInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the RunRightScript Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var RunRightScriptInputSet = function() { RunRightScriptInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the RightScriptID input for this Choreo. ((required, integer) The ID of the RightScript.) */ this.set_RightScriptID = function(value) { this.setInput("RightScriptID", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the RunRightScript Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var RunRightScriptResultSet = function(resultStream) { RunRightScriptResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(RunRightScript, choreography.Choreography); util.inherits(RunRightScriptInputSet, choreography.InputSet); util.inherits(RunRightScriptResultSet, choreography.ResultSet); exports.RunRightScript = RunRightScript; /* ShowArray Display a comrephensive set of information about the querried array such as: server(s) state information, array templates used, array state, etc. */ var ShowArray = function(session) { /* Create a new instance of the ShowArray Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowArray" ShowArray.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowArrayResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowArrayInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowArray Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowArrayInputSet = function() { ShowArrayInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowArray Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowArrayResultSet = function(resultStream) { ShowArrayResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowArray, choreography.Choreography); util.inherits(ShowArrayInputSet, choreography.InputSet); util.inherits(ShowArrayResultSet, choreography.ResultSet); exports.ShowArray = ShowArray; /* ShowDeploymentIndex Retrieve a list of server assets grouped within a particular RightScale Deployment ID. */ var ShowDeploymentIndex = function(session) { /* Create a new instance of the ShowDeploymentIndex Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowDeploymentIndex" ShowDeploymentIndex.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowDeploymentIndexResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowDeploymentIndexInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowDeploymentIndex Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowDeploymentIndexInputSet = function() { ShowDeploymentIndexInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the DeploymentID input for this Choreo. ((required, integer) The DeploymentID to only list servers in this particular RightScale deployment.) */ this.set_DeploymentID = function(value) { this.setInput("DeploymentID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerSettings input for this Choreo. ((optional, string) Display additional information about this RightScale deployment. Set True to enable.) */ this.set_ServerSettings = function(value) { this.setInput("ServerSettings", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowDeploymentIndex Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowDeploymentIndexResultSet = function(resultStream) { ShowDeploymentIndexResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowDeploymentIndex, choreography.Choreography); util.inherits(ShowDeploymentIndexInputSet, choreography.InputSet); util.inherits(ShowDeploymentIndexResultSet, choreography.ResultSet); exports.ShowDeploymentIndex = ShowDeploymentIndex; /* ShowServer Display a comrephensive set of information about the querried server such as: state information, server templates used, SSH key href, etc. */ var ShowServer = function(session) { /* Create a new instance of the ShowServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowServer" ShowServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowServerInputSet = function() { ShowServerInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowServerResultSet = function(resultStream) { ShowServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowServer, choreography.Choreography); util.inherits(ShowServerInputSet, choreography.InputSet); util.inherits(ShowServerResultSet, choreography.ResultSet); exports.ShowServer = ShowServer; /* ShowServerIndex Display an index of all servers in a RightScale account. */ var ShowServerIndex = function(session) { /* Create a new instance of the ShowServerIndex Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/ShowServerIndex" ShowServerIndex.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new ShowServerIndexResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new ShowServerIndexInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the ShowServerIndex Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var ShowServerIndexInputSet = function() { ShowServerIndexInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the ShowServerIndex Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var ShowServerIndexResultSet = function(resultStream) { ShowServerIndexResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(ShowServerIndex, choreography.Choreography); util.inherits(ShowServerIndexInputSet, choreography.InputSet); util.inherits(ShowServerIndexResultSet, choreography.ResultSet); exports.ShowServerIndex = ShowServerIndex; /* StartServer Start a server associated with a particular Server ID. Optionally, this Choreo can also poll the startup process and verify server startup. */ var StartServer = function(session) { /* Create a new instance of the StartServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/StartServer" StartServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new StartServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new StartServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the StartServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var StartServerInputSet = function() { StartServerInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the PollingTimeLimit input for this Choreo. ((optional, integer) Server status polling. Enable by specifying a time limit - in minutes - for the duration of the server state polling.) */ this.set_PollingTimeLimit = function(value) { this.setInput("PollingTimeLimit", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the StartServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var StartServerResultSet = function(resultStream) { StartServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "State" output from this Choreo execution. ((string) The server 'state' parsed from the Rightscale response.) */ this.get_State = function() { return this.getResult("State"); } /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(StartServer, choreography.Choreography); util.inherits(StartServerInputSet, choreography.InputSet); util.inherits(StartServerResultSet, choreography.ResultSet); exports.StartServer = StartServer; /* StopServer Stop a RightScale server instance. Optionally, this Choreo can also poll the stop process and verify server termination. */ var StopServer = function(session) { /* Create a new instance of the StopServer Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/StopServer" StopServer.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new StopServerResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new StopServerInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the StopServer Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var StopServerInputSet = function() { StopServerInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, integer) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the PollingTimeLimit input for this Choreo. ((optional, integer) Server status polling. Enable by specifying a time limit - in minutes - for the duration of the server state polling.) */ this.set_PollingTimeLimit = function(value) { this.setInput("PollingTimeLimit", value); } /* Set the value of the ServerID input for this Choreo. ((required, integer) The RightScale Server ID that is to be stopped.) */ this.set_ServerID = function(value) { this.setInput("ServerID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the StopServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var StopServerResultSet = function(resultStream) { StopServerResultSet.super_.call(this, resultStream); /* Retrieve the value for the "State" output from this Choreo execution. ((string) The server 'state' parsed from the Rightscale response.) */ this.get_State = function() { return this.getResult("State"); } /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(StopServer, choreography.Choreography); util.inherits(StopServerInputSet, choreography.InputSet); util.inherits(StopServerResultSet, choreography.ResultSet); exports.StopServer = StopServer; /* TerminateArrayInstances Terminate an array instance. */ var TerminateArrayInstances = function(session) { /* Create a new instance of the TerminateArrayInstances Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/RightScale/TerminateArrayInstances" TerminateArrayInstances.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new TerminateArrayInstancesResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new TerminateArrayInstancesInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the TerminateArrayInstances Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var TerminateArrayInstancesInputSet = function() { TerminateArrayInstancesInputSet.super_.call(this); /* Set the value of the AccountID input for this Choreo. ((required, string) The RightScale Account ID.) */ this.set_AccountID = function(value) { this.setInput("AccountID", value); } /* Set the value of the Password input for this Choreo. ((required, password) The RightScale account password.) */ this.set_Password = function(value) { this.setInput("Password", value); } /* Set the value of the ServerArrayID input for this Choreo. ((required, integer) The ID of a server array.) */ this.set_ServerArrayID = function(value) { this.setInput("ServerArrayID", value); } /* Set the value of the SubDomain input for this Choreo. ((conditional, string) The Rightscale sub-domain appropriate for your Rightscale account. Defaults to "my" for legacy accounts. Other sub-domains include: jp-8 (Legacy Cloud Platform), us-3, us-4 (Unified Cloud Platform).) */ this.set_SubDomain = function(value) { this.setInput("SubDomain", value); } /* Set the value of the Username input for this Choreo. ((required, string) The RightScale username.) */ this.set_Username = function(value) { this.setInput("Username", value); } } /* A ResultSet with methods tailored to the values returned by the TerminateArrayInstances Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var TerminateArrayInstancesResultSet = function(resultStream) { TerminateArrayInstancesResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Rightscale in XML format.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(TerminateArrayInstances, choreography.Choreography); util.inherits(TerminateArrayInstancesInputSet, choreography.InputSet); util.inherits(TerminateArrayInstancesResultSet, choreography.ResultSet); exports.TerminateArrayInstances = TerminateArrayInstances;
nikmeiser/temboo-geocode
node_modules/temboo/Library/RightScale.js
JavaScript
mit
67,107
// Copyright (c) 2011-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. #include "omnicoinamountfield.h" #include "omnicoinunits.h" #include "guiconstants.h" #include "qvaluecombobox.h" #include <QApplication> #include <QAbstractSpinBox> #include <QHBoxLayout> #include <QKeyEvent> #include <QLineEdit> /** QSpinBox that uses fixed-point numbers internally and uses our own * formatting/parsing functions. */ class AmountSpinBox: public QAbstractSpinBox { Q_OBJECT public: explicit AmountSpinBox(QWidget *parent): QAbstractSpinBox(parent), currentUnit(OmnicoinUnits::OMC), singleStep(100000) // satoshis { setAlignment(Qt::AlignRight); connect(lineEdit(), SIGNAL(textEdited(QString)), this, SIGNAL(valueChanged())); } QValidator::State validate(QString &text, int &pos) const { if(text.isEmpty()) return QValidator::Intermediate; bool valid = false; parse(text, &valid); /* Make sure we return Intermediate so that fixup() is called on defocus */ return valid ? QValidator::Intermediate : QValidator::Invalid; } void fixup(QString &input) const { bool valid = false; CAmount val = parse(input, &valid); if(valid) { input = OmnicoinUnits::format(currentUnit, val, false, OmnicoinUnits::separatorAlways); lineEdit()->setText(input); } } CAmount value(bool *valid_out=0) const { return parse(text(), valid_out); } void setValue(const CAmount& value) { lineEdit()->setText(OmnicoinUnits::format(currentUnit, value, false, OmnicoinUnits::separatorAlways)); Q_EMIT valueChanged(); } void stepBy(int steps) { bool valid = false; CAmount val = value(&valid); val = val + steps * singleStep; val = qMin(qMax(val, CAmount(0)), OmnicoinUnits::maxMoney()); setValue(val); } void setDisplayUnit(int unit) { bool valid = false; CAmount val = value(&valid); currentUnit = unit; if(valid) setValue(val); else clear(); } void setSingleStep(const CAmount& step) { singleStep = step; } QSize minimumSizeHint() const { if(cachedMinimumSizeHint.isEmpty()) { ensurePolished(); const QFontMetrics fm(fontMetrics()); int h = lineEdit()->minimumSizeHint().height(); int w = fm.width(OmnicoinUnits::format(OmnicoinUnits::OMC, OmnicoinUnits::maxMoney(), false, OmnicoinUnits::separatorAlways)); w += 2; // cursor blinking space QStyleOptionSpinBox opt; initStyleOption(&opt); QSize hint(w, h); QSize extra(35, 6); opt.rect.setSize(hint + extra); extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this).size(); // get closer to final result by repeating the calculation opt.rect.setSize(hint + extra); extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this).size(); hint += extra; hint.setHeight(h); opt.rect = rect(); cachedMinimumSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this) .expandedTo(QApplication::globalStrut()); } return cachedMinimumSizeHint; } private: int currentUnit; CAmount singleStep; mutable QSize cachedMinimumSizeHint; /** * Parse a string into a number of base monetary units and * return validity. * @note Must return 0 if !valid. */ CAmount parse(const QString &text, bool *valid_out=0) const { CAmount val = 0; bool valid = OmnicoinUnits::parse(currentUnit, text, &val); if(valid) { if(val < 0 || val > OmnicoinUnits::maxMoney()) valid = false; } if(valid_out) *valid_out = valid; return valid ? val : 0; } protected: bool event(QEvent *event) { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); return QAbstractSpinBox::event(&periodKeyEvent); } } return QAbstractSpinBox::event(event); } StepEnabled stepEnabled() const { if (isReadOnly()) // Disable steps when AmountSpinBox is read-only return StepNone; if (text().isEmpty()) // Allow step-up with empty field return StepUpEnabled; StepEnabled rv = 0; bool valid = false; CAmount val = value(&valid); if(valid) { if(val > 0) rv |= StepDownEnabled; if(val < OmnicoinUnits::maxMoney()) rv |= StepUpEnabled; } return rv; } Q_SIGNALS: void valueChanged(); }; #include "omnicoinamountfield.moc" OmnicoinAmountField::OmnicoinAmountField(QWidget *parent) : QWidget(parent), amount(0) { amount = new AmountSpinBox(this); amount->setLocale(QLocale::c()); amount->installEventFilter(this); amount->setMaximumWidth(170); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new OmnicoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0,0,0,0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(valueChanged()), this, SIGNAL(valueChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void OmnicoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } void OmnicoinAmountField::setEnabled(bool fEnabled) { amount->setEnabled(fEnabled); unit->setEnabled(fEnabled); } bool OmnicoinAmountField::validate() { bool valid = false; value(&valid); setValid(valid); return valid; } void OmnicoinAmountField::setValid(bool valid) { if (valid) amount->setStyleSheet(""); else amount->setStyleSheet(STYLE_INVALID); } bool OmnicoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } return QWidget::eventFilter(object, event); } QWidget *OmnicoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); QWidget::setTabOrder(amount, unit); return unit; } CAmount OmnicoinAmountField::value(bool *valid_out) const { return amount->value(valid_out); } void OmnicoinAmountField::setValue(const CAmount& value) { amount->setValue(value); } void OmnicoinAmountField::setReadOnly(bool fReadOnly) { amount->setReadOnly(fReadOnly); } void OmnicoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, OmnicoinUnits::UnitRole).toInt(); amount->setDisplayUnit(newUnit); } void OmnicoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); } void OmnicoinAmountField::setSingleStep(const CAmount& step) { amount->setSingleStep(step); }
MeshCollider/Omnicoin
src/qt/omnicoinamountfield.cpp
C++
mit
8,247
var http = require('http') var https = require('https') var corsify = require('corsify') var collect = require('stream-collector') var pump = require('pump') var iterate = require('random-iterate') var limiter = require('size-limit-stream') var eos = require('end-of-stream') var flushHeaders = function (res) { if (res.flushHeaders) { res.flushHeaders() } else { if (!res._header) res._implicitHeader() res._send('') } } module.exports = function (opts) { var channels = {} var maxBroadcasts = (opts && opts.maxBroadcasts) || Infinity var get = function (channel) { if (channels[channel]) return channels[channel] channels[channel] = {name: channel, subscribers: []} return channels[channel] } var cors = corsify({ "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE", "Access-Control-Allow-Headers": "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization" }) var onRequest = cors(function (req, res) { if (req.url === '/') { res.end(JSON.stringify({name: 'signalhub', version: require('./package').version}, null, 2) + '\n') return } if (req.url.slice(0, 4) !== '/v1/') { res.statusCode = 404 res.end() return } var name = req.url.slice(4).split('?')[0] if (req.method === 'POST') { collect(pump(req, limiter(64 * 1024)), function (err, data) { if (err) return res.end() if (!channels[name]) return res.end() var channel = get(name) server.emit('publish', channel.name, data) data = Buffer.concat(data).toString() var ite = iterate(channel.subscribers) var next var cnt = 0 while ((next = ite()) && cnt++ < maxBroadcasts) { next.write('data: ' + data + '\n\n') } res.end() }) return } if (req.method === 'GET') { res.setHeader('Content-Type', 'text/event-stream; charset=utf-8') var app = name.split('/')[0] var channelNames = name.slice(app.length + 1) channelNames.split(',').forEach(function (channelName) { var channel = get(app + '/' + channelName) server.emit('subscribe', channel.name) channel.subscribers.push(res) eos(res, function () { var i = channel.subscribers.indexOf(res) if (i > -1) channel.subscribers.splice(i, 1) if (!channel.subscribers.length && channel === channels[channel.name]) delete channels[channel.name] }) }) flushHeaders(res) return } res.statusCode = 404 res.end() }) var server = ((opts && opts.key) ? https : http).createServer(opts) server.on('request', onRequest) return server }
supriyantomaftuh/signalhub
server.js
JavaScript
mit
2,767
<?php include("../partials/header.php"); include("../inc/database.php"); include("controller.php"); if (strlen($_SERVER["QUERY_STRING"])>0){ $result_response = process_request($_GET["length"],$_GET["width"],$_GET["rent_type"]); //make this a hash so you can access the values with a string $db = $result_response[0]; $num_results = count($db); $request_sent=true; $width = $result_response[1]; $length=$result_response[2]; $rent_type=$result_response[3]; } ?> <section><h1>Available Units:</h1></section> <section><?php render_available();?></section> <section> <?php if (count(available_units(get_data()))>20){;?> <h1>Search For Prices and Units</h1> </section> <section> <form id="unit_form"> <fieldset> <label for="width">Select Storage Width:</label><br> <select name="width" form="unit_form" id="width"> <?php display_width_options();?> </select> <br><br> <label for="length" >Select Storage Length:</label><br> <select name="length" form="unit_form" id="length-selector"> <option id ="4" value="6">4</option> <option id = "5" value="5">5</option> <option id = "6" value="6">6</option> <option id = "7" value="7">7</option> <option id = "8" value="8">8</option> <option id = "9" value="9">9</option> <option id = "10" value="10">10</option> <option id = "11" value="11">11</option> <option id = "12" value="12">12</option> <option id = "20" value="20">20</option> <option id = "22" value="22">22</option> </select> <br><br> <div id="billing_options"> <label for="rent_type">Select Billing Plan:</label><br> <select name="rent_type" id="rent_type" value="monthly"> <option value="monthly">monthly</option> <option value="weekly">weekly</option> </select> <br><br> <input type="submit"> </div> </fieldset> </form> </section> <section id = "form-results"> </section> <?php } ?> <?php include("../partials/footer.php");?>
JordanLittell/bidwell
pricing/index.php
PHP
mit
2,056
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users'); var centers = require('../../app/controllers/centers'); // Centers Routes app.route('/centers') .get(centers.list) app.route('/centers') .get(centers.create) app.route('/centers/:centerId') .get(centers.read) .put(users.requiresLogin, centers.hasAuthorization, centers.update) .delete(users.requiresLogin, centers.hasAuthorization, centers.delete); // Finish by binding the Center middleware app.param('centerId', centers.centerByID); };
jiashenwang/LG_report
app/routes/centers.server.routes.js
JavaScript
mit
561
# encoding: utf-8 require "mongoid/criterion/complex" require "mongoid/criterion/exclusion" require "mongoid/criterion/inclusion" require "mongoid/criterion/optional" module Mongoid #:nodoc: # The +Criteria+ class is the core object needed in Mongoid to retrieve # objects from the database. It is a DSL that essentially sets up the # selector and options arguments that get passed on to a <tt>Mongo::Collection</tt> # in the Ruby driver. Each method on the +Criteria+ returns self to they # can be chained in order to create a readable criterion to be executed # against the database. # # Example setup: # # <tt>criteria = Criteria.new</tt> # # <tt>criteria.only(:field).where(:field => "value").skip(20).limit(20)</tt> # # <tt>criteria.execute</tt> class Criteria include Criterion::Exclusion include Criterion::Inclusion include Criterion::Optional include Enumerable attr_reader :collection, :ids, :klass, :options, :selector attr_accessor :documents delegate :aggregate, :avg, :blank?, :count, :distinct, :empty?, :execute, :first, :group, :id_criteria, :last, :max, :min, :one, :page, :paginate, :per_page, :sum, :to => :context # Concatinate the criteria with another enumerable. If the other is a # +Criteria+ then it needs to get the collection from it. def +(other) entries + comparable(other) end # Returns the difference between the criteria and another enumerable. If # the other is a +Criteria+ then it needs to get the collection from it. def -(other) entries - comparable(other) end # Returns true if the supplied +Enumerable+ or +Criteria+ is equal to the results # of this +Criteria+ or the criteria itself. # # This will force a database load when called if an enumerable is passed. # # Options: # # other: The other +Enumerable+ or +Criteria+ to compare to. def ==(other) case other when Criteria self.selector == other.selector && self.options == other.options when Enumerable return (execute.entries == other) else return false end end # Returns true if the supplied +Object+ is an instance of +Criteria+ or # +Scope+. def self.===(other) super || Scope === other end # Return or create the context in which this criteria should be executed. # # This will return an Enumerable context if the class is embedded, # otherwise it will return a Mongo context for root classes. def context @context ||= Contexts.context_for(self) end # Iterate over each +Document+ in the results. This can take an optional # block to pass to each argument in the results. # # Example: # # <tt>criteria.each { |doc| p doc }</tt> def each(&block) context.iterate(&block) self end # Return true if the criteria has some Document or not # # Example: # # <tt>criteria.exists?</tt> def exists? context.count > 0 end # Merges the supplied argument hash into a single criteria # # Options: # # criteria_conditions: Hash of criteria keys, and parameter values # # Example: # # <tt>criteria.fuse(:where => { :field => "value"}, :limit => 20)</tt> # # Returns <tt>self</tt> def fuse(criteria_conditions = {}) criteria_conditions.inject(self) do |criteria, (key, value)| criteria.send(key, value) end end # Create the new +Criteria+ object. This will initialize the selector # and options hashes, as well as the type of criteria. # # Options: # # type: One of :all, :first:, or :last # klass: The class to execute on. def initialize(klass) @selector, @options, @klass, @documents = {}, {}, klass, [] end # Merges another object into this +Criteria+. The other object may be a # +Criteria+ or a +Hash+. This is used to combine multiple scopes together, # where a chained scope situation may be desired. # # Options: # # other: The +Criteria+ or +Hash+ to merge with. # # Example: # # <tt>criteria.merge({ :conditions => { :title => "Sir" } })</tt> def merge(other) @selector.update(other.selector) @options.update(other.options) @documents = other.documents end # Used for chaining +Criteria+ scopes together in the for of class methods # on the +Document+ the criteria is for. # # Options: # # name: The name of the class method on the +Document+ to chain. # args: The arguments passed to the method. # # Returns: <tt>Criteria</tt> def method_missing(name, *args) if @klass.respond_to?(name) new_scope = @klass.send(name, *args) new_scope.merge(self) if Criteria === new_scope return new_scope else return entries.send(name, *args) end end alias :to_ary :to_a # Returns the selector and options as a +Hash+ that would be passed to a # scope for use with named scopes. def scoped scope_options = @options.dup sorting = scope_options.delete(:sort) scope_options[:order_by] = sorting if sorting { :where => @selector }.merge(scope_options) end # Translate the supplied arguments into a +Criteria+ object. # # If the passed in args is a single +String+, then it will # construct an id +Criteria+ from it. # # If the passed in args are a type and a hash, then it will construct # the +Criteria+ with the proper selector, options, and type. # # Options: # # args: either a +String+ or a +Symbol+, +Hash combination. # # Example: # # <tt>Criteria.translate(Person, "4ab2bc4b8ad548971900005c")</tt> # <tt>Criteria.translate(Person, :conditions => { :field => "value"}, :limit => 20)</tt> def self.translate(*args) klass = args[0] params = args[1] || {} unless params.is_a?(Hash) return klass.criteria.id_criteria(params) end conditions = params.delete(:conditions) || {} if conditions.include?(:id) conditions[:_id] = conditions[:id] conditions.delete(:id) end return klass.criteria.where(conditions).extras(params) end protected # Filters the unused options out of the options +Hash+. Currently this # takes into account the "page" and "per_page" options that would be passed # in if using will_paginate. # # Example: # # Given a criteria with a selector of { :page => 1, :per_page => 40 } # # <tt>criteria.filter_options</tt> # selector: { :skip => 0, :limit => 40 } def filter_options page_num = @options.delete(:page) per_page_num = @options.delete(:per_page) if (page_num || per_page_num) @options[:limit] = limits = (per_page_num || 20).to_i @options[:skip] = (page_num || 1).to_i * limits - limits end end # Return the entries of the other criteria or the object. Used for # comparing criteria or an enumerable. def comparable(other) other.is_a?(Criteria) ? other.entries : other end # Update the selector setting the operator on the value for each key in the # supplied attributes +Hash+. # # Example: # # <tt>criteria.update_selector({ :field => "value" }, "$in")</tt> def update_selector(attributes, operator) attributes.each do |key, value| unless @selector[key] @selector[key] = { operator => value } else new_value = @selector[key].values.first + value @selector[key] = { operator => new_value } end end; self end end end
adorr/mongoid
lib/mongoid/criteria.rb
Ruby
mit
7,764
//============================================================================== // TorqueLab -> // Copyright (c) 2015 All Right Reserved, http://nordiklab.com/ //------------------------------------------------------------------------------ //============================================================================== $VisibilityOptionsLoaded = false; $VisibilityClassLoaded = false; $EVisibilityLayers_Initialized = false; /* virtual void GuiInspector::addInspect ( (id object,(bool autoSync=true)) ) [virtual] Add the object to the list of objects being inspected. virtual void GuiInspector::apply ( ) [virtual] apply() - Force application of inspected object's attributes virtual int GuiInspector::findByObject ( ) [virtual] findByObject( SimObject ) - returns the id of an awake inspector that is inspecting the passed object if one exists. virtual string GuiInspector::getInspectObject ( ) [virtual] getInspectObject( int index=0 ) - Returns currently inspected object virtual int GuiInspector::getNumInspectObjects ( () ) [virtual] Return the number of objects currently being inspected. virtual void GuiInspector::inspect ( ) [virtual] Inspect(Object) virtual void GuiInspector::refresh ( ) [virtual] Reinspect the currently selected object. virtual void GuiInspector::removeInspect ( (id object) ) [virtual] Remove the object from the list of objects being inspected. virtual Script GuiInspector::setAllGroupStateScript ( (string this, string obj, string groupState) ) [virtual] virtual void GuiInspector::setName ( ) [virtual] setName(NewObjectName) virtual void GuiInspector::setObjectField ( ) [virtual] setObjectField( fieldname, data ) - Set a named fields value on the inspected object if it exists. This triggers all the usual callbacks that would occur if the field had been changed through the gui. virtual Script GuiInspector::toggleDynamicGroupScript ( (string this, string obj) ) [virtual] virtual Script GuiInspector::toggleGroupScript ( (string this, string obj, string fieldName) ) [virtual] */
NordikLab/TorqueLab
tlab/EditorLab/gui/editorTools/EGlobalInspector.cs
C#
mit
2,081
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("Breeze.ContextProvider.EF6")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("IdeaBlade")] [assembly: AssemblyProduct("Breeze.ContextProvider.EF6")] [assembly: AssemblyCopyright("Copyright © IdeaBlade 2012-2016")] [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("192d55d3-534d-4cfd-9c75-741e8951e1d7")] // 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.5.5.0")] [assembly: AssemblyFileVersion("1.5.5.0")]
jspuij/breeze.server.net
Breeze.ContextProvider.EF6/Properties/AssemblyInfo.cs
C#
mit
1,451
class ImageUploader < CarrierWave::Uploader::Base include CarrierWave::RMagick def store_dir "vanzeiro/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end version :thumb do process resize_to_fill: [69, 69] end version :thumb2x do process resize_to_fill: [312, 312] end def extension_whitelist %w(jpg jpeg gif png) end def filename "file.#{file.extension}" if file end end
Cabuum/vanzeiro
app/uploaders/image_uploader.rb
Ruby
mit
438
package io.picopalette.apps.event_me.Utils; import android.annotation.SuppressLint; import android.content.Context; import android.support.design.widget.CoordinatorLayout; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.view.View; import com.facebook.drawee.view.SimpleDraweeView; import io.picopalette.apps.event_me.R; /** * Created by Aswin Sundar on 14-06-2017. */ public class ImageBehaviour extends CoordinatorLayout.Behavior<SimpleDraweeView> { private final static float MIN_AVATAR_PERCENTAGE_SIZE = 0.3f; private final static int EXTRA_FINAL_AVATAR_PADDING = 80; private final static String TAG = "behavior"; private final Context mContext; private float mAvatarMaxSize; private float mFinalLeftAvatarPadding; private float mStartPosition; private int mStartXPosition; private float mStartToolbarPosition; public ImageBehaviour(Context context, AttributeSet attrs) { mContext = context; init(); mFinalLeftAvatarPadding = context.getResources().getDimension(R.dimen.activity_horizontal_margin); } private void init() { bindDimensions(); } private void bindDimensions() { mAvatarMaxSize = mContext.getResources().getDimension(R.dimen.image_width); } private int mStartYPosition; private int mFinalYPosition; private int finalHeight; private int mStartHeight; private int mFinalXPosition; @Override public boolean layoutDependsOn(CoordinatorLayout parent, SimpleDraweeView child, View dependency) { return dependency instanceof Toolbar; } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, SimpleDraweeView child, View dependency) { maybeInitProperties(child, dependency); final int maxScrollDistance = (int) (mStartToolbarPosition - getStatusBarHeight()); float expandedPercentageFactor = dependency.getY() / maxScrollDistance; float distanceYToSubtract = ((mStartYPosition - mFinalYPosition) * (1f - expandedPercentageFactor)) + (child.getHeight()/2); float distanceXToSubtract = ((mStartXPosition - mFinalXPosition) * (1f - expandedPercentageFactor)) + (child.getWidth()/2); float heightToSubtract = ((mStartHeight - finalHeight) * (1f - expandedPercentageFactor)); child.setY(mStartYPosition - distanceYToSubtract); child.setX(mStartXPosition - distanceXToSubtract); int proportionalAvatarSize = (int) (mAvatarMaxSize * (expandedPercentageFactor)); CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams(); lp.width = (int) (mStartHeight - heightToSubtract); lp.height = (int) (mStartHeight - heightToSubtract); child.setLayoutParams(lp); return true; } @SuppressLint("PrivateResource") private void maybeInitProperties(SimpleDraweeView child, View dependency) { if (mStartYPosition == 0) mStartYPosition = (int) (dependency.getY()); if (mFinalYPosition == 0) mFinalYPosition = (dependency.getHeight() /2); if (mStartHeight == 0) mStartHeight = child.getHeight(); if (finalHeight == 0) finalHeight = mContext.getResources().getDimensionPixelOffset(R.dimen.image_small_width); if (mStartXPosition == 0) mStartXPosition = (int) (child.getX() + (child.getWidth() / 2)); if (mFinalXPosition == 0) mFinalXPosition = mContext.getResources().getDimensionPixelOffset(R.dimen.abc_action_bar_content_inset_material) + (finalHeight / 2); if (mStartToolbarPosition == 0) mStartToolbarPosition = dependency.getY() + (dependency.getHeight()/2); } public int getStatusBarHeight() { int result = 0; int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = mContext.getResources().getDimensionPixelSize(resourceId); } return result; } }
picopalette/event-me
app/src/main/java/io/picopalette/apps/event_me/Utils/ImageBehaviour.java
Java
mit
4,149
require "rubygems" require "bundler/setup" require "mini_magick" require "sample_file/version" require "sample_file/base" require "sample_file/image" require "sample_file/video" module SampleFile class << self def image(type='png', opts={}) Image.new(type, opts).file end def image_path(type='png', opts={}) Image.new(type, opts).file_path end def video(type='h264', opts={}) Video.new(type, opts).file end def video_path(type='h264', opts={}) Video.new(type, opts).file_path end end end
mcls/sample_file
lib/sample_file.rb
Ruby
mit
553
<?php namespace JoshP\MainBundle\Entity; use Doctrine\ORM\Mapping as ORM; use FOS\UserBundle\Model\User as BaseUser; /** * User * * @ORM\Table() * @ORM\Entity(repositoryClass="JoshP\MainBundle\Entity\UserRepository") */ class User extends BaseUser { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * Get id * * @return integer */ public function getId() { return $this->id; } }
mushiie/hosting
src/src/JoshP/MainBundle/Entity/User.php
PHP
mit
555
const path = require('path') const merge = require('webpack-merge') const webpack = require('webpack') const baseWebpackConfig = require('./webpack.base.config') const ExtractTextPlugin = require("extract-text-webpack-plugin") const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') function resolve (dir) { return path.join(__dirname, '..', dir) } module.exports = merge(baseWebpackConfig, { output: { path: resolve('dist'), filename: '[name].[hash].js' }, plugins: [ // optimize css for production new OptimizeCSSPlugin({ cssProcessorOptions: { safe: true } }), new ExtractTextPlugin('style.[hash].css'), // split vendor js into separate file new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module) { // this assumes your vendor imports exist in the node_modules directory return module.context && module.context.indexOf("node_modules") !== -1; } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', chunks: ['vendor'] }), ] })
jocodev1/mithril-cli
src/build/webpack.prod.config.js
JavaScript
mit
1,266
/** * db.hpp * * Database abstraction part of Disc Data Base. * * Copyright (c) 2010-2011 Wincent Balin * * Based upon ddb.pl, created years before and serving faithfully until today. * * Uses SQLite database version 3. * * Published under MIT license. See LICENSE file for further information. */ #include "db.hpp" #include <sstream> #include <utility> #include <cassert> #include <boost/foreach.hpp> // Use shortcut from example #define foreach BOOST_FOREACH // Deprecated features not wanted #define BOOST_FILESYSTEM_NO_DEPRECATED #include <boost/filesystem.hpp> // Use a shortcut namespace fs = boost::filesystem; DB::DB(Print* print) { // Store pointer to the printer p = print; // Perform initialization init(); } void DB::init(void) { // Reset database pointer db = NULL; // Set version version = 1; // Define database format format.push_back("CREATE TABLE ddb (directory TEXT NOT NULL, file TEXT, disc TEXT NOT NULL)"); format.push_back("CREATE INDEX ddb_index ON ddb (directory, file, disc)"); format.push_back("CREATE TABLE ddb_version(version INTEGER NOT NULL)"); std::ostringstream ddb_version_table_contents; ddb_version_table_contents << "INSERT INTO ddb_version VALUES (" << version << ")"; format.push_back(ddb_version_table_contents.str()); } DB::~DB(void) throw(DBError) { // Close database close(); } void DB::open(const char* dbname, bool initialize) throw(DBError) { std::string error_message = std::string("Could not open file ") + dbname; int result; // Assume database is not open already assert(db == NULL); p->msg("Opening database...", Print::VERBOSE); // Open database result = sqlite3_open_v2(dbname, &db, SQLITE_OPEN_READWRITE, NULL); if(result != SQLITE_OK) throw(DBError(error_message), DBError::FILE_ERROR); p->msg("Done.", Print::DEBUG); } void DB::close(void) throw(DBError) { std::string error_message = "Could not close database"; int result; p->msg("Closing database...", Print::VERBOSE); // Close database result = sqlite3_close(db); // If something went wrong, throw an exception if(result != SQLITE_OK) throw(DBError(error_message, DBError::FILE_ERROR)); p->msg("Done.", Print::DEBUG); } bool DB::has_correct_format(void) throw(DBError) { const char* version_check = "SELECT COUNT(*) AS count, version FROM ddb_version"; std::string error_message = "Could not check database correctness"; int result; bool format_is_correct = false; // Prepare SQL statement sqlite3_stmt* stmt; result = sqlite3_prepare_v2(db, version_check, -1, &stmt, NULL); if(result != SQLITE_OK) throw(DBError(error_message, DBError::PREPARE_STATEMENT)); // Execute SQL statement result = sqlite3_step(stmt); if(result != SQLITE_ROW) throw(DBError(error_message, DBError::EXECUTE_STATEMENT)); // Result should have only one row if(sqlite3_column_int(stmt, 0) == 1) { // Version in database should be equal to the version of this class format_is_correct = (sqlite3_column_int(stmt, 1) == version); } // Finalize SQL statement result = sqlite3_finalize(stmt); if(result != SQLITE_OK) throw(DBError(error_message, DBError::FINALIZE_STATEMENT)); if(!format_is_correct) p->msg("Database has wrong format!", Print::INFO); // Return correctness return format_is_correct; } bool DB::is_disc_present(const char* discname) throw(DBError) { const char* disc_presence_check = "SELECT DISTINCT disc FROM ddb WHERE disc LIKE ?"; int result; bool disc_present = false; std::string error_message = "Could not check disc presence"; // Prepare SQL statement sqlite3_stmt* stmt; result = sqlite3_prepare_v2(db, disc_presence_check, -1, &stmt, NULL); if(result != SQLITE_OK) throw(DBError(error_message, DBError::PREPARE_STATEMENT)); // Execute SQL statement result = sqlite3_step(stmt); // Check whether we have at least one disc in the database if(result == SQLITE_ROW) { disc_present = true; } else if(result == SQLITE_DONE) { disc_present = false; } else { // We got an error throw(DBError(error_message, DBError::EXECUTE_STATEMENT)); } // Finalize SQL statement result = sqlite3_finalize(stmt); if(result != SQLITE_OK) throw(DBError(error_message, DBError::FINALIZE_STATEMENT)); // Return disc presence return disc_present; } void DB::add_disc(const char* disc_name, const char* starting_path) throw(DBError) { const char* begin_transaction = "BEGIN"; const char* add_entry = "INSERT INTO ddb (directory, file, disc) VALUES (?, ?, ?)"; const char* end_transaction = "COMMIT"; std::string error_message = std::string("Could not add disc ") + disc_name; int result; // Declare disc root directory fs::path disc_path(starting_path); // Check, whether disc path is a directory if(!fs::is_directory(disc_path)) throw(DBError(std::string("Path ") + starting_path + " is not a directory", DBError::FILE_ERROR)); // Container of file names std::vector<std::pair<fs::path, bool> > filenames; // Open directory and iterate through it recursively fs::path current_path; bool current_path_is_directory; fs::recursive_directory_iterator end; for(fs::recursive_directory_iterator dir(disc_path); dir != end; dir++) { current_path = dir->path(); current_path_is_directory = fs::is_directory(current_path); // Put current file name into vector filenames.push_back(std::make_pair(current_path, current_path_is_directory)); } // Sort filenames sort(filenames.begin(),filenames.end()); // Print file names, if verbosity is set high enough if(p->get_verbosity() >= Print::VERBOSE_DEBUG) { std::pair<fs::path, bool> it; foreach(it, filenames) { std::cout << (it.second ? "Directory" : "File") << " " << it.first << std::endl; } } // Begin transaction result = sqlite3_exec(db, begin_transaction, NULL, NULL, NULL); if(result != SQLITE_OK) throw(DBError(error_message, DBError::BEGIN_TRANSACTION)); // Prepare SQL statement sqlite3_stmt* stmt; sqlite3_prepare_v2(db, add_entry, -1, &stmt, NULL); if(result != SQLITE_OK) throw(DBError(error_message, DBError::PREPARE_STATEMENT)); // Bind disc name sqlite3_bind_text(stmt, 3, disc_name, -1, SQLITE_STATIC); if(result != SQLITE_OK) throw(DBError(error_message, DBError::BIND_PARAMETER)); p->msg("Inserting files into database...", Print::VERBOSE); // Add files bool file_is_directory; fs::path path; std::string d_entry; std::string f_entry; std::pair<fs::path, bool> it; foreach(it, filenames) { path = it.first; file_is_directory = it.second; d_entry = file_is_directory ? path.generic_string() : path.parent_path().generic_string(); f_entry = file_is_directory ? "NULL" : path.filename().generic_string(); // Reset SQL statement result = sqlite3_reset(stmt); if(result != SQLITE_OK) throw(DBError(error_message, DBError::RESET_STATEMENT)); // Bind directory and file result = sqlite3_bind_text(stmt, 1, d_entry.c_str(), -1, SQLITE_STATIC); if(result != SQLITE_OK) throw(DBError(error_message, DBError::BIND_PARAMETER)); result = sqlite3_bind_text(stmt, 2, f_entry.c_str(), -1, SQLITE_STATIC); if(result != SQLITE_OK) throw(DBError(error_message, DBError::BIND_PARAMETER)); // Execute SQL statement result = sqlite3_step(stmt); // Check for errors if(result != SQLITE_DONE) throw(DBError(error_message, DBError::EXECUTE_STATEMENT)); } // End transaction result = sqlite3_exec(db, end_transaction, NULL, NULL, NULL); if(result != SQLITE_OK) throw(DBError(error_message, DBError::END_TRANSACTION)); p->msg("Done.", Print::DEBUG); } void DB::remove_disc(const char* disc_name) throw(DBError) { const char* remove_query = "DELETE FROM ddb WHERE disc=?"; int result; std::string error_message = std::string("Could not remove disc ") + disc_name; // Initialize and prepare SQL statement sqlite3_stmt* stmt; result = sqlite3_prepare_v2(db, remove_query, -1, &stmt, NULL); if(result != SQLITE_OK) throw(DBError(error_message, DBError::PREPARE_STATEMENT)); // Bind disc name result = sqlite3_bind_text(stmt, 1, disc_name, -1, SQLITE_STATIC); if(result != SQLITE_OK) throw(DBError(error_message, DBError::BIND_PARAMETER)); // Execute SQL statement result = sqlite3_step(stmt); if(result != SQLITE_DONE) throw(DBError(error_message, DBError::EXECUTE_STATEMENT)); // Clean up result = sqlite3_finalize(stmt); if(result != SQLITE_OK) throw(DBError(error_message, DBError::FINALIZE_STATEMENT)); } void DB::list_files(const char* disc_name, bool directories_only) throw(DBError) { const char* list_files_query = "SELECT directory,file FROM ddb WHERE disc LIKE ?"; const char* list_directories_query = "SELECT DISTINCT directory FROM ddb WHERE disc LIKE ?"; const char* list_query = directories_only ? list_directories_query : list_files_query; std::string error_message = "Could not list " + directories_only ? "directories" : "files"; int result; // Prepare statement sqlite3_stmt* stmt; result = sqlite3_prepare_v2(db, list_query, -1, &stmt, NULL); if(result != SQLITE_OK) throw(DBError(error_message, DBError::PREPARE_STATEMENT)); // Bind disc name result = sqlite3_bind_text(stmt, 1, disc_name, -1, SQLITE_STATIC); if(result != SQLITE_OK) throw(DBError(error_message, DBError::BIND_PARAMETER)); // Get data const char* directory; const char* file; while(true) { // Execute SQL statement result = sqlite3_step(stmt); // Check whether we have at least one disc in the database if(result == SQLITE_ROW) { if(directories_only) { directory = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)); p->add_directory(disc_name, directory); } else { directory = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)); file = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1)); p->add_file(disc_name, directory, file); } } else if(result == SQLITE_DONE) { // No more results break; } else { // We got an error throw(DBError(error_message, DBError::EXECUTE_STATEMENT)); } } // Finalize statement result = sqlite3_finalize(stmt); if(result != SQLITE_OK) throw(DBError(error_message, DBError::FINALIZE_STATEMENT)); }
wincentbalin/DDB
db.cpp
C++
mit
11,489
package gea.api; public class Api extends Thread{ }
acalvoa/GEA-FRAMEWORK
src/gea/api/Api.java
Java
mit
55
<div class="set-area"> <form id="search" action="" method="get" class="searchform"> 用户名:<input type="text" value="<?=!empty($search['username']) ? $search['username'] : ''?>" name="username" class="input-txt w100" style=""> 真实姓名:<input type="text" value="<?=!empty($search['realname']) ? $search['realname'] : ''?>" name="realname" class="input-txt w100" style=""> 手机号:<input type="text" value="<?=!empty($search['mobile']) ? $search['mobile'] : ''?>" name="mobile" class="input-txt w100" style=""> <input type="submit" value="查 询" class="input-btn w70" > </form> <form method="post" id="form1" action="#"> <table class="table table-s1" width="100%" cellpadding="0" cellspacing="0" border="0"> <thead class="tb-tit-bg"> <tr> <th><div class="th-gap"><input type="checkbox" onclick="selallck(this)"> </div></th> <th><div class="th-gap">ID</div></th> <th><div class="th-gap">手机号</div></th> <th><div class="th-gap">注册时间</div></th> <th><div class="th-gap">操作</div></th> </tr> </thead> <tfoot class="td-foot-bg"> <tr> <td colspan="10"> <input type="button" value="删 除" onclick="delitem('a', this)"> <div class="pre-next"> <?php if(!empty($page_html)){ echo $page_html;}?></div></td> </tr> </tfoot> <tbody> <?php if( !empty( $list ) ):?> <?php foreach( $list as $k => $v ): $k++?> <tr id="item_<?=$v['id']?>"> <td><input type="checkbox" value="<?php echo $v['id'];?>" ></td> <td><?php echo $v['id'];?></td> <td> <?php echo $v['mobile'];?></td> <td><?php echo date('Y-m-d H:i:s' , $v['addtime']);?></td> <td> <a onclick="delitem('<?php echo $v['id']?>',this)" title="删除" href="javascript:;">删除</a> </td> </tr> <?php endforeach;?> <?php else:?> <tr> <td colspan="10><div class="no-data">没有数据</div></td> </tr> <?php endif;?> </tbody> </table> </form> </div> </div>
zl0314/ruida
bak/application/views/manager/usercp/index.php
PHP
mit
2,329
require 'spec_helper' module Donaghy module Middleware describe Stats do let(:manager) { man = mock(:manager, name: "test_mock_manager"); man.stub_chain(:async, :event_handler_finished).and_return(true); man } let(:event_handler) { EventHandler.new(manager) } let(:event) do Event.from_hash({ path: "ohhi", payload: {cool: true} }) end before do Donaghy.middleware do |m| m.clear m.add Stats end end after do event_handler.terminate if event_handler.alive? end describe "when successful" do before do event_handler.handle(event) end it "should inc the complete count" do storage.get('complete').to_i.should == 1 end it "should have in progress back down to 0 when its done" do storage.get('inprogress_count').to_i.should == 0 end it "should unset the inprogress id" do Array(storage.get('inprogress')).length.should == 0 end it "should remove the inprogress event" do storage.get("inprogress:#{event.id}").should be_nil end end describe "when erroring" do before do counter = 0 event.stub(:path) do |args| if counter == 0 counter += 1 raise StandardError end true end ->() { event_handler.handle(event) }.should raise_error(StandardError) end it "should not inc complete" do storage.get("complete").should be_nil end it "should cleanup inprogress" do storage.get('inprogress_count').to_i.should == 0 Array(storage.get('inprogress')).should be_empty storage.get("inprogress:#{event.id}").should be_nil end it "should save a json representation of the failure" do JSON.parse(storage.get("failure:#{event.id}"))['exception'].should == 'StandardError' end it "should add the failure id to the failures set" do storage.member_of?('failures', event.id).should be_true end it "should inc the failed count and raise the standard error" do storage.get('failed').to_i.should == 1 end describe "on its next successful pass through" do let(:second_eventhandler) { EventHandler.new(manager) } before do event.unstub(:path) second_eventhandler.handle(event) end after do second_eventhandler.terminate if second_eventhandler.alive? end it "should remove the failure id" do storage.member_of?('failures', event.id).should be_false end it "should delete the failures json" do storage.get("failure:#{event.id}").should be_nil end end end def storage Donaghy.storage end end end end
Amicus/donaghy
spec/lib/donaghy/middleware/stats_spec.rb
Ruby
mit
3,047
// extglyde // // Glyde Glue Plugin // (c)2015 by Cylexia, All Rights Reserved // // Version: 1.15.0625 // // MIT License var ExtGlyde = { GLUE_STOP_ACTION: -200, plane: null, // Canvas resources: null, styles: null, buttons: null, keys: null, button_sequence: [], timers: null, timer_manager: null, action: "", action_params: "", resume_label: "", last_action_id: "", window_title: "", window_width: -1, window_height: -1, background_colour: "#fff", _inited: false, init: function( canvas, filemanager ) { "use strict"; if( !ExtGlyde._inited ) { ExtGlyde.plane = canvas; ExtGlyde.reset(); ExtGlyde._inited = true; return true; } return false; }, reset: function() { ExtGlyde.clearUI(); ExtGlyde.resources = null; ExtGlyde.styles = null; ExtGlyde.timers = null; ExtGlyde.last_action_id = ""; ExtGlyde.window_title = ""; ExtGlyde.window_width = -1; ExtGlyde.window_height = -1; ExtGlyde.background_colour = "#fff"; }, setSize: function( w, h ) { ExtGlyde.window_width = w; ExtGlyde.window_height = h; ExtGlyde.plane.width = w;//(w + "px"); ExtGlyde.plane.height = h;//(h + "px"); ExtGlyde._drawRect( ExtGlyde.getBitmap(), { x: 0, y: 0, width: w, height: h, colour: ExtGlyde.background_colour }, true ); }, getWindowTitle: function() { return ExtGlyde.window_title; }, getWindowWidth: function() { return ExtGlyde.window_width; }, getWindowHeight: function() { return ExtGlyde.window_height; }, /** * If set then the script requests that the given action be performed then resumed from * getResumeLabel(). This is cleared once read * @return the action or null */ getAction: function() { var o = ExtGlyde.action; ExtGlyde.action = null; return o; }, getActionParams: function() { return ExtGlyde.action_params; }, /** * Certain actions call back to the runtime host and need to be resumed, resume from this label * This is cleared once read * @return the label */ getResumeLabel: function() { var o = ExtGlyde.resume_label; ExtGlyde.resume_label = null; return o; }, /** * The bitmap the drawing operations use * @return */ getBitmap: function() { return ExtGlyde.plane.getContext( "2d" ); }, /** * Called when this is attached to a {@link com.cylexia.mobile.lib.glue.Glue} instance * * @param g the instance being attached to */ glueAttach: function( f_plugin, f_glue ) { window.addEventListener( "keydown", function( e ) { ExtGlyde._keyDownHandler( f_glue, (e || window.event) ); } ); window.addEventListener( "keypress", function( e ) { ExtGlyde._keyPressHandler( f_glue, (e || window.event) ); } ); }, /** * Called to execute a glue command * * @param w the command line. The command is in "_" * @param vars the current Glue variables map * @return 1 if the command was successful, 0 if it failed or -1 if it didn't belong to this * plugin */ glueCommand: function( glue, w, vars ) { var cmd = Dict.valueOf( w, "_" ); if( cmd && cmd.startsWith( "f." ) ) { var wc = Dict.valueOf( w, cmd ); cmd = cmd.substring( 2 ); if( (cmd == "setwidth") || (cmd == "setviewwidth") ) { return ExtGlyde.setupView( w ); } else if( cmd == "settitle" ) { return ExtGlyde.setTitle( wc, w ); } else if( cmd == "doaction" ) { return ExtGlyde.doAction( wc, w ); } else if( (cmd == "clear") || (cmd == "clearview") ) { ExtGlyde.clearUI(); } else if( cmd == "loadresource" ) { return ExtGlyde.loadResource( glue, wc, Dict.valueOf( w, "as" ) ); } else if( cmd == "removeresource" ) { if( ExtGlyde.resources !== null ) { delete ExtGlyde.resources[wc]; } } else if( cmd == "setstyle" ) { ExtGlyde.setStyle( wc, w ); } else if( cmd == "getlastactionid" ) { Dict.set( vars, Dict.valueOf( w, "into" ), ExtGlyde.last_action_id ); } else if( cmd == "onkey" ) { if( ExtGlyde.keys === null ) { ExtGlyde.keys = Dict.create(); } var ke = Dict.create(); Dict.set( ke, "label", Dict.valueOf( w, "goto" ) ); Dict.set( ke, "id", Dict.valueOf( w, "useid" ) ); Dict.set( ExtGlyde.keys, wc, ke ); } else if( cmd == "starttimer" ) { ExtGlyde._startTimer( glue, wc, Dict.intValueOf( w, "interval" ), Dict.valueOf( w, "ontickgoto" ) ); } else if( cmd == "stoptimer" ) { ExtGlyde._stopTimer( wc ); } else if( cmd == "stopalltimers" ) { ExtGlyde._stopTimer( "" ); } else if( cmd == "drawas" ) { ExtGlyde.drawAs( wc, w ); } else if( cmd == "writeas" ) { // TODO: colour return ExtGlyde.writeAs( wc, w ); } else if( (cmd == "markas") || (cmd == "addbutton") ) { return ExtGlyde.markAs( wc, w ); } else if( cmd == "paintrectas" ) { return ExtGlyde.paintRectAs( wc, w, false ); } else if( cmd == "paintfilledrectas" ) { return ExtGlyde.paintRectAs( wc, w, true ); } else if( cmd == "exit" ) { if( chrome && chrome.app ) { chrome.app.window.current().close(); } else if( window ) { window.close(); } return Glue.PLUGIN_DONE_EXIT_ALL; } else { return -1; } return 1; } return 0; }, getLabelForButtonAt: function( i_x, i_y ) { if( ExtGlyde.buttons !== null ) { for( var i = 0; i < ExtGlyde.button_sequence.length; i++ ) { var id = ExtGlyde.button_sequence[i]; var btn = ExtGlyde.buttons[id]; var r = ExtGlyde.Button.getRect( btn ); if( ExtGlyde.Rect.containsPoint( r, i_x, i_y ) ) { ExtGlyde.last_action_id = id; return ExtGlyde.Button.getLabel( btn ); } } } return null; }, /** * Get the id of the button at the given index * @param index the index of the button * @return the id or null if the index is out of bounds */ getButtonIdAtIndex: function( index ) { if( ExtGlyde.button_sequence.length > 0 ) { if( (index >= 0) && (index < ExtGlyde.button_sequence.length) ) { return ExtGlyde.button_sequence[index]; } } return null; }, /** * Get the rect of the given indexed button * @param index the button index * @return the rect as ExtGlyde.Rect or null if index is out of bounds */ getButtonRectAtIndex: function( index ) { var id = ExtGlyde.getButtonIdAtIndex( index ); if( id !== null ) { return ExtGlyde.Button.getRect( ExtGlyde.buttons[id] ); } return null; }, /** * Return the label for the given indexed button. Also sets the lastActionId value * @param index the index * @return the label or null if index is out of bounds */ getButtonLabelAtIndex: function( index ) { if( (index >= 0) && (index < ExtGlyde.button_sequence.length) ) { var id = button_sequence[index]; if( id !== null ) { ExtGlyde.last_action_id = id; return ExtGlyde.Button.getLabel( buttons[id] ); } } return null; }, getButtonCount: function() { return ExtGlyde.button_sequence.length; }, /** * Add a definition to the (lazily created) styles map. Note, the complete string is stored * so beware that keys like "_" and "f.setstyle" are added too * @param name string: the name of the style * @param data map: the complete arguments string */ setStyle: function( name, data ) { if( ExtGlyde.styles === null ) { ExtGlyde.styles = Dict.create(); } Dict.set( ExtGlyde.styles, name, data ); }, setupView: function( w ) { if( Dict.containsKey( w, "backgroundcolour" ) ) { ExtGlyde.background_colour = Dict.valueOf( w, "backgroundcolour" ); } else { this.background = "#fff"; } ExtGlyde.setSize( Dict.intValueOf( w, Dict.valueOf( w, "_" ) ), Dict.intValueOf( w, "height" ) ); return true; }, setTitle: function( wc, w ) { var tb_title = _.e( "tb_title" ); if( tb_title ) { tb_title.removeChild( tb_title.childNodes[0] ); _.at( tb_title, wc ); } if( window ) { window.title = wc; document.title = wc; } _.e( "windowtitlebar" ).style["display"] = (wc ? "block" : "none"); return 1; }, clearUI: function() { ExtGlyde.button_sequence = []; if( ExtGlyde.buttons !== null ) { Dict.delete( ExtGlyde.buttons ); } ExtGlyde.buttons = Dict.create(); if( ExtGlyde.keys !== null ) { Dict.delete( ExtGlyde.keys ); } ExtGlyde.keys = Dict.create(); ExtGlyde.setSize( ExtGlyde.window_width, ExtGlyde.window_height ); }, doAction: function( s_action, d_w ) { "use strict"; ExtGlyde.action = s_action; ExtGlyde.action_params = Dict.valueOf( d_w, "args", Dict.valueOf( d_w, "withargs" ) ); var done_label = Dict.valueOf( d_w, "ondonegoto" ); ExtGlue.resume_label = ( done_label + "\t" + Dict.valueOf( d_w, "onerrorgoto", done_label ) + "\t" + Dict.valueOf( d_w, "onunsupportedgoto", done_label ) ); return ExtFrontEnd.GLUE_STOP_ACTION; // expects labels to be DONE|ERROR|UNSUPPORTED }, // TODO: this should use a rect and alignment options along with colour support writeAs: function( s_id, d_args ) { "use strict"; ExtGlyde.updateFromStyle( d_args ); var text = Dict.valueOf( d_args, "value" ); var rect = ExtGlyde.Rect.createFromCommandArgs( d_args ); var x = ExtGlyde.Rect.getLeft( rect ); var y = ExtGlyde.Rect.getTop( rect ); var rw = ExtGlyde.Rect.getWidth( rect ); var rh = ExtGlyde.Rect.getHeight( rect ); var size = Dict.intValueOf( d_args, "size", 2 ); var thickness = Dict.intValueOf( d_args, "thickness", 1 ); var tw = (VecText.getGlyphWidth( size, thickness ) * text.length); var th = VecText.getGlyphHeight( size, thickness ); var tx, ty; if( rw > 0 ) { var align = Dict.valueOf( d_args, "align", "2" ); if( (align == "2") || (align == "centre") ) { tx = (x + ((rw - tw) / 2)); } else if( (align == "1" ) || (align == "right") ) { tx = (x + (rw - tw)); } else { tx = x; } } else { rw = tw; tx = x; } if( rh > 0 ) { ty = (y + ((rh - th) / 2)); } else { rh = th; ty = y; } VecText.drawString( ExtGlyde.getBitmap(), text, Dict.valueOf( d_args, "colour", "#000" ), tx, ty, size, thickness, (thickness + 1) ); rect = ExtGlyde.Rect.create( x, y, rw, rh ); // Dict: ExtGlyde.Rect return ExtGlyde.buttonise( s_id, rect, d_args ); }, drawAs: function( s_id, d_args ) { ExtGlyde.updateFromStyle( d_args ); var rect = ExtGlyde.Rect.createFromCommandArgs( d_args ); var rid = Dict.valueOf( d_args, "id", Dict.valueOf( d_args, "resource" ) ); if( ExtGlyde.resources !== null ) { var b = rid.indexOf( '.' ); if( b > -1 ) { var resid = rid.substring( 0, b ); var imgid = rid.substring( (b + 1) ); var keys = Dict.keys( ExtGlyde.resources ); for( var i = 0; i < keys.length; i++ ) { var imgmap = Dict.valueOf( ExtGlyde.resources, keys[i] ); // imgmap: ExtGlyde.ImageMap var x = ExtGlyde.Rect.getLeft( rect ); var y = ExtGlyde.Rect.getTop( rect ); if( ExtGlyde.ImageMap.drawToCanvas( imgmap, imgid, ExtGlyde.getBitmap(), x, y ) ) { var maprect = ExtGlyde.ImageMap.getRectWithId( imgmap, imgid ); var imgrect = ExtGlyde.Rect.create( x, y, ExtGlyde.Rect.getWidth( maprect ), ExtGlyde.Rect.getHeight( maprect ) ); return ExtGlyde.buttonise( s_id, imgrect, d_args ); } } } } return false; }, markAs: function( s_id, d_args ) { ExtGlyde.updateFromStyle( d_args ); return ExtGlyde.buttonise( s_id, ExtGlyde.Rect.createFromCommandArgs( d_args ), m_args ); }, paintRectAs: function( s_id, d_args, b_filled ) { ExtGlyde.updateFromStyle( d_args ); var rect = ExtGlyde.Rect.createFromCommandArgs( d_args ); var d = Dict.create(); Dict.set( d, "rect", rect ); Dict.set( d, "colour", Dict.valueOf( d_args, "colour", "#000" ) ); ExtGlyde._drawRect( ExtGlyde.getBitmap(), d, b_filled ); return ExtGlyde.buttonise( s_id, rect, d_args ); }, buttonise: function( s_id, d_rect, d_args ) { "use strict"; if( Dict.containsKey( d_args, "border" ) ) { var d = Dict.create(); Dict.set( d, "rect", d_rect ); Dict.set( d, "colour", Dict.valueOf( d_args, "colour", "#000" ) ); ExtGlyde._drawRect( ExtGlyde.getBitmap(), d ); } if( Dict.containsKey( d_args, "onclickgoto" ) ) { return ExtGlyde.addButton( s_id, d_rect, Dict.valueOf( d_args, "onclickgoto" ) ); } else { return true; } }, addButton: function( s_id, d_rect, s_label ) { if( ExtGlyde.buttons === null ) { ExtGlyde.buttons = Dict.create(); ExtGlyde.button_sequence = []; } if( !Dict.containsKey( ExtGlyde.buttons, s_id ) ) { Dict.set( ExtGlyde.buttons, s_id, ExtGlyde.Button.createFromRect( d_rect, s_label ) ); ExtGlyde.button_sequence.push( s_id ); return true; } return false; }, updateFromStyle: function( d_a ) { "use strict"; if( (ExtGlyde.styles === null) || (ExtGlyde.styles.length === 0) ) { return; } if( Dict.containsKey( d_a, "style" ) ) { var style = Dict.valueOf( styles, Dict.valueOf( d_a, "style" ) ); var keys = Dict.keys( style ); for( var i = 0; i < keys.length; i++ ) { var k = keys[i]; if( !Dict.containsKey( d_a, k ) ) { Dict.set( d_a, k, Dict.valueOf( style, keys[i] ) ); } } } }, loadResource: function( o_glue, s_src, s_id ) { if( ExtGlyde.resources === null ) { ExtGlyde.resources = Dict.create(); } if( Dict.containsKey( ExtGlyde.resources, s_id ) ) { // deallocate } // resources can be replaced using the same ids var data = GlueFileManager.readText( s_src ); Dict.set( ExtGlyde.resources, s_id, ExtGlyde.ImageMap.create( data ) ); return true; }, _drawRect: function( o_context, d_def, b_filled ) { "use strict"; var x, y, w, h; if( Dict.containsKey( d_def, "rect" ) ) { var r = Dict.dictValueOf( d_def, "rect" ); x = ExtGlyde.Rect.getLeft( r ); y = ExtGlyde.Rect.getTop( r ); w = ExtGlyde.Rect.getWidth( r ); h = ExtGlyde.Rect.getHeight( r ); } else { x = Dict.intValueOf( d_def, "x" ); y = Dict.intValueOf( d_def, "y" ); w = Dict.intValueOf( d_def, "width" ); h = Dict.intValueOf( d_def, "height" ); } if( b_filled ) { o_context.fillStyle = Dict.valueOf( d_def, "colour", "#000" ); o_context.fillRect( x, y, w, h ); } else { o_context.fillStyle = "none"; o_context.strokeStyle = Dict.valueOf( d_def, "colour", "#000" ); o_context.lineWidth = 1; o_context.strokeRect( x, y, w, h ); } }, _timerFired: function() { if( ExtGlyde.timers ) { for( var id in ExtGlyde.timers ) { var t = ExtGlyde.timers[id]; t["count"]--; if( t["count"] === 0 ) { t["count"] = t["reset"]; Glue.run( t["glue"], t["label"] ); } } } }, _startTimer: function( o_glue, s_id, i_tenths, s_label ) { if( !ExtGlyde.timers ) { ExtGlyde.timer_manager = window.setInterval( ExtGlyde._timerFired, 100 ); // install our timer ExtGlyde.timers = {}; } var t = { "glue": o_glue, "count": i_tenths, "reset": i_tenths, "label": s_label }; ExtGlyde.timers[s_id] = t; }, _stopTimer: function( s_id ) { if( !ExtGlyde.timers ) { return; } if( s_id ) { if( ExtGlyde.timers[s_id] ) { delete ExtGlyde.timers[s_id]; } if( ExtGlyde.timers.length > 0 ) { return; } } // out of timers or requested that we stop them all if( ExtGlyde.timer_manager ) { window.clearInterval( ExtGlyde.timer_manager ); ExtGlyde.timer_manager = null; } ExtGlyde.timers = null; }, // keyboard handling _keyDownHandler: function( f_glue, e ) { e = (e || window.event); var kmap = { 37: "direction_left", 38: "direction_up", 39: "direction_right", 40: "direction_down", 27: "escape", 9: "tab", 13: "enter", 8: "backspace", 46: "delete", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12" }; if( e.keyCode in kmap ) { if( ExtGlyde._notifyKeyPress( f_glue, kmap[e.keyCode] ) ) { e.preventDefault(); } } }, _keyPressHandler: function( f_glue, e ) { e = (e || window.event ); if( ExtGlyde._notifyKeyPress( f_glue, String.fromCharCode( e.charCode ) ) ) { e.preventDefault(); } }, _notifyKeyPress: function( f_glue, s_key ) { // boolean if( ExtGlyde.keys && (s_key in ExtGlyde.keys) ) { var ke = ExtGlyde.keys[s_key]; ExtGlyde.last_action_id = Dict.valueOf( ke, "id" ); Glue.run( f_glue, Dict.valueOf( ke, "label" ) ); return true; } return false; }, /** * Stores a button */ Button: { create: function( i_x, i_y, i_w, i_h, s_label ) { // Dict: ExtGlyde.Button return Button.createFromRect( ExtGlyde.Rect.create( i_x, i_y, i_w, i_h ), s_label ); }, createFromRect: function( d_rect, s_label ) { // Dict: ExtGlyde.Button var d = Dict.create(); Dict.set( d, "rect", d_rect ); Dict.set( d, "label", s_label ); return d; }, getLabel: function( d_button ) { return d_button.label; }, getRect: function( d_button ) { return d_button.rect; } }, /** * Access to a Rect */ Rect: { create: function( i_x, i_y, i_w, i_h ) { // Dict: ExtGlyde.Rect var r = Dict.create(); Dict.set( r, "x", i_x ); Dict.set( r, "y", i_y ); Dict.set( r, "w", i_w ); Dict.set( r, "h", i_h ); return r; }, createFromCommandArgs: function( d_args ) { // Dict: ExtGlyde.Rect "use strict"; var x = Dict.intValueOf( d_args, "x", Dict.intValueOf( d_args, "atx" ) ); var y = Dict.intValueOf( d_args, "y", Dict.intValueOf( d_args, "aty" ) ); var w = Dict.intValueOf( d_args, "width" ); var h = Dict.intValueOf( d_args, "height" ); return ExtGlyde.Rect.create( x, y, w, h ); }, containsPoint: function( d_rect, i_x, i_y ) { var rx = Dict.intValueOf( d_rect, "x" ); var ry = Dict.intValueOf( d_rect, "y" ); if( (i_x >= rx) && (i_y >= ry) ) { if( (i_x < (rx + Dict.intValueOf( d_rect, "w" ))) && (i_y < (ry + Dict.intValueOf( d_rect, "h" ))) ) { return true; } } return false; }, getLeft: function( o_rect ) { return o_rect.x; }, getTop: function( o_rect ) { return o_rect.y; }, getWidth: function( o_rect ) { return o_rect.w; }, getHeight: function( o_rect ) { return o_rect.h; }, getRight: function( o_rect ) { return (o_rect.x + o_rect.w); }, getBottom: function( o_rect ) { return (o_rect.y + o_rect.h); } }, /** * Processes a .map source loading the image named in it or the specified image * @returns a Dict for use with ExtGlyde.ImageMap */ ImageMap: { create: function( s_mapdata ) { // Dict: ImageMap var im = Dict.create(); var im_rects = Dict.create(); var e, i; var key, value; var bmpsrc; while( (i = s_mapdata.indexOf( ";" )) > -1 ) { var line = s_mapdata.substr( 0, i ).trim(); s_mapdata = s_mapdata.substr( (i + 1) ); e = line.indexOf( "=" ); if( e > -1 ) { key = line.substring( 0, e ); value = line.substring( (e + 1) ); if( key.startsWith( "." ) ) { if( key == ".img" ) { if( !bmpsrc ) { bmpsrc = value; } } } else { Dict.set( im_rects, key, ExtGlyde.ImageMap._decodeRect( value ) ); } } } Dict.set( im, "image", ExtGlyde.ImageMap._loadBitmap( bmpsrc ) ); Dict.set( im, "rects", im_rects ); return im; }, getRectWithId: function( o_imap, s_id ) { // Dict: ExtGlyde.Rect var d_rects = Dict.dictValueOf( o_imap, "rects" ); return Dict.dictValueOf( d_rects, s_id ); }, drawToCanvas: function( o_imap, s_id, o_context, i_x, i_y ) { "use strict"; var src = ExtGlyde.ImageMap.getRectWithId( o_imap, s_id ); // Dict: ExtGlyde.Rect if( src !== null ) { var w = ExtGlyde.Rect.getWidth( src ); var h = ExtGlyde.Rect.getHeight( src ); o_context.drawImage( o_imap.image, ExtGlyde.Rect.getLeft( src ), ExtGlyde.Rect.getTop( src ), w, h, i_x, i_y, w, h ); return true; } return false; }, _loadBitmap: function( s_src ) { var data = GlueFileManager.readBinary( s_src ); if( data !== null ) { return data; } // show an error some how return null; }, _decodeRect: function( s_e ) { // Dict if( s_e.charAt( 1 ) == ':' ) { var l = (s_e.charCodeAt( 0 ) - 48); var i = 2, x, y, w, h; x = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) ); i += l; y = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) ); i += l; w = ExtGlyde.ImageMap.toInt( s_e.substring( i, (i + l) ) ); i += l; h = ExtGlyde.ImageMap.toInt( s_e.substring( i ) ); return ExtGlyde.Rect.create( x, y, w, h ); } return null; }, toInt: function( s_v ) { var n = parseInt( s_v ); if( !isNaN( n ) ) { return n; } return 0; } } };
cylexia/glyde-chromeapp
glue/extglyde.js
JavaScript
mit
21,282
// Copyright (c) 2014 blinkbox Entertainment Limited. All rights reserved. package com.blinkboxbooks.android.authentication; import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.accounts.NetworkErrorException; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import com.blinkboxbooks.android.api.BBBApiConstants; import com.blinkboxbooks.android.api.model.BBBTokenResponse; import com.blinkboxbooks.android.api.net.BBBRequest; import com.blinkboxbooks.android.api.net.BBBRequestFactory; import com.blinkboxbooks.android.api.net.BBBRequestManager; import com.blinkboxbooks.android.api.net.BBBResponse; import com.blinkboxbooks.android.controller.AccountController; import com.blinkboxbooks.android.ui.account.LoginActivity; import com.blinkboxbooks.android.util.LogUtils; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; /** * Implementation of AbstractAccountAuthenticator. Subclasses only need to override the getLaunchAuthenticatorActivityIntent() method to return an Intent which will launch * an Activity which is a subclass of AccountAuthenticatorActivity */ public class BBBAuthenticator extends AbstractAccountAuthenticator { private static final String TAG = BBBAuthenticator.class.getSimpleName(); private final Context mContext; public BBBAuthenticator(Context context) { super(context); mContext = context; } /** * {inheritDoc} */ public Bundle addAccount(AccountAuthenticatorResponse accountAuthenticatorResponse, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { Intent intent = new Intent(mContext, LoginActivity.class); intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse); Bundle bundle = new Bundle(); bundle.putParcelable(AccountManager.KEY_INTENT, intent); return bundle; } /** * {inheritDoc} */ public Bundle confirmCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, Bundle options) throws NetworkErrorException { return null; } /** * {inheritDoc} */ public Bundle editProperties(AccountAuthenticatorResponse accountAuthenticatorResponse, String accountType) { throw new UnsupportedOperationException(); } /** * {inheritDoc} */ public Bundle getAuthToken(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String authTokenType, Bundle options) throws NetworkErrorException { AccountManager am = AccountManager.get(mContext); //first check to see if we already have an access token in the AccountManager cache String accessToken = am.peekAuthToken(account, authTokenType); if (accessToken != null) { Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); result.putString(AccountManager.KEY_AUTHTOKEN, accessToken); return result; } //if we don't have a valid access token we try and get a new one with the refresh token String refreshToken = am.getUserData(account, BBBApiConstants.PARAM_REFRESH_TOKEN); String clientId = am.getUserData(account, BBBApiConstants.PARAM_CLIENT_ID); String clientSecret = am.getUserData(account, BBBApiConstants.PARAM_CLIENT_SECRET); if (!TextUtils.isEmpty(refreshToken)) { BBBRequest request = BBBRequestFactory.getInstance().createGetRefreshAuthTokenRequest(refreshToken, clientId, clientSecret); BBBResponse response = BBBRequestManager.getInstance().executeRequestSynchronously(request); if (response == null) { throw new NetworkErrorException("Could not get auth token with refresh token"); } String json = response.getResponseData(); BBBTokenResponse authenticationResponse = null; if (json != null) { try { authenticationResponse = new Gson().fromJson(json, BBBTokenResponse.class); } catch (JsonSyntaxException e) { LogUtils.d(TAG, e.getMessage(), e); } } if (authenticationResponse != null) { accessToken = authenticationResponse.access_token; refreshToken = authenticationResponse.refresh_token; if (!TextUtils.isEmpty(accessToken)) { Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, BBBApiConstants.AUTHTOKEN_TYPE); result.putString(AccountManager.KEY_AUTHTOKEN, authenticationResponse.access_token); AccountController.getInstance().setAccessToken(account, accessToken); AccountController.getInstance().setRefreshToken(account, refreshToken); return result; } } } //if we can't get an access token via the cache or by using the refresh token we must return an Intent which will launch an Activity allowing the user to perform manual authentication Intent intent = new Intent(mContext, LoginActivity.class); intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse); intent.putExtra(BBBApiConstants.PARAM_USERNAME, account.name); intent.putExtra(BBBApiConstants.PARAM_AUTHTOKEN_TYPE, authTokenType); Bundle bundle = new Bundle(); bundle.putParcelable(AccountManager.KEY_INTENT, intent); return bundle; } /** * {inheritDoc} */ public String getAuthTokenLabel(String authTokenType) { //we don't need to display the authTokenType in the account manager so we return null return null; } /** * {inheritDoc} */ public Bundle hasFeatures(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String[] features) throws NetworkErrorException { Bundle result = new Bundle(); result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false); return result; } /** * {inheritDoc} */ public Bundle updateCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String authTokenType, Bundle options) throws NetworkErrorException { return null; } }
blinkboxbooks/android-app
app/src/main/java/com/blinkboxbooks/android/authentication/BBBAuthenticator.java
Java
mit
6,858
using Heisenslaught.Infrastructure.MongoDb; using System.Collections.Generic; namespace Heisenslaught.Draft { public interface IDraftStore : ICrudMongoStore<string, DraftModel> { DraftModel FindByDraftToken(string draftToken); List<DraftModel> FindByUserId(string userId); } }
chetjan/heisenslaught
src/Heisenslaught/Context/Draft/Stores/IDraftStore.cs
C#
mit
309
import React, { Component, PropTypes } from 'react'; import { Image } from 'react-bootstrap'; require('./styles.scss'); class SocialBar extends Component { constructor(props) { super(props); } render() { const { icon, url } = this.props; return ( <a href={url} target="_blank"> <Image src={icon} className="profile-header-social-icon" /> </a> ); } } SocialBar.propTypes = { children: PropTypes.any, icon: PropTypes.any.isRequired, url: PropTypes.string.isRequired, }; export default SocialBar;
sebacorrea33/todoinstitutos
src/containers/ProfilePage/ProfileHeader/SocialIcon.js
JavaScript
mit
602
<!doctype html> <html> <head> <title>我抢到红包啦</title> <meta charset="utf-8"> <meta name="keywords" content="倍全,倍全商城,倍全订货,社区O2O,社区便利店,网上超市,济南社区020,便利店O2O,济南社区便利店" /> <meta name="description" content="倍全商城-倍全旗下品牌,济南同城最快速的便利店商品订购派送网站" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="bookmark" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <meta content="width=device-width, minimum-scale=1,initial-scale=1, maximum-scale=1, user-scalable=1;" id="viewport" name="viewport" /> <meta content="yes" name="apple-mobile-web-app-capable" /> <meta content="black" name="apple-mobile-web-app-status-bar-style" /> <meta content="telephone=no" name="format-detection" /> <!--<link rel="/touch/apple-touch-startup-image" href="startup.png" />--> <!--<link rel="apple-touch-icon" href="/touch/iphon_tetris_icon.png"/>--> <link type="text/css" rel="stylesheet" href="<?php echo $this->res_base . "/" . 'bqmart/template/css/com/com.css'; ?>"/> <link type="text/css" rel="stylesheet" href="<?php echo $this->res_base . "/" . 'bqmart/template/css/home/index.css'; ?>"/> <link type="text/css" rel="stylesheet" href="<?php echo $this->res_base . "/" . 'bqmart/template/css/cart/index.css'; ?>" /> <script src="<?php echo $this->res_base . "/" . 'bqmart/js/jquery.js'; ?>"></script> <script src="<?php echo $this->res_base . "/" . 'bqmart/template/js/com/com.js'; ?>"></script> <script src="<?php echo $this->res_base . "/" . 'bqmart/template/js/com/template.js'; ?>"></script> </head> <body> <div class="com-content"> <div class="com-header-area" id="js-com-header-area"> <dfn></dfn> <span class="bq_header_title" style="padding-left:0px;">抢红包成功</span> <div class="clear"></div> </div> <div class="com-content-area" id="js-com-content-area" style=" margin:0px;"> <div class="page-role cart_empty-page"> <div class="pxui-area"> <div class="cart_empty-top"> <p> <span class="cart_empty-topicon"></span>今天又赚大发了~~ </p> </div> <div class="bq_cplb_bg" ></div> <div class="cart_empty-info"> <div class="login_success-img"> <img src="themes/bqmart/template/images/cart/bq_login_success.png" > </div> <p> 红包金额:<span style="color:red;"><?php echo $this->_var['hongbao']['coupon_value']; ?></span>个大金元宝 </p> <p> 使用次数:<span style="color:red;"><?php echo $this->_var['hongbao']['use_times']; ?></span>次 </p> <p>倍全曹操为你待命中……</p> <div class="cart_empty-btn"> <a type="button" href="/index.php?app=store&id=<?php echo $this->_var['sid']; ?>" >去 逛 逛</a> </div> <div class="login_success-btn"> <a type="button" href="/index.php?app=hongbao" >查看红包</a> </div> </div> </div> </div> <?php echo $this->fetch('member.footer.html'); ?> </div> </div> <?php echo $this->fetch('store.menu.html'); ?> </body> </html>
guotao2000/ecmall
temp/compiled/wapmall/qhb.success.html.php
PHP
mit
3,740
from django import forms from django.core.validators import validate_email from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from .utils import get_user_model class PasswordRecoveryForm(forms.Form): username_or_email = forms.CharField() error_messages = { 'not_found': _("Sorry, this user doesn't exist."), } def __init__(self, *args, **kwargs): self.case_sensitive = kwargs.pop('case_sensitive', True) search_fields = kwargs.pop('search_fields', ('username', 'email')) super(PasswordRecoveryForm, self).__init__(*args, **kwargs) message = ("No other fields than email are supported " "by default") if len(search_fields) not in (1, 2): raise ValueError(message) for field in search_fields: if field not in ['username', 'email']: raise ValueError(message) labels = { 'username': _('Username'), 'email': _('Email'), 'both': _('Username or Email'), } User = get_user_model() # noqa if getattr(User, 'USERNAME_FIELD', 'username') == 'email': self.label_key = 'email' elif len(search_fields) == 1: self.label_key = search_fields[0] else: self.label_key = 'both' self.fields['username_or_email'].label = labels[self.label_key] def clean_username_or_email(self): username = self.cleaned_data['username_or_email'] cleaner = getattr(self, 'get_user_by_%s' % self.label_key) self.cleaned_data['user'] = cleaner(username) return username def get_user_by_username(self, username): key = 'username__%sexact' % ('' if self.case_sensitive else 'i') User = get_user_model() try: user = User._default_manager.get(**{key: username}) except User.DoesNotExist: raise forms.ValidationError(self.error_messages['not_found'], code='not_found') return user def get_user_by_email(self, email): validate_email(email) key = 'email__%sexact' % ('' if self.case_sensitive else 'i') User = get_user_model() try: user = User._default_manager.get(**{key: email}) except User.DoesNotExist: raise forms.ValidationError(self.error_messages['not_found'], code='not_found') return user def get_user_by_both(self, username): key = '__%sexact' key = key % '' if self.case_sensitive else key % 'i' f = lambda field: Q(**{field + key: username}) filters = f('username') | f('email') User = get_user_model() try: user = User._default_manager.get(filters) except User.DoesNotExist: raise forms.ValidationError(self.error_messages['not_found'], code='not_found') except User.MultipleObjectsReturned: raise forms.ValidationError(_("Unable to find user.")) return user class PasswordResetForm(forms.Form): password1 = forms.CharField( label=_('New password'), widget=forms.PasswordInput, ) password2 = forms.CharField( label=_('New password (confirm)'), widget=forms.PasswordInput, ) error_messages = { 'password_mismatch': _("The two passwords didn't match."), } def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(PasswordResetForm, self).__init__(*args, **kwargs) def clean_password2(self): password1 = self.cleaned_data.get('password1', '') password2 = self.cleaned_data['password2'] if not password1 == password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch') return password2 def save(self, commit=True): self.user.set_password(self.cleaned_data['password1']) if commit: get_user_model()._default_manager.filter(pk=self.user.pk).update( password=self.user.password, ) return self.user
xsunfeng/cir
password_reset/forms.py
Python
mit
4,276
'use strict'; describe('heroList', function(){ //Load module that contains the heroList component beforeEach(module('heroList')); describe('HeroListController', function(){ it('should create a `heroes` model with 6 heroes', inject(function($componentController){ var ctrl = $componentController('heroList'); expect(ctrl.heroes.length).toBe(6); })); }); });
MichaelRandall/heroes-villians
app/hero-list/hero-list.component.spec.js
JavaScript
mit
377
// to be used if new modules are added to MSF. Mamoru.Sync.allModules = function(){ var moduleFixtures = { exploit: 'module.exploits', post: 'module.post', auxiliary: 'module.auxiliary', payload: 'module.payloads', encoder: 'module.encoders', nop: 'module.nops', }; // get module stats from MSF //var modStats = msfAPI.clientExec(Mamoru.API.client,['core.module_stats']); var fullModArray = []; for (key in moduleFixtures) { var modCatArray = msfAPI.clientExec([moduleFixtures[key]]); for(var i=0;i<modCatArray.length;i++){ if(!moduleIsInMongo(modCatArray[i],key)){ fullModArray.push({mod:modCatArray[i],cat:key}) } } }; var aJob = new Job(Mamoru.Collections.Jobs, 'syncModules', {modules:fullModArray}); aJob.priority('high').save(); Mamoru.Queues.fixtures.trigger(); } // sync MSF workspaces with Mamoru projects Mamoru.Sync.allProjects = function(){ var tempConsole = Mamoru.Utils.createConsole() var msfWorkspacesObj = msfAPI.clientExec(['db.workspaces']); for(var i=0;i<msfWorkspacesObj.workspaces.length;i++){ if(Mamoru.Collections.Projects.find({name:msfWorkspacesObj.workspaces[i].name}).count() === 0){ Mamoru.Collections.Projects.insert(msfWorkspacesObj.workspaces[i]); } } Mamoru.Utils.destroyConsole(tempConsole.id); } Mamoru.Sync.Sessions = function(){ var knownSessions = Mamoru.Collections.Sessions.find(); var currentSessions = Mamoru.Utils.listSessions(); var numSessions = Object.keys(currentSessions).length; if(numSessions > 0){ for(var k in currentSessions){ if(Mamoru.Collections.Sessions.findOne({exploit_uuid: currentSessions[k]["exploit_uuid"] }) == undefined ){ currentSessions[k]["startedAt"] = moment.now(); currentSessions[k]["runBy"] = Meteor.users.findOne(Meteor.userId()).username; currentSessions[k]["sessionId"] = k; currentSessions[k]["established"] = true; Mamoru.Collections.Sessions.insert(currentSessions[k]); } } } else { // set sessions as not established... var oldSessionsList = knownSessions.fetch() var updateObj = {established: false, stoppedAt: moment.now()} for(var i=0; i < oldSessionsList.length(); i++){ Mamoru.Collections.Sessions.update({_id: oldSessionsList[i]._id }, {$set: updateObj }); } } } // used to compare mongo and pg records to determine if something needs to be syncronized.. function checkHost(msfRecord, mongoRecord){ //console.log(msfRecord); var needsUpdate = false; var fieldsToUpdate = {} for(var key in msfRecord){ if(msfRecord[key] != mongoRecord[key]){ fieldsToUpdate[key] = msfRecord[key]; needsUpdate = true; } } var msfServices = Mamoru.Utils.getHostServices(msfRecord.address) if(msfServices){ msfServices = msfServices.map((service)=>{ delete service.host; return service; }); } if(msfServices.length != mongoRecord.services.length){ needsUpdate = true; fieldsToUpdate.services = msfServices; } var msfNotes = Mamoru.Utils.getHostNotes(msfRecord.address) if(msfNotes){ msfServices = msfNotes.map((note)=>{ delete note.host; return note; }); } if(msfNotes.length != mongoRecord.notes.length){ needsUpdate = true; fieldsToUpdate.notes = msfNotes; } var msfVulns = Mamoru.Utils.getHostVulns(msfRecord.address) if(msfVulns){ msfVulns = msfVulns.map((vuln)=>{ delete vuln.host; return vuln; }); } if(msfVulns.length != mongoRecord.vulns.length){ needsUpdate = true; fieldsToUpdate.vulns = msfVulns; } return {needsUpdate:needsUpdate,toUpdate:fieldsToUpdate} } Mamoru.Sync.AllProjectHosts = function(projectName){ let thisWorkspace = Mamoru.Collections.Projects.findOne({name:projectName}); Mamoru.Utils.setProject(thisWorkspace.name); //get hosts array from msf let hostsObj = msfAPI.clientExec(['db.hosts', {}]); // loop hosts array for(var h=0;h<hostsObj.hosts.length;h++){ let thisHost = Mamoru.Collections.Hosts.findOne({projectId:thisWorkspace._id, address:hostsObj.hosts[h].address}); //if that host does not exist, retrieve hosts services and insert into mongo if(!thisHost){ //set extra fields not returned directly from MSF for mongo organization / 'relationships' console.log(`syncing host ${hostsObj.hosts[h].address} from pg to mongo`) hostsObj.hosts[h].projectId = thisWorkspace._id // insert in mongo, which will trigger insert hook. Mamoru.Collections.Hosts.insert(hostsObj.hosts[h]); // else update according to what is in msf for the host } else { console.log('host exists'); var ch = checkHost(hostsObj.hosts[h],thisHost); // if MSF update_at date is not the same as mongos update_at date if(ch.needsUpdate) { console.log('host needs update'); // will not trigger hook Mamoru.Collections.Hosts.direct.update(thisHost._id, {$set:ch.toUpdate}); } } } } Mamoru.Sync.projectHost = function(projectSlug, hostAddress){ let thisWorkspace = Mamoru.Collections.Projects.findOne({slug:projectSlug}); Mamoru.Utils.setProject(thisWorkspace.name); let hostFromMSF = Mamoru.Utils.hostInfo(hostAddress)[0]; let thisHost = Mamoru.Collections.Hosts.findOne({projectId:thisWorkspace._id, address:hostAddress}); //if that host does not exist, retrieve hosts services and insert into mongo if(!thisHost){ //set extra fields not returned directly from MSF for mongo organization / 'relationships' hostFromMSF.projectId = thisWorkspace._id // insert in mongo, which will trigger insert hook. Mamoru.Collections.Hosts.insert(hostFromMSF); // else update according to what is in msf for the host } else { console.log('host exists'); var ch = checkHost(hostFromMSF,thisHost); if(ch.needsUpdate) { console.log('host needs update'); // will not trigger hook Mamoru.Collections.Hosts.direct.update(thisHost._id, {$set:ch.toUpdate}); } } } Mamoru.Sync.ConsolePool = function(){ var poolSize = Meteor.settings.consolePoolSize let currentConsoles = Mamoru.Utils.listConsoles(); if(currentConsoles.consoles && currentConsoles.consoles.length != poolSize){ try { createConsolePool() } catch(err){ console.log("whoa, creating console pool failed: try again in 5 seconds"); Meteor.setTimeout(()=>{Mamoru.Sync.ConsolePool()}, 5000); } } } // scoped to this file function createConsolePool(){ var poolSize = Meteor.settings.consolePoolSize //check if there are existing consoles let existingConsoles = Mamoru.Utils.listConsoles(); console.log(existingConsoles); let numExistingConsoles = existingConsoles.consoles.length console.log(`there are ${numExistingConsoles} existing consoles`); //array of existing console Ids according to MSF let existingConsoleMsfIds = existingConsoles.consoles.map((cons)=>{ return cons.id; }); // remove any consoles in mongo that do not have a matching MSF consoles let numConsolesRemoved = Mamoru.Collections.Consoles.direct.remove({msfId:{$nin:existingConsoleMsfIds}}); if(numConsolesRemoved){ console.log(`removed ${numConsolesRemoved} consoles, from the collection which do not match msf consoles`); } //remove extras consoles if(numExistingConsoles > poolSize){ let consolesToRemove = existingConsoles.splice(0,existingConsoles-poolSize) for(let i=0;i<consolesToRemove.length;i++){ let existsInMongo = Mamoru.Collections.Consoles.findOne({msfId:consolesToRemove[i].id}); if(existsInMongo){ Mamoru.Collections.Consoles.remove(existsInMongo._id); } else { Mamoru.Utils.destroyConsole(consolesToRemove[i].id); } console.log(`removed extra consoleId: ${consolesToRemove[i].id}`); } //add consoles if not enough } else if (numExistingConsoles < poolSize){ for(; numExistingConsoles < poolSize; numExistingConsoles++){ let newConsole = Mamoru.Collections.Consoles.insert({}); let newConsoleId = Mamoru.Collections.Consoles.findOne(newConsole).msfId console.log(`added consoleId: ${newConsoleId} to the pool`); } //ensure msfIds are syncronized } else { Mamoru.Collections.Consoles.direct.remove({}); existingConsoles.forEach((msfConsole)=>{ Mamoru.Collections.Consoles.direct.insert( { msfId:msfConsole.id, prompt:msfConsole.prompt, busy:msfConsole.busy, createdAt:moment().unix() } ); console.log(`synced consoleId: ${msfConsole.id}`); }); } }
mamoru-vm/mamoru
mamoru/server/lib/sync.js
JavaScript
mit
9,615
<?php namespace Ds\Component\System\Query; /** * Class TenantParameters * * @package Ds\Component\System */ class TenantParameters implements Parameters { use Base; }
DigitalState/Core
src/System/Query/TenantParameters.php
PHP
mit
177
require 'childprocess' require 'tempfile' require 'shellwords' require 'aruba/errors' require 'aruba/processes/basic_process' require 'aruba/platform' # Aruba module Aruba # Platforms module Processes # Spawn a process for command # # `SpawnProcess` is not meant for direct use - `SpawnProcess.new` - by # users. Only it's public methods are part of the public API of aruba, e.g. # `#stdin`, `#stdout`. # # @private class SpawnProcess < BasicProcess # Use as default launcher def self.match?(mode) true end # Create process # # @params [String] cmd # Command string # # @params [Integer] exit_timeout # The timeout until we expect the command to be finished # # @params [Integer] io_wait_timeout # The timeout until we expect the io to be finished # # @params [String] working_directory # The directory where the command will be executed def initialize(cmd, exit_timeout, io_wait_timeout, working_directory, environment = ENV.to_hash.dup, main_class = nil, stop_signal = nil, startup_wait_time = 0) super @process = nil @stdout_cache = nil @stderr_cache = nil end # Run the command # # @yield [SpawnProcess] # Run code for process which was started # # rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/CyclomaticComplexity def start # rubocop:disable Metrics/LineLength fail CommandAlreadyStartedError, %(Command "#{commandline}" has already been started. Please `#stop` the command first and `#start` it again. Alternatively use `#restart`.\n#{caller.join("\n")}) if started? # rubocop:enable Metrics/LineLength @started = true @process = ChildProcess.build(*[command_string.to_a, arguments].flatten) @stdout_file = Tempfile.new('aruba-stdout-') @stderr_file = Tempfile.new('aruba-stderr-') @stdout_file.sync = true @stderr_file.sync = true @exit_status = nil @duplex = true before_run @process.leader = true @process.io.stdout = @stdout_file @process.io.stderr = @stderr_file @process.duplex = @duplex @process.cwd = @working_directory @process.environment.update(environment) begin Aruba.platform.with_environment(environment) do @process.start sleep startup_wait_time end rescue ChildProcess::LaunchError => e raise LaunchError, "It tried to start #{cmd}. " + e.message end after_run yield self if block_given? end # rubocop:enable Metrics/MethodLength # rubocop:enable Metrics/CyclomaticComplexity # Access to stdout of process def stdin return if @process.exited? @process.io.stdin end # Access to stdout of process # # @param [Hash] opts # Options # # @option [Integer] wait_for_io # Wait for IO to be finished # # @return [String] # The content of stdout def stdout(opts = {}) return @stdout_cache if stopped? wait_for_io opts.fetch(:wait_for_io, io_wait_timeout) do @process.io.stdout.flush open(@stdout_file.path).read end end # Access to stderr of process # # @param [Hash] opts # Options # # @option [Integer] wait_for_io # Wait for IO to be finished # # @return [String] # The content of stderr def stderr(opts = {}) return @stderr_cache if stopped? wait_for_io opts.fetch(:wait_for_io, io_wait_timeout) do @process.io.stderr.flush open(@stderr_file.path).read end end def read_stdout # rubocop:disable Metrics/LineLength Aruba.platform.deprecated('The use of "#read_stdout" is deprecated. Use "#stdout" instead. To reduce the time to wait for io, pass `:wait_for_io => 0` or some suitable for your use case') # rubocop:enable Metrics/LineLength stdout(:wait_for_io => 0) end def write(input) return if stopped? @process.io.stdin.write(input) @process.io.stdin.flush self end # Close io def close_io(name) return if stopped? if RUBY_VERSION < '1.9' @process.io.send(name.to_sym).close else @process.io.public_send(name.to_sym).close end end # Stop command def stop(*) return @exit_status if stopped? begin @process.poll_for_exit(@exit_timeout) rescue ChildProcess::TimeoutError @timed_out = true end terminate end # Wait for command to finish def wait @process.wait end # Terminate command def terminate return @exit_status if stopped? unless @process.exited? if @stop_signal # send stop signal ... send_signal @stop_signal # ... and set the exit status wait else @process.stop end end @exit_status = @process.exit_code @stdout_cache = read_temporary_output_file @stdout_file @stderr_cache = read_temporary_output_file @stderr_file # @stdout_file = nil # @stderr_file = nil @started = false @exit_status end # Output pid of process # # This is the PID of the spawned process. def pid @process.pid end # Send command a signal # # @param [String] signal # The signal, i.e. 'TERM' def send_signal(signal) fail CommandAlreadyStoppedError, %(Command "#{commandline}" with PID "#{pid}" has already stopped.) if @process.exited? Process.kill signal, pid rescue Errno::ESRCH raise CommandAlreadyStoppedError, %(Command "#{commandline}" with PID "#{pid}" has already stopped.) end # Return file system stats for the given command # # @return [Aruba::Platforms::FilesystemStatus] # This returns a File::Stat-object def filesystem_status Aruba.platform.filesystem_status.new(command_string.to_s) end # Content of command # # @return [String] # The content of the script/command. This might be binary output as # string if your command is a binary executable. def content File.read command_string.to_s end private def command_string # gather fully qualified path cmd = Aruba.platform.which(command, environment['PATH']) # rubocop:disable Metrics/LineLength fail LaunchError, %(Command "#{command}" not found in PATH-variable "#{environment['PATH']}".) if cmd.nil? # rubocop:enable Metrics/LineLength Aruba.platform.command_string.new(cmd) end def wait_for_io(time_to_wait, &block) sleep time_to_wait.to_i block.call end def read_temporary_output_file(file) file.flush file.rewind data = file.read file.close data end end end end
jasnow/aruba
lib/aruba/processes/spawn_process.rb
Ruby
mit
7,406
package com.github.scaronthesky.eternalwinterwars.view.entities; public interface IMeasureableEntity { public float getWidth(); public float getHeight(); }
hinogi/eternalwinterwars
src/com/github/scaronthesky/eternalwinterwars/view/entities/IMeasureableEntity.java
Java
mit
160