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.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("03. Divide by 7 and 5")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03. Divide by 7 and 5")] [assembly: AssemblyCopyright("Copyright © 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("e39d4973-5720-4482-88c8-6b5370631ff7")] // 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")]
Camyul/CSharp-2016--Before-Begining
03. Operators and Expressions/03. Divide by 7 and 5/Properties/AssemblyInfo.cs
C#
mit
1,418
<?php namespace DataSift\Tests\Stubs; use DataSift_IStreamConsumerEventHandler; class StubEventHandler implements DataSift_IStreamConsumerEventHandler { public function onConnect($consumer) { } public function onInteraction($consumer, $interaction, $hash) { } public function onDeleted($consumer, $interaction, $hash) { } public function onStatus($consumer, $type, $info) { } public function onWarning($consumer, $message) { } public function onError($consumer, $message) { } public function onDisconnect($consumer) { } public function onStopped($consumer, $reason) { } }
datasift/datasift-php
tests/Stubs/StubEventHandler.php
PHP
mit
678
// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "ParserFlatbuffersSerializeFixture.hpp" #include <armnnDeserializer/IDeserializer.hpp> #include <string> TEST_SUITE("Deserializer_Reshape") { struct ReshapeFixture : public ParserFlatbuffersSerializeFixture { explicit ReshapeFixture(const std::string &inputShape, const std::string &targetShape, const std::string &outputShape, const std::string &dataType) { m_JsonString = R"( { inputIds: [0], outputIds: [2], layers: [ { layer_type: "InputLayer", layer: { base: { layerBindingId: 0, base: { index: 0, layerName: "InputLayer", layerType: "Input", inputSlots: [{ index: 0, connection: {sourceLayerIndex:0, outputSlotIndex:0 }, }], outputSlots: [ { index: 0, tensorInfo: { dimensions: )" + inputShape + R"(, dataType: )" + dataType + R"( }}] } }}}, { layer_type: "ReshapeLayer", layer: { base: { index: 1, layerName: "ReshapeLayer", layerType: "Reshape", inputSlots: [{ index: 0, connection: {sourceLayerIndex:0, outputSlotIndex:0 }, }], outputSlots: [ { index: 0, tensorInfo: { dimensions: )" + inputShape + R"(, dataType: )" + dataType + R"( }}]}, descriptor: { targetShape: )" + targetShape + R"(, } }}, { layer_type: "OutputLayer", layer: { base:{ layerBindingId: 2, base: { index: 2, layerName: "OutputLayer", layerType: "Output", inputSlots: [{ index: 0, connection: {sourceLayerIndex:0, outputSlotIndex:0 }, }], outputSlots: [ { index: 0, tensorInfo: { dimensions: )" + outputShape + R"(, dataType: )" + dataType + R"( }, }], }}}, }] } )"; SetupSingleInputSingleOutput("InputLayer", "OutputLayer"); } }; struct SimpleReshapeFixture : ReshapeFixture { SimpleReshapeFixture() : ReshapeFixture("[ 1, 9 ]", "[ 3, 3 ]", "[ 3, 3 ]", "QuantisedAsymm8") {} }; struct SimpleReshapeFixture2 : ReshapeFixture { SimpleReshapeFixture2() : ReshapeFixture("[ 2, 2, 1, 1 ]", "[ 2, 2, 1, 1 ]", "[ 2, 2, 1, 1 ]", "Float32") {} }; TEST_CASE_FIXTURE(SimpleReshapeFixture, "ReshapeQuantisedAsymm8") { RunTest<2, armnn::DataType::QAsymmU8>(0, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }); } TEST_CASE_FIXTURE(SimpleReshapeFixture2, "ReshapeFloat32") { RunTest<4, armnn::DataType::Float32>(0, { 111, 85, 226, 3 }, { 111, 85, 226, 3 }); } }
ARM-software/armnn
src/armnnDeserializer/test/DeserializeReshape.cpp
C++
mit
4,881
'use strict'; // Teams controller angular.module('teams').controller('TeamsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Teams', 'Players', '$filter', function($scope, $stateParams, $location, Authentication, Teams, Players, $filter) { $scope.authentication = Authentication; // Create new Team $scope.create = function() { // Create new Team object var team = new Teams ({ name: this.name }); // Redirect after save team.$save(function(response) { $location.path('teams/' + response._id); // Clear form fields $scope.name = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Team $scope.remove = function(team) { if ( team ) { team.$remove(); for (var i in $scope.teams) { if ($scope.teams [i] === team) { $scope.teams.splice(i, 1); } } } else { $scope.team.$remove(function() { $location.path('teams'); }); } }; // Update existing Team $scope.update = function() { var team = $scope.team; team.$update(function() { $location.path('teams/' + team._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Find a list of Teams $scope.find = function() { $scope.teams = Teams.query(); }; // Find existing Team $scope.findOne = function() { $scope.team = Teams.get({ teamId: $stateParams.teamId }); $scope.players = Players.query({ 'team': $stateParams.teamId }); }; } ]);
nithinreddygaddam/ScoreNow
public/modules/teams/controllers/teams.client.controller.js
JavaScript
mit
1,559
package info.jchein.apps.nr.codetest.ingest.app; import info.jchein.apps.nr.codetest.ingest.config.IngestConfiguration; import info.jchein.apps.nr.codetest.ingest.config.ParametersConfiguration; import info.jchein.apps.nr.codetest.ingest.messages.EventConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; public class SpringMain implements CommandLineRunner { // private static final Logger LOG = LoggerFactory.getLogger(SpringMain.class); public static void main(String[] args) throws InterruptedException { SpringApplication app = new SpringApplicationBuilder( SpringMain.class, IngestConfiguration.class, EventConfiguration.class, ParametersConfiguration.class) .headless(true) .main(SpringMain.class).application(); app.run(args); } @Autowired ApplicationWatchdog applicationWatchdog; @Autowired ConfigurableApplicationContext applicationContext; // CTXT.registerShutdownHook(); // Thread.sleep(2000); // CTXT.stop(); @Override public void run(String... args) throws Exception { applicationContext.registerShutdownHook(); applicationContext.start(); applicationWatchdog.blockUntilTerminatedOrInterrupted(); } }
jheinnic/reactor-readnums
readnums-app/src/main/java/info/jchein/apps/nr/codetest/ingest/app/SpringMain.java
Java
mit
1,517
package linguadde.exception; import java.util.LinkedHashSet; import java.util.Set; public class NoTranslationException extends Exception { private static final Set<String> messages = new LinkedHashSet<String>(); public NoTranslationException(String message) { super(message); messages.add(message); } public static Set<String> getMessages() { return messages; } }
Theyssen/LinguAdde
src/main/java/linguadde/exception/NoTranslationException.java
Java
mit
412
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ /* eslint no-console: ["error", { allow: ["log"] }] */ const gulp = require('gulp'); const modifyFile = require('gulp-modify-file'); const path = require('path'); const rollup = require('rollup'); const buble = require('rollup-plugin-buble'); const replace = require('rollup-plugin-replace'); const commonjs = require('rollup-plugin-commonjs'); const resolve = require('rollup-plugin-node-resolve'); const vue = require('rollup-plugin-vue'); function buildKs(cb) { const env = process.env.NODE_ENV || 'development'; const target = process.env.TARGET || 'universal'; const buildPath = env === 'development' ? './build' : './packages'; let f7VuePath = path.resolve(__dirname, `../${buildPath}/vue/framework7-vue.esm.js`); let f7Path = path.resolve(__dirname, `../${buildPath}/core/framework7.esm.bundle`); if (process.platform.indexOf('win') === 0) { f7VuePath = f7VuePath.replace(/\\/g, '/'); f7Path = f7Path.replace(/\\/g, '/'); } gulp.src('./kitchen-sink/vue/index.html') .pipe(modifyFile((content) => { if (env === 'development') { return content .replace('../../packages/core/css/framework7.min.css', '../../build/core/css/framework7.css') .replace('../../packages/core/js/framework7.min.js', '../../build/core/js/framework7.js'); } return content .replace('../../build/core/css/framework7.css', '../../packages/core/css/framework7.min.css') .replace('../../build/core/js/framework7.js', '../../packages/core/js/framework7.min.js'); })) .pipe(gulp.dest('./kitchen-sink/vue')); rollup.rollup({ input: './kitchen-sink/vue/src/app.js', plugins: [ replace({ delimiters: ['', ''], 'process.env.NODE_ENV': JSON.stringify(env), 'process.env.TARGET': JSON.stringify(target), "'framework7-vue'": () => `'${f7VuePath}'`, "'framework7/framework7.esm.bundle'": () => `'${f7Path}'`, }), resolve({ jsnext: true }), commonjs(), vue(), buble({ objectAssign: 'Object.assign', }), ], onwarn(warning, warn) { const ignore = ['EVAL']; if (warning.code && ignore.indexOf(warning.code) >= 0) { return; } warn(warning); }, }).then(bundle => bundle.write({ format: 'umd', name: 'app', strict: true, sourcemap: false, file: './kitchen-sink/vue/js/app.js', })).then(() => { if (cb) cb(); }).catch((err) => { console.log(err); if (cb) cb(); }); } module.exports = buildKs;
AdrianV/Framework7
scripts/build-ks-vue.js
JavaScript
mit
2,621
package introsde.document.ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for measure complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="measure"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="dateRegistered" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="measureType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="measureValue" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;element name="measureValueType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="mid" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "measure", propOrder = { "dateRegistered", "measureType", "measureValue", "measureValueType", "mid" }) public class Measure { protected String dateRegistered; protected String measureType; protected double measureValue; protected String measureValueType; protected int mid; /** * Gets the value of the dateRegistered property. * * @return * possible object is * {@link String } * */ public String getDateRegistered() { return dateRegistered; } /** * Sets the value of the dateRegistered property. * * @param value * allowed object is * {@link String } * */ public void setDateRegistered(String value) { this.dateRegistered = value; } /** * Gets the value of the measureType property. * * @return * possible object is * {@link String } * */ public String getMeasureType() { return measureType; } /** * Sets the value of the measureType property. * * @param value * allowed object is * {@link String } * */ public void setMeasureType(String value) { this.measureType = value; } /** * Gets the value of the measureValue property. * */ public double getMeasureValue() { return measureValue; } /** * Sets the value of the measureValue property. * */ public void setMeasureValue(double value) { this.measureValue = value; } /** * Gets the value of the measureValueType property. * * @return * possible object is * {@link String } * */ public String getMeasureValueType() { return measureValueType; } /** * Sets the value of the measureValueType property. * * @param value * allowed object is * {@link String } * */ public void setMeasureValueType(String value) { this.measureValueType = value; } /** * Gets the value of the mid property. * */ public int getMid() { return mid; } /** * Sets the value of the mid property. * */ public void setMid(int value) { this.mid = value; } }
robzenn92/introsde
assignment_3_client/src/introsde/document/ws/Measure.java
Java
mit
3,546
/* * Angular 2 decorators and services */ import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import {LocationStrategy, PlatformLocation, Location} from '@angular/common'; import * as $ from 'jquery'; import {AppRunner} from './core/appRunner'; /* * App Component * Top Level Component */ @Component({ selector: 'app', encapsulation: ViewEncapsulation.None, styleUrls: [ './app.component.css' ], template: ` <router-outlet></router-outlet> ` }) export class AppComponent implements OnInit { constructor(private appRunner: AppRunner) { this.appRunner.run(); } public ngOnInit() { } public isLogin() { /*let titlee = this.location.prepareExternalUrl(this.location.path()); titlee = titlee.slice(1); if ('/login' === titlee) { return false; } else { return true; }*/ } }
antpost/antpost-client
src/app/app.component.ts
TypeScript
mit
948
<?php namespace Richpolis\ShoppingCartBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Richpolis\ShoppingCartBundle\Entity\CategoriaProducto; use Richpolis\ShoppingCartBundle\Form\CategoriaProductoType; /** * CategoriaProducto controller. * * @Route("/categoriaproducto") */ class CategoriaProductoController extends Controller { /** * Lists all CategoriaProducto entities. * * @Route("/", name="categoriaproducto") * @Method("GET") * @Template() */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('RichpolisShoppingCartBundle:CategoriaProducto')->findAll(); return array( 'entities' => $entities, ); } /** * Creates a new CategoriaProducto entity. * * @Route("/", name="categoriaproducto_create") * @Method("POST") * @Template("RichpolisShoppingCartBundle:CategoriaProducto:new.html.twig") */ public function createAction(Request $request) { $entity = new CategoriaProducto(); $form = $this->createCreateForm($entity); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('categoriaproducto_show', array('id' => $entity->getId()))); } return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Creates a form to create a CategoriaProducto entity. * * @param CategoriaProducto $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm(CategoriaProducto $entity) { $form = $this->createForm(new CategoriaProductoType(), $entity, array( 'action' => $this->generateUrl('categoriaproducto_create'), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Create')); return $form; } /** * Displays a form to create a new CategoriaProducto entity. * * @Route("/new", name="categoriaproducto_new") * @Method("GET") * @Template() */ public function newAction() { $entity = new CategoriaProducto(); $form = $this->createCreateForm($entity); return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Finds and displays a CategoriaProducto entity. * * @Route("/{id}", name="categoriaproducto_show") * @Method("GET") * @Template() */ public function showAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('RichpolisShoppingCartBundle:CategoriaProducto')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find CategoriaProducto entity.'); } $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), ); } /** * Displays a form to edit an existing CategoriaProducto entity. * * @Route("/{id}/edit", name="categoriaproducto_edit") * @Method("GET") * @Template() */ public function editAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('RichpolisShoppingCartBundle:CategoriaProducto')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find CategoriaProducto entity.'); } $editForm = $this->createEditForm($entity); $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Creates a form to edit a CategoriaProducto entity. * * @param CategoriaProducto $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createEditForm(CategoriaProducto $entity) { $form = $this->createForm(new CategoriaProductoType(), $entity, array( 'action' => $this->generateUrl('categoriaproducto_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $form->add('submit', 'submit', array('label' => 'Update')); return $form; } /** * Edits an existing CategoriaProducto entity. * * @Route("/{id}", name="categoriaproducto_update") * @Method("PUT") * @Template("RichpolisShoppingCartBundle:CategoriaProducto:edit.html.twig") */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('RichpolisShoppingCartBundle:CategoriaProducto')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find CategoriaProducto entity.'); } $deleteForm = $this->createDeleteForm($id); $editForm = $this->createEditForm($entity); $editForm->handleRequest($request); if ($editForm->isValid()) { $em->flush(); return $this->redirect($this->generateUrl('categoriaproducto_edit', array('id' => $id))); } return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Deletes a CategoriaProducto entity. * * @Route("/{id}", name="categoriaproducto_delete") * @Method("DELETE") */ public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('RichpolisShoppingCartBundle:CategoriaProducto')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find CategoriaProducto entity.'); } $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('categoriaproducto')); } /** * Creates a form to delete a CategoriaProducto entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('categoriaproducto_delete', array('id' => $id))) ->setMethod('DELETE') ->add('submit', 'submit', array('label' => 'Delete')) ->getForm() ; } }
richpolis/sf2Maldivino
src/Richpolis/ShoppingCartBundle/Controller/CategoriaProductoController.php
PHP
mit
7,257
namespace ArmyOfCreatures.Extended.Specialties { using System; using System.Globalization; using ArmyOfCreatures.Logic.Specialties; public class DoubleDamage : Specialty { private int rounds; public DoubleDamage(int rounds) { if (rounds <= 0) { throw new ArgumentOutOfRangeException("rounds", "The number of rounds should be greater than 0"); } if (rounds > 10) { throw new ArgumentOutOfRangeException("rounds", "The number of rounds should be lesser than 11"); } this.rounds = rounds; } public override decimal ChangeDamageWhenAttacking( Logic.Battles.ICreaturesInBattle attackerWithSpecialty, Logic.Battles.ICreaturesInBattle defender, decimal currentDamage) { if (attackerWithSpecialty == null) { throw new ArgumentNullException("attackerWithSpecialty"); } if (defender == null) { throw new ArgumentNullException("defender"); } return currentDamage * 2; } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0}({1})", base.ToString(), this.rounds); } } }
enchev-93/Telerik-Academy
03.C Sharp OOP/Exam OOP/Problem2/Source/ArmyOfCreatures/Extended/Specialties/DoubleDamage.cs
C#
mit
1,391
using System; using System.Collections.Generic; using System.Data.SQLite; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DescontosFidelidade { public static class DbHelper { public const string DbFileName = @".dados"; public static string BackupAppDataPath { get { var pathBase = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return pathBase + @"\DescontosFidelidade\Backup\"; } } public static string BackupDocumentsPath { get { var pathBase = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); return pathBase + @"\DescontosFidelidade\Backup\"; } } private static string _dataBasePath = null; public static string DataBaseLocation { get { return _dataBasePath ?? (_dataBasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DbFileName)); } } public static bool ExistsDataBase() { return File.Exists(DataBaseLocation); } public static bool CanRestoreDataBase() { var localAppData = Path.Combine(BackupAppDataPath, DbFileName); var localProgramFiles = Path.Combine(BackupDocumentsPath, DbFileName); if (File.Exists(localAppData)) { File.Copy(localAppData, DataBaseLocation); File.SetAttributes(DataBaseLocation, FileAttributes.Hidden); return true; } else if (File.Exists(localProgramFiles)) { File.Copy(localProgramFiles, DataBaseLocation); File.SetAttributes(DataBaseLocation, FileAttributes.Hidden); return true; } return false; } public static void CreateNewDataBase() { SQLiteConnection.CreateFile(DataBaseLocation); File.SetAttributes(DataBaseLocation, FileAttributes.Hidden); using (var cn = new SQLiteConnection("Data Source=" + DataBaseLocation)) { cn.Open(); using (var cmd = cn.CreateCommand()) { cmd.CommandText = @"create table Cliente (Codigo INTEGER, Nome TEXT, Endereco TEXT, Telefone TEXT)"; cmd.ExecuteNonQuery(); } using (var cmd = cn.CreateCommand()) { cmd.CommandText = @"create table Produto (Codigo INTEGER, Produto TEXT, PrecoTabela REAL)"; cmd.ExecuteNonQuery(); } using (var cmd = cn.CreateCommand()) { cmd.CommandText = @"create table Desconto (Produto INTEGER, Cliente INTEGER, PrecoVenda REAL)"; cmd.ExecuteNonQuery(); } } Backup(); } public static void Backup() { Directory.CreateDirectory(BackupDocumentsPath); Directory.CreateDirectory(BackupAppDataPath); File.Copy(DataBaseLocation, BackupDocumentsPath + DbFileName, true); File.Copy(DataBaseLocation, BackupAppDataPath + DbFileName, true); File.SetAttributes(BackupDocumentsPath + DbFileName, FileAttributes.Normal); File.SetAttributes(BackupAppDataPath + DbFileName, FileAttributes.Normal); } } }
chalkmaster/TabelaDescontos
src/DescontosFidelidade/DBHelper.cs
C#
mit
3,616
class AddPrecisionToBudgets < ActiveRecord::Migration def change add_column :budgets, :precision, :integer end end
cowbell/splitr
db/migrate/20130916102637_add_precision_to_budgets.rb
Ruby
mit
123
using System.Drawing; using System.IO; // ReSharper disable once CheckNamespace namespace Quarks.ImageExtensions { public static class ImageExtensions { public static byte[] ToByteArray(this Bitmap image) { using (image) using (var stream = new MemoryStream()) { image.Save(stream, System.Drawing.Imaging.ImageFormat.Png); return stream.ToArray(); } } } }
SeatwaveOpenSource/pdiffy
PDiffy/Quarks/ImageExtensions/ToByteArray.cs
C#
mit
475
require 'rails_helper' require "#{Rails.root}/lib/wiki_pageviews" describe WikiPageviews do describe '.views_for_article' do context 'for a popular article' do let(:title) { 'Selfie' } let(:start_date) { '2015-10-01'.to_date } let(:end_date) { '2015-11-01'.to_date } let(:subject) do WikiPageviews.views_for_article(title, start_date: start_date, end_date: end_date) end it 'returns a hash of daily views for all the requested dates' do VCR.use_cassette 'wiki_pageviews/views_for_article' do expect(subject).to be_a Hash expect(subject.count).to eq(32) end end it 'always returns the same value for a certain date' do VCR.use_cassette 'wiki_pageviews/views_for_article' do expect(subject['20151001']).to eq(2164) end end end end describe '.average_views_for_article' do let(:subject) { WikiPageviews.average_views_for_article(title) } context 'for a popular article' do let(:title) { 'Selfie' } it 'returns the average page views' do VCR.use_cassette 'wiki_pageviews/average_views' do expect(subject).to be > 500 end end end context 'for an article with a slash in the title' do let(:title) { 'HIV/AIDS' } it 'returns the average page views' do VCR.use_cassette 'wiki_pageviews/average_views' do expect(subject).to be > 500 end end end context 'for an article with an apostrophe in the title' do let(:title) { "Broussard's" } it 'returns the average page views' do VCR.use_cassette 'wiki_pageviews/average_views' do expect(subject).to be > 1 end end end context 'for an article with quote marks in the title' do let(:title) { '"Weird_Al"_Yankovic' } it 'returns the average page views' do VCR.use_cassette 'wiki_pageviews/average_views' do expect(subject).to be > 50 end end end context 'for an article with unicode characters in the title' do let(:title) { 'André_the_Giant' } it 'returns the average page views' do VCR.use_cassette 'wiki_pageviews/average_views' do expect(subject).to be > 50 end end end context 'for an article that does not exist' do let(:title) { 'THIS_IS_NOT_A_REAL_ARTICLE' } it 'returns nil' do VCR.use_cassette 'wiki_pageviews/average_views' do expect(subject).to be_nil end end end end end
ragesoss/WikiEduDashboard
spec/lib/wiki_pageviews_spec.rb
Ruby
mit
2,631
module Kakera class Memoizer def initialize @table = {} end def memoizer parser, offset &block return block.call if parser.is_a? Operator dump = parser.dump offset if @table.key? dump @table[dump] else node = block.call @table[dump] = node unless node.terminal? end end end end
phi2dao/kakera
lib/kakera/string_parser.rb
Ruby
mit
362
import {expect} from 'chai'; import {camel_case} from '../src'; describe('CamelCase', () => { it('should be exists.', () => { expect(camel_case).to.be.exists; }); it('should convert helloThere to HelloThere.', () => { expect(camel_case('helloThere')).to.be.equals('HelloThere'); }); it('should convert i_am_a_robot to IAmARobot.', () => { expect(camel_case('i_am_a_robot')).to.be.equals('IAmARobot'); }); });
indianajone/strcaser
test/CamelCase.js
JavaScript
mit
464
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _base = require('./base'); var _base2 = _interopRequireDefault(_base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var config = { appEnv: 'test' // don't remove the appEnv property here }; exports.default = Object.freeze(Object.assign(_base2.default, config));
GGGGino/react-event-layer
lib/config/test.js
JavaScript
mit
403
from ddt import ddt, data from django.test import TestCase from six.moves import mock from waldur_core.core import utils from waldur_core.structure import tasks from waldur_core.structure.tests import factories, models class TestDetectVMCoordinatesTask(TestCase): @mock.patch('requests.get') def test_task_sets_coordinates(self, mock_request_get): ip_address = "127.0.0.1" expected_latitude = 20 expected_longitude = 20 instance = factories.TestNewInstanceFactory() mock_request_get.return_value.ok = True response = {"ip": ip_address, "latitude": expected_latitude, "longitude": expected_longitude} mock_request_get.return_value.json.return_value = response tasks.detect_vm_coordinates(utils.serialize_instance(instance)) instance.refresh_from_db() self.assertEqual(instance.latitude, expected_latitude) self.assertEqual(instance.longitude, expected_longitude) @mock.patch('requests.get') def test_task_does_not_set_coordinates_if_response_is_not_ok(self, mock_request_get): instance = factories.TestNewInstanceFactory() mock_request_get.return_value.ok = False tasks.detect_vm_coordinates(utils.serialize_instance(instance)) instance.refresh_from_db() self.assertIsNone(instance.latitude) self.assertIsNone(instance.longitude) @ddt class ThrottleProvisionTaskTest(TestCase): @data( dict(size=tasks.ThrottleProvisionTask.DEFAULT_LIMIT + 1, retried=True), dict(size=tasks.ThrottleProvisionTask.DEFAULT_LIMIT - 1, retried=False), ) def test_if_limit_is_reached_provisioning_is_delayed(self, params): link = factories.TestServiceProjectLinkFactory() factories.TestNewInstanceFactory.create_batch( size=params['size'], state=models.TestNewInstance.States.CREATING, service_project_link=link) vm = factories.TestNewInstanceFactory( state=models.TestNewInstance.States.CREATION_SCHEDULED, service_project_link=link) serialized_vm = utils.serialize_instance(vm) mocked_retry = mock.Mock() tasks.ThrottleProvisionTask.retry = mocked_retry tasks.ThrottleProvisionTask().si( serialized_vm, 'create', state_transition='begin_starting').apply() self.assertEqual(mocked_retry.called, params['retried'])
opennode/nodeconductor
waldur_core/structure/tests/unittests/test_tasks.py
Python
mit
2,443
<?php /** * Author: Wing Ming Chan * Copyright (c) 2014 Wing Ming Chan <chanw@upstate.edu> * MIT Licensed * Modification history: */ class DataDefinitionBlock extends Block { const DEBUG = false; const TYPE = T::DATABLOCK; /** * The constructor * @param $service the AssetOperationHandlerService object * @param $identifier the identifier object */ public function __construct( AssetOperationHandlerService $service, stdClass $identifier ) { parent::__construct( $service, $identifier ); if( $this->getProperty()->structuredData != NULL ) { $this->processStructuredData(); } else { $this->xhtml = $this->getProperty()->xhtml; } } public function appendSibling( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } //if( self::DEBUG ) { echo "DDB::L51 calling SD::appendSibling" . BR; } $this->structured_data->appendSibling( $node_name ); $this->edit(); return $this; } public function copyDataTo( $block ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $block->setStructuredData( $this->getStructuredData() ); return $this; } public function createNInstancesForMultipleField( $number, $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $number = intval( $number ); if( ! $number > 0 ) { throw new UnacceptableValueException( "The value $number is not a number." ); } if( !$this->hasNode( $node_name ) ) { throw new NodeException( "The node $node_name does not exist." ); } $num_of_instances = $this->getNumberOfSiblings( $node_name ); if( $num_of_instances < $number ) // more needed { while( $this->getNumberOfSiblings( $node_name ) != $number ) { $this->appendSibling( $node_name ); } } else if( $instances_wanted < $number ) { while( $this->getNumberOfSiblings( $node_name ) != $number ) { $this->removeLastSibling( $node_name ); } } return $this; } public function displayDataDefinition() { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->getDataDefinition()->displayXML(); return $this; } public function displayXhtml() { if( !$this->hasStructuredData() ) { $xhtml_string = XMLUtility::replaceBrackets( $this->xhtml ); echo S_H2 . 'XHTML' . E_H2; echo $xhtml_string . HR; } return $this; } public function edit() { // edit the asset $asset = new stdClass(); $block = $this->getProperty(); $block->metadata = $this->getMetadata()->toStdClass(); if( $this->structured_data != NULL ) { $block->structuredData = $this->structured_data->toStdClass(); $block->xhtml = NULL; } else { $block->structuredData = NULL; $block->xhtml = $this->xhtml; } $asset->{ $p = $this->getPropertyName() } = $block; // edit asset $service = $this->getService(); $service->edit( $asset ); if( !$service->isSuccessful() ) { throw new EditingFailureException( M::EDIT_ASSET_FAILURE . $service->getMessage() ); } return $this->reloadProperty(); } public function getAssetNodeType( $identifier ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getAssetNodeType( $identifier ); } public function getBlockId( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getBlockId( $node_name ); } public function getBlockPath( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getBlockPath( $node_name ); } public function getDataDefinition() { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getDataDefinition(); } public function getFileId( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getFileId( $node_name ); } public function getFilePath( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getFilePath( $node_name ); } public function getIdentifiers() { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getIdentifiers(); } public function getLinkableId( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getLinkableId( $node_name ); } public function getLinkablePath( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getLinkablePath( $node_name ); } public function getNodeType( $identifier ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getNodeType( $identifier ); } public function getNumberOfSiblings( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } if( trim( $node_name ) == "" ) { throw new EmptyValueException( M::EMPTY_IDENTIFIER ); } if( !$this->hasIdentifier( $node_name ) ) { throw new NodeException( "The node $node_name does not exist" ); } return $this->structured_data->getNumberOfSiblings( $node_name ); } public function getPageId( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getPageId( $node_name ); } public function getPagePath( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getPagePath( $node_name ); } public function getStructuredData() { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data; } public function getSymlinkId( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getSymlinkId( $node_name ); } public function getSymlinkPath( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getSymlinkPath( $node_name ); } public function getText( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getText( $node_name ); } public function getTextNodeType( $identifier ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->getTextNodeType( $identifier ); } public function getXhtml() { return $this->xhtml; } public function hasIdentifier( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK . " " . $this->getPath() ); } return $this->hasNode( $node_name ); } public function hasNode( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->hasNode( $node_name ); } public function hasStructuredData() { return $this->structured_data != NULL; } public function isAssetNode( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->isAssetNode( $node_name ); } public function isGroupNode( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->isGroupNode( $node_name ); } public function isMultiple( $field_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->getDataDefinition()->isMultiple( $field_name ); } public function isRequired( $identifier ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->isRequired( $identifier ); } public function isTextNode( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->isTextNode( $node_name ); } public function isWYSIWYG( $identifier ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->isWYSIWYG( $identifier ); } public function removeLastSibling( $node_name ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->removeLastSibling( $node_name ); $this->edit(); return $this; } public function replaceByPattern( $pattern, $replace, $include=NULL ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->replaceByPattern( $pattern, $replace, $include ); return $this; } public function replaceXhtmlByPattern( $pattern, $replace ) { if( $this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_XHTML_BLOCK ); } $this->xhtml = preg_replace( $pattern, $replace, $this->xhtml ); return $this; } public function replaceText( $search, $replace, $include=NULL ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->replaceText( $search, $replace, $include ); return $this; } public function searchText( $string ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } return $this->structured_data->searchText( $string ); } public function searchXhtml( $string ) { if( $this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_XHTML_BLOCK ); } return strpos( $this->xhtml, $string ) !== false; } public function setBlock( $node_name, Block $block=NULL ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->setBlock( $node_name, $block ); return $this; } public function setFile( $node_name, File $file=NULL ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->setFile( $node_name, $file ); return $this; } public function setLinkable( $node_name, Linkable $linkable=NULL ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->setLinkable( $node_name, $linkable ); return $this; } public function setPage( $node_name, Page $page=NULL ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->setPage( $node_name, $page ); return $this; } public function setStructuredData( StructuredData $structured_data ) { $this->structured_data = $structured_data; $this->edit(); $this->processStructuredData(); return $this; } public function setSymlink( $node_name, Symlink $symlink=NULL ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->setSymlink( $node_name, $symlink ); return $this; } public function setText( $node_name, $text ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->setText( $node_name, $text ); return $this; } public function setXhtml( $xhtml ) { if( !$this->hasStructuredData() ) { $this->xhtml = $xhtml; } else { throw new WrongBlockTypeException( M::NOT_XHTML_BLOCK ); } return $this; } public function swapData( $node_name1, $node_name2 ) { if( !$this->hasStructuredData() ) { throw new WrongBlockTypeException( M::NOT_DATA_BLOCK ); } $this->structured_data->swapData( $node_name1, $node_name2 ); $this->edit()->processStructuredData(); return $this; } private function processStructuredData() { $this->structured_data = new StructuredData( $this->getProperty()->structuredData, $this->getService() ); } private $structured_data; private $xhtml; } ?>
alynch-ece-its/php-cascade-ws
asset_classes/DataDefinitionBlock.class.php
PHP
mit
13,117
<?php Class extension_nested_cats extends Extension{ public function about(){ return array('name' => 'Nested Cats', 'version' => '1.0', 'release-date' => '2009-03-28', 'author' => array('name' => 'Andrey Lubinov', 'website' => 'http://las.kiev.ua', 'email' => 'andrey.lubinov@gmail.com') ); } public function uninstall(){ $this->_Parent->Database->query("DROP TABLE `tbl_fields_nested_cats`"); $this->_Parent->Database->query("DROP TABLE `tbl_ext_nested_cats`"); $this->_Parent->Database->query("DELETE FROM `tbl_fields` WHERE `type` = 'nested_cats'"); } public function install(){ $this->_Parent->Database->query("CREATE TABLE `tbl_ext_nested_cats` ( `id` int(11) NOT NULL auto_increment, `parent` int(11) NOT NULL, `title` varchar(255) NOT NULL, `handle` varchar(55) NOT NULL, `lft` int(11) NOT NULL, `rgt` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `lft` (`lft`), KEY `rgt` (`rgt`) ) ENGINE=MyISAM "); $this->_Parent->Database->query("INSERT INTO `tbl_ext_nested_cats` (`parent`, `title`, `handle`, `lft`, `rgt`) VALUES (0, 'Root', 'root', 0, 1) "); $this->_Parent->Database->query("CREATE TABLE `tbl_fields_nested_cats` ( `id` int(11) unsigned NOT NULL auto_increment, `field_id` int(11) unsigned NOT NULL, `related_field_id` VARCHAR(255) NOT NULL, PRIMARY KEY (`id`), KEY `field_id` (`field_id`) )"); return true; } public function fetchNavigation(){ return array( array( 'location' => 400, 'name' => 'Categories', 'children' => array( array( 'name' => 'Overview', 'link' => '/overview/' ) ) ) ); } #### Fetching Tree by $field, starting from a $start node, excluding $exclude branch function getTree($field,$start,$exclude=NULL) { if(!$root = $this->_Parent->Database->fetchRow(0, "SELECT `lft`, `rgt` FROM `tbl_ext_nested_cats` WHERE `$field` = '$start' LIMIT 1")) return false; if($exclude) $exclude = join(',', range($exclude['lft'], $exclude['rgt'])); if(!$result = $this->_Parent->Database->fetch(" SELECT * FROM `tbl_ext_nested_cats` WHERE (lft BETWEEN {$root['lft']} AND {$root['rgt']}) ".($exclude ? ' AND (`lft` NOT IN('.$exclude.')) AND (`rgt` NOT IN('.$exclude.'))' : NULL)." ORDER BY lft ASC ")) return false; return $result; } #### Nowhere used yet function getPath($field, $val) { if(!$cat = $this->_Parent->Database->fetchRow(0,"SELECT lft, rgt FROM `tbl_ext_nested_cats` WHERE `$field` = $val LIMIT 1 ")) return false; if(!$path = $this->_Parent->Database->fetch("SELECT id,title,handle FROM `tbl_ext_nested_cats` WHERE lft <= {$cat['lft']} AND rgt >= {$cat['rgt']} ORDER BY lft ASC ")) return false; return $path; } function getCat($id) { if(!$result = $this->_Parent->Database->fetchRow(0,"SELECT * FROM `tbl_ext_nested_cats` WHERE id=$id LIMIT 1 ")) return false; return $result; } function buildSelectField($field, $start, $current, $parent=NULL, $element_name, $fieldnamePrefix=NULL, $fieldnamePostfix=NULL, $exclude=NULL, $settingsPannel=NULL) { if(!$tree = $this->getTree($field,$start,$exclude)) return Widget::Select(NULL, NULL, array('disabled' => 'true')); $right = array($tree[0]['rgt']); if(!$settingsPannel) { $options = array(array(NULL,NULL,'None')); } elseif ($settingsPannel && count($tree) == 1) { return new XMLElement('p', __('It looks like youre trying to create a field. Perhaps you want categories first? <br/><a href="%s">Click here to create some.</a>', array(URL . '/symphony/extension/nested_cats/overview/new/'))); } else { $options = array(array($tree[0]['id'], NULL,'Full Tree')); } array_shift($tree); $selected = isset($parent) ? $parent : $current; foreach ($tree as $o){ while ($right[count($right)-1]<$o['rgt']) { array_pop($right); } $options[] = array( $o['id'], $o['id'] == $selected, str_repeat('- ',count($right)-1) . $o['title'] ); $right[] = $o['rgt']; } $select = Widget::Select( 'fields'.$fieldnamePrefix.'['.$element_name.']'.$fieldnamePostfix, $options, count($tree)>0 ? NULL : array('disabled' => 'true')); return $select; } function AddCat($fields) { if(empty($fields['parent'])){ $n = $this->_Parent->Database->fetchRow(0, "SELECT id, rgt FROM `tbl_ext_nested_cats` WHERE lft=0 "); } else { $n = $this->_Parent->Database->fetchRow(0, "SELECT rgt FROM `tbl_ext_nested_cats` WHERE id = {$fields['parent']} "); } $parent = empty($fields['parent']) ? $n['id'] : $fields['parent']; $this->_Parent->Database->query("UPDATE `tbl_ext_nested_cats` SET lft=lft+2 WHERE lft>{$n['rgt']}"); $this->_Parent->Database->query("UPDATE `tbl_ext_nested_cats` SET rgt=rgt+2 WHERE rgt>={$n['rgt']}"); $title = $this->makeTitle($fields['title']); $handle = $this->makeUniqueHandle($fields['title']); $this->_Parent->Database->query("INSERT INTO `tbl_ext_nested_cats` SET parent='$parent', lft={$n['rgt']}, rgt={$n['rgt']}+1, title='$title', handle='$handle' "); return true; } function removeCat($id) { ### Check if category wasn't already deleted before as someones' child if($this->_Parent->Database->fetchVar("count", 0, "SELECT count(*) as `count` FROM `tbl_ext_nested_cats` WHERE `id` = '$id' LIMIT 1")) { $child = $this->getTree('id', $id); foreach ($child as $c) { $ids[] = $c['id']; } $this->_Parent->Database->delete('tbl_ext_nested_cats', " `id` IN ('".implode("', '", $ids)."')"); ### Removing related entries from fields table if($fieldIds = $this->_Parent->Database->fetchCol('field_id',"SELECT `field_id` FROM `tbl_fields_nested_cats` WHERE `related_field_id` IN ('".implode("', '", $ids)."')")){ $this->_Parent->Database->delete('tbl_fields_nested_cats', " `related_field_id` IN ('".implode("', '", $ids)."')"); /* ### Not So easy =) foreach($fieldIds as $fieldId){ $this->_Parent->Database->delete('tbl_entries_data_'.$fieldId, " `relation_id` IN ('".@implode("', '", $ids)."')"); } */ } $root = $this->_Parent->Database->fetchVar('id', 0, "SELECT `id` FROM `tbl_ext_nested_cats` WHERE `lft` = 0 LIMIT 1"); $this->rebuildTree($root,0); } return true; } function rebuildTree($parent, $left) { $right = $left+1; $result = $this->_Parent->Database->fetch('SELECT id FROM `tbl_ext_nested_cats` '. 'WHERE parent="'.$parent.'" ORDER BY lft ASC;'); foreach ($result as $r) { $right = $this->rebuildTree($r['id'], $right); } $this->_Parent->Database->query('UPDATE `tbl_ext_nested_cats` SET lft='.$left.', rgt='.$right.' WHERE id="'.$parent.'";'); return $right+1; } function updateCat($fields) { $title = $this->makeTitle($fields['title']); $handle = $this->makeUniqueHandle($fields['title'], $fields['id']); if(empty($fields['parent']) || $fields['parent'] !== $this->_Parent->Database->fetchVar('parent', 0, "SELECT parent FROM `tbl_ext_nested_cats` WHERE id = {$fields['id']}")) { $root = $this->_Parent->Database->fetchVar('id', 0, "SELECT `id` FROM `tbl_ext_nested_cats` WHERE `lft` = 0 LIMIT 1"); $newParent = $this->_Parent->Database->fetchRow(0, "SELECT `id`, `lft`, `rgt` FROM `tbl_ext_nested_cats` WHERE `id` = '".(empty($fields['parent']) ? $root : $fields['parent'] )."'" ); if(!$this->_Parent->Database->query("UPDATE `tbl_ext_nested_cats` SET title = '$title', handle = '$handle', parent = {$newParent['id']}, lft = {$newParent['rgt']} WHERE id = {$fields['id']} ")) return false; $this->RebuildTree($root,0); } else { if(!$this->_Parent->Database->query("UPDATE `tbl_ext_nested_cats` SET title='$title', handle='$handle' WHERE `id` ='$fields[id]'")) return false; } return true; } function makeUniqueHandle($title, $id=NULL){ $handle = Lang::createHandle($title); ### if handle is unique if(!$this->_Parent->Database->fetchVar("count", 0, "SELECT count(*) as `count` FROM `tbl_ext_nested_cats` WHERE ".(!is_null($id) ? " `id` != $id AND " : NULL)." `handle` = '$handle' LIMIT 1") ) {return $handle;} ### handle is not unique else { $count = $this->_Parent->Database->fetchVar("count", 0, "SELECT count(*) as `count` FROM `tbl_ext_nested_cats` WHERE `handle` LIKE '" . $handle . "%' LIMIT 1"); return $handle .= '-' . ($count+1); } } function makeTitle($title){ return General::sanitize( function_exists('mysql_real_escape_string') ? mysql_real_escape_string(trim($title)) : addslashes(trim($title)) ); } }
bauhouse/sym-extensions
extensions/nested_cats/extension.driver.php
PHP
mit
8,944
require 'spec_helper' describe process("sge_execd") do it { should be_running } end describe port(803) do it { should be_listening } end describe process("sshd") do it { should be_running } end describe port(22) do it { should be_listening } end
IMPIMBA/vagrant-mesh-net
serverspec/spec/compute/compute_spec.rb
Ruby
mit
258
import React from 'react' import ColorWheel from './ColorWheel.jsx' React.render(<ColorWheel title='ColorWheel' />, document.querySelector('#color-wheel'))
naush/simple-slice-example
entry.js
JavaScript
mit
157
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-site-sidebar', templateUrl: 'sidebar.component.html', styleUrls: ['sidebar.component.scss'] }) export class SidebarComponent implements OnInit { constructor() { } ngOnInit() { } }
burhanayan/angular-blog
app/site/containers/sidebar/sidebar.component.ts
TypeScript
mit
280
<?php //ajuntar la libreria excel include "./lib/PHPExcel.php"; require("../ez_sql_core.php"); require("../ez_sql_postgresql.php"); $objPHPExcel = new PHPExcel(); //nueva instancia $objPHPExcel->getProperties()->setCreator("SIFDA"); //autor $objPHPExcel->getProperties()->setTitle("Prueba para generar excel"); //titulo $conexion = new ezSQL_postgresql('sifda', 'sifda', 'sifda24022015', 'localhost'); $temp_fi = $_REQUEST['fi']; $temp_ff = $_REQUEST['ff']; $temp_tipo = $_REQUEST['tp']; //$temp_us = $_REQUEST['user']; if ($temp_ff ==0 and $temp_fi ==0) {$datos = $conexion->get_results("SELECT de.nombre as dependencia,sts.nombre,ss.descripcion,ss.fecha_recepcion, ss.fecha_requiere FROM public.sifda_solicitud_servicio ss inner join public.fos_user_user us on (us.id = ss.user_id) inner join public.ctl_dependencia_establecimiento dep on (dep.id = us.id_dependencia_establecimiento) inner join public.sifda_tipo_servicio sts on (sts.id = ss.id_tipo_servicio) inner join public.ctl_dependencia de on (de.id = dep.id_dependencia) where id_estado=3;"); } else {$datos = $conexion->get_results("SELECT de.nombre as dependencia,sts.nombre,ss.descripcion,ss.fecha_recepcion, ss.fecha_requiere FROM public.sifda_solicitud_servicio ss inner join public.fos_user_user us on (us.id = ss.user_id) inner join public.ctl_dependencia_establecimiento dep on (dep.id = us.id_dependencia_establecimiento) inner join public.sifda_tipo_servicio sts on (sts.id = ss.id_tipo_servicio) inner join public.ctl_dependencia de on (de.id = dep.id_dependencia) where id_estado=3 and ss.id_tipo_servicio = '$temp_tipo' and fecha_recepcion >= '$temp_fi' and fecha_recepcion <= '$temp_ff'"); } //inicio estilos $titulo = new PHPExcel_Style(); //nuevo estilo $titulo->applyFromArray( array('alignment' => array( //alineacion 'wrap' => false, 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER ), 'font' => array( //fuente 'bold' => true, 'size' => 20 ) )); $subtitulo = new PHPExcel_Style(); //nuevo estilo $subtitulo->applyFromArray( array('fill' => array( //relleno de color 'type' => PHPExcel_Style_Fill::FILL_SOLID, //'color' => array('argb' => 'FFCCFFCC') 'color' => array('argb' => 'CCFFFF') ), 'borders' => array( //bordes 'top' => array('style' => PHPExcel_Style_Border::BORDER_THIN), 'right' => array('style' => PHPExcel_Style_Border::BORDER_THIN), 'bottom' => array('style' => PHPExcel_Style_Border::BORDER_THIN), 'left' => array('style' => PHPExcel_Style_Border::BORDER_THIN) ) )); $bordes = new PHPExcel_Style(); //nuevo estilo $bordes->applyFromArray( array('borders' => array( 'top' => array('style' => PHPExcel_Style_Border::BORDER_THIN), 'right' => array('style' => PHPExcel_Style_Border::BORDER_THIN), 'bottom' => array('style' => PHPExcel_Style_Border::BORDER_THIN), 'left' => array('style' => PHPExcel_Style_Border::BORDER_THIN) ) )); //fin estilos $objPHPExcel->createSheet(0); //crear hoja $objPHPExcel->setActiveSheetIndex(0); //seleccionar hora $objPHPExcel->getActiveSheet()->setTitle("Solicitudes Rechazadas"); //establecer titulo de hoja //orientacion hoja $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE); //tipo papel $objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER); //establecer impresion a pagina completa $objPHPExcel->getActiveSheet()->getPageSetup()->setFitToPage(true); $objPHPExcel->getActiveSheet()->getPageSetup()->setFitToWidth(1); $objPHPExcel->getActiveSheet()->getPageSetup()->setFitToHeight(0); //fin: establecer impresion a pagina completa //establecer margenes $margin = 0.5 / 2.54; // 0.5 centimetros $marginBottom = 1.2 / 2.54; //1.2 centimetros $objPHPExcel->getActiveSheet()->getPageMargins()->setTop($margin); $objPHPExcel->getActiveSheet()->getPageMargins()->setBottom($marginBottom); $objPHPExcel->getActiveSheet()->getPageMargins()->setLeft($margin); $objPHPExcel->getActiveSheet()->getPageMargins()->setRight($margin); //fin: establecer margenes //incluir una imagen $objDrawing = new PHPExcel_Worksheet_Drawing(); //$objDrawing->setPath('img/logo.png'); //ruta $objDrawing->setPath('../banner.png'); //ruta $objDrawing->setHeight(75); //altura $objDrawing->setCoordinates('A1'); $objDrawing->setWorksheet($objPHPExcel->getActiveSheet()); //incluir la imagen //fin: incluir una imagen //establecer titulos de impresion en cada hoja $objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 6); $fila=6; $objPHPExcel->getActiveSheet()->SetCellValue("A$fila", "Reporte de Solicitudes de Servicio Rechazadas"); $objPHPExcel->getActiveSheet()->mergeCells("A$fila:I$fila"); //unir celdas $objPHPExcel->getActiveSheet()->setSharedStyle($titulo, "A$fila:I$fila"); //establecer estilo //titulos de columnas $fila+=1; $objPHPExcel->getActiveSheet()->SetCellValue("A$fila", 'Num'); $objPHPExcel->getActiveSheet()->SetCellValue("B$fila", 'Dependencia'); $objPHPExcel->getActiveSheet()->SetCellValue("C$fila", 'Tipo de Servicio'); $objPHPExcel->getActiveSheet()->SetCellValue("D$fila", 'Descripción'); $objPHPExcel->getActiveSheet()->SetCellValue("E$fila", 'Fecha requiere'); $objPHPExcel->getActiveSheet()->SetCellValue("F$fila", 'Fecha recepción'); $objPHPExcel->getActiveSheet()->setSharedStyle($subtitulo, "A$fila:B$fila"); //establecer estilo $objPHPExcel->getActiveSheet()->setSharedStyle($subtitulo, "C$fila:D$fila"); $objPHPExcel->getActiveSheet()->setSharedStyle($subtitulo, "E$fila:F$fila"); $objPHPExcel->getActiveSheet()->getStyle("A$fila:B$fila")->getFont()->setBold(true); //negrita $objPHPExcel->getActiveSheet()->getStyle("C$fila:D$fila")->getFont()->setBold(true); //negrita $objPHPExcel->getActiveSheet()->getStyle("E$fila:F$fila")->getFont()->setBold(true); //negrita //rellenar con contenido /*for ($i = 0; $i < 10; $i++) { $fila+=1; $objPHPExcel->getActiveSheet()->SetCellValue("A$fila", 'Garabatos'); $objPHPExcel->getActiveSheet()->SetCellValue("B$fila", 'Linux'); //Establecer estilo $objPHPExcel->getActiveSheet()->setSharedStyle($bordes, "A$fila:B$fila"); }*/ foreach ($datos as $value) { $item = $item +1; $fila+=1; //$row = $row -1; //$pdf->Cell(15,7,utf8_decode($item),1); //$pdf->Cell(15,7,utf8_decode($value->id),1,0,'C'); $objPHPExcel->getActiveSheet()->SetCellValue("A$fila","$item"); $objPHPExcel->getActiveSheet()->SetCellValue("B$fila","$value->dependencia"); $objPHPExcel->getActiveSheet()->SetCellValue("C$fila","$value->nombre"); $objPHPExcel->getActiveSheet()->SetCellValue("D$fila","$value->descripcion"); $objPHPExcel->getActiveSheet()->SetCellValue("E$fila","$value->fecha_requiere"); $objPHPExcel->getActiveSheet()->SetCellValue("F$fila","$value->fecha_recepcion"); //Establecer estilo $objPHPExcel->getActiveSheet()->setSharedStyle($bordes, "A$fila:B$fila:C$fila:D$fila:E$fila:F$fila"); } //insertar formula //$fila+=2; //$objPHPExcel->getActiveSheet()->SetCellValue("A$fila", 'SUMA'); //$objPHPExcel->getActiveSheet()->SetCellValue("B$fila", '=1+2'); //recorrer las columnas foreach (range('A', 'B','C','D') as $columnID) { //autodimensionar las columnas $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true); } //establecer pie de impresion en cada hoja $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('&R&F página &P / &N'); // Guardar como excel 2007 $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); //Escribir archivo // Establecer formado de Excel 2007 header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // nombre del archivo header('Content-Disposition: attachment; filename="solicitudesRechazadas.xlsx"'); //forzar a descarga por el navegador $objWriter->save('php://output');
axelljt/sifda-3.0
web/reports1/phpexcel/solicitudesRechazadasExcel.php
PHP
mit
7,945
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2013 The NovaCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "db.h" #include "miner.h" #include "kernel.h" using namespace std; ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // string strMintMessage = "Info: Mining suspended due to locked wallet."; string strMintWarning; extern unsigned int nMinerSleep; int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; double dFeePerKb; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = dFeePerKb = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; int64 nLastCoinStakeSearchInterval = 0; // We want to sort transactions by priority and fee, so: typedef boost::tuple<double, double, CTransaction*> TxPriority; class TxPriorityCompare { bool byFee; public: TxPriorityCompare(bool _byFee) : byFee(_byFee) { } bool operator()(const TxPriority& a, const TxPriority& b) { if (byFee) { if (a.get<1>() == b.get<1>()) return a.get<0>() < b.get<0>(); return a.get<1>() < b.get<1>(); } else { if (a.get<0>() == b.get<0>()) return a.get<1>() < b.get<1>(); return a.get<0>() < b.get<0>(); } } }; // CreateNewBlock: create new block (without proof-of-work/proof-of-stake) CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake) { // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); if (!fProofOfStake) { CReserveKey reservekey(pwallet); txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; } else txNew.vout[0].SetEmpty(); // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); // Largest block you're willing to create: unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2); // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); // How much of the block should be dedicated to high-priority transactions, // included regardless of the fees they pay unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 11000); nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); // Minimum block size you want to create; block will be filled with free transactions // until there are no more or the block reaches this size: unsigned int nBlockMinSize = GetArg("-blockminsize", 0); nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); // Fee-per-kilobyte amount considered the same as "free" // Be careful setting this: if you set it to zero then // a transaction spammer can cheaply fill blocks using // 1-satoshi-fee transactions. It should be set above the real // cost to you of processing a transaction. int64 nMinTxFee = MIN_TX_FEE; if (mapArgs.count("-mintxfee")) ParseMoney(mapArgs["-mintxfee"], nMinTxFee); CBlockIndex* pindexPrev = pindexBest; pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake); // Collect memory pool transactions into the block int64 nFees = 0; { LOCK2(cs_main, mempool.cs); CCoinsViewCache view(*pcoinsTip, true); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; // This vector will be sorted into a priority queue: vector<TxPriority> vecPriority; vecPriority.reserve(mempool.mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; int64 nTotalIn = 0; bool fMissingInputs = false; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction CCoins coins; if (!view.GetCoins(txin.prevout.hash, coins)) { // This should never happen; all transactions in the memory // pool should connect to either transactions in the chain // or other transactions in the memory pool. if (!mempool.mapTx.count(txin.prevout.hash)) { printf("ERROR: mempool transaction missing input\n"); if (fDebug) assert("mempool transaction missing input" == 0); fMissingInputs = true; if (porphan) vOrphan.pop_back(); break; } // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue; continue; } int64 nValueIn = coins.vout[txin.prevout.n].nValue; nTotalIn += nValueIn; int nConf = pindexPrev->nHeight - coins.nHeight; dPriority += (double)nValueIn * nConf; } if (fMissingInputs) continue; // Priority is sum(valuein * age) / txsize unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); dPriority /= nTxSize; // This is a more accurate fee-per-kilobyte than is used by the client code, because the // client code rounds up the size to the nearest 1K. That's good, because it gives an // incentive to create smaller transactions. double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0); if (porphan) { porphan->dPriority = dPriority; porphan->dFeePerKb = dFeePerKb; } else vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second)); } // Collect transactions into block uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; bool fSortedByFee = (nBlockPrioritySize <= 0); TxPriorityCompare comparer(fSortedByFee); std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); while (!vecPriority.empty()) { unsigned int nAdjTime = GetAdjustedTime(); // Take highest priority transaction off the priority queue: double dPriority = vecPriority.front().get<0>(); double dFeePerKb = vecPriority.front().get<1>(); CTransaction& tx = *(vecPriority.front().get<2>()); std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); vecPriority.pop_back(); // second layer cached modifications just for this transaction CCoinsViewCache viewTemp(view, true); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= nBlockMaxSize) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Timestamp limit if ((tx.nTime > nAdjTime) || (fProofOfStake && tx.nTime > pblock->vtx[0].nTime)) continue; // Simplify transaction fee - allow free = false int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK); // Skip free transactions if we're past the minimum block size: if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) continue; // Prioritize by fee once past the priority size or we run out of high-priority // transactions: if (!fSortedByFee && ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250))) { fSortedByFee = true; comparer = TxPriorityCompare(fSortedByFee); std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); } if (!tx.CheckInputs(viewTemp, CS_ALWAYS, true, false)) continue; int64 nTxFees = tx.GetValueIn(viewTemp)-tx.GetValueOut(); if (nTxFees < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(viewTemp); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; /* * We need to call UpdateCoins using actual block timestamp, so don't perform this here. * CTxUndo txundo; if (!tx.UpdateCoins(viewTemp, txundo, pindexPrev->nHeight+1, pblock->nTime)) continue; */ // push changes from the second layer cache to the first one viewTemp.Flush(); uint256 hash = tx.GetHash(); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; if (fDebug && GetBoolArg("-printpriority")) { printf("priority %.1f feeperkb %.1f txid %s\n", dPriority, dFeePerKb, tx.GetHash().ToString().c_str()); } // Add transactions that depend on this one to the priority queue if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) { vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx)); std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); } } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; if (fDebug && GetBoolArg("-printpriority")) printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize); if (!fProofOfStake) pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight, nFees); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime()); pblock->nTime = max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime())); if (!fProofOfStake) pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; } return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Pre-build hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hashBlock = pblock->GetHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); if(!pblock->IsProofOfWork()) return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str()); if (hashBlock > hashTarget) return error("CheckWork() : proof-of-work not meeting target"); //// debug print printf("CheckWork() : new proof-of-work block found \n hash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("CheckWork() : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[hashBlock] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("CheckWork() : ProcessBlock, block not accepted"); } return true; } bool CheckStake(CBlock* pblock, CWallet& wallet) { uint256 proofHash = 0, hashTarget = 0; uint256 hashBlock = pblock->GetHash(); bool fFatal = false; if(!pblock->IsProofOfStake()) return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str()); // verify hash target and signature of coinstake tx if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget, fFatal, true)) return error("CheckStake() : proof-of-stake checking failed"); //// debug print printf("CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), proofHash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("CheckStake() : generated block is stale"); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[hashBlock] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("CheckStake() : ProcessBlock, block not accepted"); } return true; } void StakeMiner(CWallet *pwallet) { SetThreadPriority(THREAD_PRIORITY_LOWEST); // Make this thread recognisable as the mining thread RenameThread("novacoin-miner"); // Each thread has its own counter unsigned int nExtraNonce = 0; while (true) { if (fShutdown) return; while (pwallet->IsLocked()) { strMintWarning = strMintMessage; Sleep(1000); if (fShutdown) return; } while (vNodes.empty() || IsInitialBlockDownload()) { Sleep(1000); if (fShutdown) return; } strMintWarning = ""; // // Create new block // CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, true)); if (!pblock.get()) return; IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); // Trying to sign a block if (pblock->SignBlock(*pwallet)) { strMintWarning = _("Stake generation: new block found!"); SetThreadPriority(THREAD_PRIORITY_NORMAL); CheckStake(pblock.get(), *pwallet); SetThreadPriority(THREAD_PRIORITY_LOWEST); Sleep(1000); } else Sleep(nMinerSleep); } }
Infernoman/Sembros-Next
src/miner.cpp
C++
mit
19,473
#!/usr/bin/env python # encoding: utf-8 """ Make a grid of synths for a set of attenuations. 2015-04-30 - Created by Jonathan Sick """ import argparse import numpy as np from starfisher.pipeline import PipelineBase from androcmd.planes import BasicPhatPlanes from androcmd.phatpipeline import ( SolarZIsocs, SolarLockfile, PhatGaussianDust, PhatCrowding) from androcmd.phatpipeline import PhatCatalog def main(): args = parse_args() av_grid = np.arange(0., args.max_av, args.delta_av) if args.av is not None: av = float(args.av) run_pipeline(brick=args.brick, av=av, run_fit=args.fit) else: for av in av_grid: run_pipeline(brick=args.brick, av=av, run_fit=args.fit) def parse_args(): parser = argparse.ArgumentParser( description="Grid of synths for a set of Av") parser.add_argument('brick', type=int) parser.add_argument('--max-av', type=float, default=1.5) parser.add_argument('--delta-av', type=float, default=0.1) parser.add_argument('--fit', action='store_true', default=False) parser.add_argument('--av', default=None) return parser.parse_args() def run_pipeline(brick=23, av=0., run_fit=False): dataset = PhatCatalog(brick) pipeline = Pipeline(root_dir="b{0:d}_{1:.2f}".format(brick, av), young_av=av, old_av=av, av_sigma_ratio=0.25, isoc_args=dict(isoc_kind='parsec_CAF09_v1.2S', photsys_version='yang')) print(pipeline) print('av {0:.1f} done'.format(av)) if run_fit: pipeline.fit('f475w_f160w', ['f475w_f160w'], dataset) pipeline.fit('rgb', ['f475w_f814w_rgb'], dataset) pipeline.fit('ms', ['f475w_f814w_ms'], dataset) class Pipeline(BasicPhatPlanes, SolarZIsocs, SolarLockfile, PhatGaussianDust, PhatCrowding, PipelineBase): """A pipeline for fitting PHAT bricks with solar metallicity isochrones.""" def __init__(self, **kwargs): super(Pipeline, self).__init__(**kwargs) if __name__ == '__main__': main()
jonathansick/androcmd
scripts/dust_grid.py
Python
mit
2,095
var objc = require('../') objc.dlopen('/System/Library/Frameworks/AppKit.framework/AppKit'); NSApplication = objc.objc_getClass('NSApplication'); console.log(NSApplication); var sharedApplication = objc.sel_registerName('sharedApplication'); var app = objc.objc_msgSend(NSApplication, sharedApplication); console.log(app);
TooTallNate/node-objc
tests/test2.js
JavaScript
mit
326
/* * Elfenben - Javascript using tree syntax! This is the compiler written in javascipt * */ var version = "1.0.16", banner = "// Generated by Elfenben v" + version + "\n", isWhitespace = /\s/, isFunction = /^function\b/, validName = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/, noReturn = /^var\b|^set\b|^throw\b/, isHomoiconicExpr = /^#args-if\b|^#args-shift\b|^#args-second\b/, noSemiColon = false, indentSize = 4, indent = -indentSize, keywords = {}, macros = {}, errors = [], include_dirs = [__dirname + "/../includes", "includes"], fs, path, SourceNode = require('source-map').SourceNode if (typeof window === "undefined") { fs = require('fs') path = require('path') } if (!String.prototype.repeat) { String.prototype.repeat = function(num) { return new Array(num + 1).join(this) } } var parse = function(code, filename) { code = "(" + code + ")" var length = code.length, pos = 1, lineno = 1, colno = 1, token_begin_colno = 1 var parser = function() { var tree = [], token = "", isString = false, isSingleString = false, isJSArray = 0, isJSObject = 0, isListComplete = false, isComment = false, isRegex = false, isEscape = false, handleToken = function() { if (token) { tree.push(new SourceNode(lineno, token_begin_colno - 1, filename, token, token)) token = "" } } tree._line = lineno tree._filename = filename while (pos < length) { var c = code.charAt(pos) pos++ colno++ if (c == "\n") { lineno++ colno = 1 if (isComment) { isComment = false } } if (isComment) { continue } if (isEscape) { isEscape = false token += c continue } // strings if (c == '"' || c == '`') { isString = !isString token += c continue } if (isString) { if (c === "\n") { token += "\\n" } else { if (c === "\\") { isEscape = true } token += c } continue } if (c == "'") { isSingleString = !isSingleString token += c continue } if (isSingleString) { token += c continue } // data types if (c == '[') { isJSArray++ token += c continue } if (c == ']') { if (isJSArray === 0) { handleError(4, tree._line, tree._filename) } isJSArray-- token += c continue } if (isJSArray) { token += c continue } if (c == '{') { isJSObject++ token += c continue } if (c == '}') { if (isJSObject === 0) { handleError(6, tree._line, tree._filename) } isJSObject-- token += c continue } if (isJSObject) { token += c continue } if (c == ";") { isComment = true continue } // regex // regex in function position with first char " " is a prob. Use \s instead. if (c === "/" && !(tree.length === 0 && token.length === 0 && isWhitespace.test(code.charAt(pos)))) { isRegex = !isRegex token += c continue } if (isRegex) { if (c === "\\") { isEscape = true } token += c continue } if (c == "(") { handleToken() // catch e.g. "blah(" token_begin_colno = colno tree.push(parser()) continue } if (c == ")") { isListComplete = true handleToken() token_begin_colno = colno break } if (isWhitespace.test(c)) { if (c == '\n') lineno-- handleToken() if (c == '\n') lineno++ token_begin_colno = colno continue } token += c } if (isString) handleError(3, tree._line, tree._filename) if (isRegex) handleError(14, tree._line, tree._filename) if (isSingleString) handleError(3, tree._line, tree._filename) if (isJSArray > 0) handleError(5, tree._line, tree._filename) if (isJSObject > 0) handleError(7, tree._line, tree._filename) if (!isListComplete) handleError(8, tree._line, tree._filename) return tree } var ret = parser() if (pos < length) { handleError(10) } return ret } var handleExpressions = function(exprs) { indent += indentSize var ret = new SourceNode(), l = exprs.length, indentstr = " ".repeat(indent) exprs.forEach(function(expr, i, exprs) { var exprName, tmp = null, r = "" if (Array.isArray(expr)) { exprName = expr[0].name if (exprName === "include") ret.add(handleExpression(expr)) else tmp = handleExpression(expr) } else { tmp = expr } if (i === l - 1 && indent) { if (!noReturn.test(exprName)) r = "return " } if (tmp) { var endline = noSemiColon ? "\n" : ";\n" noSemiColon = false ret.add([indentstr + r, tmp, endline]) } }) indent -= indentSize return ret } var handleExpression = function(expr) { if (!expr || !expr[0]) { return null } var command = expr[0].name if (macros[command]) { expr = macroExpand(expr) if (Array.isArray(expr)) { return handleExpression(expr) } else { return expr } } if (typeof command === "string") { if (keywords[command]) { return keywords[command](expr) } if (command.charAt(0) === ".") { var ret = new SourceNode() ret.add(Array.isArray(expr[1]) ? handleExpression(expr[1]) : expr[1]) ret.prepend("(") ret.add([")", expr[0]]) return ret } } handleSubExpressions(expr) var fName = expr[0] if (!fName) { handleError(1, expr._line) } if (isFunction.test(fName)) fName = new SourceNode(null, null, null, ['(', fName, ')']) exprNode = new SourceNode (null, null, null, expr.slice(1)).join(",") return new SourceNode (null, null, null, [fName, "(", exprNode, ")"]) } var handleSubExpressions = function(expr) { expr.forEach(function(value, i, t) { if (Array.isArray(value)) t[i] = handleExpression(value) }) } var macroExpand = function(tree) { var command = tree[0].name, template = macros[command]["template"], code = macros[command]["code"], replacements = {} for (var i = 0; i < template.length; i++) { if (template[i].name == "rest...") { replacements["~rest..."] = tree.slice(i + 1) } else { if (tree.length === i + 1) { // we are here if any macro arg is not set handleError(12, tree._line, tree._filename, command) } replacements["~" + template[i].name] = tree[i + 1] } } var replaceCode = function(source) { var ret = [] ret._line = tree._line ret._filename = tree._filename // Handle homoiconic expressions in macro var expr_name = source[0] ? source[0].name : "" if (isHomoiconicExpr.test(expr_name)) { var replarray = replacements["~" + source[1].name] if (expr_name === "#args-shift") { if (!Array.isArray(replarray)) { handleError(13, tree._line, tree._filename, command) } var argshift = replarray.shift() if (typeof argshift === "undefined") { handleError(12, tree._line, tree._filename, command) } return argshift } if (expr_name === "#args-second") { if (!Array.isArray(replarray)) { handleError(13, tree._line, tree._filename, command) } var argsecond = replarray.splice(1, 1)[0] if (typeof argsecond === "undefined") { handleError(12, tree._line, tree._filename, command) } return argsecond } if (expr_name === "#args-if") { if (!Array.isArray(replarray)) { handleError(13, tree._line, tree._filename, command) } if (replarray.length) { return replaceCode(source[2]) } else if (source[3]) { return replaceCode(source[3]) } else { return } } } for (var i = 0; i < source.length; i++) { if (Array.isArray(source[i])) { var replcode = replaceCode(source[i]) if (typeof replcode !== "undefined") { ret.push(replcode) } } else { var token = source[i], tokenbak = token, isATSign = false if (token.name.indexOf("@") >= 0) { isATSign = true tokenbak = new SourceNode(token.line, token.column, token.source, token.name.replace("@", ""), token.name.replace("@", "")) } if (replacements[tokenbak.name]) { var repl = replacements[tokenbak.name] if (isATSign || tokenbak.name == "~rest...") { for (var j = 0; j < repl.length; j++) { ret.push(repl[j]) } } else { ret.push(repl) } } else { ret.push(token) } } } return ret } return replaceCode(code) } var handleCompOperator = function(arr) { if (arr.length < 3) handleError(0, arr._line) handleSubExpressions(arr) if (arr[0] == "=") arr[0] = "===" if (arr[0] == "!=") arr[0] = "!==" var op = arr.shift() var ret = new SourceNode() for (i = 0; i < arr.length - 1; i++) ret.add (new SourceNode (null, null, null, [arr[i], " ", op, " ", arr[i + 1]])) ret.join (' && ') ret.prepend('(') ret.add(')') return ret } var handleArithOperator = function(arr) { if (arr.length < 3) handleError(0, arr._line) handleSubExpressions(arr) var op = new SourceNode() op.add([" ", arr.shift(), " "]) var ret = new SourceNode() ret.add(arr) ret.join (op) ret.prepend("(") ret.add(")") return ret } var handleLogicalOperator = handleArithOperator var handleVariableDeclarations = function(arr, varKeyword){ if (arr.length < 3) handleError(0, arr._line, arr._filename) if (arr.length > 3) { indent += indentSize } handleSubExpressions(arr) var ret = new SourceNode () ret.add(varKeyword + " ") for (var i = 1; i < arr.length; i = i + 2) { if (i > 1) { ret.add(",\n" + " ".repeat(indent)) } if (!validName.test(arr[i])) handleError(9, arr._line, arr._filename) ret.add([arr[i], ' = ', arr[i + 1]]) } if (arr.length > 3) { indent -= indentSize } return ret } keywords["var"] = function(arr) { return handleVariableDeclarations(arr, "var") } keywords["const"] = function(arr) { return handleVariableDeclarations(arr, "const") } keywords["let"] = function(arr) { return handleVariableDeclarations(arr, "let") } keywords["new"] = function(arr) { if (arr.length < 2) handleError(0, arr._line, arr._filename) var ret = new SourceNode() ret.add(handleExpression(arr.slice(1))) ret.prepend ("new ") return ret } keywords["throw"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) var ret = new SourceNode() ret.add(Array.isArray(arr[1]) ? handleExpression(arr[1]) : arr[1]) ret.prepend("(function(){throw ") ret.add(";})()") return ret } keywords["set"] = function(arr) { if (arr.length < 3 || arr.length > 4) handleError(0, arr._line, arr._filename) if (arr.length == 4) { arr[1] = (Array.isArray(arr[2]) ? handleExpression(arr[2]) : arr[2]) + "[" + arr[1] + "]" arr[2] = arr[3] } return new SourceNode(null, null, null, [arr[1], " = ", (Array.isArray(arr[2]) ? handleExpression(arr[2]) : arr[2])]) } keywords["function"] = function(arr) { var ret var fName, fArgs, fBody if (arr.length < 2) handleError(0, arr._line, arr._filename) if(Array.isArray(arr[1])) { // an anonymous function fArgs = arr[1] fBody = arr.slice(2) } else if(!Array.isArray(arr[1]) && Array.isArray(arr[2])) { // a named function fName = arr[1] fArgs = arr[2] fBody = arr.slice(3) } else handleError(0, arr._line) ret = new SourceNode(null, null, null, fArgs) ret.join(",") ret.prepend("function" + (fName ? " " + fName.name : "") + "(") ret.add([") {\n",handleExpressions(fBody), " ".repeat(indent), "}"]) if(fName) noSemiColon = true return ret } keywords["try"] = function(arr) { if (arr.length < 3) handleError(0, arr._line, arr._filename) var c = arr.pop(), ind = " ".repeat(indent), ret = new SourceNode() ret.add(["(function() {\n" + ind + "try {\n", handleExpressions(arr.slice(1)), "\n" + ind + "} catch (e) {\n" + ind + "return (", (Array.isArray(c) ? handleExpression(c) : c), ")(e);\n" + ind + "}\n" + ind + "})()"]) return ret } keywords["if"] = function(arr) { if (arr.length < 3 || arr.length > 4) handleError(0, arr._line, arr._filename) indent += indentSize handleSubExpressions(arr) var ret = new SourceNode() ret.add(["(", arr[1], " ?\n" + " ".repeat(indent), arr[2], " :\n" + " ".repeat(indent), (arr[3] || "undefined"), ")"]) indent -= indentSize return ret } keywords["get"] = function(arr) { if (arr.length != 3) handleError(0, arr._line, arr._filename) handleSubExpressions(arr) return new SourceNode(null, null, null, [arr[2], "[", arr[1], "]"]) } keywords["str"] = function(arr) { if (arr.length < 2) handleError(0, arr._line, arr._filename) handleSubExpressions(arr) var ret = new SourceNode() ret.add(arr.slice(1)) ret.join (",") ret.prepend("[") ret.add("].join('')") return ret } keywords["array"] = function(arr) { var ret = new SourceNode() if (arr.length == 1) { ret.add("[]") return ret } indent += indentSize handleSubExpressions(arr) ret.add("[\n" + " ".repeat(indent)) for (var i = 1; i < arr.length; ++i) { if (i > 1) { ret.add(",\n" + " ".repeat(indent)) } ret.add(arr[i]) } indent -= indentSize ret.add("\n" + " ".repeat(indent) + "]") return ret } keywords["object"] = function(arr) { var ret = new SourceNode() if (arr.length == 1) { ret.add("{}") return ret } indent += indentSize handleSubExpressions(arr) ret.add("{\n" + " ".repeat(indent)) for (var i = 1; i < arr.length; i = i + 2) { if (i > 1) { ret.add(",\n" + " ".repeat(indent)) } ret.add([arr[i], ': ', arr[i + 1]]) } indent -= indentSize ret.add("\n" + " ".repeat(indent) + "}") return ret } var includeFile = (function () { var included = [] return function(filename) { if (included.indexOf(filename) !== -1) return "" included.push(filename) var code = fs.readFileSync(filename) var tree = parse(code, filename) return handleExpressions(tree) } })() keywords["include"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) indent -= indentSize var filename = arr[1].name if (typeof filename === "string") filename = filename.replace(/["']/g, "") var found = false; include_dirs.concat([path.dirname(arr._filename)]) .forEach(function(prefix) { if (found) { return; } try { filename = fs.realpathSync(prefix + '/' +filename) found = true; } catch (err) { } }); if (!found) { handleError(11, arr._line, arr._filename) } var ret = new SourceNode() ret = includeFile(filename) indent += indentSize return ret } keywords["javascript"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) noSemiColon = true arr[1].replaceRight(/"/g, '') return arr[1] } keywords["macro"] = function(arr) { if (arr.length != 4) handleError(0, arr._line, arr._filename) macros[arr[1].name] = {template: arr[2], code: arr[3]} return "" } keywords["+"] = handleArithOperator keywords["-"] = handleArithOperator keywords["*"] = handleArithOperator keywords["/"] = handleArithOperator keywords["%"] = handleArithOperator keywords["="] = handleCompOperator keywords["!="] = handleCompOperator keywords[">"] = handleCompOperator keywords[">="] = handleCompOperator keywords["<"] = handleCompOperator keywords["<="] = handleCompOperator keywords["||"] = handleLogicalOperator keywords["&&"] = handleLogicalOperator keywords["!"] = function(arr) { if (arr.length != 2) handleError(0, arr._line, arr._filename) handleSubExpressions(arr) return "(!" + arr[1] + ")" } var handleError = function(no, line, filename, extra) { throw new Error(errors[no] + ((extra) ? " - " + extra : "") + ((line) ? "\nLine no " + line : "") + ((filename) ? "\nFile " + filename : "")) } errors[0] = "Syntax Error" errors[1] = "Empty statement" errors[2] = "Invalid characters in function name" errors[3] = "End of File encountered, unterminated string" errors[4] = "Closing square bracket, without an opening square bracket" errors[5] = "End of File encountered, unterminated array" errors[6] = "Closing curly brace, without an opening curly brace" errors[7] = "End of File encountered, unterminated javascript object '}'" errors[8] = "End of File encountered, unterminated parenthesis" errors[9] = "Invalid character in var name" errors[10] = "Extra chars at end of file. Maybe an extra ')'." errors[11] = "Cannot Open include File" errors[12] = "Invalid no of arguments to " errors[13] = "Invalid Argument type to " errors[14] = "End of File encountered, unterminated regular expression" var _compile = function(code, filename, withSourceMap, a_include_dirs) { indent = -indentSize if (a_include_dirs) include_dirs = a_include_dirs var tree = parse(code, filename) var outputNode = handleExpressions(tree) outputNode.prepend(banner) if (withSourceMap) { var outputFilename = path.basename(filename, '.elf') + '.js' var sourceMapFile = outputFilename + '.map' var output = outputNode.toStringWithSourceMap({ file: outputFilename }); fs.writeFileSync(sourceMapFile, output.map) return output.code + "\n//# sourceMappingURL=" + path.relative(path.dirname(filename), sourceMapFile); } else return outputNode.toString() } exports.version = version exports._compile = _compile exports.parseWithSourceMap = function(code, filename) { var tree = parse(code, filename) var outputNode = handleExpressions(tree) outputNode.prepend(banner) return outputNode.toStringWithSourceMap(); }
Nappa9693/elfenben
lib/ls.js
JavaScript
mit
21,053
using ExifLibrary; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; namespace ImageSort { enum DirOpt { NONE, DAY, MONTH, YEAR } enum FileRule { ORIGINAL, INCREMENT } struct userSelection { public string source; public string destination; public bool move; public string directoryFormat; public FileRule fileRule; public bool recursive; public bool log; public bool remove; public bool pause; } struct workerState { public string progressLabel; public int numFiles; public int filesProcessed; } public partial class MainForm : Form { /// <summary> /// Class constructor. /// Directory format and filename rule comboboxes are initialised. /// </summary> public MainForm() { InitializeComponent(); filenameRule.SelectedIndex = 0; directoryFormat1.SelectedIndex = 0; directoryFormat2.SelectedIndex = 0; directoryFormat3.SelectedIndex = 0; } /// <summary> /// Asynchronous worker thread. This method uses the Worker class along with the /// StreamWriter class to loop through the discovered files and write a log file /// if the user requested one. /// </summary> /// <param name="sender">The worker thread object</param> /// <param name="e">Arguments passed to the worker thread</param> private void workerThread_DoWork(object sender, DoWorkEventArgs e) { int files = 0; // Number of files discovered (also used for the loop) int progress = 0; // Progress through the files (expected to increment to files) int processed = 0; // Number of files processed (`COPY` or `MOVE` flag, not incremented with `NONE`) string log = ""; // The file log string. Newlines must be replaced before being written bool success = true;// True if the current file processed successfully userSelection user = (userSelection)e.Argument; using (Worker worker = new Worker(sender, e)) { for (files = 0; files < worker.state.numFiles; files++, processed++) { // Process the current file in the enumerated list success = worker.ProcessFile((worker.user.move ? 0 : files), ++progress); if (!success) { if (processed != 0) { processed--; } continue; } // Add to the file operation log log += String.Format("{0:00}:{1:00}:{2:00} {3} `{4}` -> `{5}`\n", DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, success ? (user.move ? "[MOVE]" : "[COPY]") : ("[NONE]"), worker.currentSource, worker.currentDest); } } if (user.log) { // Using the StreamWriter class, write a log of the operations completed to a new // file, in the format `YYYY-MM:DD HH-MM-SS.log`. This file is created in the // Application startup directory. using (StreamWriter streamWriter = new StreamWriter(String.Format(@"{0}\{1:0000}-{2:00}-{3:00} {4:00}-{5:00}-{6:00}.log", Application.StartupPath, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second))) { streamWriter.WriteLine(String.Format("Number of files discovered: {0}", files)); streamWriter.WriteLine(String.Format("Files {0}: {1}\n", user.move ? "moved" : "copied", processed)); streamWriter.Write(log.Replace("\n", Environment.NewLine)); } } } /// <summary> /// Updates the progress bar and progress label when the background thread /// reports that the progress has changed. /// </summary> private void workerThread_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) { workerState progress = (workerState)e.UserState; progressLabel.Text = progress.progressLabel; if (progress.numFiles != progressBar.Maximum) { progressBar.Maximum = progress.numFiles; } progressBar.Value = progress.filesProcessed; } /// <summary> /// Returns the controls to their previous enabled state /// upon background thread completion. /// </summary> private void workerThread_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { ChangeControlState(true); } /// <summary> /// Configures the folderBrowser object to request a source directory. /// Upon closure the selected path is inserted into the sourceDirectory textbox. /// </summary> private void sourceBrowseButton_Click(object sender, System.EventArgs e) { folderBrowser.Description = "Select the direcotry where your assorted images are stored."; folderBrowser.ShowNewFolderButton = false; folderBrowser.ShowDialog(); sourceDirectory.Text = folderBrowser.SelectedPath; } /// <summary> /// Configures the folderBrowser object to request a destination directory. /// Upon closure the selected path is inserted into the destination textbox. /// </summary> private void destinationButton_Click(object sender, System.EventArgs e) { folderBrowser.Description = "Select the directory where the images should be moved/copied to."; folderBrowser.ShowNewFolderButton = true; folderBrowser.ShowDialog(); destination.Text = folderBrowser.SelectedPath; } /// <summary> /// Changes the state of the pause option depending on the check state /// of the remove option. /// </summary> private void optionRemoveDuplicates_CheckedChanged(object sender, System.EventArgs e) { if (optionRemoveDuplicates.Checked) { optionPauseOnDuplicate.Enabled = false; } else { optionPauseOnDuplicate.Enabled = true; } } /// <summary> /// Changes the control states when the selected filename rule changes /// in order to enable and disable duplicate options. /// </summary> private void filenameRule_SelectedIndexChanged(object sender, EventArgs e) { ChangeControlState(true); } /// <summary> /// This method handles the validation and preparation of the main form /// when the main control button is clicked by the user. This button /// causes the background thread to begin. /// </summary> private void controlButton_Click(object sender, System.EventArgs e) { switch (controlButton.Text) { case "Start": string dirFormat = ""; string sourceDir = ""; string destDir = ""; // Validate directory entries if (!Directory.Exists(sourceDirectory.Text)) { MessageBox.Show("The source directory could not be found.", "Unable to find directory", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (!Directory.Exists(destination.Text)) { MessageBox.Show("The destination directory could not be found.", "Unable to find directory", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (sourceDirectory.Text == destination.Text && (directoryFormat1.SelectedIndex == 0 && directoryFormat2.SelectedIndex == 0 && directoryFormat3.SelectedIndex == 0)) { MessageBox.Show("Please select source and destination directories that differ.", "Identical directories", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Destination directory formatting if ((DirOpt)directoryFormat1.SelectedIndex != DirOpt.NONE) dirFormat += String.Format(@"{0}\", (DirOpt)directoryFormat1.SelectedIndex); if ((DirOpt)directoryFormat2.SelectedIndex != DirOpt.NONE) dirFormat += String.Format(@"{0}\", (DirOpt)directoryFormat2.SelectedIndex); if ((DirOpt)directoryFormat3.SelectedIndex != DirOpt.NONE) dirFormat += String.Format(@"{0}\", (DirOpt)directoryFormat3.SelectedIndex); // Insert trailing slashes if not found sourceDir = sourceDirectory.Text.EndsWith(@"\") ? sourceDirectory.Text : sourceDirectory.Text + @"\"; destDir = destination.Text.EndsWith(@"\") ? destination.Text : destination.Text + @"\"; // Prepare the environment for start Directory.CreateDirectory(destDir); ChangeControlState(false); userSelection user = new userSelection() { source = sourceDir, destination = destDir, move = optionMove.Checked ? true : false, directoryFormat = dirFormat, fileRule = (FileRule)filenameRule.SelectedIndex, recursive = optionRecursive.Checked ? true : false, log = optionLog.Checked ? true : false, remove = optionRemoveDuplicates.Checked ? true : false, pause = optionPauseOnDuplicate.Checked ? true : false }; workerThread.RunWorkerAsync(user); break; case "Stop": // TODO: Cancel Async operation break; }; } /// <summary> /// Changes the state of all the user-interactable controls on the /// form to the specified value. /// </summary> /// <param name="value">True if all the controls are to be enabled.</param> private void ChangeControlState(bool value) { sourceDirectory.Enabled = value; destination.Enabled = value; optionMove.Enabled = value; optionCopy.Enabled = value; sourceBrowseButton.Enabled = value; destinationButton.Enabled = value; directoryFormat1.Enabled = value; directoryFormat2.Enabled = value; directoryFormat3.Enabled = value; filenameRule.Enabled = value; optionRecursive.Enabled = value; optionLog.Enabled = value; controlButton.Text = value ? "Start" : "Stop"; if (filenameRule.SelectedIndex == 1) { optionRemoveDuplicates.Enabled = true; optionPauseOnDuplicate.Enabled = true; } else { optionRemoveDuplicates.Enabled = false; optionPauseOnDuplicate.Enabled = false; } } } }
StevenFrost/ImageSort
Source/MainForm.cs
C#
mit
11,721
/** * Created by Dennis Schwartz on 16/12/15. */ var THREE = require('three'); var TrackballControls = require('three.trackball'); var OrthographicTrackballControls = require('three.orthographictrackball'); var Layouts = require('./layouts'); var Fixed = Layouts.connectedMultilayer; var ForceDirectedLayered = Layouts.independentMultilayer; var Manual = Layouts.manual; var R = require('ramda'); var Defaults = require('./defaults'); function Graphics ( state ) { var stable = false; var maxWeight = state.elements.maxWeight; // Attach the current three instance to the state state.THREE = THREE; /* Create the three.js canvas/WebGL renderer */ state.renderer = createRenderer( state.visEl ); state.scene = new THREE.Scene(); createCamera( state ); /* Create Layout with elements in state */ var layout = createLayout( state ); /* Layouts specify renderers and UI builders */ var nodeRenderer = layout.nodeRenderer; //var linkRenderer = layout.linkRenderer; /** * This sets the default node rendering function */ //var linkRenderer = function ( link ) { // console.log(link); // console.log(state.elements.elements[link.from]); // // var from = nodeUI[link.from.substring(2)]; // var to = nodeUI[link.to.substring(2)]; // link.geometry.vertices[0].set(from.position.x, // from.position.y, // from.position.z); // link.geometry.vertices[1].set(to.position.x, // to.position.y, // to.position.z); // link.geometry.verticesNeedUpdate = true; //}; var nodeUIBuilder = layout.nodeUIBuilder; var linkUIBuilder = layout.linkUIBuilder; /* Create ui (look) of every element and add it to the element object */ var nodes = state.elements.nodelayers; // TODO: Save only IDs in these lists var edges = state.elements.edges; nodes.forEach(function (n) { createNodeUI(state.elements.elements['nl' + n.data.id]); }); edges.forEach(function (e) { var toID = e.data.target.substring(2); var fromID = e.data.source.substring(2); var link = state.elements.elements[ 'e' + fromID + toID ]; createLinkUI(link); }); console.log(state); /* Create controls if set */ /** * Create the UI for each node-layer in the network and add them to the scene * @param node */ function createNodeUI(node) { if (!node.ui) { node.ui = nodeUIBuilder(node); console.log('hello!'); node.position = layout.getNodePosition(node); var layers = R.map(function (i) { return i.data['id'] }, state.elements.layers); node.position.z = layers.indexOf('l' + node.data['layer']) * state.interLayerDistance; } state.scene.add(node.ui); //console.log("added"); //console.log(node.ui); } /** * Create the UI for each link and add it to the scene * @param link */ function createLinkUI(link) { if (!link.ui) { var from = link.data['source']; var to = link.data['target']; link.ui = linkUIBuilder(link); link.ui.from = from; link.ui.to = to; } state.scene.add(link.ui); } /** * This is the main Animation loop calling requestAnimationFrame on window * which in turn calls back to this function */ function run () { //if ( stop ) return; window.requestAnimationFrame( run ); if (!stable) { stable = layout.step(); } renderFrame (); state.controls.update (); } /** * Create three.js state * @param state * @returns {THREE.PerspectiveCamera} */ function createCamera ( state ) { var container = state.renderer.domElement; var camera; var controls; if ( state.cameraType === 'orthographic' ) { // Create camera camera = new THREE.OrthographicCamera( container.width / 2, container.width / -2, container.height / 2, container.height / -2, 1, 1000 ); camera.position.x = 200; camera.position.y = 100; camera.position.z = 300; camera.lookAt(state.scene.position); // Create corresponding controls if necessary if ( state.zoomingEnabled ) controls = new OrthographicTrackballControls(camera, state.renderer.domElement); } else { // Default case camera = new THREE.PerspectiveCamera(45, container.clientWidth / container.clientHeight, 0.1, 30000); if ( state.zoomingEnabled ) controls = new TrackballControls(camera, state.renderer.domElement); } camera.position.z = 400; state.camera = camera; if (state.zoomingEnabled) { controls.panSpeed = 0.8; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.addEventListener('change', renderFrame); state.controls = controls; } } /** * This function calculates and sets * the current position of each ui-element each frame. */ function renderFrame() { //Alternative version nodes.forEach(function ( node ) { var n = state.elements.elements[ 'nl' + node.data.id ]; nodeRenderer( n ); }); if ( state.directed ) { var arrowScale = 0.25; edges.forEach(function ( edge ) { var toID = edge.data.target.substring(2); var fromID = edge.data.source.substring(2); var link = state.elements.elements[ 'e' + fromID + toID ]; var from = state.elements.elements[ edge.data.source ]; var to = state.elements.elements[ edge.data.target ]; var newSourcePos = new THREE.Vector3(from.ui.position.x, from.ui.position.y, from.ui.position.z); var newTargetPos = new THREE.Vector3(to.ui.position.x, to.ui.position.y, to.ui.position.z); var arrowVec = newTargetPos.clone().sub(newSourcePos); // targetPos + norm(neg(arrowVec)) * (nodesize / 2) var nodeRadVec = arrowVec.clone().negate().normalize().multiplyScalar(state.nodesize || 6); var cursor = newTargetPos.clone().add(nodeRadVec); // point link.ui.geometry.vertices[0].set(cursor.x, cursor.y, cursor.z); link.ui.geometry.vertices[3].set(cursor.x, cursor.y, cursor.z); cursor.add(nodeRadVec.multiplyScalar(1.5)); //arrowHeadBase var arrowHeadBase = cursor.clone(); var flanker = nodeRadVec.clone().cross(new THREE.Vector3(0,0,1)).multiplyScalar(arrowScale); var w = link.data.weight || 1; var factor = 1; if ( maxWeight === 0 ) { factor = .6 - (.6 / (w + .1)); } else { if ( state.normalisation === 'log' ) { factor = 0.6 * ( Math.log(w) / Math.log(maxWeight) ); } else { factor = 0.6 * ( w / maxWeight ); } } var ribboner = flanker.clone().multiplyScalar(factor); var flank1 = cursor.clone().add(flanker); //flank 1 link.ui.geometry.vertices[1].set(flank1.x, flank1.y, flank1.z); flanker.add(flanker.negate().multiplyScalar(arrowScale * 2)); cursor.add(flanker); //flank 2 link.ui.geometry.vertices[2].set(cursor.x, cursor.y, cursor.z); // Move to Ribbon 1 cursor = arrowHeadBase.clone().add(ribboner); link.ui.geometry.vertices[4].set(cursor.x, cursor.y, cursor.z); // Move to Ribbon 2 cursor = arrowHeadBase.clone().add(ribboner.negate()); link.ui.geometry.vertices[5].set(cursor.x, cursor.y, cursor.z); var temp = newTargetPos.clone().add(newSourcePos).divideScalar(2); // Move to source // RibbonSrc1 cursor = newSourcePos.clone().add(ribboner).add(nodeRadVec.negate().multiplyScalar(1.3)); link.ui.geometry.vertices[6].set(cursor.x, cursor.y, cursor.z); // RibbonSrc2 cursor = newSourcePos.clone().add(ribboner.negate()).add(nodeRadVec); link.ui.geometry.vertices[7].set(cursor.x, cursor.y, cursor.z); link.ui.material.color.set(0x000000); //link.ui.material.transparent = true; //link.ui.material.opacity = 0.4; link.ui.geometry.verticesNeedUpdate = true; //link.ui.geometry.elementsNeedUpdate = true; //var distance = newSourcePos.distanceTo(newTargetPos); //var position = newTargetPos.clone().add(newSourcePos).divideScalar(2); //var orientation = new THREE.Matrix4();//a new orientation matrix to offset pivot //var offsetRotation = new THREE.Matrix4();//a matrix to fix pivot rotation //var offsetPosition = new THREE.Matrix4();//a matrix to fix pivot position //orientation.lookAt(newSourcePos, newTargetPos, new THREE.Vector3(0,1,0)); //offsetRotation.makeRotationX(HALF_PI);//rotate 90 degs on X //orientation.multiply(offsetRotation);//combine orientation with rotation transformations //var cylinder = link.ui.geometry;//new THREE.CylinderGeometry(1.2,1.2,distance,1,1,false); ////cylinder.applyMatrix(orientation); //link.ui.scale.y = distance; //link.ui.geometry = cylinder; //link.ui.position.set(position.x, position.y, position.z); //console.log("After"); //console.log(link.ui); }); } else { edges.forEach(function ( edge ) { var toID = edge.data.target.substring(2); var fromID = edge.data.source.substring(2); var link = state.elements.elements[ 'e' + fromID + toID ]; var from = state.elements.elements[ edge.data.source ]; var to = state.elements.elements[ edge.data.target ]; link.ui.geometry.vertices[0].set(from.ui.position.x, from.ui.position.y, from.ui.position.z); link.ui.geometry.vertices[1].set(to.ui.position.x, to.ui.position.y, to.ui.position.z); link.ui.geometry.verticesNeedUpdate = true; }); } state.renderer.render(state.scene, state.camera); } function rebuildUI () { //Object.keys(nodeUI).forEach(function (nodeId) { // scene.remove(nodeUI[nodeId]); //}); //nodeUI = {}; // //Object.keys(linkUI).forEach(function (linkId) { // scene.remove(linkUI[linkId]); //}); //linkUI = {}; // // //network.get( 'nodes' ).forEach(function (n) { // createNodeUI(n); //}); //network.get( 'edges' ).forEach(function (e) { // createLinkUI(e); //}); // Remove old UI nodes.forEach(function (n) { var node = state.elements.elements['nl' + n.data.id]; state.scene.remove(node.ui); node.ui = undefined; }); edges.forEach(function (e) { var toID = e.data.target.substring(2); var fromID = e.data.source.substring(2); var link = state.elements.elements[ 'e' + fromID + toID ]; state.scene.remove(link.ui); link.ui = undefined; }); // Create new UI nodes.forEach(function (n) { createNodeUI(state.elements.elements['nl' + n.data.id]); }); edges.forEach(function (e) { var toID = e.data.target.substring(2); var fromID = e.data.source.substring(2); var link = state.elements.elements[ 'e' + fromID + toID ]; createLinkUI(link); }); } /** * Check if the given Layout was already instantiated or is only a name. * If a name -> create new Layout * @param state * @returns {*} */ function createLayout ( state ) { var input = state.layout; input = input === undefined ? 'ForceDirectedLayered' : input.name; network = state.elements; console.log(state); if ( typeof input === 'string' ) { var layout; if ( input === 'Fixed' ) { console.log(state.physicsSettings); return new Fixed( network, state ); } if ( input === 'ForceDirectedLayered' ) { return new ForceDirectedLayered( network, state ); } if ( input === 'ForceDirected' ) { return new ForceDirected(network, settings); } if ( input === 'Manual' ) { return new Manual( state.elements ); } } else if ( input ) { return input; } throw new Error ( "The layout " + input + " could not be created!" ); } return { THREE: THREE, run: run, resetStable: function () { stable = false; layout.resetStable(); }, /** * You can set the nodeUIBuilder function yourself * allowing for custom UI settings * @param callback */ setNodeUI: function (callback) { nodeUIBuilder = callback; rebuildUI(); return this; }, /** * You can set the nodeUIBuilder function yourself * allowing for custom UI settings * @param callback */ setLinkUI: function (callback) { linkUIBuilder = callback; rebuildUI(); return this; } }; /** * Create the three.js renderer * @param container * @returns {*} */ function createRenderer ( container ) { var webGlSupport = webgl_detect(); var renderer = webGlSupport ? new THREE.WebGLRenderer( { container: container, antialias: true } ) : new THREE.CanvasRenderer( container ); var width = container.clientWidth || window.innerWidth; var height = container.clientHeight || window.innerHeight; renderer.setSize( width, height ); renderer.setClearColor( 0xffffff, 1 ); console.log(renderer); if ( container ) { container.appendChild( renderer.domElement ); } else { document.body.appendChild( renderer.domElement ); } return renderer; } /** * http://stackoverflow.com/questions/11871077/proper-way-to-detect-webgl-support * @param return_context * @returns {*} */ function webgl_detect(return_context) { if (!!window.WebGLRenderingContext) { var canvas = document.createElement("canvas"), names = ["webgl", "experimental-webgl", "moz-webgl", "webkit-3d"], context = false; for(var i=0;i<4;i++) { try { context = canvas.getContext(names[i]); if (context && typeof context.getParameter == "function") { // WebGL is enabled if (return_context) { // return WebGL object if the function's argument is present return {name:names[i], gl:context}; } // else, return just true return true; } } catch(e) {} } // WebGL is supported, but disabled return false; } // WebGL not supported return false; } } module.exports = Graphics;
DennisSchwartz/biojs-vis-munavi
lib/graphics.js
JavaScript
mit
16,458
using System; using System.Drawing; using CanmanSharp.Core; namespace CanmanSharp.BuiltIn.Filters { public class Brightness : FilterBase { private readonly int _adjust; public Brightness(double Adjust) { _adjust = (int) Math.Floor(255*(Adjust/100)); } public override Color Process(Color layerColor) { int r = layerColor.R + _adjust; int g = layerColor.G + _adjust; int b = layerColor.B + _adjust; return Color.FromArgb(layerColor.A, Utils.ClampRGB(r), Utils.ClampRGB(g), Utils.ClampRGB(b)); } } }
sangcu/camansharp
CanmanSharp.BuiltIn/Filters/Brightness.cs
C#
mit
631
using Parkitect.UI; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace Fireworks.UI.Tracks { /// <summary> /// This is the visible firework "item" that the user will drag around on the screen. /// </summary> public class FireworkUIData : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerDownHandler, IPointerEnterHandler, IPointerExitHandler { public string Firework { get { return _firework; } set { if (string.IsNullOrEmpty(value)) { HasFirework = false; gameObject.name = "No Firework"; } else { HasFirework = true; gameObject.name = value; } _firework = value; ChangeImageState(); } } private string _firework; public bool HasFirework { get; private set; } private bool mouseOver = false; private bool beingDragged = false; public string Time { get { return _time; } set { _time = value; } } private string _time; public FireworkUITrack parentTrack; public Color loadedColor; public Color emptyColor; private Vector2 offset; private void Start() { emptyColor = Color.clear; loadedColor.r = Random.value; loadedColor.b = Random.value; loadedColor.g = Random.value; loadedColor.a = 1.0f; ChangeImageState(); } public void ChangeImageState() { Image image = gameObject.GetComponent<Image>(); float alpha = 1.0f; if (!parentTrack.Interactable) { alpha = FireworkUITrack.UI_NONINTERACTABLE_ALPHA; } loadedColor.a = alpha; if (HasFirework) { image.color = loadedColor; } else { image.color = emptyColor; } } /// <summary> /// This will recalculate our onscreen position to align us with the slot we currently reside in. /// </summary> public void RecalculatePosition() { FireworkUISlot slot = parentTrack.GetSlotAtTime(Time); transform.SetParent(slot.transform, true); transform.localPosition = Vector3.zero; } public void OnBeginDrag(PointerEventData eventData) { if (!HasFirework || !parentTrack.Interactable) { return; } beingDragged = true; gameObject.GetComponentInChildren<CanvasGroup>().blocksRaycasts = false; transform.SetParent(transform.parent.parent.parent, true); OnDrag(eventData); } public void OnDrag(PointerEventData eventData) { if (!HasFirework || !parentTrack.Interactable) { return; } transform.position = eventData.position - offset; } public void OnEndDrag(PointerEventData eventData) { if (!HasFirework) { return; } gameObject.GetComponentInChildren<CanvasGroup>().blocksRaycasts = true; RecalculatePosition(); beingDragged = false; if (!mouseOver && !beingDragged) { UITooltipController.Instance.hideTooltip(); } } public void OnPointerDown(PointerEventData eventData) { if (!parentTrack.Interactable) { return; } if (HasFirework) { if (eventData.button == PointerEventData.InputButton.Right) { parentTrack.RemoveFirework(Time); } else if (eventData.button == PointerEventData.InputButton.Left) { offset = eventData.position - new Vector2(this.transform.position.x, this.transform.position.y); } } else { Dropdown.OptionData fireworkOption = ShowWindow.fireworkDropdown.options[ShowWindow.fireworkDropdown.value]; parentTrack.AddFirework(Time, fireworkOption.text); } } public void OnPointerEnter(PointerEventData eventData) { mouseOver = true; UITooltipController.Instance.showTooltip(Firework, true); } public void OnPointerExit(PointerEventData eventData) { mouseOver = false; if (!mouseOver && !beingDragged) { UITooltipController.Instance.hideTooltip(); } } } }
Jay2645/Parkitect-Fireworks
UI/FireworkUIData.cs
C#
mit
3,818
// // MonoTests.System.Web.Services.Description.OperationMessageTest.cs // // Author: // Erik LeBel <eriklebel@yahoo.ca> // // (C) 2003 Erik LeBel // using NUnit.Framework; using System; using System.Web.Services.Description; using System.Xml; namespace MonoTests.System.Web.Services.Description { [TestFixture] public class OperationMessageTest { OperationMessage operation; [SetUp] public void InitializeOperation() { // workaround: OperationInput, OperationOutput and OperationFault are all empty derivations of OperationMessage operation = new OperationInput(); } [Test] public void TestDefaultProperties() { Assertion.AssertEquals(String.Empty, operation.Documentation); Assertion.AssertNull(operation.Name); Assertion.AssertEquals(XmlQualifiedName.Empty, operation.Message); Assertion.AssertNull(operation.Operation); } } }
jjenki11/blaze-chem-rendering
qca_designer/lib/ml-pnet-0.8.1/mcs-sources/class/System.Web.Services/Test/System.Web.Services.Description/OperationMessageTest.cs
C#
mit
877
<?php namespace Cetera; include_once('../include/common.php'); $application->connectDb(); $application->initSession(); $application->initPlugins(); if (isset($_REQUEST['locale'])) { $application->setLocale($_REQUEST['locale']); } $translator = $application->getTranslator(); foreach (Theme::enum() as $theme) $theme->addTranslation($translator); $data = array( 'templateExistsReplace' => $translator->_('Такой шаблон уже существует. Перезаписать?'), 'materialLocked' => $translator->_('материал редактируется пользователем <{0}>'), 'resetDefault' => $translator->_('Сбросить к первоначальному значению'), 'prev' => $translator->_('Назад'), 'next' => $translator->_('Дальше'), 'propsMain' => $translator->_('Основные'), 'synonym' => $translator->_('Синонимы'), 'materialNotSaved' => $translator->_('Материал не сохранен'), 'materialSaved' => $translator->_('Материал сохранен'), 'materialFixFields' => $translator->_('Исправьте неправильно заполненные поля'), 'color_lengthText' => $translator->_('3 или 6 знаков'), 'color_blankText' => $translator->_('Неправильный формат'), 'num' => $translator->_('Только целые положительные числа или 0'), 'page' => $translator->_('Страница'), 'fileNotFound' => $translator->_('Файл не существует'), 'fileCreate' => $translator->_('Создать файл?'), 'accessDenied' => $translator->_('Доступ запрещен'), 'fileChanged' => $translator->_('Файл изменен'), 'saveChanges' => $translator->_('Сохранить изменения?'), 'expandAll' => $translator->_('Развернуть все'), 'requestException' => $translator->_('Ошибка соединения с сервером.'), 'addTheme' => $translator->_('Установить тему'), 'activate' => $translator->_('Активировать'), 'activity' => $translator->_('Активность'), 'actvt' => $translator->_('Акт.'), 'theme' => $translator->_('Тема'), 'used' => $translator->_('Используется'), 'apply' => $translator->_('Применить'), 'themePrefs' => $translator->_('Настройки темы'), 'addArea' => $translator->_('Добавить область'), 'add' => $translator->_('Область'), 'addWidget' => $translator->_('Создать виджет'), 'template' => $translator->_('Шаблон'), 'menu' => $translator->_('Меню'), 'depth' => $translator->_('Глубина'), 'rootFolder' => $translator->_('Корневой раздел'), 'catalog' => $translator->_('Раздел'), 'order' => $translator->_('Порядок'), 'sort' => $translator->_('Сортировка'), 'srt' => $translator->_('Сорт.'), 'matCount' => $translator->_('Кол-во материалов'), 'domainName' => $translator->_('Доменное имя'), 'linkTo' => $translator->_('Ссылка на'), 'setup' => $translator->_('Настроить'), 'save' => $translator->_('Сохранить'), 'saveAs' => $translator->_('Сохранить как'), 'properties' => $translator->_('Свойства'), 'typeDeleteWarning' => $translator->_('Внимание!<br>Вы удаляете тип {0}. Вместе с этим будут удалены все разделы этого типа,<br>а также все материалы из этих разделов.\n\nПродолжить?'), 'fieldAdd' => $translator->_('Добавить поле'), 'fieldEdit' => $translator->_('Изменить поле'), 'description' => $translator->_('Описание'), 'typeCreate' => $translator->_('Новый тип материалов'), 'typeFixed' => $translator->_('Встроенные типы'), 'typeUser' => $translator->_('Пользовательские типы'), 'dataType' => $translator->_('Тип данных'), 'fields' => $translator->_('Поля'), 'invalidSize' => $translator->_('Неправильный размер'), 'requiredField' => $translator->_('Обязательное поле'), 'hiddenField' => $translator->_('Скрытое поле'), 'showField' => $translator->_('Видимое'), 'variants' => $translator->_('Варианты значений'), 'defaultValue' => $translator->_('Значение по умолчанию'), 'editor' => $translator->_('Редактор'), 'fromCatalog' => $translator->_('Из раздела'), 'fromCurrentCatalog' => $translator->_('Из текущего раздела'), 'fromCatalog2' => $translator->_('От раздела'), 'tipa' => $translator->_('типа'), 'yes' => $translator->_('да'), 'no' => $translator->_('нет'), 'materialType' => $translator->_('Тип материалов'), 'no' => $translator->_('№'), 'title' => $translator->_('Заголовок'), 'author' => $translator->_('Автор'), 'published' => $translator->_('Опубликован'), 'unpublished' => $translator->_('Не опубликован'), 'attention' => $translator->_('Внимание!'), 'msgCatLink' => $translator->_('Этот раздел является ссылкой. Перейти в исходный раздел для просмотра материалов?'), 'materialDelete' => $translator->_('Удалить материал'), 'newMaterial' => $translator->_('Создать'), 'newMaterialAs' => $translator->_('Создать по образцу'), 'delete' => $translator->_('Удалить'), 'publish' => $translator->_('Опубликовать'), 'unpublish' => $translator->_('Распубликовать'), 'preview' => $translator->_('Посмотреть на сервере'), 'move' => $translator->_('Переместить'), 'materialDeep' => $translator->_('Показать материалы из подразделов'), 'usersBo' => $translator->_('Показывать только пользователей BackOffice'), 'filter' => $translator->_('Фильтр'), 'nickname' => $translator->_('Псевдоним'), 'total' => $translator->_('Всего'), 'users' => $translator->_('Пользователи'), 'createServer' => $translator->_('Создать сервер'), 'newCatalog' => $translator->_('Новый раздел'), 'newLink' => $translator->_('Создать ссылку на раздел'), 'catProps' => $translator->_('Свойства раздела'), 'copy' => $translator->_('Копировать'), 'copySub' => $translator->_('Копировать подразделы'), 'copyMaterials' => $translator->_('Копировать материалы'), 'copyTo' => $translator->_('Копировать в'), 'confirmation' => $translator->_('Подтверждение'), 'login' => $translator->_('Вход'), 'logout' => $translator->_('Выход'), 'username' => $translator->_('Пользователь'), 'password' => $translator->_('Пароль'), 'lang' => $translator->_('Язык'), 'remember' => $translator->_('запомнить'), 'forgetPassword' => $translator->_('Забыли пароль'), 'recoverPassword' => $translator->_('Создать новый пароль и отправить его на e-mail?'), 'needUsername' => $translator->_('Введите имя пользователя'), 'add' => $translator->_('Добавить'), 'close' => $translator->_('Закрыть'), 'refresh' => $translator->_('Обновить'), 'wait' => $translator->_('Подождите ...'), 'ok' => $translator->_('OK'), 'cancel' => $translator->_('Отмена'), 'upper' => $translator->_('Выше'), 'downer' => $translator->_('Ниже'), 'add' => $translator->_('Добавить'), 'edit' => $translator->_('Изменить'), 'remove' => $translator->_('Удалить'), 'removing' => $translator->_('Удаление'), 'upload' => $translator->_('Загрузка файла'), 'upload2' => $translator->_('Загрузить с компьютера'), 'upload3' => $translator->_('Загрузка файлов'), 'uploadCat' => $translator->_('Каталог на сервере'), 'file' => $translator->_('Файл'), 'chooseFile' => $translator->_('Выберите файл'), 'doUpload' => $translator->_('Загрузить'), 'doUpload2' => $translator->_('Загрузить файл'), 'doUpload3' => $translator->_('Загрузить несколько файлов'), 'fileSelect' => $translator->_('Выбор файла'), 'selectFile' => $translator->_('Выбрать из структуры'), 'dirCreate' => $translator->_('Создать каталог'), 'dirDelete' => $translator->_('Удалить каталог'), 'fileDelete' => $translator->_('Удалить файл'), 'fvTable' => $translator->_('В виде таблицы'), 'fvPreview' => $translator->_('Эскизы'), 'directories' => $translator->_('Каталоги'), 'noFiles' => $translator->_('нет файлов'), 'name' => $translator->_('Имя'), 'date' => $translator->_('Дата'), 'size' => $translator->_('Размер'), 'recent' => $translator->_('Недавние'), 'server' => $translator->_('Сервер'), 'error' => $translator->_('Ошибка'), 'more' => $translator->_('Подробнее'), 'material' => $translator->_('Материал'), 'undelete' => $translator->_('Отменить удаление'), 'noname' => $translator->_('- без заголовка -'), 'picToBeDeleted' => $translator->_('Изображение будет удалено'), 'off' => $translator->_('отключен'), 'do_off' => $translator->_('Отключить'), 'do_on' => $translator->_('Включить'), 'reload' => $translator->_('Обновить'), 'r_u_sure' => $translator->_('Вы уверены?'), 'addPlugin' => $translator->_('Добавить плагин'), 'installed' => $translator->_('установлен'), 'installed_f' => $translator->_('установлена'), 'version' => $translator->_('Версия'), 'author' => $translator->_('Автор'), 'needCms' => $translator->_('CMS'), 'any' => $translator->_('любая'), 'from' => $translator->_('от'), 'to' => $translator->_('до'), 'install' => $translator->_('Установить'), 'upgrade' => $translator->_('Обновить/Переустановить'), 'pluginInstall' => $translator->_('Установка/обновление'), 'upgradeAvail' => $translator->_('доступна свежая версия'), 'loading' => $translator->_('Загрузка ...'), 'reloading' => $translator->_('Перезагрузка ...'), 'wait' => $translator->_('Подождите ...'), 'toFrontOffice' => $translator->_('Перейти на сайт'), ); $data = array_merge($data, $translator->getMessages()); echo json_encode($data);
cetera-labs/cetera-cms
cms/lang/data.php
PHP
mit
11,461
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProductionHelperForTI3.Domain { public class Planet { public int ResourceValue { get; set; } } }
dirkrombauts/production-helper-for-ti3
ProductionHelperForTI3.Domain/Planet.cs
C#
mit
247
<html> <head> <title> NLRB targets workers' rights (again) </title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <?php include "../../legacy-includes/Script.htmlf" ?> </head> <body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0"> <table width="744" cellspacing="0" cellpadding="0" border="0"> <tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td> <td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?> </td></tr></table> <table width="744" cellspacing="0" cellpadding="0" border="0"> <tr><td width="18" bgcolor="FFCC66"></td> <td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td> <td width="18"></td> <td width="480" valign="top"> <?php include "../../legacy-includes/BodyInsert.htmlf" ?> <font face="Arial, Helvetica, sans-serif" size="2"><b>ISSUES IN THE LABOR MOVEMENT</b></font><br> <font face="Times New Roman, Times, serif" size="5"><b>NLRB targets workers' rights (again)</b></font><p> <font face="Times New Roman, Times, serif" size="2"><b>By Darrin Hoop, UFCW Local 21</b></font><font face="Arial, Helvetica, sans-serif" size="2"> | November 3, 2006 | Page 15</font><p> <font face="Times New Roman, Times, serif" size="3">THE KENTUCKY River case recently handed down by the National Labor Relations Board (NLRB) could prevent millions of workers labeled as "supervisors" from joining or remaining in unions.<p> But it's only the latest in a series of anti-union rulings by that body under the administration of George W. Bush. The NLRB under Bush has also stripped the right to form unions from graduate research assistants, disabled workers in vocational programs, and workers hired through temporary agencies.<p> Now the Kentucky River case makes a bleak picture for workers' rights even worse.<p> According to a 2002 Government Accounting Office report, 25 percent of the civilian workforce--32 million workers--is without any legal protection to form unions. These include, in part, farm workers, domestic workers and independent contractors.<p> The largest group of employees without collective bargaining rights, some 10.2 million people, are those deemed supervisors by the NLRB--a category that now includes charge nurses, according to the Kentucky River ruling.<p> In order to understand how labor has gotten to this point, we must look at the history of the NLRB, a federal agency with headquarters in Washington and 34 regional offices. It's run by a five-person board whose members are appointed by the president, with the approval of the Senate, for staggered five-year terms.<p> The NLRB's job is to define bargaining units, hold elections, certify union elections and to interpret and apply the provisions of the National Labor Relations Act (NLRA) of 1935, originally known as the Wagner Act. The law acknowledged workers' right to form unions and made it illegal for employers to refuse to bargain with them.<p> Roosevelt backed the NLRA because he recognized that working-class anger was reaching a boiling point in the early 1930s. He hoped to prevent a working-class rebellion, and he needed workers' votes in order to win re-election in 1936.<p> The Taft-Hartley Act, passed in 1947, dramatically restricted the NLRA in response to the biggest strike wave in U.S. history.<p> During the 12 months after the Second World War ended in 1945, more than five million workers were involved in strikes. Taft-Hartley outlawed wildcat strikes, solidarity strikes known as secondary boycotts, and mass picketing. It also required all union officials to sign affidavits stating that they weren't members of the Communist Party.<p> A less well-known provision excluded supervisors from the right to join unions by including a broad definition of employees who have a managerial responsibility to hire, fire, or discipline other employees if "the exercise of such authority is not of a merely routine or clerical nature, but requires the use of independent judgment"--language cited in the Kentucky River ruling.<p> Democratic President Harry Truman vetoed Taft-Hartley in June 1947, knowing that the Republican-controlled Congress had more than enough votes to override his veto. By the middle of 1948, Truman had used the law 12 times to break strikes. As Sharon Smith points out in her book <i>Subterranean Fire,</i> by 1957, the law had severely weakened the labor movement.<p> For almost 60 years, the official labor movement has failed to mount a successful challenge to the crushing weight of Taft Hartley. Today, reliance on the Democratic Party, labor-management partnership, corporate campaigns, and a weakening of union democracy has opened the door to a new round of attacks.<p> As an increasing number of U.S. workers are thrown back into pre-NLRA 1935 working conditions, workers would do well to follow the model of unions like the California Nurses Association, where 30,000 members have already signed pledges to strike if their employers try to implement the new Kentucky River ruling.<p> After all, it was the three great mass strikes of 1934 in Toledo, San Francisco and Minneapolis that compelled Congress to "grant" the right to join unions under the original NLRA. Learning from that history will be key to politically arming the labor movement to move forward today.<p> <?php include "../../legacy-includes/BottomNavLinks.htmlf" ?> <td width="12"></td> <td width="108" valign="top"> <?php include "../../legacy-includes/RightAdFolder.htmlf" ?> </td> </tr> </table> </body> </html>
ISO-tech/sw-d8
web/2006-2/608/608_15_NLRB.php
PHP
mit
5,633
<?xml version="1.0" ?><!DOCTYPE TS><TS language="it" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About profitcoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;profitcoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2014 Profitcoin team Copyright © 2014 The profitcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <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> Questo è un software sperimentale. Distribuito sotto la licenza software MIT/X11, vedi il file COPYING incluso oppure su http://www.opensource.org/licenses/mit-license.php. Questo prodotto include software sviluppato dal progetto OpenSSL per l&apos;uso del Toolkit OpenSSL (http://www.openssl.org/), software crittografico scritto da Eric Young (eay@cryptsoft.com) e software UPnP scritto da Thomas Bernard.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Fai doppio click per modificare o cancellare l&apos;etichetta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Crea un nuovo indirizzo</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia l&apos;indirizzo attualmente selezionato nella clipboard</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your profitcoin 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 line="+60"/> <source>&amp;Copy Address</source> <translation>&amp;Copia l&apos;indirizzo</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 profitcoin 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>Cancella l&apos;indirizzo attualmente selezionato dalla lista</translation> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified profitcoin 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;Cancella</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Copia &amp;l&apos;etichetta</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Modifica</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Finestra passphrase</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Inserisci la passphrase</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nuova passphrase</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ripeti la passphrase</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <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>Inserisci la passphrase per il portamonete.&lt;br/&gt;Per piacere usare unapassphrase di &lt;b&gt;10 o più caratteri casuali&lt;/b&gt;, o &lt;b&gt;otto o più parole&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Cifra il portamonete</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Sblocca il portamonete</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per decifrare il portamonete,</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decifra il portamonete</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Cambia la passphrase</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Inserisci la vecchia e la nuova passphrase per il portamonete.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Conferma la cifratura del portamonete</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 COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Si è sicuri di voler cifrare il portamonete?</translation> </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>IMPORTANTE: qualsiasi backup del portafoglio effettuato precedentemente dovrebbe essere sostituito con il file del portafoglio criptato appena generato. Per ragioni di sicurezza, i backup precedenti del file del portafoglio non criptato diventeranno inservibili non appena si inizi ad usare il nuovo portafoglio criptato.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Attenzione: tasto Blocco maiuscole attivo.</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Portamonete cifrato</translation> </message> <message> <location line="-58"/> <source>profitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Cifratura del portamonete fallita</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Cifratura del portamonete fallita a causa di un errore interno. Il portamonete non è stato cifrato.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Le passphrase inserite non corrispondono.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Sblocco del portamonete fallito</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La passphrase inserita per la decifrazione del portamonete è errata.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Decifrazione del portamonete fallita</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Passphrase del portamonete modificata con successo.</translation> </message> </context> <context> <name>ProfitcoinGUI</name> <message> <location filename="../profitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation>Firma il &amp;messaggio...</translation> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation>Sto sincronizzando con la rete...</translation> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation>&amp;Sintesi</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostra lo stato generale del portamonete</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transazioni</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Cerca nelle transazioni</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>&amp;Esci</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Chiudi applicazione</translation> </message> <message> <location line="+6"/> <source>Show information about profitcoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Informazioni su &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostra informazioni su Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opzioni...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifra il portamonete...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Portamonete...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambia la passphrase...</translation> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a profitcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for profitcoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>Backup portamonete in un&apos;altra locazione</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Cambia la passphrase per la cifratura del portamonete</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>Finestra &amp;Debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Apri la console di degugging e diagnostica</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Verifica messaggio...</translation> </message> <message> <location line="-202"/> <source>profitcoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+180"/> <source>&amp;About profitcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Mostra/Nascondi</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Impostazioni</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Aiuto</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation>Barra degli strumenti &quot;Tabs&quot;</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>profitcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to profitcoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About profitcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about profitcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Aggiornato</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>In aggiornamento...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <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="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Transazione inviata</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Transazione ricevuta</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantità: %2 Tipo: %3 Indirizzo: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid profitcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;sbloccato&lt;/b&gt;</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;bloccato&lt;/b&gt;</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </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 numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation><numerusform>%n ora</numerusform><numerusform>%n ore</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n giorno</numerusform><numerusform>%n giorni</numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../profitcoin.cpp" line="+109"/> <source>A fatal error occurred. profitcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>Avviso di rete</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>Quantità:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Byte:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>Priorità:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Commissione:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Low Output:</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation>no</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>Dopo Commissione:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation>Resto:</translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation>(de)seleziona tutto</translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>Modalità Albero</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>Modalità Lista</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>Conferme:</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Confermato</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>Priorità</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Copia l&apos;indirizzo</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia l&apos;etichetta</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Copia l&apos;ID transazione</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>Copia quantità</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>Copia commissione</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Copia dopo commissione</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Copia byte</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Copia priorità</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Copia low output</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Copia resto</translation> </message> <message> <location line="+317"/> <source>highest</source> <translation>massima</translation> </message> <message> <location line="+1"/> <source>high</source> <translation>alta</translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation>medio-alta</translation> </message> <message> <location line="+1"/> <source>medium</source> <translation>media</translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation>medio-bassa</translation> </message> <message> <location line="+1"/> <source>low</source> <translation>bassa</translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation>infima</translation> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation>si</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>resto da %1 (%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation>(resto)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Modifica l&apos;indirizzo</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Indirizzo</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 type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>Nuovo indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nuovo indirizzo d&apos;invio</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Modifica indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Modifica indirizzo d&apos;invio</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>L&apos;indirizzo inserito &quot;%1&quot; è già in rubrica.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid profitcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Impossibile sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Generazione della nuova chiave non riuscita.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>profitcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </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>Opzioni</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principale</translation> </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. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Paga la &amp;commissione</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start profitcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start profitcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>Rete</translation> </message> <message> <location line="+6"/> <source>Automatically open the profitcoin 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>Mappa le porte tramite l&apos;&amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the profitcoin 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>&amp;IP del proxy:</translation> </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>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta del proxy (es. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Version:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versione SOCKS del proxy (es. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Finestra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Mostra solo un&apos;icona nel tray quando si minimizza la finestra</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizza sul tray invece che sulla barra delle applicazioni</translation> </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>Riduci ad icona, invece di uscire dall&apos;applicazione quando la finestra viene chiusa. Quando questa opzione è attivata, l&apos;applicazione verrà chiusa solo dopo aver selezionato Esci nel menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizza alla chiusura</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Mostra</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Lingua Interfaccia Utente:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting profitcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unità di misura degli importi in:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Scegli l&apos;unità di suddivisione predefinita per l&apos;interfaccia e per l&apos;invio di monete</translation> </message> <message> <location line="+9"/> <source>Whether to show profitcoin 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>&amp;Mostra gli indirizzi nella lista delle transazioni</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation>Mostrare/non mostrare le funzionalita&apos; di controllo della moneta.</translation> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancella</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>predefinito</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting profitcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>L&apos;indirizzo proxy che hai fornito è invalido.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Modulo</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the profitcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>Saldo spendibile attuale</translation> </message> <message> <location line="+71"/> <source>Immature:</source> <translation>Immaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Importo scavato che non è ancora maturato</translation> </message> <message> <location line="+20"/> <source>Total:</source> <translation>Totale:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Saldo totale attuale</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transazioni recenti&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>fuori sincrono</translation> </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 type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </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>Nome del client</translation> </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="+348"/> <source>N/A</source> <translation>N/D</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versione client</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informazione</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Versione OpenSSL in uso</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempo di avvio</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rete</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Numero connessioni</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Block chain</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Numero attuale di blocchi</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Numero totale stimato di blocchi</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Ora dell blocco piu recente</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Apri</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the profitcoin-Qt help message to get a list with possible profitcoin 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>&amp;Console</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data di creazione</translation> </message> <message> <location line="-104"/> <source>profitcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>profitcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>File log del Debug</translation> </message> <message> <location line="+7"/> <source>Open the profitcoin 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>Svuota console</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the profitcoin 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>Usa le frecce direzionali per navigare la cronologia, and &lt;b&gt;Ctrl-L&lt;/b&gt; per cancellarla.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scrivi &lt;b&gt;help&lt;/b&gt; per un riassunto dei comandi disponibili</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Spedisci Profitcoin</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation>Funzionalità di Coin Control</translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation>Input...</translation> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation>selezionato automaticamente</translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation>Fondi insufficienti!</translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>Quantità:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Byte:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 hack</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation>Priorità:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>Commissione:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Low Output:</translation> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>Dopo Commissione:</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Spedisci a diversi beneficiari in una volta sola</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Aggiungi beneficiario</translation> </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>Cancella &amp;tutto</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+16"/> <source>123.456 hack</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Conferma la spedizione</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Spedisci</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a profitcoin address (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>Copia quantità</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>Copia commissione</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Copia dopo commissione</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Copia byte</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Copia priorità</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Copia low output</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Copia resto</translation> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Conferma la spedizione di profitcoin</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>L&apos;indirizzo del beneficiario non è valido, per cortesia controlla.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>L&apos;importo da pagare dev&apos;essere maggiore di 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>L&apos;importo è superiore al saldo attuale</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Il totale è superiore al saldo attuale includendo la commissione %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Trovato un indirizzo doppio, si può spedire solo una volta a ciascun indirizzo in una singola operazione.</translation> </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> <message> <location line="+251"/> <source>WARNING: Invalid profitcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Importo:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Paga &amp;a:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Inserisci un&apos;etichetta per questo indirizzo, per aggiungerlo nella rubrica</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <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>Incollare l&apos;indirizzo dagli appunti</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 type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a profitcoin address (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Firme - Firma / Verifica un messaggio</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Firma il messaggio</translation> </message> <message> <location line="-118"/> <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>Puoi firmare messeggi con i tuoi indirizzi per dimostrare che sono tuoi. Fai attenzione a non firmare niente di vago, visto che gli attacchi di phishing potrebbero cercare di spingerti a mettere la tua firma su di loro. Firma solo dichiarazioni completamente dettagliate con cui sei d&apos;accordo.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Incollare l&apos;indirizzo dagli appunti</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>Inserisci qui il messaggio che vuoi firmare</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Copia la firma corrente nella clipboard</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this profitcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Reimposta tutti i campi della firma</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <location line="-64"/> <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>Inserisci l&apos;indirizzo per la firma, il messaggio (verifica di copiare esattamente anche i ritorni a capo, gli spazi, le tabulazioni, etc) e la firma qui sotto, per verificare il messaggio. Verifica che il contenuto della firma non sia più grande di quello del messaggio per evitare attacchi di tipo man-in-the-middle.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified profitcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Reimposta tutti i campi della verifica messaggio</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a profitcoin address (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clicca &quot;Firma il messaggio&quot; per ottenere la firma</translation> </message> <message> <location line="+3"/> <source>Enter profitcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>L&apos;indirizzo inserito non è valido.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Per favore controlla l&apos;indirizzo e prova ancora</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>L&apos;indirizzo profitcoin inserito non è associato a nessuna chiave.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Sblocco del portafoglio annullato.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>La chiave privata per l&apos;indirizzo inserito non è disponibile.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Firma messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Messaggio firmato.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Non è stato possibile decodificare la firma.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Per favore controlla la firma e prova ancora.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>La firma non corrisponde al sunto del messaggio.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verifica messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Messaggio verificato.</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation>in conflitto</translation> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/non confermato</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 conferme</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Stato</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, trasmesso attraverso %n nodo</numerusform><numerusform>, trasmesso attraverso %n nodi</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Sorgente</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generato</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Da</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>A</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>proprio indirizzo</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etichetta</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura in %n ulteriore blocco</numerusform><numerusform>matura in altri %n blocchi</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>non accettate</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Commissione transazione</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Importo netto</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Messaggio</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Commento</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID della transazione</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 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>Informazione di debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transazione</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Input</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>vero</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, non è stato ancora trasmesso con successo</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>sconosciuto</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Dettagli sulla transazione</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Questo pannello mostra una descrizione dettagliata della transazione</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Confermato (%1 conferme)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation>Offline</translation> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation>Non confermato:</translation> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>In conferma (%1 di %2 conferme raccomandate)</translation> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation>In conflitto</translation> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Immaturo (%1 conferme, sarà disponibile fra %2)</translation> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Questo blocco non è stato ricevuto da altri nodi e probabilmente non sarà accettato!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generati, ma non accettati</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ricevuto da</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento a te stesso</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(N / a)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stato della transazione. Passare con il mouse su questo campo per vedere il numero di conferme.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e ora in cui la transazione è stata ricevuta.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo di transazione.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Indirizzo di destinazione della transazione.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Importo rimosso o aggiunto al saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Tutti</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Oggi</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Questa settimana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Questo mese</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Il mese scorso</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Quest&apos;anno</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervallo...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>A te</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Altro</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Inserisci un indirizzo o un&apos;etichetta da cercare</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Importo minimo</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copia l&apos;indirizzo</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copia l&apos;ID transazione</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Modifica l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostra i dettagli della transazione</translation> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confermato</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervallo:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>a</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>profitcoin-core</name> <message> <location filename="../profitcoinstrings.cpp" line="+33"/> <source>profitcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Utilizzo:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or profitcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Lista comandi </translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Aiuto su un comando </translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>Opzioni: </translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: profitcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: profitcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Specifica il file portafoglio (nella cartella dati)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specifica la cartella dati </translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Imposta la dimensione cache del database in megabyte (predefinita: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Mantieni al massimo &lt;n&gt; connessioni ai peer (predefinite: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Connessione ad un nodo per ricevere l&apos;indirizzo del peer, e disconnessione</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Specifica il tuo indirizzo pubblico</translation> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Soglia di disconnessione dei peer di cattiva qualità (predefinita: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numero di secondi di sospensione che i peer di cattiva qualità devono trascorrere prima di riconnettersi (predefiniti: 86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv4: %s</translation> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <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="-5"/> <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="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accetta da linea di comando e da comandi JSON-RPC </translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>Esegui in background come demone e accetta i comandi </translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Utilizza la rete di prova </translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accetta connessioni dall&apos;esterno (predefinito: 1 se no -proxy o -connect)</translation> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv6, tornando su IPv4: %s</translation> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Attenzione: -paytxfee è molto alta. Questa è la commissione che si paga quando si invia una transazione.</translation> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong profitcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Attenzione: errore di lettura di wallet.dat! Tutte le chiave lette correttamente, ma i dati delle transazioni o le voci in rubrica potrebbero mancare o non essere corretti.</translation> </message> <message> <location line="-18"/> <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>Attenzione: wallet.dat corrotto, dati salvati! Il wallet.dat originale salvato come wallet.{timestamp}.bak in %s; se il tuo bilancio o le transazioni non sono corrette dovresti ripristinare da un backup.</translation> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tenta di recuperare le chiavi private da un wallet.dat corrotto</translation> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>Opzioni creazione blocco:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>Connetti solo al nodo specificato</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Scopri proprio indirizzo IP (predefinito: 1 se in ascolto e no -externalip)</translation> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Impossibile mettersi in ascolto su una porta. Usa -listen=0 se vuoi usare questa opzione.</translation> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Buffer di ricezione massimo per connessione, &lt;n&gt;*1000 byte (predefinito: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Buffer di invio massimo per connessione, &lt;n&gt;*1000 byte (predefinito: 1000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Connetti solo a nodi nella rete &lt;net&gt; (IPv4, IPv6 o Tor)</translation> </message> <message> <location line="+28"/> <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="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Profitcoin Wiki for SSL setup instructions)</source> <translation>Opzioni SSL: (vedi il wiki di Profitcoin per le istruzioni di configurazione SSL)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Invia le informazioni di trace/debug alla console invece che al file debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <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>Imposta dimensione minima del blocco in bytes (predefinita: 0)</translation> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Riduci il file debug.log all&apos;avvio del client (predefinito: 1 se non impostato -debug)</translation> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specifica il timeout di connessione in millisecondi (predefinito: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Usa UPnP per mappare la porta in ascolto (predefinito: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usa UPnP per mappare la porta in ascolto (predefinito: 1 when listening)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>Nome utente per connessioni JSON-RPC </translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Attenzione: questa versione è obsoleta, aggiornamento necessario!</translation> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrotto, salvataggio fallito</translation> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>Password per connessioni JSON-RPC </translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=profitcoinrpc 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;profitcoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Consenti connessioni JSON-RPC dall&apos;indirizzo IP specificato </translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Inviare comandi al nodo in esecuzione su &lt;ip&gt; (predefinito: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Esegui il comando quando il miglior block cambia(%s nel cmd è sostituito dall&apos;hash del blocco)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Esegui comando quando una transazione del portafoglio cambia (%s in cmd è sostituito da TxID)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <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>Upgrade wallet to latest format</source> <translation>Aggiorna il wallet all&apos;ultimo formato</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Impostare la quantità di chiavi di riserva a &lt;n&gt; (predefinita: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ripeti analisi della catena dei blocchi per cercare le transazioni mancanti dal portamonete </translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utilizzare OpenSSL (https) per le connessioni JSON-RPC </translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>File certificato del server (predefinito: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chiave privata del server (predefinito: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation>Questo messaggio di aiuto </translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. profitcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>profitcoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Impossibile collegarsi alla %s su questo computer (bind returned error %d, %s)</translation> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Consenti ricerche DNS per aggiungere nodi e collegare </translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Caricamento indirizzi...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Errore caricamento wallet.dat: Wallet corrotto</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of profitcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart profitcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Errore caricamento wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Indirizzo -proxy non valido: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rete sconosciuta specificata in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Versione -socks proxy sconosciuta richiesta: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Impossibile risolvere -bind address: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Impossibile risolvere indirizzo -externalip: &apos;%s&apos;</translation> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Importo non valido per -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Importo non valido</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Fondi insufficienti</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Caricamento dell&apos;indice del blocco...</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Elérendő csomópont megadása and attempt to keep the connection open</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. profitcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Caricamento portamonete...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Non è possibile retrocedere il wallet</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Non è possibile scrivere l&apos;indirizzo predefinito</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Ripetere la scansione...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Caricamento completato</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>Per usare la opzione %s</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>Errore</translation> </message> <message> <location line="+6"/> <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>Devi settare rpcpassword=&lt;password&gt; nel file di configurazione: %s Se il file non esiste, crealo con i permessi di amministratore</translation> </message> </context> </TS>
profitcoinproject/profitcoin
src/qt/locale/profitcoin_it.ts
TypeScript
mit
119,594
<?php require 'autoload.php'; /** * This example shows the basic usage of file filesystem it self to store scan information * about your scans. If you would use this code in real life please make sure you store the output file (data.yml) * in a secure location on your drive. */ $path = dirname(__FILE__)."/assets"; $newfile = $path.'/new.tmp'; $timefile = $path.'/time.txt'; $datafile = $path.'/data.yml'; /** * Oke lets instantiate a new service and scan the assets folder inside * our current folder and write the data.yml file to the filesystem using the Filesystem adapter. */ $scan = new Redbox\Scan\ScanService(new Redbox\Scan\Adapter\Filesystem($datafile)); if ($scan->index($path, 'Basic scan', date("Y-m-d H:i:s")) == false) { throw new Exception('Writing datafile failed.'); } /** * After indexing the directory let's create a new file and update an other so * we can see if the filesystem picks it up. */ file_put_contents($newfile, 'Hello world'); file_put_contents($timefile, time()); /** * Oke the changes have been made lets scan the assets directory again for changes. */ $report = $scan->scan(); /** * Do the cleanup. This is not needed if this where to be real code. */ unlink($newfile); /** * Output the changes since index action. */ if(php_sapi_name() == "cli") { echo "New files\n\n"; foreach ($report->getNewfiles() as $file) { echo $file->getFilename().' '.Redbox\Scan\Filesystem\FileInfo::getFileHash($file->getRealPath())."\n"; } echo "\nModified Files\n\n"; foreach ($report->getModifiedFiles() as $file) { echo $file->getFilename().' '.Redbox\Scan\Filesystem\FileInfo::getFileHash($file->getRealPath())."\n"; } echo "\n"; } else { echo '<h1>New files</h1>'; foreach ($report->getNewfiles() as $file) { echo '<li>'.$file->getFilename().' '.Redbox\Scan\Filesystem\FileInfo::getFileHash($file->getRealPath()).'</li>'; } echo '</ul>'; echo '<h1>Modified Files</h1>'; foreach ($report->getModifiedFiles() as $file) { echo '<li>'.$file->getFilename().' '.Redbox\Scan\Filesystem\FileInfo::getFileHash($file->getRealPath()).'</li>'; } echo '</ul>'; }
johnnymast/redbox-scan
examples/basic.php
PHP
mit
2,200
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "net.h" #include "strlcpy.h" #include "base58.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { struct in_addr ip; short port; }; #pragma pack(pop) string EncodeAddress(const CService& addr) { struct ircaddr tmp; if (addr.GetInAddr(&tmp.ip)) { tmp.port = htons(addr.GetPort()); vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } return ""; } bool DecodeAddress(string str, CService& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CService(tmp.ip, ntohs(tmp.port)); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != string::npos) return 1; if (psz2 && strLine.find(psz2) != string::npos) return 2; if (psz3 && strLine.find(psz3) != string::npos) return 3; if (psz4 && strLine.find(psz4) != string::npos) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); CNetAddr addr(strHost, true); if (!addr.IsValid()) return false; ipRet = addr; return true; } void ThreadIRCSeed(void* parg) { // Make this thread recognisable as the IRC seeding thread RenameThread("bitcoin-ircseed"); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exited\n"); } void ThreadIRCSeed2(void* parg) { // Don't connect to IRC if we won't use IPv4 connections. if (IsLimited(NET_IPV4)) return; // ... or if we won't make outbound connections and won't accept inbound ones. if (mapArgs.count("-connect") && fNoListen) return; // ... or if IRC is not enabled. if (!GetBoolArg("-irc", true)) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; int nNameRetry = 0; while (!fShutdown) { CService addrConnect("188.122.74.140", 6667); // eu.undernet.org CService addrIRC("irc.rizon.net", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses CService addrLocal; string strMyName; // Don't use our IP as our nick if we're not listening // or if it keeps failing because the nick is already in use. if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3) strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); if (strMyName == "") strMyName = strprintf("x%"PRI64u"", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); nNameRetry++; Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } nNameRetry = 0; Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CNetAddr addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); // Don't use our IP as our nick if we're not listening if (!fNoListen && addrFromIRC.IsRoutable()) { // IRC lets you to re-nick AddLocal(addrFromIRC, LOCAL_IRC); strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #AndroidsTokenTEST2\r"); Send(hSocket, "WHO #AndroidsTokenTEST2\r"); } else { // randomly join #AndroidsToken00-#AndroidsToken05 // int channel_number = GetRandInt(5); // Channel number is always 0 for initial release int channel_number = 0; Send(hSocket, strprintf("JOIN #AndroidsToken%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #AndroidsToken%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (addrman.Add(addr, addrConnect, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif
elrapido80/AndroidsTokens
src/irc.cpp
C++
mit
10,962
require "spec_helper" describe PivotalSync::Person do end
ready4god2513/pivotal_sync
spec/pivotal_sync/person_spec.rb
Ruby
mit
61
require 'sinatra/base' require 'sinatra/json' require 'nokogiri' module Downloader module Web class App < Sinatra::Base set :port, Proc.new { ENV['PORT_WEB'].to_i } # set :server, 'webrick' get '/progress/:id.?:format?' do |id, format| progress = begin DB_SLAVE[:downloads][download_id: id][:progress] rescue "-1" end case format when 'json' content_type :json json file: { id: id, progress: progress } when 'xml' content_type :xml Nokogiri::XML::Builder.new do |xml| xml.file do xml.id id xml.progress progress end end.to_xml.to_s end end end end end
arefaslani/uut_download_downloader
lib/downloader/web/app.rb
Ruby
mit
769
const minimatch = require( "minimatch" ); const webpack = require( "webpack" ); const _ = require( "lodash" ); module.exports = function( options ) { function isMatchingModule( mod ) { return mod.resource && _.some( options.paths, path => minimatch( mod.resource, path ) ); } return new webpack.optimize.CommonsChunkPlugin( { name: options.name, filename: options.filename, minChunks: isMatchingModule } ); };
LeanKit-Labs/nonstop-index-ui
tasks/tools/pathChunkingPlugin.js
JavaScript
mit
424
<?php namespace NiclasHedam; class ColorName { public static $colors = [ 'Acid Green' => [176, 191, 26], 'Aero' => [124, 185, 232], 'Aero Blue' => [201, 255, 229], 'African Violet' => [178, 132, 190], 'Air Force Blue (RAF)' => [93, 138, 168], 'Air Force Blue (USAF)' => [0, 48, 143], 'Air Superiority Blue' => [114, 160, 193], 'Alabama Crimson' => [175, 0, 42], 'Alice Blue' => [240, 248, 255], 'Alizarin Crimson' => [227, 38, 54], 'Alloy Orange' => [196, 98, 16], 'Almond' => [239, 222, 205], 'Amaranth' => [229, 43, 80], 'Amaranth Deep Purple' => [171, 39, 79], 'Amaranth Pink' => [241, 156, 187], 'Amaranth Purple' => [171, 39, 79], 'Amaranth Red' => [211, 33, 45], 'Amazon' => [59, 122, 87], 'Amber' => [255, 191, 0], 'Amber (SAE/ECE)' => [255, 126, 0], 'American Rose' => [255, 3, 62], 'Amethyst' => [153, 102, 204], 'Android Green' => [164, 198, 57], 'Anti-Flash White' => [242, 243, 244], 'Antique Brass' => [205, 149, 117], 'Antique Bronze' => [102, 93, 30], 'Antique Fuchsia' => [145, 92, 131], 'Antique Ruby' => [132, 27, 45], 'Antique White' => [250, 235, 215], 'Ao (English)' => [0, 128, 0], 'Apple Green' => [141, 182, 0], 'Apricot' => [251, 206, 177], 'Aqua' => [0, 255, 255], 'Aquamarine' => [127, 255, 212], 'Arctic Lime' => [208, 255, 20], 'Army Green' => [75, 83, 32], 'Arsenic' => [59, 68, 75], 'Artichoke' => [143, 151, 121], 'Arylide Yellow' => [233, 214, 107], 'Ash Grey' => [178, 190, 181], 'Asparagus' => [135, 169, 107], 'Atomic Tangerine' => [255, 153, 102], 'Auburn' => [165, 42, 42], 'Aureolin' => [253, 238, 0], 'AuroMetalSaurus' => [110, 127, 128], 'Avocado' => [86, 130, 3], 'Azure' => [0, 127, 255], 'Azure (Web Color)' => [240, 255, 255], 'Azure Mist' => [240, 255, 255], 'Azureish White' => [219, 233, 244], 'Baby Blue' => [137, 207, 240], 'Baby Blue Eyes' => [161, 202, 241], 'Baby Pink' => [244, 194, 194], 'Baby Powder' => [254, 254, 250], 'Baker-Miller Pink' => [255, 145, 175], 'Ball Blue' => [33, 171, 205], 'Banana Mania' => [250, 231, 181], 'Banana Yellow' => [255, 225, 53], 'Bangladesh Green' => [0, 106, 78], 'Barbie Pink' => [224, 33, 138], 'Barn Red' => [124, 10, 2], 'Battleship Grey' => [132, 132, 130], 'Bazaar' => [152, 119, 123], 'Beau Blue' => [188, 212, 230], 'Beaver' => [159, 129, 112], 'Beige' => [245, 245, 220], "B'dazzled Blue" => [46, 88, 148], 'Big Dip O’ruby' => [156, 37, 66], 'Bisque' => [255, 228, 196], 'Bistre' => [61, 43, 31], 'Bistre Brown' => [150, 113, 23], 'Bitter Lemon' => [202, 224, 13], 'Bitter Lime' => [191, 255, 0], 'Bittersweet' => [254, 111, 94], 'Bittersweet Shimmer' => [191, 79, 81], 'Black' => [0, 0, 0], 'Black Bean' => [61, 12, 2], 'Black Leather Jacket' => [37, 53, 41], 'Black Olive' => [59, 60, 54], 'Blanched Almond' => [255, 235, 205], 'Blast-Off Bronze' => [165, 113, 100], 'Bleu De France' => [49, 140, 231], 'Blizzard Blue' => [172, 229, 238], 'Blond' => [250, 240, 190], 'Blue' => [0, 0, 255], 'Blue (Crayola)' => [31, 117, 254], 'Blue (Munsell)' => [0, 147, 175], 'Blue (NCS)' => [0, 135, 189], 'Blue (Pantone)' => [0, 24, 168], 'Blue (Pigment)' => [51, 51, 153], 'Blue (RYB)' => [2, 71, 254], 'Blue Bell' => [162, 162, 208], 'Blue-Gray' => [102, 153, 204], 'Blue-Green' => [13, 152, 186], 'Blue Lagoon' => [172, 229, 238], 'Blue-Magenta Violet' => [85, 53, 146], 'Blue Sapphire' => [18, 97, 128], 'Blue-Violet' => [138, 43, 226], 'Blue Yonder' => [80, 114, 167], 'Blueberry' => [79, 134, 247], 'Bluebonnet' => [28, 28, 240], 'Blush' => [222, 93, 131], 'Bole' => [121, 68, 59], 'Bondi Blue' => [0, 149, 182], 'Bone' => [227, 218, 201], 'Boston University Red' => [204, 0, 0], 'Bottle Green' => [0, 106, 78], 'Boysenberry' => [135, 50, 96], 'Brandeis Blue' => [0, 112, 255], 'Brass' => [181, 166, 66], 'Brick Red' => [203, 65, 84], 'Bright Cerulean' => [29, 172, 214], 'Bright Green' => [102, 255, 0], 'Bright Lavender' => [191, 148, 228], 'Bright Lilac' => [216, 145, 239], 'Bright Maroon' => [195, 33, 72], 'Bright Navy Blue' => [25, 116, 210], 'Bright Pink' => [255, 0, 127], 'Bright Turquoise' => [8, 232, 222], 'Bright Ube' => [209, 159, 232], 'Brilliant Azure' => [51, 153, 255], 'Brilliant Lavender' => [244, 187, 255], 'Brilliant Rose' => [255, 85, 163], 'Brink Pink' => [251, 96, 127], 'British Racing Green' => [0, 66, 37], 'Bronze' => [205, 127, 50], 'Bronze Yellow' => [115, 112, 0], 'Brown (Traditional)' => [150, 75, 0], 'Brown (Web)' => [165, 42, 42], 'Brown-Nose' => [107, 68, 35], 'Brown Yellow' => [204, 153, 102], 'Brunswick Green' => [27, 77, 62], 'Bubble Gum' => [255, 193, 204], 'Bubbles' => [231, 254, 255], 'Buff' => [240, 220, 130], 'Bud Green' => [123, 182, 97], 'Bulgarian Rose' => [72, 6, 7], 'Burgundy' => [128, 0, 32], 'Burlywood' => [222, 184, 135], 'Burnt Orange' => [204, 85, 0], 'Burnt Sienna' => [233, 116, 81], 'Burnt Umber' => [138, 51, 36], 'Byzantine' => [189, 51, 164], 'Byzantium' => [112, 41, 99], 'Cadet' => [83, 104, 114], 'Cadet Blue' => [95, 158, 160], 'Cadet Grey' => [145, 163, 176], 'Cadmium Green' => [0, 107, 60], 'Cadmium Orange' => [237, 135, 45], 'Cadmium Red' => [227, 0, 34], 'Cadmium Yellow' => [255, 246, 0], 'Café Au Lait' => [166, 123, 91], 'Café Noir' => [75, 54, 33], 'Cal Poly Green' => [30, 77, 43], 'Cambridge Blue' => [163, 193, 173], 'Camel' => [193, 154, 107], 'Cameo Pink' => [239, 187, 204], 'Camouflage Green' => [120, 134, 107], 'Canary Yellow' => [255, 239, 0], 'Candy Apple Red' => [255, 8, 0], 'Candy Pink' => [228, 113, 122], 'Capri' => [0, 191, 255], 'Caput Mortuum' => [89, 39, 32], 'Cardinal' => [196, 30, 58], 'Caribbean Green' => [0, 204, 153], 'Carmine' => [150, 0, 24], 'Carmine (M&P)' => [215, 0, 64], 'Carmine Pink' => [235, 76, 66], 'Carmine Red' => [255, 0, 56], 'Carnation Pink' => [255, 166, 201], 'Carnelian' => [179, 27, 27], 'Carolina Blue' => [86, 160, 211], 'Carrot Orange' => [237, 145, 33], 'Castleton Green' => [0, 86, 63], 'Catalina Blue' => [6, 42, 120], 'Catawba' => [112, 54, 66], 'Cedar Chest' => [201, 90, 73], 'Ceil' => [146, 161, 207], 'Celadon' => [172, 225, 175], 'Celadon Blue' => [0, 123, 167], 'Celadon Green' => [47, 132, 124], 'Celeste' => [178, 255, 255], 'Celestial Blue' => [73, 151, 208], 'Cerise' => [222, 49, 99], 'Cerise Pink' => [236, 59, 131], 'Cerulean' => [0, 123, 167], 'Cerulean Blue' => [42, 82, 190], 'Cerulean Frost' => [109, 155, 195], 'CG Blue' => [0, 122, 165], 'CG Red' => [224, 60, 49], 'Chamoisee' => [160, 120, 90], 'Champagne' => [247, 231, 206], 'Charcoal' => [54, 69, 79], 'Charleston Green' => [35, 43, 43], 'Charm Pink' => [230, 143, 172], 'Chartreuse (Traditional)' => [223, 255, 0], 'Chartreuse (Web)' => [127, 255, 0], 'Cherry' => [222, 49, 99], 'Cherry Blossom Pink' => [255, 183, 197], 'Chestnut' => [149, 69, 53], 'China Pink' => [222, 111, 161], 'China Rose' => [168, 81, 110], 'Chinese Red' => [170, 56, 30], 'Chinese Violet' => [133, 96, 136], 'Chocolate (Traditional)' => [123, 63, 0], 'Chocolate (Web)' => [210, 105, 30], 'Chrome Yellow' => [255, 167, 0], 'Cinereous' => [152, 129, 123], 'Cinnabar' => [227, 66, 52], 'Cinnamon[Citation Needed]' => [210, 105, 30], 'Citrine' => [228, 208, 10], 'Citron' => [159, 169, 31], 'Claret' => [127, 23, 52], 'Classic Rose' => [251, 204, 231], 'Cobalt Blue' => [0, 71, 171], 'Cocoa Brown' => [210, 105, 30], 'Coconut' => [150, 90, 62], 'Coffee' => [111, 78, 55], 'Columbia Blue' => [196, 216, 226], 'Congo Pink' => [248, 131, 121], 'Cool Black' => [0, 46, 99], 'Cool Grey' => [140, 146, 172], 'Copper' => [184, 115, 51], 'Copper (Crayola)' => [218, 138, 103], 'Copper Penny' => [173, 111, 105], 'Copper Red' => [203, 109, 81], 'Copper Rose' => [153, 102, 102], 'Coquelicot' => [255, 56, 0], 'Coral' => [255, 127, 80], 'Coral Pink' => [248, 131, 121], 'Coral Red' => [255, 64, 64], 'Cordovan' => [137, 63, 69], 'Corn' => [251, 236, 93], 'Cornell Red' => [179, 27, 27], 'Cornflower Blue' => [100, 149, 237], 'Cornsilk' => [255, 248, 220], 'Cosmic Latte' => [255, 248, 231], 'Coyote Brown' => [129, 97, 62], 'Cotton Candy' => [255, 188, 217], 'Cream' => [255, 253, 208], 'Crimson' => [220, 20, 60], 'Crimson Glory' => [190, 0, 50], 'Crimson Red' => [153, 0, 0], 'Cyan' => [0, 255, 255], 'Cyan Azure' => [78, 130, 180], 'Cyan-Blue Azure' => [70, 130, 191], 'Cyan Cobalt Blue' => [40, 88, 156], 'Cyan Cornflower Blue' => [24, 139, 194], 'Cyan (Process)' => [0, 183, 235], 'Cyber Grape' => [88, 66, 124], 'Cyber Yellow' => [255, 211, 0], 'Daffodil' => [255, 255, 49], 'Dandelion' => [240, 225, 48], 'Dark Blue' => [0, 0, 139], 'Dark Blue-Gray' => [102, 102, 153], 'Dark Brown' => [101, 67, 33], 'Dark Brown-Tangelo' => [136, 101, 78], 'Dark Byzantium' => [93, 57, 84], 'Dark Candy Apple Red' => [164, 0, 0], 'Dark Cerulean' => [8, 69, 126], 'Dark Chestnut' => [152, 105, 96], 'Dark Coral' => [205, 91, 69], 'Dark Cyan' => [0, 139, 139], 'Dark Electric Blue' => [83, 104, 120], 'Dark Goldenrod' => [184, 134, 11], 'Dark Gray (X11)' => [169, 169, 169], 'Dark Green' => [1, 50, 32], 'Dark Green (X11)' => [0, 100, 0], 'Dark Gunmetal' => [0, 100, 0], 'Dark Imperial Blue' => [110, 110, 249], 'Dark Jungle Green' => [26, 36, 33], 'Dark Khaki' => [189, 183, 107], 'Dark Lava' => [72, 60, 50], 'Dark Lavender' => [115, 79, 150], 'Dark Liver' => [83, 75, 79], 'Dark Liver (Horses)' => [84, 61, 55], 'Dark Magenta' => [139, 0, 139], 'Dark Medium Gray' => [169, 169, 169], 'Dark Midnight Blue' => [0, 51, 102], 'Dark Moss Green' => [74, 93, 35], 'Dark Olive Green' => [85, 107, 47], 'Dark Orange' => [255, 140, 0], 'Dark Orchid' => [153, 50, 204], 'Dark Pastel Blue' => [119, 158, 203], 'Dark Pastel Green' => [3, 192, 60], 'Dark Pastel Purple' => [150, 111, 214], 'Dark Pastel Red' => [194, 59, 34], 'Dark Pink' => [231, 84, 128], 'Dark Powder Blue' => [0, 51, 153], 'Dark Puce' => [79, 58, 60], 'Dark Purple' => [48, 25, 52], 'Dark Raspberry' => [135, 38, 87], 'Dark Red' => [139, 0, 0], 'Dark Salmon' => [233, 150, 122], 'Dark Scarlet' => [86, 3, 25], 'Dark Sea Green' => [143, 188, 143], 'Dark Sienna' => [60, 20, 20], 'Dark Sky Blue' => [140, 190, 214], 'Dark Slate Blue' => [72, 61, 139], 'Dark Slate Gray' => [47, 79, 79], 'Dark Spring Green' => [23, 114, 69], 'Dark Tan' => [145, 129, 81], 'Dark Tangerine' => [255, 168, 18], 'Dark Taupe' => [72, 60, 50], 'Dark Terra Cotta' => [204, 78, 92], 'Dark Turquoise' => [0, 206, 209], 'Dark Vanilla' => [209, 190, 168], 'Dark Violet' => [148, 0, 211], 'Dark Yellow' => [155, 135, 12], 'Dartmouth Green' => [0, 112, 60], "Davy's Grey" => [85, 85, 85], 'Debian Red' => [215, 10, 83], 'Deep Aquamarine' => [64, 130, 109], 'Deep Carmine' => [169, 32, 62], 'Deep Carmine Pink' => [239, 48, 56], 'Deep Carrot Orange' => [233, 105, 44], 'Deep Cerise' => [218, 50, 135], 'Deep Champagne' => [250, 214, 165], 'Deep Chestnut' => [185, 78, 72], 'Deep Coffee' => [112, 66, 65], 'Deep Fuchsia' => [193, 84, 193], 'Deep Green' => [5, 102, 8], 'Deep Green-Cyan Turquoise' => [14, 124, 97], 'Deep Jungle Green' => [0, 75, 73], 'Deep Koamaru' => [51, 51, 102], 'Deep Lemon' => [245, 199, 26], 'Deep Lilac' => [153, 85, 187], 'Deep Magenta' => [204, 0, 204], 'Deep Maroon' => [130, 0, 0], 'Deep Mauve' => [212, 115, 212], 'Deep Moss Green' => [53, 94, 59], 'Deep Peach' => [255, 203, 164], 'Deep Pink' => [255, 20, 147], 'Deep Puce' => [169, 92, 104], 'Deep Red' => [133, 1, 1], 'Deep Ruby' => [132, 63, 91], 'Deep Saffron' => [255, 153, 51], 'Deep Sky Blue' => [0, 191, 255], 'Deep Space Sparkle' => [74, 100, 108], 'Deep Spring Bud' => [85, 107, 47], 'Deep Taupe' => [126, 94, 96], 'Deep Tuscan Red' => [102, 66, 77], 'Deep Violet' => [51, 0, 102], 'Deer' => [186, 135, 89], 'Denim' => [21, 96, 189], 'Desaturated Cyan' => [102, 153, 153], 'Desert' => [193, 154, 107], 'Desert Sand' => [237, 201, 175], 'Desire' => [234, 60, 83], 'Diamond' => [185, 242, 255], 'Dim Gray' => [105, 105, 105], 'Dirt' => [155, 118, 83], 'Dodger Blue' => [30, 144, 255], 'Dogwood Rose' => [215, 24, 104], 'Dollar Bill' => [133, 187, 101], 'Donkey Brown' => [102, 76, 40], 'Drab' => [150, 113, 23], 'Duke Blue' => [0, 0, 156], 'Dust Storm' => [229, 204, 201], 'Dutch White' => [239, 223, 187], 'Earth Yellow' => [225, 169, 95], 'Ebony' => [85, 93, 80], 'Ecru' => [194, 178, 128], 'Eerie Black' => [27, 27, 27], 'Eggplant' => [97, 64, 81], 'Eggshell' => [240, 234, 214], 'Egyptian Blue' => [16, 52, 166], 'Electric Blue' => [125, 249, 255], 'Electric Crimson' => [255, 0, 63], 'Electric Cyan' => [0, 255, 255], 'Electric Green' => [0, 255, 0], 'Electric Indigo' => [111, 0, 255], 'Electric Lavender' => [244, 187, 255], 'Electric Lime' => [204, 255, 0], 'Electric Purple' => [191, 0, 255], 'Electric Ultramarine' => [63, 0, 255], 'Electric Violet' => [143, 0, 255], 'Electric Yellow' => [255, 255, 51], 'Emerald' => [80, 200, 120], 'Eminence' => [108, 48, 130], 'English Green' => [27, 77, 62], 'English Lavender' => [180, 131, 149], 'English Red' => [171, 75, 82], 'English Violet' => [86, 60, 92], 'Eton Blue' => [150, 200, 162], 'Eucalyptus' => [68, 215, 168], 'Fallow' => [193, 154, 107], 'Falu Red' => [128, 24, 24], 'Fandango' => [181, 51, 137], 'Fandango Pink' => [222, 82, 133], 'Fashion Fuchsia' => [244, 0, 161], 'Fawn' => [229, 170, 112], 'Feldgrau' => [77, 93, 83], 'Feldspar' => [253, 213, 177], 'Fern Green' => [79, 121, 66], 'Ferrari Red' => [255, 40, 0], 'Field Drab' => [108, 84, 30], 'Firebrick' => [178, 34, 34], 'Fire Engine Red' => [206, 32, 41], 'Flame' => [226, 88, 34], 'Flamingo Pink' => [252, 142, 172], 'Flattery' => [107, 68, 35], 'Flavescent' => [247, 233, 142], 'Flax' => [238, 220, 130], 'Flirt' => [162, 0, 109], 'Floral White' => [255, 250, 240], 'Fluorescent Orange' => [255, 191, 0], 'Fluorescent Pink' => [255, 20, 147], 'Fluorescent Yellow' => [204, 255, 0], 'Folly' => [255, 0, 79], 'Forest Green (Traditional)' => [1, 68, 33], 'Forest Green (Web)' => [34, 139, 34], 'French Beige' => [166, 123, 91], 'French Bistre' => [133, 109, 77], 'French Blue' => [0, 114, 187], 'French Fuchsia' => [253, 63, 146], 'French Lilac' => [134, 96, 142], 'French Lime' => [158, 253, 56], 'French Mauve' => [212, 115, 212], 'French Pink' => [253, 108, 158], 'French Plum' => [129, 20, 83], 'French Puce' => [78, 22, 9], 'French Raspberry' => [199, 44, 72], 'French Rose' => [246, 74, 138], 'French Sky Blue' => [119, 181, 254], 'French Violet' => [136, 6, 206], 'French Wine' => [172, 30, 68], 'Fresh Air' => [166, 231, 255], 'Fuchsia' => [255, 0, 255], 'Fuchsia (Crayola)' => [193, 84, 193], 'Fuchsia Pink' => [255, 119, 255], 'Fuchsia Purple' => [204, 57, 123], 'Fuchsia Rose' => [199, 67, 117], 'Fulvous' => [228, 132, 0], 'Fuzzy Wuzzy' => [204, 102, 102], 'Gainsboro' => [220, 220, 220], 'Gamboge' => [228, 155, 15], 'Gamboge Orange (Brown)' => [153, 102, 0], 'Generic Viridian' => [0, 127, 102], 'Ghost White' => [248, 248, 255], 'Giants Orange' => [254, 90, 29], 'Ginger' => [176, 101, 0], 'Glaucous' => [96, 130, 182], 'Glitter' => [230, 232, 250], 'GO Green' => [0, 171, 102], 'Gold (Metallic)' => [212, 175, 55], 'Gold (Web) (Golden)' => [255, 215, 0], 'Gold Fusion' => [133, 117, 78], 'Golden Brown' => [153, 101, 21], 'Golden Poppy' => [252, 194, 0], 'Golden Yellow' => [255, 223, 0], 'Goldenrod' => [218, 165, 32], 'Granny Smith Apple' => [168, 228, 160], 'Grape' => [111, 45, 168], 'Gray' => [128, 128, 128], 'Gray (HTML/CSS Gray)' => [128, 128, 128], 'Gray (X11 Gray)' => [190, 190, 190], 'Gray-Asparagus' => [70, 89, 69], 'Gray-Blue' => [140, 146, 172], 'Green (Color Wheel) (X11 Green)' => [0, 255, 0], 'Green (Crayola)' => [28, 172, 120], 'Green (HTML/CSS Color)' => [0, 128, 0], 'Green (Munsell)' => [0, 168, 119], 'Green (NCS)' => [0, 159, 107], 'Green (Pantone)' => [0, 173, 67], 'Green (Pigment)' => [0, 165, 80], 'Green (RYB)' => [102, 176, 50], 'Green-Blue' => [17, 100, 180], 'Green-Cyan' => [0, 153, 102], 'Green-Yellow' => [173, 255, 47], 'Grizzly' => [136, 88, 24], 'Grullo' => [169, 154, 134], 'Guppie Green' => [0, 255, 127], 'Gunmetal' => [42, 52, 57], 'Halayà Úbe' => [102, 56, 84], 'Han Blue' => [68, 108, 207], 'Han Purple' => [82, 24, 250], 'Hansa Yellow' => [233, 214, 107], 'Harlequin' => [63, 255, 0], 'Harlequin Green' => [70, 203, 24], 'Harvard Crimson' => [201, 0, 22], 'Harvest Gold' => [218, 145, 0], 'Heart Gold' => [128, 128, 0], 'Heliotrope' => [223, 115, 255], 'Heliotrope Gray' => [170, 152, 169], 'Heliotrope Magenta' => [170, 0, 187], 'Hollywood Cerise' => [244, 0, 161], 'Honeydew' => [240, 255, 240], 'Honolulu Blue' => [0, 109, 176], "Hooker's Green" => [73, 121, 107], 'Hot Magenta' => [255, 29, 206], 'Hot Pink' => [255, 105, 180], 'Hunter Green' => [53, 94, 59], 'Iceberg' => [113, 166, 210], 'Icterine' => [252, 247, 94], 'Illuminating Emerald' => [49, 145, 119], 'Imperial' => [96, 47, 107], 'Imperial Blue' => [0, 35, 149], 'Imperial Purple' => [102, 2, 60], 'Imperial Red' => [237, 41, 57], 'Inchworm' => [178, 236, 93], 'Independence' => [76, 81, 109], 'India Green' => [19, 136, 8], 'Indian Red' => [205, 92, 92], 'Indian Yellow' => [227, 168, 87], 'Indigo' => [75, 0, 130], 'Indigo Dye' => [9, 31, 146], 'Indigo (Web)' => [75, 0, 130], 'International Klein Blue' => [0, 47, 167], 'International Orange (Aerospace)' => [255, 79, 0], 'International Orange (Engineering)' => [186, 22, 12], 'International Orange (Golden Gate Bridge)' => [192, 54, 44], 'Iris' => [90, 79, 207], 'Irresistible' => [179, 68, 108], 'Isabelline' => [244, 240, 236], 'Islamic Green' => [0, 144, 0], 'Italian Sky Blue' => [178, 255, 255], 'Ivory' => [255, 255, 240], 'Jade' => [0, 168, 107], 'Japanese Carmine' => [157, 41, 51], 'Japanese Indigo' => [38, 67, 72], 'Japanese Violet' => [91, 50, 86], 'Jasmine' => [248, 222, 126], 'Jasper' => [215, 59, 62], 'Jazzberry Jam' => [165, 11, 94], 'Jelly Bean' => [218, 97, 78], 'Jet' => [52, 52, 52], 'Jonquil' => [244, 202, 22], 'Jordy Blue' => [138, 185, 241], 'June Bud' => [189, 218, 87], 'Jungle Green' => [41, 171, 135], 'Kelly Green' => [76, 187, 23], 'Kenyan Copper' => [124, 28, 5], 'Keppel' => [58, 176, 158], 'Khaki (HTML/CSS) (Khaki)' => [195, 176, 145], 'Khaki (X11) (Light Khaki)' => [240, 230, 140], 'Kobe' => [136, 45, 23], 'Kobi' => [231, 159, 196], 'Kobicha' => [107, 68, 35], 'Kombu Green' => [53, 66, 48], 'KU Crimson' => [232, 0, 13], 'La Salle Green' => [8, 120, 48], 'Languid Lavender' => [214, 202, 221], 'Lapis Lazuli' => [38, 97, 156], 'Laser Lemon' => [255, 255, 102], 'Laurel Green' => [169, 186, 157], 'Lava' => [207, 16, 32], 'Lavender (Floral)' => [181, 126, 220], 'Lavender (Web)' => [230, 230, 250], 'Lavender Blue' => [204, 204, 255], 'Lavender Blush' => [255, 240, 245], 'Lavender Gray' => [196, 195, 208], 'Lavender Indigo' => [148, 87, 235], 'Lavender Magenta' => [238, 130, 238], 'Lavender Mist' => [230, 230, 250], 'Lavender Pink' => [251, 174, 210], 'Lavender Purple' => [150, 123, 182], 'Lavender Rose' => [251, 160, 227], 'Lawn Green' => [124, 252, 0], 'Lemon' => [255, 247, 0], 'Lemon Chiffon' => [255, 250, 205], 'Lemon Curry' => [204, 160, 29], 'Lemon Glacier' => [253, 255, 0], 'Lemon Lime' => [227, 255, 0], 'Lemon Meringue' => [246, 234, 190], 'Lemon Yellow' => [255, 244, 79], 'Lenurple' => [186, 147, 216], 'Licorice' => [26, 17, 16], 'Liberty' => [84, 90, 167], 'Light Apricot' => [253, 213, 177], 'Light Blue' => [173, 216, 230], 'Light Brilliant Red' => [254, 46, 46], 'Light Brown' => [181, 101, 29], 'Light Carmine Pink' => [230, 103, 113], 'Light Cobalt Blue' => [136, 172, 224], 'Light Coral' => [240, 128, 128], 'Light Cornflower Blue' => [147, 204, 234], 'Light Crimson' => [245, 105, 145], 'Light Cyan' => [224, 255, 255], 'Light Deep Pink' => [255, 92, 205], 'Light French Beige' => [200, 173, 127], 'Light Fuchsia Pink' => [249, 132, 239], 'Light Goldenrod Yellow' => [250, 250, 210], 'Light Gray' => [211, 211, 211], 'Light Grayish Magenta' => [204, 153, 204], 'Light Green' => [144, 238, 144], 'Light Hot Pink' => [255, 179, 222], 'Light Khaki' => [240, 230, 140], 'Light Medium Orchid' => [211, 155, 203], 'Light Moss Green' => [173, 223, 173], 'Light Orchid' => [230, 168, 215], 'Light Pastel Purple' => [177, 156, 217], 'Light Pink' => [255, 182, 193], 'Light Red Ochre' => [233, 116, 81], 'Light Salmon' => [255, 160, 122], 'Light Salmon Pink' => [255, 153, 153], 'Light Sea Green' => [32, 178, 170], 'Light Sky Blue' => [135, 206, 250], 'Light Slate Gray' => [119, 136, 153], 'Light Steel Blue' => [176, 196, 222], 'Light Taupe' => [179, 139, 109], 'Light Thulian Pink' => [230, 143, 172], 'Light Yellow' => [255, 255, 224], 'Lilac' => [200, 162, 200], 'Lime (Color Wheel)' => [191, 255, 0], 'Lime (Web) (X11 Green)' => [0, 255, 0], 'Lime Green' => [50, 205, 50], 'Limerick' => [157, 194, 9], 'Lincoln Green' => [25, 89, 5], 'Linen' => [250, 240, 230], 'Lion' => [193, 154, 107], 'Liseran Purple' => [222, 111, 161], 'Little Boy Blue' => [108, 160, 220], 'Liver' => [103, 76, 71], 'Liver (Dogs)' => [184, 109, 41], 'Liver (Organ)' => [108, 46, 31], 'Liver Chestnut' => [152, 116, 86], 'Livid' => [102, 153, 204], 'Lumber' => [255, 228, 205], 'Lust' => [230, 32, 32], 'Macaroni And Cheese' => [255, 189, 136], 'Magenta' => [255, 0, 255], 'Magenta (Crayola)' => [255, 85, 163], 'Magenta (Dye)' => [202, 31, 123], 'Magenta (Pantone)' => [208, 65, 126], 'Magenta (Process)' => [255, 0, 144], 'Magenta Haze' => [159, 69, 118], 'Magenta-Pink' => [204, 51, 139], 'Magic Mint' => [170, 240, 209], 'Magnolia' => [248, 244, 255], 'Mahogany' => [192, 64, 0], 'Maize' => [251, 236, 93], 'Majorelle Blue' => [96, 80, 220], 'Malachite' => [11, 218, 81], 'Manatee' => [151, 154, 170], 'Mango Tango' => [255, 130, 67], 'Mantis' => [116, 195, 101], 'Mardi Gras' => [136, 0, 133], 'Marigold' => [234, 162, 33], 'Maroon (Crayola)' => [195, 33, 72], 'Maroon (HTML/CSS)' => [128, 0, 0], 'Maroon (X11)' => [176, 48, 96], 'Mauve' => [224, 176, 255], 'Mauve Taupe' => [145, 95, 109], 'Mauvelous' => [239, 152, 170], 'May Green' => [76, 145, 65], 'Maya Blue' => [115, 194, 251], 'Meat Brown' => [229, 183, 59], 'Medium Aquamarine' => [102, 221, 170], 'Medium Blue' => [0, 0, 205], 'Medium Candy Apple Red' => [226, 6, 44], 'Medium Carmine' => [175, 64, 53], 'Medium Champagne' => [243, 229, 171], 'Medium Electric Blue' => [3, 80, 150], 'Medium Jungle Green' => [28, 53, 45], 'Medium Lavender Magenta' => [221, 160, 221], 'Medium Orchid' => [186, 85, 211], 'Medium Persian Blue' => [0, 103, 165], 'Medium Purple' => [147, 112, 219], 'Medium Red-Violet' => [187, 51, 133], 'Medium Ruby' => [170, 64, 105], 'Medium Sea Green' => [60, 179, 113], 'Medium Sky Blue' => [128, 218, 235], 'Medium Slate Blue' => [123, 104, 238], 'Medium Spring Bud' => [201, 220, 135], 'Medium Spring Green' => [0, 250, 154], 'Medium Taupe' => [103, 76, 71], 'Medium Turquoise' => [72, 209, 204], 'Medium Tuscan Red' => [121, 68, 59], 'Medium Vermilion' => [217, 96, 59], 'Medium Violet-Red' => [199, 21, 133], 'Mellow Apricot' => [248, 184, 120], 'Mellow Yellow' => [248, 222, 126], 'Melon' => [253, 188, 180], 'Metallic Seaweed' => [10, 126, 140], 'Metallic Sunburst' => [156, 124, 56], 'Mexican Pink' => [228, 0, 124], 'Midnight Blue' => [25, 25, 112], 'Midnight Green (Eagle Green)' => [0, 73, 83], 'Mikado Yellow' => [255, 196, 12], 'Mindaro' => [227, 249, 136], 'Ming' => [54, 116, 125], 'Mint' => [62, 180, 137], 'Mint Cream' => [245, 255, 250], 'Mint Green' => [152, 255, 152], 'Misty Rose' => [255, 228, 225], 'Moccasin' => [250, 235, 215], 'Mode Beige' => [150, 113, 23], 'Moonstone Blue' => [115, 169, 194], 'Mordant Red 19' => [174, 12, 0], 'Moss Green' => [138, 154, 91], 'Mountain Meadow' => [48, 186, 143], 'Mountbatten Pink' => [153, 122, 141], 'MSU Green' => [24, 69, 59], 'Mughal Green' => [48, 96, 48], 'Mulberry' => [197, 75, 140], 'Mustard' => [255, 219, 88], 'Myrtle Green' => [49, 120, 115], 'Nadeshiko Pink' => [246, 173, 198], 'Napier Green' => [42, 128, 0], 'Naples Yellow' => [250, 218, 94], 'Navajo White' => [255, 222, 173], 'Navy' => [0, 0, 128], 'Navy Purple' => [148, 87, 235], 'Neon Carrot' => [255, 163, 67], 'Neon Fuchsia' => [254, 65, 100], 'Neon Green' => [57, 255, 20], 'New Car' => [33, 79, 198], 'New York Pink' => [215, 131, 127], 'Non-Photo Blue' => [164, 221, 237], 'North Texas Green' => [5, 144, 51], 'Nyanza' => [233, 255, 219], 'Ocean Boat Blue' => [0, 119, 190], 'Ochre' => [204, 119, 34], 'Office Green' => [0, 128, 0], 'Old Burgundy' => [67, 48, 46], 'Old Gold' => [207, 181, 59], 'Old Heliotrope' => [86, 60, 92], 'Old Lace' => [253, 245, 230], 'Old Lavender' => [121, 104, 120], 'Old Mauve' => [103, 49, 71], 'Old Moss Green' => [134, 126, 54], 'Old Rose' => [192, 128, 129], 'Old Silver' => [132, 132, 130], 'Olive' => [128, 128, 0], 'Olive Drab (' => [107, 142, 35], 'Olive Drab' => [60, 52, 31], 'Olivine' => [154, 185, 115], 'Onyx' => [53, 56, 57], 'Opera Mauve' => [183, 132, 167], 'Orange (Color Wheel)' => [255, 127, 0], 'Orange (Crayola)' => [255, 117, 56], 'Orange (Pantone)' => [255, 88, 0], 'Orange (RYB)' => [251, 153, 2], 'Orange (Web)' => [255, 165, 0], 'Orange Peel' => [255, 159, 0], 'Orange-Red' => [255, 69, 0], 'Orange-Yellow' => [248, 213, 104], 'Orchid' => [218, 112, 214], 'Orchid Pink' => [242, 189, 205], 'Orioles Orange' => [251, 79, 20], 'Otter Brown' => [101, 67, 33], 'Outer Space' => [65, 74, 76], 'Outrageous Orange' => [255, 110, 74], 'Oxford Blue' => [0, 33, 71], 'OU Crimson Red' => [153, 0, 0], 'Pacific Blue' => [28, 169, 201], 'Pakistan Green' => [0, 102, 0], 'Palatinate Blue' => [39, 59, 226], 'Palatinate Purple' => [104, 40, 96], 'Pale Aqua' => [188, 212, 230], 'Pale Blue' => [175, 238, 238], 'Pale Brown' => [152, 118, 84], 'Pale Carmine' => [175, 64, 53], 'Pale Cerulean' => [155, 196, 226], 'Pale Chestnut' => [221, 173, 175], 'Pale Copper' => [218, 138, 103], 'Pale Cornflower Blue' => [171, 205, 239], 'Pale Cyan' => [135, 211, 248], 'Pale Gold' => [230, 190, 138], 'Pale Goldenrod' => [238, 232, 170], 'Pale Green' => [152, 251, 152], 'Pale Lavender' => [220, 208, 255], 'Pale Magenta' => [249, 132, 229], 'Pale Magenta-Pink' => [255, 153, 204], 'Pale Pink' => [250, 218, 221], 'Pale Plum' => [221, 160, 221], 'Pale Red-Violet' => [219, 112, 147], 'Pale Robin Egg Blue' => [150, 222, 209], 'Pale Silver' => [201, 192, 187], 'Pale Spring Bud' => [236, 235, 189], 'Pale Taupe' => [188, 152, 126], 'Pale Turquoise' => [175, 238, 238], 'Pale Violet' => [204, 153, 255], 'Pale Violet-Red' => [219, 112, 147], 'Pansy Purple' => [120, 24, 74], 'Paolo Veronese Green' => [0, 155, 125], 'Papaya Whip' => [255, 239, 213], 'Paradise Pink' => [230, 62, 98], 'Paris Green' => [80, 200, 120], 'Pastel Blue' => [174, 198, 207], 'Pastel Brown' => [131, 105, 83], 'Pastel Gray' => [207, 207, 196], 'Pastel Green' => [119, 221, 119], 'Pastel Magenta' => [244, 154, 194], 'Pastel Orange' => [255, 179, 71], 'Pastel Pink' => [222, 165, 164], 'Pastel Purple' => [179, 158, 181], 'Pastel Red' => [255, 105, 97], 'Pastel Violet' => [203, 153, 201], 'Pastel Yellow' => [253, 253, 150], 'Patriarch' => [128, 0, 128], "Payne's Grey" => [83, 104, 120], 'Peach' => [255, 203, 164], 'Peach-Orange' => [255, 204, 153], 'Peach Puff' => [255, 218, 185], 'Peach-Yellow' => [250, 223, 173], 'Pear' => [209, 226, 49], 'Pearl' => [234, 224, 200], 'Pearl Aqua' => [136, 216, 192], 'Pearly Purple' => [183, 104, 162], 'Peridot' => [230, 226, 0], 'Periwinkle' => [204, 204, 255], 'Permanent Geranium Lake' => [225, 44, 44], 'Persian Blue' => [28, 57, 187], 'Persian Green' => [0, 166, 147], 'Persian Indigo' => [50, 18, 122], 'Persian Orange' => [217, 144, 88], 'Persian Pink' => [247, 127, 190], 'Persian Plum' => [112, 28, 28], 'Persian Red' => [204, 51, 51], 'Persian Rose' => [254, 40, 162], 'Persimmon' => [236, 88, 0], 'Peru' => [205, 133, 63], 'Phlox' => [223, 0, 255], 'Phthalo Blue' => [0, 15, 137], 'Phthalo Green' => [18, 53, 36], 'Picton Blue' => [69, 177, 232], 'Pictorial Carmine' => [195, 11, 78], 'Piggy Pink' => [253, 221, 230], 'Pine Green' => [1, 121, 111], 'Pineapple' => [86, 60, 92], 'Pink' => [255, 192, 203], 'Pink (Pantone)' => [215, 72, 148], 'Pink Flamingo' => [252, 116, 253], 'Pink Lace' => [255, 221, 244], 'Pink Lavender' => [216, 178, 209], 'Pink-Orange' => [255, 153, 102], 'Pink Pearl' => [231, 172, 207], 'Pink Raspberry' => [152, 0, 54], 'Pink Sherbet' => [247, 143, 167], 'Pistachio' => [147, 197, 114], 'Platinum' => [229, 228, 226], 'Plum' => [142, 69, 133], 'Plum (Web)' => [221, 160, 221], 'Pomp And Power' => [134, 96, 142], 'Popstar' => [190, 79, 98], 'Portland Orange' => [255, 90, 54], 'Powder Blue' => [176, 224, 230], 'Princeton Orange' => [245, 128, 37], 'Prune' => [112, 28, 28], 'Prussian Blue' => [0, 49, 83], 'Psychedelic Purple' => [223, 0, 255], 'Puce' => [204, 136, 153], 'Puce Red' => [114, 47, 55], 'Pullman Brown (UPS Brown)' => [100, 65, 23], 'Pullman Green' => [59, 51, 28], 'Pumpkin' => [255, 117, 24], 'Purple (HTML)' => [128, 0, 128], 'Purple (Munsell)' => [159, 0, 197], 'Purple (X11)' => [160, 32, 240], 'Purple Heart' => [105, 53, 156], 'Purple Mountain Majesty' => [150, 120, 182], 'Purple Navy' => [78, 81, 128], 'Purple Pizzazz' => [254, 78, 218], 'Purple Taupe' => [80, 64, 77], 'Purpureus' => [154, 78, 174], 'Quartz' => [81, 72, 79], 'Queen Blue' => [67, 107, 149], 'Queen Pink' => [232, 204, 215], 'Quinacridone Magenta' => [142, 58, 89], 'Rackley' => [93, 138, 168], 'Radical Red' => [255, 53, 94], 'Raisin Black' => [36, 33, 36], 'Rajah' => [251, 171, 96], 'Raspberry' => [227, 11, 93], 'Raspberry Glace' => [145, 95, 109], 'Raspberry Pink' => [226, 80, 152], 'Raspberry Rose' => [179, 68, 108], 'Raw Sienna' => [214, 138, 89], 'Raw Umber' => [130, 102, 68], 'Razzle Dazzle Rose' => [255, 51, 204], 'Razzmatazz' => [227, 37, 107], 'Razzmic Berry' => [141, 78, 133], 'Rebecca Purple' => [102, 51, 153], 'Red' => [255, 0, 0], 'Red (Crayola)' => [238, 32, 77], 'Red (Munsell)' => [242, 0, 60], 'Red (NCS)' => [196, 2, 51], 'Red (Pantone)' => [237, 41, 57], 'Red (Pigment)' => [237, 28, 36], 'Red (RYB)' => [254, 39, 18], 'Red-Brown' => [165, 42, 42], 'Red Devil' => [134, 1, 17], 'Red-Orange' => [255, 83, 73], 'Red-Purple' => [228, 0, 120], 'Red-Violet' => [199, 21, 133], 'Redwood' => [164, 90, 82], 'Regalia' => [82, 45, 128], 'Registration Black' => [0, 0, 0], 'Resolution Blue' => [0, 35, 135], 'Rhythm' => [119, 118, 150], 'Rich Black' => [0, 64, 64], 'Rich Black (FOGRA29)' => [1, 11, 19], 'Rich Black (FOGRA39)' => [1, 2, 3], 'Rich Brilliant Lavender' => [241, 167, 254], 'Rich Carmine' => [215, 0, 64], 'Rich Electric Blue' => [8, 146, 208], 'Rich Lavender' => [167, 107, 207], 'Rich Lilac' => [182, 102, 210], 'Rich Maroon' => [176, 48, 96], 'Rifle Green' => [68, 76, 56], 'Roast Coffee' => [112, 66, 65], 'Robin Egg Blue' => [0, 204, 204], 'Rocket Metallic' => [138, 127, 128], 'Roman Silver' => [131, 137, 150], 'Rose' => [255, 0, 127], 'Rose Bonbon' => [249, 66, 158], 'Rose Ebony' => [103, 72, 70], 'Rose Gold' => [183, 110, 121], 'Rose Madder' => [227, 38, 54], 'Rose Pink' => [255, 102, 204], 'Rose Quartz' => [170, 152, 169], 'Rose Red' => [194, 30, 86], 'Rose Taupe' => [144, 93, 93], 'Rose Vale' => [171, 78, 82], 'Rosewood' => [101, 0, 11], 'Rosso Corsa' => [212, 0, 0], 'Rosy Brown' => [188, 143, 143], 'Royal Azure' => [0, 56, 168], 'Royal Blue' => [65, 105, 225], 'Royal Fuchsia' => [202, 44, 146], 'Royal Purple' => [120, 81, 169], 'Royal Yellow' => [250, 218, 94], 'Ruber' => [206, 70, 118], 'Rubine Red' => [209, 0, 86], 'Ruby' => [224, 17, 95], 'Ruby Red' => [155, 17, 30], 'Ruddy' => [255, 0, 40], 'Ruddy Brown' => [187, 101, 40], 'Ruddy Pink' => [225, 142, 150], 'Rufous' => [168, 28, 7], 'Russet' => [128, 70, 27], 'Russian Green' => [103, 146, 103], 'Russian Violet' => [50, 23, 77], 'Rust' => [183, 65, 14], 'Rusty Red' => [218, 44, 67], 'Sacramento State Green' => [0, 86, 63], 'Saddle Brown' => [139, 69, 19], 'Safety Orange' => [255, 120, 0], 'Safety Orange (Blaze Orange)' => [255, 103, 0], 'Safety Yellow' => [238, 210, 2], 'Saffron' => [244, 196, 48], 'Sage' => [188, 184, 138], "St. Patrick's Blue" => [35, 41, 122], 'Salmon' => [250, 128, 114], 'Salmon Pink' => [255, 145, 164], 'Sand' => [194, 178, 128], 'Sand Dune' => [150, 113, 23], 'Sandstorm' => [236, 213, 64], 'Sandy Brown' => [244, 164, 96], 'Sandy Taupe' => [150, 113, 23], 'Sangria' => [146, 0, 10], 'Sap Green' => [80, 125, 42], 'Sapphire' => [15, 82, 186], 'Sapphire Blue' => [0, 103, 165], 'Satin Sheen Gold' => [203, 161, 53], 'Scarlet' => [253, 14, 53], 'Schauss Pink' => [255, 145, 175], 'School Bus Yellow' => [255, 216, 0], "Screamin' Green" => [118, 255, 122], 'Sea Blue' => [0, 105, 148], 'Sea Green' => [46, 139, 87], 'Seal Brown' => [89, 38, 11], 'Seashell' => [255, 245, 238], 'Selective Yellow' => [255, 186, 0], 'Sepia' => [112, 66, 20], 'Shadow' => [138, 121, 93], 'Shadow Blue' => [119, 139, 165], 'Shampoo' => [255, 207, 241], 'Shamrock Green' => [0, 158, 96], 'Sheen Green' => [143, 212, 0], 'Shimmering Blush' => [217, 134, 149], 'Shocking Pink' => [252, 15, 192], 'Shocking Pink (Crayola)' => [255, 111, 255], 'Sienna' => [136, 45, 23], 'Silver' => [192, 192, 192], 'Silver Chalice' => [172, 172, 172], 'Silver Lake Blue' => [93, 137, 186], 'Silver Pink' => [196, 174, 173], 'Silver Sand' => [191, 193, 194], 'Sinopia' => [203, 65, 11], 'Skobeloff' => [0, 116, 116], 'Sky Blue' => [135, 206, 235], 'Sky Magenta' => [207, 113, 175], 'Slate Blue' => [106, 90, 205], 'Slate Gray' => [112, 128, 144], 'Smalt (Dark Powder Blue)' => [0, 51, 153], 'Smitten' => [200, 65, 134], 'Smoke' => [115, 130, 118], 'Smoky Black' => [16, 12, 8], 'Smoky Topaz' => [147, 61, 65], 'Snow' => [255, 250, 250], 'Soap' => [206, 200, 239], 'Solid Pink' => [137, 56, 67], 'Sonic Silver' => [117, 117, 117], 'Spartan Crimson' => [158, 19, 22], 'Space Cadet' => [29, 41, 81], 'Spanish Bistre' => [128, 117, 50], 'Spanish Blue' => [0, 112, 184], 'Spanish Carmine' => [209, 0, 71], 'Spanish Crimson' => [229, 26, 76], 'Spanish Gray' => [152, 152, 152], 'Spanish Green' => [0, 145, 80], 'Spanish Orange' => [232, 97, 0], 'Spanish Pink' => [247, 191, 190], 'Spanish Red' => [230, 0, 38], 'Spanish Sky Blue' => [0, 255, 255], 'Spanish Violet' => [76, 40, 130], 'Spanish Viridian' => [0, 127, 92], 'Spicy Mix' => [139, 95, 77], 'Spiro Disco Ball' => [15, 192, 252], 'Spring Bud' => [167, 252, 0], 'Spring Green' => [0, 255, 127], 'Star Command Blue' => [0, 123, 184], 'Steel Blue' => [70, 130, 180], 'Steel Pink' => [204, 51, 204], 'Stil De Grain Yellow' => [250, 218, 94], 'Stizza' => [153, 0, 0], 'Stormcloud' => [79, 102, 106], 'Straw' => [228, 217, 111], 'Strawberry' => [252, 90, 141], 'Sunglow' => [255, 204, 51], 'Sunray' => [227, 171, 87], 'Sunset' => [250, 214, 165], 'Sunset Orange' => [253, 94, 83], 'Super Pink' => [207, 107, 169], 'Tan' => [210, 180, 140], 'Tangelo' => [249, 77, 0], 'Tangerine' => [242, 133, 0], 'Tangerine Yellow' => [255, 204, 0], 'Tango Pink' => [228, 113, 122], 'Taupe' => [72, 60, 50], 'Taupe Gray' => [139, 133, 137], 'Tea Green' => [208, 240, 192], 'Tea Rose' => [244, 194, 194], 'Teal' => [0, 128, 128], 'Teal Blue' => [54, 117, 136], 'Teal Deer' => [153, 230, 179], 'Teal Green' => [0, 130, 127], 'Telemagenta' => [207, 52, 118], 'Tenné' => [205, 87, 0], 'Terra Cotta' => [226, 114, 91], 'Thistle' => [216, 191, 216], 'Thulian Pink' => [222, 111, 161], 'Tickle Me Pink' => [252, 137, 172], 'Tiffany Blue' => [10, 186, 181], "Tiger's Eye" => [224, 141, 60], 'Timberwolf' => [219, 215, 210], 'Titanium Yellow' => [238, 230, 0], 'Tomato' => [255, 99, 71], 'Toolbox' => [116, 108, 192], 'Topaz' => [255, 200, 124], 'Tractor Red' => [253, 14, 53], 'Trolley Grey' => [128, 128, 128], 'Tropical Rain Forest' => [0, 117, 94], 'Tropical Violet' => [205, 164, 222], 'True Blue' => [0, 115, 207], 'Tufts Blue' => [65, 125, 193], 'Tulip' => [255, 135, 141], 'Tumbleweed' => [222, 170, 136], 'Turkish Rose' => [181, 114, 129], 'Turquoise' => [64, 224, 208], 'Turquoise Blue' => [0, 255, 239], 'Turquoise Green' => [160, 214, 180], 'Tuscan' => [250, 214, 165], 'Tuscan Brown' => [111, 78, 55], 'Tuscan Red' => [124, 72, 72], 'Tuscan Tan' => [166, 123, 91], 'Tuscany' => [192, 153, 153], 'Twilight Lavender' => [138, 73, 107], 'Tyrian Purple' => [102, 2, 60], 'UA Blue' => [0, 51, 170], 'UA Red' => [217, 0, 76], 'Ube' => [136, 120, 195], 'UCLA Blue' => [83, 104, 149], 'UCLA Gold' => [255, 179, 0], 'UFO Green' => [60, 208, 112], 'Ultramarine' => [63, 0, 255], 'Ultramarine Blue' => [65, 102, 245], 'Ultra Pink' => [255, 111, 255], 'Ultra Red' => [252, 108, 133], 'Umber' => [99, 81, 71], 'Unbleached Silk' => [255, 221, 202], 'United Nations Blue' => [91, 146, 229], 'University Of California Gold' => [183, 135, 39], 'Unmellow Yellow' => [255, 255, 102], 'UP Forest Green' => [1, 68, 33], 'UP Maroon' => [123, 17, 19], 'Upsdell Red' => [174, 32, 41], 'Urobilin' => [225, 173, 33], 'USAFA Blue' => [0, 79, 152], 'USC Cardinal' => [153, 0, 0], 'USC Gold' => [255, 204, 0], 'University Of Tennessee Orange' => [247, 127, 0], 'Utah Crimson' => [211, 0, 63], 'Vanilla' => [243, 229, 171], 'Vanilla Ice' => [243, 143, 169], 'Vegas Gold' => [197, 179, 88], 'Venetian Red' => [200, 8, 21], 'Verdigris' => [67, 179, 174], 'Vermilion' => [217, 56, 30], 'Veronica' => [160, 32, 240], 'Very Light Azure' => [116, 187, 251], 'Very Light Blue' => [102, 102, 255], 'Very Light Malachite Green' => [100, 233, 134], 'Very Light Tangelo' => [255, 176, 119], 'Very Pale Orange' => [255, 223, 191], 'Very Pale Yellow' => [255, 255, 191], 'Violet' => [143, 0, 255], 'Violet (Color Wheel)' => [127, 0, 255], 'Violet (RYB)' => [134, 1, 175], 'Violet (Web)' => [238, 130, 238], 'Violet-Blue' => [50, 74, 178], 'Violet-Red' => [247, 83, 148], 'Viridian' => [64, 130, 109], 'Viridian Green' => [0, 150, 152], 'Vista Blue' => [124, 158, 217], 'Vivid Amber' => [204, 153, 0], 'Vivid Auburn' => [146, 39, 36], 'Vivid Burgundy' => [159, 29, 53], 'Vivid Cerise' => [218, 29, 129], 'Vivid Cerulean' => [0, 170, 238], 'Vivid Crimson' => [204, 0, 51], 'Vivid Gamboge' => [255, 153, 0], 'Vivid Lime Green' => [166, 214, 8], 'Vivid Malachite' => [0, 204, 51], 'Vivid Mulberry' => [184, 12, 227], 'Vivid Orange' => [255, 95, 0], 'Vivid Orange Peel' => [255, 160, 0], 'Vivid Orchid' => [204, 0, 255], 'Vivid Raspberry' => [255, 0, 108], 'Vivid Red' => [247, 13, 26], 'Vivid Red-Tangelo' => [223, 97, 36], 'Vivid Sky Blue' => [0, 204, 255], 'Vivid Tangelo' => [240, 116, 39], 'Vivid Tangerine' => [255, 160, 137], 'Vivid Vermilion' => [229, 96, 36], 'Vivid Violet' => [159, 0, 255], 'Vivid Yellow' => [255, 227, 2], 'Volt' => [206, 255, 0], 'Warm Black' => [0, 66, 66], 'Waterspout' => [164, 244, 249], 'Weldon Blue' => [124, 152, 171], 'Wenge' => [100, 84, 82], 'Wheat' => [245, 222, 179], 'White' => [255, 255, 255], 'White Smoke' => [245, 245, 245], 'Wild Blue Yonder' => [162, 173, 208], 'Wild Orchid' => [212, 112, 162], 'Wild Strawberry' => [255, 67, 164], 'Wild Watermelon' => [252, 108, 133], 'Willpower Orange' => [253, 88, 0], 'Windsor Tan' => [167, 85, 2], 'Wine' => [114, 47, 55], 'Wine Dregs' => [103, 49, 71], 'Wisteria' => [201, 160, 220], 'Wood Brown' => [193, 154, 107], 'Xanadu' => [115, 134, 120], 'Yale Blue' => [15, 77, 146], 'Yankees Blue' => [28, 40, 65], 'Yellow' => [255, 255, 0], 'Yellow (Crayola)' => [252, 232, 131], 'Yellow (Munsell)' => [239, 204, 0], 'Yellow (NCS)' => [255, 211, 0], 'Yellow (Pantone)' => [254, 223, 0], 'Yellow (Process)' => [255, 239, 0], 'Yellow (RYB)' => [254, 254, 51], 'Yellow-Green' => [154, 205, 50], 'Yellow Orange' => [255, 174, 66], 'Yellow Rose' => [255, 240, 0], 'Zaffre' => [0, 20, 168], 'Zinnwaldite Brown' => [44, 22, 8], 'Zomp' => [57, 167, 142], ]; public static function nameFromColor(Color $color) { $bestMatch = ''; $bestDifference = 100.0; foreach (static::$colors as $key => $RawOtherColor) { $otherColor = Color::fromRGB($RawOtherColor[0], $RawOtherColor[1], $RawOtherColor[2]); $difference = $color->differenceBetween($otherColor); if ($bestDifference > $difference) { $bestMatch = $key; $bestDifference = $difference; } } return $bestMatch; } }
NiclasHedam/color
src/ColorName.php
PHP
mit
83,557
// Private array of chars to use var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); var ID = {}; ID.uuid = function (len, radix) { var chars = CHARS, uuid = [], i; radix = radix || chars.length; if (len) { // Compact form for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix]; } else { // rfc4122, version 4 form var r; // rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; uuid[14] = '4'; // Fill in random data. At i==19 set the high bits of clock sequence as // per rfc4122, sec. 4.1.5 for (i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | Math.random()*16; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } } return uuid.join(''); }; // A more performant, but slightly bulkier, RFC4122v4 solution. We boost performance // by minimizing calls to random() ID.uuidFast = function() { var chars = CHARS, uuid = new Array(36), rnd=0, r; for (var i = 0; i < 36; i++) { if (i==8 || i==13 || i==18 || i==23) { uuid[i] = '-'; } else if (i==14) { uuid[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; r = rnd & 0xf; rnd = rnd >> 4; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } return uuid.join(''); }; // A more compact, but less performant, RFC4122v4 solution: ID.uuidCompact = function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }; module.exports = ID;
blackjk3/react-form-builder
src/UUID.js
JavaScript
mit
1,663
// ==UserScript== // @name mineAI // @namespace minesAI // @include http://minesweeperonline.com/#beginner-night // @version 1 // @required http://localhost:8000/convnetjs.js // @grant none // ==/UserScript== // Load the library. var D = document; var appTarg = D.getElementsByTagName ('head')[0] || D.body || D.documentElement; var jsNode = D.createElement ('script'); jsNode.src = 'http://localhost:8000/convnetjs.js'; jsNode.addEventListener ("load", initConvNetJsOnDelay, false); appTarg.appendChild (jsNode); // Allow some time for the library to initialize after loading. function initConvNetJsOnDelay () { setTimeout (initConvNetJs, 666); } // Call the library's start-up function, if any. Note needed use of unsafeWindow. function initConvNetJs () { // species a 2-layer neural network with one hidden layer of 20 neurons var layer_defs = []; // ConvNetJS works on 3-Dimensional volumes (sx, sy, depth), but if you're not dealing with images // then the first two dimensions (sx, sy) will always be kept at size 1 layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth:2}); // declare 4 neurons, followed by ReLU (rectified linear unit non-linearity) layer_defs.push({type:'fc', num_neurons:4, activation:'relu'}); // 3 more for good measure layer_defs.push({type:'fc', num_neurons:3, activation:'relu'}); // declare the linear classifier on top of the previous hidden layer layer_defs.push({type:'softmax', num_classes:2}); // defined our net with unsafeWindow for use in GreaseMonkey var net = new unsafeWindow.convnetjs.Net(); // create our net with layers as defined above net.makeLayers(layer_defs); // define trainer var trainer = new convnetjs.SGDTrainer(net, {learning_rate:0.01, l2_decay:0.001}); // define inputs (XOR) var t1 = new convnetjs.Vol([0, 0]); // class 0 var t2 = new convnetjs.Vol([0, 1]); // class 1 var t3 = new convnetjs.Vol([1, 0]); // class 1 var t4 = new convnetjs.Vol([1, 1]); // class 0 // train for 1000 iterations with corresponding classes for (var i = 0; i < 1000; i++) { trainer.train(t1, 0); trainer.train(t2, 1); trainer.train(t3, 1); trainer.train(t4, 0); } // learned probability var prob00 = net.forward(t1); var prob01 = net.forward(t2); var prob10 = net.forward(t3); var prob11 = net.forward(t4); // log probability console.log('p(0 | 00): ' + prob00.w[0] + ", p(1 | 00): " + prob00.w[1]); console.log('p(0 | 01): ' + prob01.w[0] + ", p(1 | 01): " + prob01.w[1]); console.log('p(0 | 10): ' + prob10.w[0] + ", p(1 | 10): " + prob10.w[1]); console.log('p(0 | 11): ' + prob11.w[0] + ", p(1 | 11): " + prob11.w[1]); } alert("Done");
cirquit/Personal-Repository
JS/minesweeper/minesweeperNN.js
JavaScript
mit
2,855
<?php namespace Hyperframework\Web; use Exception; abstract class HttpException extends Exception { private $statusCode; private $statusReasonPhrase; /** * @param string $message * @param int $statusCode * @param string $statusReasonPhrase * @param Exception $previous */ public function __construct( $message, $statusCode, $statusReasonPhrase, $previous = null ) { if ($message === null) { $message = $statusCode . ' ' . $statusReasonPhrase . '.'; } parent::__construct($message, 0, $previous); $this->statusCode = $statusCode; $this->statusReasonPhrase = $statusReasonPhrase; } /** * @return string */ public function getStatus() { return $this->statusCode . ' ' . $this->statusReasonPhrase; } /** * @return int */ public function getStatusCode() { return $this->statusCode; } /** * @return string */ public function getStatusReasonPhrase() { return $this->statusReasonPhrase; } /** * @return array */ public function getHttpHeaders() { return []; } }
hyperframework/hyperframework
lib/Web/HttpException.php
PHP
mit
1,190
package processing import "github.com/gopherjs/gopherjs/js" //////////////////////////////////////////////////////////// // COLOR //Creating and reading: func Color(params ...interface{}) *js.Object { switch len(params) { case 1: return pG.Call("color", params[0]) case 2: return pG.Call("color", params[0], params[1]) case 3: return pG.Call("color", params[0], params[1], params[2]) case 4: return pG.Call("color", params[0], params[1], params[2], params[3]) default: println("Error in Color function (1)") return nil } } func Alpha(color *js.Object) int { return pG.Call("alpha", color).Int() } func Blue(color *js.Object) int { return pG.Call("blue", color).Int() } func Brightness(color *js.Object) int { return pG.Call("brightness", color).Int() } func Green(color *js.Object) int { return pG.Call("green", color).Int() } func Hue(color *js.Object) int { return pG.Call("hue", color).Int() } func LerpColor(from interface{}, to interface{}, amt float64) *js.Object { return pG.Call("lerpColor", from, to, amt) } func Lightness(color *js.Object) int { return pG.Call("lightness", color).Int() } func Red(color *js.Object) int { return pG.Call("red", color).Int() } func Saturation(color *js.Object) int { return pG.Call("saturation", color).Int() } //Setting: func Background(values ...interface{}) { switch len(values) { case 1: pG.Call("background", values[0]) break case 2: pG.Call("background", values[0].(int), values[1].(int)) break case 3: pG.Call("background", values[0].(int), values[1].(int), values[2].(int)) break default: println("Error in background function (2)...") return } } func Clear() { pG.Call("clear") } func ColorMode(mode string, maxValues ...int) { switch len(maxValues) { case 0: pG.Call("colorMode", mode) break case 1: pG.Call("colorMode", mode, maxValues[0]) break case 2: pG.Call("colorMode", mode, maxValues[0], maxValues[1]) break case 3: pG.Call("colorMode", mode, maxValues[0], maxValues[1], maxValues[2]) break case 4: pG.Call("colorMode", mode, maxValues[0], maxValues[1], maxValues[2], maxValues[3]) break default: println("Error in colorMode (1)") return } } func Fill(firstValue interface{}, extraValues ...float64) { switch len(extraValues) { case 0: /* Darwin! typeOfFirstValue := reflect.TypeOf(firstValue).Name() if typeOfFirstValue == reflect.Int.String() || typeOfFirstValue == reflect.Float64.String(){ pG.Call("fill", firstValue.(float64)) } */ pG.Call("fill", firstValue) break case 1: pG.Call("fill", firstValue, extraValues[0]) break case 2: pG.Call("fill", firstValue, extraValues[0], extraValues[1]) break case 3: pG.Call("fill", firstValue, extraValues[0], extraValues[1], extraValues[2]) break } } func NoFill() { pG.Call("noFill") } func NoStroke() { pG.Call("noStroke") } func Stroke(firstValue interface{}, extraValues ...int) { switch len(extraValues) { case 0: pG.Call("stroke", firstValue) break case 1: pG.Call("stroke", firstValue, extraValues[0]) break case 2: pG.Call("stroke", firstValue, extraValues[0], extraValues[1]) break case 3: pG.Call("stroke", firstValue, extraValues[0], extraValues[1], extraValues[2]) break } } func StrokeWeight(weight int) { pG.Call("strokeWeight", weight) }
bregydoc/PGoJs
Processing/colorPkg.go
GO
mit
3,341
# -*- coding: utf-8 -*- """ @file @brief Customer notebook exporters. """ import os from textwrap import indent from traitlets import default from traitlets.config import Config from jinja2 import DictLoader from nbconvert.exporters import RSTExporter from nbconvert.filters.pandoc import convert_pandoc def convert_pandoc_rst(source, from_format, to_format, extra_args=None): """ Overwrites `convert_pandoc <https://github.com/jupyter/nbconvert/blob/master/nbconvert/filters/pandoc.py>`_. @param source string to convert @param from_format from format @param to_format to format @param extra_args extra arguments @return results """ return convert_pandoc(source, from_format, to_format, extra_args=None) def process_raw_html(source, extra_args=None): """ Replaces the output of `add_menu_notebook <http://www.xavierdupre.fr/app/jyquickhelper/helpsphinx/jyquickhelper/ helper_in_notebook.html#jyquickhelper.helper_in_notebook.add_notebook_menu>`_ by: :: .. contents:: :local: """ if source is None: return source # pragma: no cover if 'var update_menu = function() {' in source: return "\n\n.. contents::\n :local:\n\n" return "\n\n.. raw:: html\n\n" + indent(source, prefix=' ') class UpgradedRSTExporter(RSTExporter): """ Exports :epkg:`rst` documents. Overwrites `RSTExporter <https://github.com/jupyter/ nbconvert/blob/master/nbconvert/exporters/rst.py>`_. * It replaces `convert_pandoc <https://github.com/jupyter/ nbconvert/blob/master/nbconvert/filters/pandoc.py>`_ by @see fn convert_pandoc_rst. * It converts :epkg:`svg` into :epkg:`png` if possible, see @see fn process_raw_html. * It replaces some known :epkg:`javascript`. The output of function `add_menu_notebook <http://www.xavierdupre.fr/app/jyquickhelper/helpsphinx/jyquickhelper/ helper_in_notebook.html#jyquickhelper.helper_in_notebook.add_notebook_menu>`_ is replaced by ``.. contents::``. .. index:: notebook export, nbconvert It extends the template `rst.tpl <https://github.com/jupyter/nbconvert/blob/master/nbconvert/templates/rst.tpl>`_. New template is `rst_modified.tpl <https://github.com/sdpython/pyquickhelper/blob/master/ src/pyquickhelper/helpgen/rst_modified.tpl>`_. It follows the hints given at `Programatically creating templates <https://nbconvert.readthedocs.io/en/latest/ nbconvert_library.html#Programatically-creating-templates>`_. :epkg:`jyquickhelper` should add a string highly recognizable when adding a menu. """ def __init__(self, *args, **kwargs): """ Overwrites the extra loaders to get the right template. """ filename = os.path.join(os.path.dirname(__file__), 'rst_modified.tpl') with open(filename, 'r', encoding='utf-8') as f: content = f.read() filename = os.path.join(os.path.dirname(__file__), 'rst.tpl') with open(filename, 'r', encoding='utf-8') as f: content2 = f.read() dl = DictLoader({'rst_modified.tpl': content, 'rst.tpl': content2}) kwargs['extra_loaders'] = [dl] RSTExporter.__init__(self, *args, **kwargs) def default_filters(self): """ Overrides in subclasses to provide extra filters. This should return an iterable of 2-tuples: (name, class-or-function). You should call the method on the parent class and include the filters it provides. If a name is repeated, the last filter provided wins. Filters from user-supplied config win over filters provided by classes. """ for k, v in RSTExporter.default_filters(self): yield (k, v) yield ('convert_pandoc_rst', convert_pandoc_rst) yield ('process_raw_html', process_raw_html) output_mimetype = 'text/restructuredtext' export_from_notebook = "reST" @default('template_file') def _template_file_default(self): return "rst_modified.tpl" @default('file_extension') def _file_extension_default(self): return '.rst' @default('template_name') def _template_name_default(self): return 'rst' @property def default_config(self): c = Config({ 'ExtractOutputPreprocessor': { 'enabled': True, 'output_filename_template': '{unique_key}_{cell_index}_{index}{extension}' }, 'HighlightMagicsPreprocessor': { 'enabled': True }, }) c.merge(super(UpgradedRSTExporter, self).default_config) return c
sdpython/pyquickhelper
src/pyquickhelper/helpgen/notebook_exporter.py
Python
mit
4,770
<?php namespace BRMManager\Model; class NotifyTemplates extends \Model { public static $_table = 'notifytemplates'; public static function template($orm, $filter) { return $orm->where('name', $filter); } public function newEmail() { // This will create a new email for this template. } }
tylerjuniorcollege/brm-manager
app/src/Model/NotifyTemplates.php
PHP
mit
300
package annotation; import java.lang.annotation.*; /** * Desc: * 创建自定义注解 * Created by WangGuoku on 2017/9/27 16:05. */ @Documented @Target(ElementType.FIELD) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface MyAnno{ String getName() default ""; }
HaHaBird/JavaLearinigProject
src/annotation/MyAnno.java
Java
mit
287
define(function () { 'use strict'; ({ get foo () { console.log( 'effect' ); return {}; } }).foo.bar; ({ get foo () { return {}; } }).foo.bar.baz; ({ get foo () { console.log( 'effect' ); return () => {}; } }).foo(); ({ get foo () { return () => console.log( 'effect' ); } }).foo(); ({ get foo () { console.log( 'effect' ); return () => () => {}; } }).foo()(); ({ get foo () { return () => () => console.log( 'effect' ); } }).foo()(); });
corneliusweig/rollup
test/form/samples/getter-return-values/_expected/amd.js
JavaScript
mit
503
<?php namespace App\Http\Controllers\MemberAuth; use App\Address; use App\Member; use App\Http\Requests; use Illuminate\Support\Facades\Hash; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\RegistersUsers; use Illuminate\Support\Facades\Auth; use Cornford\Googlmapper\Facades\MapperFacade as Mapper; class RegisterController extends Controller { /* |-------------------------------------------------------------------------- | Register Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users as well as their | validation and creation. By default this controller uses a trait to | provide this functionality without requiring any additional code. | */ use RegistersUsers; public function __construct() { $this->middleware('member.guest'); } public function register(Requests\Frontend\RegisterNewMember $request) { $address = Address::where('zip', '=', $request->zip)->where('city', '=', $request->city)->where('street', '=', $request->street)->where('housenumber', '=', $request->housenumber)->first(); if (!$address) { $geo = Mapper::location('Germany' . $request->zip . $request->street . $request->housenumber); $newaddress = Address::create(array( 'zip' => $request->zip, 'city' => $request->city, 'street' => $request->street, 'housenumber' => $request->housenumber, 'latitude' => $geo->getLatitude(), 'longitude' => $geo->getLongitude() )); $address = $newaddress; } $member = Member::create([ 'lastname' => $request->lastname, 'firstname' => $request->firstname, 'birthday' => $request->birthday, 'phone' => $request->phone, 'mobile' => $request->mobile, 'email' => $request->email, 'address_id' => $address->id, 'role_id' => 3, 'job' => $request->job, 'employer' => $request->employer, 'university' => $request->university, 'courseofstudies' => $request->courseofstudies, 'password' => Hash::make($request->password), 'remember_token' => Auth::viaRemember() ]); Auth::guard('member')->loginUsingId($member->id); return redirect('/')->with('status', 'Successfully registered. Welcome!'); } public function showRegistrationForm() { return view('auth.member.register'); } protected function guard() { return Auth::guard('member'); } }
mlechler/Bewerbungscoaching
app/Http/Controllers/MemberAuth/RegisterController.php
PHP
mit
2,745
<script src="<?=base_url('assets/jwplayer7/jwplayer.js')?>"></script> <script>jwplayer.key="<?=$this->M_setting->get_jwplayer_key()?>";</script> <link href="<?php echo base_url(); ?>assets/css/bootstrap-combined.no-icons.min.css" rel="stylesheet"> <link href="<?php echo base_url(); ?>assets/css/style1.css" rel="stylesheet" /> <link href="<?php echo base_url(); ?>assets/css/landing_page/landing_page9.css" rel="stylesheet" /> <link rel="stylesheet" href="<?php echo base_url()?>assets/css/dist/viewer.css"> <link rel="stylesheet" href="<?php echo base_url()?>assets/css/dist/css/main.css"> <script src="<?php echo base_url()?>assets/css/dist/viewer.js"></script> <script src="<?php echo base_url()?>assets/css/dist/js/main.js"></script> <link href="<?php echo base_url(); ?>assets/playermusic/css/jplayer.blue.monday.min.css" rel="stylesheet" /> <script type="text/javascript" src="<?php echo base_url(); ?>assets/playermusic/dist/jplayer/jquery.jplayer.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/playermusic/dist/add-on/jplayer.playlist.min.js"></script> <script type="text/javascript"> $(".effect_slide").click(function(){ $(this).parent().parent().find("img").click(); }) </script> <div class="wrap bg-landing" style=""> <div class="container bg-lg-ct" style="width: 90%;"> <div> <div class="col-md-12 profile-maxheight dis-n"> <?php if (!empty($users[0]->banner_image)) {?> <img src="<?php echo base_url(); ?>uploads/<?php echo $users[0]->id; ?>/photo/banner/<?php echo $users[0]->banner_image; ?>" class="n-ds" style="width:102.70%;margin-left:-15px;"/> <?php } else { } ?> <div class="col-md-6 profile-landing"> <div class="col-md-3 col-xs-12 pro-img-1"> <img class="avata_landing" src="<?php echo $this->M_user->get_avata($users[0]->id)?>"/> </div> <div class="col-md-9 col-xs-12 pro-img-2"> <h1 class="text-h1"><?php echo ucfirst($name); ?></h1> <span><?php if(isset($genres[0]['name'])) echo ucfirst($genres[0]['name']); ?></span> <span class="mg"><?php echo ucfirst($city); if (!empty($country_code[0]['countrycode'])) { echo ', '.ucfirst($country_code[0]['countrycode']); }; ?></span> </div> </div> <div class="col-md-6 col-xs-12 info_social"> <?php if (!empty($users[0]->bio)) { echo $this->Member_model->short_Text_Bio($users[0]->bio); } ?> <p class="text-justify" style="margin-left: -15px;margin-top: 20px;margin-bottom: 20px;"> <a href="<?php echo $users[0]->twitter_username; ?>" target="_blank" title="Twitter"> <span class="relative inline" style="height:24px;width:24px"> <img alt="Icon_twitter" class="centerer--y" src="https://gp1.wac.edgecastcdn.net/802892/production_static/20151016092753/images/v4/standard_resources/social_icons/icon_twitter.png?1445003519" style="z-index:1"> </span> </a> <a href="<?php echo $users[0]->instagram_username; ?>" title="Instagram"> <span class="relative inline" style="height:24px;width:24px"> <img alt="Icon_instagram" class="centerer--y" src="https://gp1.wac.edgecastcdn.net/802892/production_static/20151016092753/images/v4/standard_resources/social_icons/icon_instagram.png?1445003519" style="z-index:1"> </span> </a> <a href="<?php echo $users[0]->youtube_username; ?>" target="_blank" title="YouTube"> <span class="relative inline" style="height:24px;width:24px"> <img alt="Icon_youtube" class="centerer--y" src="https://gp1.wac.edgecastcdn.net/802892/production_static/20151016092753/images/v4/standard_resources/social_icons/icon_youtube.png?1445003519" style="z-index:1"> </span> </a> <a href="<?php echo $users[0]->facebook_username; ?>" target="_blank" title="Facebook"> <span class="relative inline" style="height:24px;width:24px"> <img alt="Icon_facebook" class="centerer--y" src="https://gp1.wac.edgecastcdn.net/802892/production_static/20151016092753/images/v4/standard_resources/social_icons/icon_facebook.png?1445003519" style="z-index:1"> </span> </a> </p> </div> </div> <div class="col-md-12 remove_padding"> <div class="col-md-4 padding_left"> <?php if (!empty($users[0]->status)){ ?> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <div class="status_view">Status: <?php echo $users[0]->status; ?></div> </div> <?php } ?> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><a href="<?php echo base_url().$name; ?>/photos"><img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_photo.png" /> Photos</a></h2> <span class="liner_landing"></span> <div class="col-md-12 remove_padding"> <ul class="docs-pictures clearfix"> <?php $count = count($photos); if ($count == 3) { $i = 0; foreach ($photos as $pt) { ?> <li class="col-md-4 col-xs-4"> <div class="image_fix_value" style="background: url('<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>');"></div> <img width="1px" style="width: 1px !important;" data-original="<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>" src="<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>" class="img-responsive"/> </li> <?php ++$i; } } elseif ($count == 2) { $i = 0; foreach ($photos as $pt) { ?> <li class="col-md-4 col-xs-4"> <div class="image_fix_value" style="background: url('<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>');"></div> <img width="1px" style="width: 1px !important;" data-original="<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>" src="<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>"class="img-responsive"/> </li> <?php ++$i; } ?> <li class="col-md-4 col-xs-4"> <div class="image_fix_value" style="background: url('<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>');"></div> <img width="1px" style="width: 1px !important;" data-original="<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>" src="<?php echo base_url(); ?>assets/images/default-img.gif" class="img-responsive"/> </li> <?php } elseif ($count == 1) { foreach ($photos as $pt) { ?> <li class="col-md-4 col-xs-4"> <div class="image_fix_value" style="background: url('<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>');"></div> <img width="1px" style="width: 1px !important;" data-original="<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>" src="<?php echo base_url(); ?>uploads/<?php echo $pt['user_id']; ?>/photo/<?php echo $pt['filename']; ?>" class="img-responsive"/> </li> <?php } ?> <div class="col-md-4 col-xs-4"> <img width="100" src="<?php echo base_url(); ?>assets/images/default-img.gif" class="img-responsive"/> </div> <div class="col-md-4 col-xs-4"> <img width="100" src="<?php echo base_url(); ?>assets/images/default-img.gif"class="img-responsive"/> </div> <?php } else { ?> <div class="col-md-4 col-xs-4"> <img width="100" src="<?php echo base_url(); ?>assets/images/default-img.gif" class="img-responsive"/> </div> <div class="col-md-4 col-xs-4"> <img width="100" src="<?php echo base_url(); ?>assets/images/default-img.gif" class="img-responsive"/> </div> <div class="col-md-4 col-xs-4"> <img width="100" src="<?php echo base_url(); ?>assets/images/default-img.gif" class="img-responsive"/> </div> <?php } ?> </ul> </div> </div> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_member.png" /> Member</h2> <span class="liner_landing"></span> <div class="col-md-12 remove_padding"> <!--<div> <div class="col-md-3 col-xs-3"> <img width="70" src="<?php echo base_url(); ?>assets/images/2.jpg"/> </div> <div class="col-xs-9 col-md-9 remove_padding"> <span class="col-xs-12"><span class="ListName" itemprop="name"><a href="#">Lamberg Smith</a></span></span> <span class="col-xs-12 DisName">Multi-Instrumentalist</span> </div> </div>--> <?php foreach($members as $member){ ?> <div class="carousel-info"> <img alt="" src="<?php echo base_url(); ?>uploads/<?php echo $member['artist_id'];?>/image_member/<?php echo $member['member_image'];?>" class="pull-left"> <div class="pull-left"> <span class="testimonials-name"><a href="#"><?php echo $member['name_member']; ?></a></span> <span class="testimonials-post"><?php echo $member['contribution'];?></span> </div> </div> <?php } ?><!-- carousel-info --> </div> </div> <?php if (isset($blogs) && count($blogs) > 0) {?> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><a href="<?php echo base_url('artist/allblogs').'/'.$id; ?>"><img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_blog.png" /> Recent Blogs</a></h2> <span class="liner_landing"></span> <div class="col-md-12 remove_padding"> <?php foreach ($blogs as $row) {?> <div class="mb1"> <div class="mb1-blog-img"> <img class="img-responsive" width="150" src="<?php echo base_url('uploads/'.$row['user_id'].'/photo/blogs/'.$row['image_rep']) ?>" /> </div> <div class="mb1-blog-content"> <strong> <a href="<?php echo base_url('artist/blogs').'/'.$user_data['id']?>" class="blog_entry_header ellipsis h6-size"><?php echo $row['title']?></a> </strong> <div class="" style="color: #000;"> <span style=" font-size: small;"><?php echo date('M d, Y', $row['time'])?></span> </div> <div style="color: #000;"> <?php $text = strip_tags($row['introduction']); $desLength = strlen($text); //var_dump($desLength);exit; $stringMaxLength = 120; if ($desLength > $stringMaxLength) { $des = substr($text, 0, $stringMaxLength); $text = $des.'...'; echo $text; } else { echo $row['introduction']; } ?> </div> </div> </div> <?php if (end($blogs) != $row) { echo '<hr style="margin-bottom:0px;" />'; } } ?> </div> </div> <?php } ?> <?php if (isset($events) && count($events) > 0) { ?> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><a href="#"><img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_git_event.png" /> Events</a></h2> <span class="liner_landing"></span> <div class="col-md-12 remove_padding"> <?php foreach ($events as $event) { ?> <div class="wp_content_list"> <a href="#" class="show_ev item" data-event="<?=$event['event_id']; ?>" style="font-size: 16px;text-decoration: none;" data-toggle="modal" data-target="#showEvent"> <figure class="effect-bubba" style="float: left; width: 100px;margin: 5px;"> <img class="img-responsive" src="<?php if (!empty($event['event_banner'])) { echo base_url().'uploads/'.$event['user_id'].'/photo/banner_events/'.$event['event_banner']; } ?>" /> </figure> <span class="OtListName"><?php echo ucfirst($event['event_title']); ?></span><br /> <span class="DisName"><?php custom_echo_html($event['event_desc'], 400); ?> </span> </a><br /> <div class="clearfix"></div> </div> <?php } ?> </div> </div> <?php } ?> </div> <div class="col-md-4 margin_center"> <?php if (isset($album_songs) && count($album_songs) > 0) {?> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><a href="<?php echo base_url('artist/allsong').'/'.$id; ?>"><img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_songs.png" /> Songs</a></h2> <span class="liner_landing"></span> <div class="col-md-12 remove_padding"> <div class="panel-group" id="accordion"> <?php $i = 1; foreach ($album_songs as $album_song) { ?> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse<?php echo $i; ?>"> Album <?php echo $album_song['name']; ?> </a> </h4> </div> <div id="collapse<?php echo $i; ?>" class="panel-collapse collapse <?php if ($i == 1) { echo 'in'; } ?>"> <div class="panel-body remove_padding"> <?php $video_by_albums = $this->M_audio_song->get_songs_by_album($album_song['id']); ?> <script type="text/javascript"> $(document).ready(function(){ new jPlayerPlaylist({ jPlayer: "#jquery_jplayer_<?php echo $album_song['id']; ?>", cssSelectorAncestor: "#jp_container_<?php echo $album_song['id']; ?>" }, [ <?php foreach ($video_by_albums as $video_by_album) { $array_avai = explode(',', $video_by_album['availability']); ?> { title:"<?php echo $video_by_album['song_name'] ?>", mp3:"<?php echo 'http://d2c1n1yejcka7l.cloudfront.net/uploads/'.$id.'/audio/'.$video_by_album['audio_file'] ?>", poster: "<?php echo base_url().'uploads/'.$id.'/img_playlist/'.$album_song['image_file']; ?>", <?php if (in_array('2', $array_avai)) { ?> link_download: "<?=base_url('artist/downloadsong/'.$video_by_album['id'])?>", download: true <?php } ?> }, <?php } ?> ], { swfPath: "<?php echo base_url('assets/playermusic/dist/jplayer') ?>", supplied: "webmv, ogv, m4v, oga, mp3", useStateClassSkin: true, autoBlur: false, smoothPlayBar: true, keyEnabled: true, audioFullScreen: true }); }); </script> <div id="jp_container_<?php echo $album_song['id']; ?>" class="jp-video jp-video-270p" role="application" aria-label="media player"> <div class="jp-type-playlist"> <div id="jquery_jplayer_<?php echo $album_song['id']; ?>" class="jp-jplayer"></div> <div class="jp-gui"> <div class="jp-video-play"> <button class="jp-video-play-icon" role="button" tabindex="0">play</button> </div> <div class="jp-interface"> <div class="jp-progress"> <div class="jp-seek-bar"> <div class="jp-play-bar"></div> </div> </div> <div class="jp-current-time" role="timer" aria-label="time">&nbsp;</div> <div class="jp-duration" role="timer" aria-label="duration">&nbsp;</div> <div class="jp-controls-holder"> <div class="jp-controls"> <button class="jp-previous" role="button" tabindex="0">previous</button> <button class="jp-play" role="button" tabindex="0">play</button> <button class="jp-next" role="button" tabindex="0">next</button> <button class="jp-stop" role="button" tabindex="0">stop</button> </div> <div class="jp-volume-controls"> <button class="jp-mute" role="button" tabindex="0">mute</button> <button class="jp-volume-max" role="button" tabindex="0">max volume</button> <div class="jp-volume-bar"> <div class="jp-volume-bar-value"></div> </div> </div> <div class="jp-toggles"> <button class="jp-repeat" role="button" tabindex="0">repeat</button> <button class="jp-shuffle" role="button" tabindex="0">shuffle</button> <button class="jp-full-screen" role="button" tabindex="0">full screen</button> </div> </div> <div class="jp-details"> <div class="jp-title" aria-label="title">&nbsp;</div> </div> </div> </div> <div class="jp-playlist"> <ul> <!-- The method Playlist.displayPlaylist() uses this unordered list --> <li>&nbsp;</li> </ul> </div> <div class="jp-no-solution"> <span>Update Required</span> To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>. </div> </div> </div> </div> </div> </div> <?php ++$i; } ?> </div> </div> </div> <?php } ?> <?php if (isset($videos) && count($videos) > 0) {?> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><a href="<?php echo base_url('artist/allvideos').'/'.$id; ?>"><img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_video.png" /> Videos</a></h2> <span class="liner_landing"></span> <div class="col-md-12 remove_padding"> <?php foreach ($videos as $video) { if ($video['type'] == 'file') { $link_video = base_url().'uploads/'.$video['user_id'].'/video/'.$video['name_file']; } else { $link_video = $video['link_video']; } ?> <div class="wp_content_list"> <div class="col-md-4 col-xs-4"> <a href="#videos" onclick="javascript:playvideo(<?php echo "'".$link_video."'"; ?>,$(this))" data-toggle="modal" data-target="#videos"> <div class="image_fix_value_video" style="background: url('<?=$this->M_video->get_image_video($video['id'])?>');"></div> </a> </div> <div class="col-xs-8 col-md-8 remove_padding"> <span class="col-xs-12 content_video_title"><?php echo $video['name_video']; ?></span> </div> <div class="clearfix_check"></div> </div> <?php } ?> </div> </div> <?php } ?> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><a href="<?php echo base_url('artist/allcomment').'/'.$id;?>"> <img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_comment.png" /> Comments</a></h2> <span class="liner_landing"></span> <div class="col-md-12 remove_padding"> <div class="wp_content_list"> <?php if (empty($comments)) { ?> <span class="col-md-12" style="font-size: 16px;">No Comment.</span> <?php } foreach ($comments as $comment) { ?> <span class="col-md-12" style="font-size: 16px;"> <a href="<?=$this->M_user->get_home_page($comment['client'])?>"> <img width="60" style="min-height: 40px;margin-bottom: 5px;margin-right: 10px;" src="<?=$this->M_user->get_avata($comment['user_id'])?>" /> </a> <span class="OtListName"><a href="<?=$this->M_user->get_home_page($comment['client'])?>" class="posi_img" style="position:absolute;"> <?=$this->M_user->get_name($comment['client'])?> </a> </span> <span class="DisName"><?php echo ucfirst($comment['comment']); ?></span> <?php if (end($comments) != $comment) { echo '<hr class="hr-small" />'; } ?> </span> <?php } ?> </div> </div> <div class="col-md-12 remove_padding"> </div> <div class="text-center"> <a href="#" class="btn btn-default Dnew" data-toggle="modal" data-target="#addComment">Comment</a> </div> </div> </div> <div class="col-md-4 padding_right"> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_amp.png" /> AMP</h2> <span class="liner_landing"></span> <div class="col-md-12 remove_padding"> <?php echo $this->M_audio_song->get_shortcode_AMP($id)?> </div> </div> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><a href="<?php echo base_url('social_media');?>"><img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_quickactions.png" /> Quick Actions</a></h2> <span class="liner_landing"></span> <div class="col-md-6 searchform"> <button class="btn btn-default col-xs-12" style="margin-top: 20px;padding: 15px;">Share</button> </div> <div class="col-md-6 searchform"> <?php $home_page = $this->uri->segment(1); $results = $this->db->where('home_page', $home_page) ->get('users')->result_array(); foreach ($results as $result) { $user_i = $result['id']; } $isset = $this->db->where('user_id', $user_i)->where('fan_id', $user_id)->get('fans')->num_rows(); ?> <a href="<?php if ($isset > 0) { echo '#'; } else { echo base_url().'artist/comefan/'.$user_id.'/'.$home_page; } ?>" class="btn Dnew <?php if ($isset > 0) { echo 'btn-default'; } else { echo 'btn-default'; } ?> col-xs-12" style="margin-top: 20px;padding: 15px;<?php if ($isset > 0) { echo 'cursor: no-drop;'; } ?>">Be Come A Fan</a> </div> <!--BTN ADD CONTACT--> <?php if ($users[0]->id != $user_data['id']) { ?> <div class="col-md-12 searchform"> <a class="btn btn-default col-xs-12" href="#" style="margin-top: 20px;padding: 15px;" data-toggle="modal" data-target="#invite-contact">Add Contact Chat</a> </div> <?php } ?> <!--//BTN ADD CONTACT--> </div> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><a href="<?php echo base_url('social_media');?>"><img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_status.png" /> Stats</a></h2> <span class="liner_landing"></span> <div class="col-md-12"> <div class="wp_content_list"> <i class="fa fa-music"></i> <span class="full-w" style="font-size: 16px;margin-left: 15px;">Song Plays</span> <span class="full-w-tt" style="float: right;"><span style="color: #57ce57;font-size: 12px;margin-right: 20px;"></span><?php echo $num_songs;?></span> </div> <div class="wp_content_list"> <i class="fa fa-file-video-o"></i> <span class="full-w" style="font-size: 16px;margin-left: 15px;">Video Plays</span> <span class="full-w-tt" style="float: right;"><span style="color: #57ce57;font-size: 12px;margin-right: 20px;"></span><?php echo $num_videos;?></span> </div> <div class="wp_content_list"> <i class="fa fa-users"></i> <span class="full-w" style="font-size: 16px;margin-left: 15px;">Total Fans</span> <span class="full-w-tt" style="float: right;"><span style="color: #57ce57;font-size: 12px;margin-right: 20px;"></span><?php echo $num_fands; ?></span> </div> <div class="wp_content_list"> <i class="fa fa-hand-rock-o"></i> <span class="full-w" style="font-size: 16px;margin-left: 15px;">Total Events</span> <span class="full-w-tt" style="float: right;"><span style="color: #57ce57;font-size: 12px;margin-right: 20px;"></span><?php echo $num_events; ?></span> </div> <div class="wp_content_list"> <i class="fa fa-bookmark"></i> <span class="full-w" style="font-size: 16px;margin-left: 15px;">Total Blogs</span> <span class="full-w-tt" style="float: right;"><span style="color: #57ce57;font-size: 12px;margin-right: 20px;"></span><?php echo $num_blogs; ?></span> </div> <div class="wp_content_list"> <i class="fa fa-comments"></i> <span class="full-w" style="font-size: 16px;margin-left: 15px;">Total Comments</span> <span class="full-w-tt" style="float: right;"><span style="color: #57ce57;font-size: 12px;margin-right: 20px;"></span><?php echo $num_comments; ?></span> </div> </div> </div> <?php if (isset($fans) && count($fans) > 0) { ?> <div class="row col-md-12 part_session photos_session header_new_style"> <div class="remove_part"></div> <h2 class="tt text_caplock"><a href="<?php echo base_url('artist/allfans').'/'.$id; ?>"><img class="icon_part" src="<?php echo base_url(); ?>assets/images/icon/manager_quickactions.png" /> Fans</a></h2> <span class="liner_landing"></span> <div class="col-md-12 remove_padding"> <?php $i = 0; foreach ($fans as $fan) { ?> <div class="col-md-3 col-xs-3" style="<?php if ($i == 0 || $i = 1 || $i == 2 || $i == 3) { echo 'margin-bottom: 10px;'; } if ($i == 0 || $i == 4) { } else { echo 'margin-left:-5px'; } ?>"><a href="<?php echo base_url().$fan['home_page']; ?>"><img title="<?php echo $fan['artist_name']; ?>" style="min-height: 70px;max-height: 70px;" width="70" src="<?php if (!empty($fan['avata'])) { echo base_url().'uploads/'.$fan['user_id'].'/photo/'.$fan['avata']; } else { echo base_url().'assets/images/default-img.gif'; }; ?>"/></a></div> <?php ++$i; } ?> </div> </div> <?php } ?> </div> </div> </div> </div> </div> <!-- Modal comment --> <div class="modal fade new_modal_style" id="addComment" tabindex="-1" role="dialog" aria-labelledby="myModalcomment" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <form class="" action="<?php echo base_url().'artist/membercomment'?>" method="post"> <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>" /> <input type="hidden" name="id_artist" value="<?=$id?>" /> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="tt">Add a Comment</h4> <span class="liner"></span> </div> <div class="modal-body"> <div class="form-group"> <label class="form-input col-md-2">Comment</label> <div class="input-group col-md-9"> <textarea class="form-control" name="comment" rows="6" required="" ></textarea> </div> </div> </div> <div class="modal-footer searchform"> <button type="button" class="btn btn-default Dnew" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-default Dnew">Add</button> </div> </form> </div> </div> </div> <!-- Modal showEvent --> <div class="modal fade new_modal_style" id="showEvent" tabindex="-1" role="dialog" aria-labelledby="myModalcomment" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="tt" id="myModalevent">Add a Comment</h4> <span class="liner"></span> </div> <div class="modal-body"> <div class="col-md-12"> <img id="event_banner" src="" width="535" /> </div> <div class="col-md-12 text-center" style="margin-top: 10px;"> <span id="cat" style="font-weight: bold; font-size: 18px;"></span> </div> <div class="col-md-12" style="padding:10px 30px 0px 15px;"> <span style="float: left;">Start Date: <span id="start" ></span></span> <span style="float: right;">End Date: <span id="end" style="color: red;"></span></span> </div> <div class="col-md-12" style="padding: 20px 30px"> <span id="des"></span> </div> <div class="col-md-12"> <span>Post By: <span id="post-b" style="font-weight: bold;"></span></span> </div> <div class="col-md-12"> <span>Location: <span id="lo" style="font-weight: bold;"></span></span> </div> </div> <div class="modal-footer searchform" style="border-top: none;"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Modal Invite Contact --> <div class="modal fade" id="invite-contact" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title" id="myModalLabel">Invite Contact (<?=$this->M_user->get_name($users['0']->id)?>)</h4> </div> <form class="form form-signup" action="<?php echo base_url()?>chat/invite_contact" method="post" > <input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>" /> <div class="modal-body"> <div class="form-group"> <label class="form-input col-md-3">Messages</label> <div class="input-group col-md-8"> <input type="hidden" name ="user_invite" value="<?php echo $user_data['id']?>" /> <input type="hidden" name ="user_to" id="user_id2" value="<?php echo $users['0']->id?>" /> <textarea class="form-control" rows="5" name="messages_invite">Hi <?=$this->M_user->get_name($users['0']->id)?>, I'd like to add you as a contact.</textarea> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Add to Contacts</button> </div> </form> </div> </div> </div> <!--MODAL video--> <div class="modal fade" id="videos" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog modal-lg" role="document"> <div id="video"></div> <div class="close-pop"><a href="#" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span></a></div> </div> </div> <div class="modal fade" id="photos" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog text-center" role="document"> <img src="<?php echo base_url(); ?>assets/images/adaptable.jpg" width="500" height="400"/> </div> </div> </div> <script type="text/javascript"> var url = "<?php echo base_url(); ?>"; </script> <script src="<?php echo base_url(); ?>assets/landing-page/js/landing-page-1.js"></script>
akashbachhania/jeet99
application/views/landing/landing-page-9.php
PHP
mit
47,086
import {module, inject, createRootFactory} from '../mocks'; describe('solPopmenu directive', function () { let $compile; let $rootScope; let createRoot; let rootEl; beforeEach(module('karma.templates')); beforeEach(module('ui-kit')); beforeEach(inject((_$compile_, _$rootScope_) => { $compile = _$compile_; $rootScope = _$rootScope_; createRoot = createRootFactory($compile); let html = '<div><sol-popmenu icon="list">tranclusion</sol-popmenu></div>'; rootEl = createRoot(html, $rootScope); })); it('should replace the element', () => { let menu = rootEl.find('.popmenu-popup .popmenu-content'); expect(rootEl).not.toContainElement('sol-popmenu'); }); it('should transclude content inside a ".popmenu-popup .popmenu-content" element', () => { let menu = rootEl.find('.popmenu-popup .popmenu-content'); expect(menu).toHaveText('tranclusion'); }); it('should add "fa fa-<icon>" class on toggler according to icon attribute', () => { let toggler = rootEl.find('.popmenu-toggler'); expect(toggler).toHaveClass('fa fa-list'); }); it('should toggle the "closed" class on .popmenu once the .popmenu-toggler clicked', () => { let menu = rootEl.find('.popmenu'); let toggler = rootEl.find('.popmenu-toggler'); expect(menu).not.toHaveClass('closed'); toggler.click(); toggler.click(); $rootScope.$digest(); expect(menu).toHaveClass('closed'); }); it('contains a .popmenu-toggler element', () => { let html = '<div><sol-popmenu></sol-popmenu></div>'; let rootEl = createRoot(html, $rootScope); expect(rootEl).toContainElement('.popmenu-toggler'); }); it('contains a .popmenu element', () => { let html = '<div><sol-popmenu></sol-popmenu></div>'; let rootEl = createRoot(html, $rootScope); expect(rootEl).toContainElement('.popmenu'); }); });
Tudmotu/solarizd
src/test/ui-kit/sol-popmenu.js
JavaScript
mit
2,050
package heap const ( ACC_PUBLIC = 0x0001 ACC_PRIVATE = 0x0002 ACC_PROTECTED = 0x0004 ACC_STATIC = 0x0008 ACC_FINAL = 0x0010 ACC_SUPER = 0x0020 ACC_SYNCHRONIZED = 0x0020 ACC_VOLATILE = 0x0040 ACC_BRIDGE = 0x0040 ACC_TRANSIENT = 0x0080 ACC_VARARGS = 0x0080 ACC_NATIVE = 0x0100 ACC_INTERFACE = 0x0200 ACC_ABSTRACT = 0x0400 ACC_STRICT = 0x0800 ACC_SYNTHETIC = 0x1000 ACC_ANNOTATION = 0x2000 ACC_ENUM = 0x4000 )
Frederick-S/jvmgo
runtime_data_area/heap/access_flags.go
GO
mit
510
<?php /******************************************************************************* * * filename : Reports/FRBidSheets.php * last change : 2003-08-30 * description : Creates a PDF with a silent auction bid sheet for every item. ******************************************************************************/ require '../Include/Config.php'; require '../Include/Functions.php'; require '../Include/ReportFunctions.php'; use ChurchCRM\dto\SystemConfig; use ChurchCRM\Reports\ChurchInfoReport; $iCurrentFundraiser = $_GET['CurrentFundraiser']; class PDF_FRBidSheetsReport extends ChurchInfoReport { // Constructor public function __construct() { parent::__construct('P', 'mm', $this->paperFormat); $this->leftX = 10; $this->SetFont('Times', '', 10); $this->SetMargins(15, 25); $this->SetAutoPageBreak(true, 25); } public function AddPage($orientation = '', $format = '') { global $fr_title, $fr_description; parent::AddPage($orientation, $format); // $this->SetFont("Times",'B',16); // $this->Write (8, $fr_title."\n"); // $curY += 8; // $this->Write (8, $fr_description."\n\n"); // $curY += 8; // $this->SetFont("Times",'',10); } } // Get the information about this fundraiser $sSQL = 'SELECT * FROM fundraiser_fr WHERE fr_ID='.$iCurrentFundraiser; $rsFR = RunQuery($sSQL); $thisFR = mysqli_fetch_array($rsFR); extract($thisFR); // Get all the donated items $sSQL = 'SELECT * FROM donateditem_di LEFT JOIN person_per on per_ID=di_donor_ID '. ' WHERE di_FR_ID='.$iCurrentFundraiser. ' ORDER BY SUBSTR(di_item,1,1),cast(SUBSTR(di_item,2) as unsigned integer),SUBSTR(di_item,4)'; $rsItems = RunQuery($sSQL); $pdf = new PDF_FRBidSheetsReport(); $pdf->SetTitle($fr_title); // Loop through items while ($oneItem = mysqli_fetch_array($rsItems)) { extract($oneItem); $pdf->AddPage(); $pdf->SetFont('Times', 'B', 24); $pdf->Write(5, $di_item.":\t"); $pdf->Write(5, stripslashes($di_title)."\n\n"); $pdf->SetFont('Times', '', 16); $pdf->Write(8, stripslashes($di_description)."\n"); if ($di_estprice > 0) { $pdf->Write(8, gettext('Estimated value ').'$'.$di_estprice.'. '); } if ($per_LastName != '') { $pdf->Write(8, gettext('Donated by ').$per_FirstName.' '.$per_LastName.".\n"); } $pdf->Write(8, "\n"); $widName = 100; $widPaddle = 30; $widBid = 40; $lineHeight = 7; $pdf->SetFont('Times', 'B', 16); $pdf->Cell($widName, $lineHeight, gettext('Name'), 1, 0); $pdf->Cell($widPaddle, $lineHeight, gettext('Paddle'), 1, 0); $pdf->Cell($widBid, $lineHeight, gettext('Bid'), 1, 1); if ($di_minimum > 0) { $pdf->Cell($widName, $lineHeight, '', 1, 0); $pdf->Cell($widPaddle, $lineHeight, '', 1, 0); $pdf->Cell($widBid, $lineHeight, '$'.$di_minimum, 1, 1); } for ($i = 0; $i < 20; $i += 1) { $pdf->Cell($widName, $lineHeight, '', 1, 0); $pdf->Cell($widPaddle, $lineHeight, '', 1, 0); $pdf->Cell($widBid, $lineHeight, '', 1, 1); } } header('Pragma: public'); // Needed for IE when using a shared SSL certificate if (SystemConfig::getValue('iPDFOutputType') == 1) { $pdf->Output('FRBidSheets'.date(SystemConfig::getValue("sDateFilenameFormat")).'.pdf', 'D'); } else { $pdf->Output(); }
ChurchCRM/CRM
src/Reports/FRBidSheets.php
PHP
mit
3,387
import React from 'react' import Button from 'components/Button' import Flex from 'components/Flex' import { Explanation, TextStep, Buttons } from '../styles' import explanation from 'images/bearing-explanation.svg' export class Step extends React.Component { render () { return ( <TextStep> <div> <h2>Thanks!</h2> <p> If it’s clear which way the camera is pointing, you can go to the next step and try marking the direction and angle of the view of the image. </p> <p> <Explanation alt='Camera and target' title='Camera and target' src={explanation} /> </p> </div> <Buttons> <Flex justifyContent='flex-end'> <Button onClick={this.props.skip} type='skip'>Skip</Button> <Button onClick={this.props.next} type='submit'>Continue</Button> </Flex> </Buttons> </TextStep> ) } } export default Step
nypl-spacetime/where
app/containers/Steps/BearingIntroduction/index.js
JavaScript
mit
985
<?php return array ( 'id' => 'huawei_y220_ver1_subuau10', 'fallback' => 'huawei_y220_ver1', 'capabilities' => array ( 'model_name' => 'Y220-U10', ), );
cuckata23/wurfl-data
data/huawei_y220_ver1_subuau10.php
PHP
mit
167
<?php class Remisiones_model { //status de las remisiones protected $statusRemisionPorAutorizar = 2; protected $statusRemisionCancelada = 3; protected $statusRemisionRechazada = 4; protected $statusRemisionAplicada = 5; function aceptaRemision($remisionID,$comentarios,$contactoID,$link) { //cambiamos el status de la remision $s = "UPDATE t_remision SET remision_status_id = $this->statusRemisionAplicada WHERE remision_id = '$remisionID'"; $q = mysqli_query($link,$s) or die (mysqli_error($link)); //insertamos en el log el cambio de status de la remision $this->insertaRemisionLog($this->statusRemisionAplicada,$contactoID,$remisionID,$link); //insertamos el comentario de la remision $s2 = "INSERT INTO t_remision_comentario(contacto_id, remision_comentario_comm, remision_id, remision_comentario_titulo, remision_comentario_fecha) VALUES($contactoID, '$comentarios', $remisionID, 'Remision Aceptada', NOW())"; $q2 = mysqli_query($link,$s2) or die (mysqli_error($link)); $comentarioID = mysqli_insert_id($link); $s3 = "SELECT remision_comentario_fecha AS fechaComentario FROM t_remision_comentario WHERE remision_comentario_id = $comentarioID"; $q3 = mysqli_query($link,$s3) or die (mysqli_error($link)); $r3 = mysqli_fetch_assoc($q3); //pendiente incorporar transacciones return $r3["fechaComentario"]; } function getComentariosRemision($remisionID,$link) { $s = " SELECT (IF(ISNULL(crem.contacto_id),(SELECT CONCAT(usuario_nombre,' ',usuario_apellido) FROM t_usuario WHERE usuario_id = crem.usuario_id), (SELECT CONCAT(contacto_nombre,' ',contacto_apellido) FROM t_contacto WHERE contacto_id = crem.contacto_id))) AS nombreUsuario, crem.remision_comentario_titulo AS comentarioTitulo, crem.remision_comentario_fecha AS comentarioFecha, crem.remision_comentario_comm AS comentarioRemision FROM t_remision_comentario crem WHERE crem.remision_id = $remisionID ORDER BY crem.remision_comentario_id DESC "; $q = mysqli_query($link,$s) or die (mysqli_error($link)); $rows = mysqli_num_rows($q); if ($rows > 0) { while ($r = mysqli_fetch_assoc($q)) { $resultado[] = $r; } return $resultado; }else{ return false; } } function getInfoRemision($remisionHash,$link) { $s = " SELECT rem.remision_id AS remisionID, rstat.remision_status_nombre AS remisionStatus, cli.cliente_razon AS cliente, rem.remision_correos AS correosContacto, rem.remision_planta AS asignadoPlanta, rem.remision_ubicacion AS asignadoUbicacion, asig.asignado_ccosto AS asignadoCentroCosto, rem.remision_fecha_alta AS remisionFecha, contipo.contrato_tipo_nombre AS tipoContrato, rem.remision_subtotal AS remisionSubtotal, rem.remision_iva AS remisionIva, rem.remision_total AS remisionTotal, rem.remision_folio AS remisionFolio, asig.asignado_costo AS precioUnitario, asig.asignado_id AS asignadoID, con.contrato_numero_proveedor AS numeroProveedor, con.contrato_numero AS numeroContrato, con.contrato_numero_pedido AS numeroPedido, rem.remision_subtotal_fijo AS subtotalFijo FROM t_remision rem INNER JOIN t_remision_status rstat ON rem.remision_status_id = rstat.remision_status_id INNER JOIN t_asignado asig ON rem.asignado_id = asig.asignado_id INNER JOIN t_contrato con ON con.contrato_id = asig.contrato_id INNER JOIN t_cliente cli ON asig.cliente_id = cli.cliente_id INNER JOIN t_contrato_tipo contipo ON contipo.contrato_tipo_id = asig.asignado_tipo_contrato WHERE rem.remision_encripta = '$remisionHash' "; $q = mysqli_query($link,$s) or die (mysqli_error($link)); $r = mysqli_fetch_assoc($q); $resultado = mysqli_num_rows($q); if ($resultado > 0) { return $r; }else{ return false; } } function getInfoContactoAsignado($contactoID,$numeroCorreo,$link) { $correoSeleccionado = "contacto_correo".$numeroCorreo; $s = " SELECT CONCAT(contacto_nombre,' ',contacto_apellido) AS contacto_nombre, $correoSeleccionado AS correoContacto, contacto_tel1 AS contactoTel1 FROM t_contacto WHERE contacto_id = $contactoID "; $q = mysqli_query($link,$s) or die (mysqli_error($link)); $r = mysqli_fetch_assoc($q); return $r; } function getPeriodo($remisionID,$link) { //obtener la fecha de la remision $s = " SELECT DATE(rem.remision_fecha_alta) AS remisionFecha, rem.asignado_id AS asignadoID, asig.asignado_dia_corte AS diaCorte, ctasig.asignado_corte_tipo_nombre AS tipoCorte FROM t_remision rem INNER JOIN t_asignado asig ON asig.asignado_id = rem.asignado_id INNER JOIN t_asignado_corte_tipo ctasig ON ctasig.asignado_corte_tipo_id = asig.asignado_corte_tipo_id WHERE rem.remision_id = $remisionID "; $q = mysqli_query($link,$s) or die (mysqli_error($link)); $r = mysqli_fetch_assoc($q); $resultado["fechaActual"] = $r["remisionFecha"]; //ahora obtenemos la fecha del periodo anterior, buscando la remision anterior que corresponda al mismo asignado $s2 = " SELECT DATE(remision_fecha_alta) AS remisionFecha FROM t_remision WHERE asignado_id = $r[asignadoID] AND DATE(remision_fecha_alta) < '$r[remisionFecha]' AND remision_id NOT IN($remisionID) AND (remision_status_id = 2 OR remision_status_id = 5) ORDER BY remision_id DESC LIMIT 1 "; $q2 = mysqli_query($link,$s2) or die (mysqli_error($link)); //si la consulta arrojo un resultado, se tomara la fecha de la remision anterior if (mysqli_num_rows($q2) > 0) { if ($r["tipoCorte"] == "Dia de Corte") { //descomponemos la fecha para obtener el mes de la remision actual, y envez de poner el dia actial ponemos el dia de corte $fechaArray = explode("-",$resultado["fechaActual"]); $resultado["fechaActual"] = $fechaArray[0]."-".$fechaArray[1]."-".$r["diaCorte"]; //calculamos la fecha anterior, restando un mes al mes de la fecha actual $mesAnterior = $fechaArray[1] - 1; if ($mesAnterior == 0) { $mesAnterior = "12"; }elseif($mesAnterior > 0 && $mesAnterior < 10){ $mesAnterior = "0$mesAnterior"; } $diaFechaAnterior = $r["diaCorte"] + 1; $resultado["fechaAnterior"] = $fechaArray[0]."-".$mesAnterior."-".$diaFechaAnterior; }else{ //este es corte por mes completo //descomponemos la fecha para obtener el mes de la remision actual, y envez de poner el dia actual ponemos el dia de corte $fechaArray = explode("-",$resultado["fechaActual"]); $days = date("t"); $resultado["fechaActual"] = $fechaArray[0]."-".$fechaArray[1]."-$days"; $resultado["fechaAnterior"] = $fechaArray[0]."-".$fechaArray[1]."-01"; } }else{ //si la consulta no arrojo un resultado, se toma la fecha de inicio de operacion de la asignacion de equipo $s3 = "SELECT DATE(asignado_inicio_operacion) AS asignadoFecha, asignado_primera_remision_completa AS periodoCompleto FROM t_asignado WHERE asignado_id = $r[asignadoID]"; $q3 = mysqli_query($link,$s3) or die (mysqli_error($link)); $infoAsignado = mysqli_fetch_assoc($q3); if ($infoAsignado["periodoCompleto"] == 1) { if ($r["tipoCorte"] == "Dia de Corte") { //descomponemos la fecha para obtener el mes de la remision actual, y envez de poner el dia actial ponemos el dia de corte $fechaArray = explode("-",$resultado["fechaActual"]); $resultado["fechaActual"] = $fechaArray[0]."-".$fechaArray[1]."-".$r["diaCorte"]; //calculamos la fecha anterior, restando un mes al mes de la fecha actual $mesAnterior = $fechaArray[1] - 1; if ($mesAnterior == 0) { $mesAnterior = "12"; }elseif($mesAnterior > 0 && $mesAnterior < 10){ $mesAnterior = "0$mesAnterior"; } $diaFechaAnterior = $r["diaCorte"] + 1; $resultado["fechaAnterior"] = $fechaArray[0]."-".$mesAnterior."-".$diaFechaAnterior; }else{ //este es corte por mes completo //descomponemos la fecha para obtener el mes de la remision actual, y envez de poner el dia actual ponemos el dia de corte $fechaArray = explode("-",$resultado["fechaActual"]); $days = date("t"); $resultado["fechaActual"] = $fechaArray[0]."-".$fechaArray[1]."-$days"; $resultado["fechaAnterior"] = $fechaArray[0]."-".$fechaArray[1]."-01"; } }else{ $resultado["fechaAnterior"] = $infoAsignado["asignadoFecha"]; } } return $resultado; } function getPartidasRemision($remisionID,$link) { $s = " SELECT pro.producto_serie AS productoSerie, CONCAT(ptip.producto_tipo_nombre,' ',mar.producto_marca_nombre,' ',mode.producto_modelo_nombre) AS productoDescripcion, prem.partida_remision_contador_ini AS contadorIni, prem.partida_remision_contador_fin AS contadorFin, prem.partida_remision_tipo AS tipoImpresion, prem.partida_remision_id AS partidaID, prem.remision_id AS remisionID, prem.partida_remision_total AS partidaImporte, (prem.partida_remision_contador_fin - prem.partida_remision_contador_ini) consumo, prem.asignado_soporte_leyenda AS soporteLeyenda, mode.producto_modelo_nombre AS productoModelo, (SELECT SUM(partida_remision_contador_fin) FROM t_partida_remision WHERE producto_id = pro.producto_id AND remision_id = $remisionID) AS contadorTotalEquipo FROM t_partida_remision prem INNER JOIN t_producto pro ON pro.producto_id = prem.producto_id INNER JOIN t_producto_modelo mode ON mode.producto_modelo_id = pro.producto_modelo_id INNER JOIN t_producto_marca mar ON mar.producto_marca_id = mode.producto_marca_id INNER JOIN t_producto_tipo ptip ON ptip.producto_tipo_id = pro.producto_tipo_id WHERE prem.remision_id = $remisionID "; $q = mysqli_query($link,$s) or die (mysqli_error($link)); while ($r = mysqli_fetch_assoc($q)) { $resultado[] = $r; } return $resultado; } function getPartidasExcedente($remisionID,$link) { $s = " SELECT pro.producto_serie AS productoSerie, CONCAT(ptip.producto_tipo_nombre,' ',mar.producto_marca_nombre,' ',mode.producto_modelo_nombre) AS productoDescripcion, prem.partida_remision_contador_ini AS contadorIni, prem.partida_remision_contador_fin AS contadorFin, prem.partida_remision_tipo AS tipoImpresion, prem.partida_remision_id AS partidaID, prem.remision_id AS remisionID, prem.partida_remision_total AS partidaImporte, (prem.partida_remision_contador_fin - prem.partida_remision_contador_ini) consumo, prem.asignado_soporte_leyenda AS soporteLeyenda, (premex.partida_remision_excedente_cantidad * premex.partida_remision_excedente_precio) AS importeExcedente, premex.partida_remision_excedente_cantidad AS cantidadExcedente, premex.partida_remision_excedente_precio AS precioExcedente FROM t_partida_remision_excedente premex INNER JOIN t_partida_remision prem ON prem.partida_remision_id = premex.partida_remision_id INNER JOIN t_producto pro ON pro.producto_id = prem.producto_id INNER JOIN t_producto_modelo mode ON mode.producto_modelo_id = pro.producto_modelo_id INNER JOIN t_producto_marca mar ON mar.producto_marca_id = mode.producto_marca_id INNER JOIN t_producto_tipo ptip ON ptip.producto_tipo_id = pro.producto_tipo_id WHERE premex.remision_id = $remisionID "; $q = mysqli_query($link,$s) or die (mysqli_error($link)); if (mysqli_num_rows($q) > 0) { while ($r = mysqli_fetch_assoc($q)) { $resultado[] = $r; } return $resultado; }else{ return false; } } function historialConsumo($asignadoID,$link) { $s = " SELECT prem.partida_remision_contador_ini AS contadorIni, prem.partida_remision_contador_fin AS contadorFin, (prem.partida_remision_contador_fin - prem.partida_remision_contador_ini) consumo, prem.partida_remision_tipo AS tipoImpresion, prem.partida_remision_total AS partidaImporte, DATE(rem.remision_fecha_alta) AS fechaRemision, rem.remision_id AS remisionID, pro.producto_serie AS productoSerie, prem.asignado_soporte_leyenda AS soporteLeyenda FROM t_partida_remision prem INNER JOIN t_remision rem ON rem.remision_id = prem.remision_id INNER JOIN t_producto pro ON pro.producto_id = prem.producto_id WHERE rem.asignado_id = $asignadoID AND (rem.remision_status_id = 2 OR rem.remision_status_id = 5) "; $q = mysqli_query($link,$s) or die (mysqli_error($link)); while ($r = mysqli_fetch_assoc($q)) { $resultado[] = $r; } return $resultado; } function insertarComentarioRemision($campos,$link) { $s = "INSERT INTO t_remision_comentario(remision_comentario_comm, remision_id, remision_comentario_fecha, remision_comentario_titulo, contacto_id) VALUES('$campos[comentarios]',$campos[remisionID],NOW(),'$campos[asunto]',$campos[contactoID])"; if(mysqli_query($link,$s)){ return true; }else{ return false; } } function insertaRemisionLog($status,$contactoID,$remisionID,$link) { $s = "INSERT INTO t_remision_log(contacto_id, remision_status_id, remision_id, remision_log_fecha) VALUES($contactoID,$status,$remisionID,NOW())"; $q = mysqli_query($link,$s) or die (mysqli_error($link)); //devolvemos el id de log insertado return mysqli_insert_id($link); } function rechazaRemision($remisionID,$comentarios,$contactoID,$link) { //cambiamos el status de la remision $s = "UPDATE t_remision SET remision_status_id = $this->statusRemisionRechazada WHERE remision_id = '$remisionID'"; $q = mysqli_query($link,$s) or die (mysqli_error($link)); //insertamos en el log el cambio de status de la remision $this->insertaRemisionLog($this->statusRemisionRechazada,$contactoID,$remisionID,$link); //insertamos el comentario de la remision $s2 = "INSERT INTO t_remision_comentario(contacto_id, remision_comentario_comm, remision_id, remision_comentario_titulo, remision_comentario_fecha) VALUES($contactoID, '$comentarios', $remisionID, 'Remision Rechazada', NOW())"; $q2 = mysqli_query($link,$s2) or die (mysqli_error($link)); $comentarioID = mysqli_insert_id($link); $s3 = "SELECT remision_comentario_fecha AS fechaComentario FROM t_remision_comentario WHERE remision_comentario_id = $comentarioID"; $q3 = mysqli_query($link,$s3) or die (mysqli_error($link)); $r3 = mysqli_fetch_assoc($q3); //pendiente incorporar transacciones return $r3["fechaComentario"]; } } ?>
georgesks/digirey
versiones/v0_8_0/ws/models/remisiones_model.php
PHP
mit
14,580
# frozen_string_literal: true require "concurrent/map" require "active_support/core_ext/module/attribute_accessors" require "action_view/template/resolver" module ActionView # = Action View Lookup Context # # <tt>LookupContext</tt> is the object responsible for holding all information # required for looking up templates, i.e. view paths and details. # <tt>LookupContext</tt> is also responsible for generating a key, given to # view paths, used in the resolver cache lookup. Since this key is generated # only once during the request, it speeds up all cache accesses. class LookupContext #:nodoc: attr_accessor :prefixes, :rendered_format deprecate :rendered_format deprecate :rendered_format= mattr_accessor :fallbacks, default: FallbackFileSystemResolver.instances mattr_accessor :registered_details, default: [] def self.register_detail(name, &block) registered_details << name Accessors::DEFAULT_PROCS[name] = block Accessors.define_method(:"default_#{name}", &block) Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1 def #{name} @details[:#{name}] || [] end def #{name}=(value) value = value.present? ? Array(value) : default_#{name} _set_detail(:#{name}, value) if value != @details[:#{name}] end METHOD end # Holds accessors for the registered details. module Accessors #:nodoc: DEFAULT_PROCS = {} end register_detail(:locale) do locales = [I18n.locale] locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks locales << I18n.default_locale locales.uniq! locales end register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css, :xml, :json] } register_detail(:variants) { [] } register_detail(:handlers) { Template::Handlers.extensions } class DetailsKey #:nodoc: alias :eql? :equal? @details_keys = Concurrent::Map.new @digest_cache = Concurrent::Map.new def self.digest_cache(details) @digest_cache[details_cache_key(details)] ||= Concurrent::Map.new end def self.details_cache_key(details) if details[:formats] details = details.dup details[:formats] &= Template::Types.symbols end @details_keys[details] ||= Object.new end def self.clear ActionView::ViewPaths.all_view_paths.each do |path_set| path_set.each(&:clear_cache) end ActionView::LookupContext.fallbacks.each(&:clear_cache) @view_context_class = nil @details_keys.clear @digest_cache.clear end def self.digest_caches @digest_cache.values end def self.view_context_class(klass) @view_context_class ||= klass.with_empty_template_cache end end # Add caching behavior on top of Details. module DetailsCache attr_accessor :cache # Calculate the details key. Remove the handlers from calculation to improve performance # since the user cannot modify it explicitly. def details_key #:nodoc: @details_key ||= DetailsKey.details_cache_key(@details) if @cache end # Temporary skip passing the details_key forward. def disable_cache old_value, @cache = @cache, false yield ensure @cache = old_value end private def _set_detail(key, value) # :doc: @details = @details.dup if @digest_cache || @details_key @digest_cache = nil @details_key = nil @details[key] = value end end # Helpers related to template lookup using the lookup context information. module ViewPaths attr_reader :view_paths, :html_fallback_for_js def find(name, prefixes = [], partial = false, keys = [], options = {}) @view_paths.find(*args_for_lookup(name, prefixes, partial, keys, options)) end alias :find_template :find alias :find_file :find deprecate :find_file def find_all(name, prefixes = [], partial = false, keys = [], options = {}) @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options)) end def exists?(name, prefixes = [], partial = false, keys = [], **options) @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options)) end alias :template_exists? :exists? def any?(name, prefixes = [], partial = false) @view_paths.exists?(*args_for_any(name, prefixes, partial)) end alias :any_templates? :any? # Adds fallbacks to the view paths. Useful in cases when you are rendering # a :file. def with_fallbacks view_paths = build_view_paths((@view_paths.paths + self.class.fallbacks).uniq) if block_given? ActiveSupport::Deprecation.warn <<~eowarn.squish Calling `with_fallbacks` with a block is deprecated. Call methods on the lookup context returned by `with_fallbacks` instead. eowarn begin _view_paths = @view_paths @view_paths = view_paths yield ensure @view_paths = _view_paths end else ActionView::LookupContext.new(view_paths, @details, @prefixes) end end private # Whenever setting view paths, makes a copy so that we can manipulate them in # instance objects as we wish. def build_view_paths(paths) ActionView::PathSet.new(Array(paths)) end def args_for_lookup(name, prefixes, partial, keys, details_options) name, prefixes = normalize_name(name, prefixes) details, details_key = detail_args_for(details_options) [name, prefixes, partial || false, details, details_key, keys] end # Compute details hash and key according to user options (e.g. passed from #render). def detail_args_for(options) # :doc: return @details, details_key if options.empty? # most common path. user_details = @details.merge(options) if @cache details_key = DetailsKey.details_cache_key(user_details) else details_key = nil end [user_details, details_key] end def args_for_any(name, prefixes, partial) name, prefixes = normalize_name(name, prefixes) details, details_key = detail_args_for_any [name, prefixes, partial || false, details, details_key] end def detail_args_for_any @detail_args_for_any ||= begin details = {} registered_details.each do |k| if k == :variants details[k] = :any else details[k] = Accessors::DEFAULT_PROCS[k].call end end if @cache [details, DetailsKey.details_cache_key(details)] else [details, nil] end end end # Support legacy foo.erb names even though we now ignore .erb # as well as incorrectly putting part of the path in the template # name instead of the prefix. def normalize_name(name, prefixes) prefixes = prefixes.presence parts = name.to_s.split("/") parts.shift if parts.first.empty? name = parts.pop return name, prefixes || [""] if parts.empty? parts = parts.join("/") prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts] return name, prefixes end end include Accessors include DetailsCache include ViewPaths def initialize(view_paths, details = {}, prefixes = []) @details_key = nil @digest_cache = nil @cache = true @prefixes = prefixes @details = initialize_details({}, details) @view_paths = build_view_paths(view_paths) end def digest_cache @digest_cache ||= DetailsKey.digest_cache(@details) end def with_prepended_formats(formats) details = @details.dup details[:formats] = formats self.class.new(@view_paths, details, @prefixes) end def initialize_details(target, details) registered_details.each do |k| target[k] = details[k] || Accessors::DEFAULT_PROCS[k].call end target end private :initialize_details # Override formats= to expand ["*/*"] values and automatically # add :html as fallback to :js. def formats=(values) if values values = values.dup values.concat(default_formats) if values.delete "*/*" values.uniq! invalid_values = (values - Template::Types.symbols) unless invalid_values.empty? raise ArgumentError, "Invalid formats: #{invalid_values.map(&:inspect).join(", ")}" end if values == [:js] values << :html @html_fallback_for_js = true end end super(values) end # Override locale to return a symbol instead of array. def locale @details[:locale].first end # Overload locale= to also set the I18n.locale. If the current I18n.config object responds # to original_config, it means that it has a copy of the original I18n configuration and it's # acting as proxy, which we need to skip. def locale=(value) if value config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config config.locale = value end super(default_locale) end end end
shioyama/rails
actionview/lib/action_view/lookup_context.rb
Ruby
mit
9,597
# -*- coding: utf-8 -*- import scrapy from locations.items import GeojsonPointItem DAYS = [ 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su' ] class SparNoSpider(scrapy.Spider): name = "spar_no" allowed_domains = ["spar.no"] start_urls = ( 'https://spar.no/Finn-butikk/', ) def parse(self, response): shops = response.xpath('//div[@id="js_subnav"]//li[@class="level-1"]/a/@href') for shop in shops: yield scrapy.Request( response.urljoin(shop.extract()), callback=self.parse_shop ) def parse_shop(self, response): props = {} ref = response.xpath('//h1[@itemprop="name"]/text()').extract_first() if ref: # some links redirects back to list page props['ref'] = ref.strip("\n").strip() else: return days = response.xpath('//div[@itemprop="openingHoursSpecification"]') if days: for day in days: day_list = day.xpath('.//link[@itemprop="dayOfWeek"]/@href').extract() first = 0 last = 0 for d in day_list: st = d.replace('https://purl.org/goodrelations/v1#', '')[:2] first = DAYS.index(st) if first>DAYS.index(st) else first last = DAYS.index(st) if first>DAYS.index(st) else first props['opening_hours'] = DAYS[first]+'-'+DAYS[last]+' '+day.xpath('.//meta[@itemprop="opens"]/@content').extract_first()+' '+day.xpath('.//meta[@itemprop="closes"]/@content').extract_first() phone = response.xpath('//a[@itemprop="telephone"]/text()').extract_first() if phone: props['phone'] = phone addr_full = response.xpath('//div[@itemprop="streetAddress"]/text()').extract_first() if addr_full: props['addr_full'] = addr_full postcode = response.xpath('//span[@itemprop="postalCode"]/text()').extract_first() if postcode: props['postcode'] = postcode city = response.xpath('//span[@itemprop="addressLocality"]/text()').extract_first() if city: props['city'] = city.strip() props['country'] = 'NO' lat = response.xpath('//meta[@itemprop="latitude"]/@content').extract_first() lon = response.xpath('//meta[@itemprop="longitude"]/@content').extract_first() if lat and lon: props['lat'] = float(lat) props['lon'] = float(lon) props['website'] = response.url yield GeojsonPointItem(**props)
iandees/all-the-places
locations/spiders/spar_no.py
Python
mit
2,746
""" Controller for voting related requests. """ import webapp2 from models.vote import VoteHandler from models.vote_.cast_ballot import BallotHandler from models.vote_.view_results import ResultsHandler app = webapp2.WSGIApplication([ ('/vote', VoteHandler), ('/vote/cast-ballot', BallotHandler), ('/vote/view-results', ResultsHandler) ], debug=True)
rice-apps/rice-elections
src/controllers/vote.py
Python
mit
365
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController # You should configure your model like this: # devise :omniauthable, omniauth_providers: [:twitter] # You should also create an action method in this controller like this: # def twitter # end # More info at: # https://github.com/plataformatec/devise#omniauth # GET|POST /resource/auth/twitter # def passthru # super # end # GET|POST /users/auth/twitter/callback # def failure # super # end # protected # The path used when OmniAuth fails # def after_omniauth_failure_path_for(scope) # super(scope) # end skip_before_action :verify_authenticity_token def sign_in_with(provider_name) @user = User.from_omniauth(request.env["omniauth.auth"]) # binding.pry sign_in_and_redirect @user, :event => :authentication set_flash_message(:notice, :success, :kind => provider_name) if is_navigational_format? end def facebook sign_in_with "Facebook" end def google_oauth2 sign_in_with "Google" end end
reginad1/skipdamenu
app/controllers/users/omniauth_callbacks_controller.rb
Ruby
mit
1,064
<?php abstract class ModuleGridEngine extends ModuleGridEngineCore { }
timetre/tnk
web/store/override/classes/module/ModuleGridEngine.php
PHP
mit
74
<?php $this->setProperty('author', 'Friends Of REDAXO'); if (rex::isBackend() && rex::getUser()) { rex_perm::register('modulsammlung[]'); rex_extension::register('PACKAGES_INCLUDED', function () { if (rex::getUser() && $this->getProperty('compile')) { $compiler = new rex_scss_compiler(); $scss_files = rex_extension::registerPoint(new rex_extension_point('BE_STYLE_SCSS_FILES', [$this->getPath('scss/master.scss')])); $compiler->setScssFile($scss_files); $compiler->setCssFile($this->getPath('assets/css/styles.css')); $compiler->compile(); rex_file::copy($this->getPath('assets/css/styles.css'), $this->getAssetsPath('css/styles.css')); } }); rex_view::addCssFile($this->getAssetsUrl('css/styles.css')); }
FriendsOfREDAXO/Modulsammlung
boot.php
PHP
mit
773
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import config.io.FolderManager; import config.misc.GlobalIgnoreList; import config.misc.GlobalSettings; public class KspModuleEditor { public static void main(String[] args){ try { Scanner scanner = new Scanner(new File("GlobalSettings.txt")); while(scanner.hasNext()) { String inLine = scanner.next().replaceAll("\\s", ""); if(inLine.startsWith("AddMechJeb=")) { GlobalSettings.addMechjeb = Boolean.parseBoolean(inLine.replace("AddMechJeb=", "")); } else if(inLine.startsWith("AddProtractor=")) { GlobalSettings.addProtractor = Boolean.parseBoolean(inLine.replace("AddProtractor=", "")); } else if(inLine.startsWith("AddDeadlyReentry=")) { GlobalSettings.addDeadlyReentry = Boolean.parseBoolean(inLine.replace("AddDeadlyReentry=", "")); } } scanner.close(); } catch (FileNotFoundException e) { // TODO proper error handling // we'll just keep the defaults for now... e.printStackTrace(); } try{ Scanner scanner = new Scanner(new File("FilesAndFoldersToIgnore.txt")); boolean fileMode = true; while(scanner.hasNext()) { String inLine = scanner.next().trim(); if(inLine.equals("")) { continue; } else if(inLine.equals("#Folders")) { fileMode = false; } else if(inLine.equals("#Files")) { fileMode = true; } else if(fileMode) { GlobalIgnoreList.filesToIgnore.add(inLine); } else { GlobalIgnoreList.foldersToIgnore.add(inLine); } } scanner.close(); } catch (FileNotFoundException e) { // TODO proper error handling e.printStackTrace(); } FolderManager.applyChanges(); } }
Brians200/KSP-Module-Adder
src/KspModuleEditor.java
Java
mit
1,792
export { default } from './ElectronOriginalWordmark'
fpoumian/react-devicon
src/components/electron/original-wordmark/index.js
JavaScript
mit
53
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'pronto/tailor'
ajanauskas/pronto-tailor
spec/spec_helper.rb
Ruby
mit
83
from galaxy.test.base.twilltestcase import TwillTestCase #from twilltestcase import TwillTestCase class EncodeTests(TwillTestCase): def test_00_first(self): # will run first due to its name """3B_GetEncodeData: Clearing history""" self.clear_history() def test_10_Encode_Data(self): """3B_GetEncodeData: Getting encode data""" self.run_tool('encode_import_chromatin_and_chromosomes1', hg17=['cc.EarlyRepSeg.20051216.bed'] ) # hg17=[ "cc.EarlyRepSeg.20051216.bed", "cc.EarlyRepSeg.20051216.gencode_partitioned.bed", "cc.LateRepSeg.20051216.bed", "cc.LateRepSeg.20051216.gencode_partitioned.bed", "cc.MidRepSeg.20051216.bed", "cc.MidRepSeg.20051216.gencode_partitioned.bed" ] ) self.wait() self.check_data('cc.EarlyRepSeg.20051216.bed', hid=1) # self.check_data('cc.EarlyRepSeg.20051216.gencode_partitioned.bed', hid=2) # self.check_data('cc.LateRepSeg.20051216.bed', hid=3) # self.check_data('cc.LateRepSeg.20051216.gencode_partitioned.bed', hid=4) # self.check_data('cc.MidRepSeg.20051216.bed', hid=5) # self.check_data('cc.MidRepSeg.20051216.gencode_partitioned.bed', hid=6)
jmchilton/galaxy-central
galaxy/test/functional/test_3B_GetEncodeData.py
Python
mit
1,185
import click from bitshares.amount import Amount from .decorators import online, unlock from .main import main, config from .ui import print_tx @main.group() def htlc(): pass @htlc.command() @click.argument("to") @click.argument("amount") @click.argument("symbol") @click.option( "--type", type=click.Choice(["ripemd160", "sha1", "sha256", "hash160"]), default="sha256", prompt="Hash algorithm", show_default=True, help="Hash algorithm" ) @click.option( "--hash", prompt="Hash (hex string)", hide_input=False, confirmation_prompt=True, help="Hash value as string of hex digits" ) @click.option( "--expiration", default=60 * 60, prompt="Expiration (seconds)", help="Duration of HTLC in seconds" ) @click.option( "--length", help="Length of PREIMAGE (not of hash). Generally OK " + "to leave this as 0 for unconstrained.", default=0, show_default=True ) @click.option("--account") @click.pass_context @online @unlock def create(ctx, to, amount, symbol, type, hash, expiration, length, account): """ Create an HTLC contract from a hash and lock-time """ ctx.blockchain.blocking = True tx = ctx.blockchain.htlc_create( Amount(amount, symbol), to, hash_type=type, hash_hex=hash, expiration=expiration, account=account, preimage_length=length ) tx.pop("trx", None) print_tx(tx) results = tx.get("operation_results", {}) if results: htlc_id = results[0][1] print("Your htlc_id is: {}".format(htlc_id)) @htlc.command() @click.argument("to") @click.argument("amount") @click.argument("symbol") @click.option( "--type", type=click.Choice(["ripemd160", "sha1", "sha256", "hash160"]), default="sha256", prompt="Hash algorithm", show_default=True, help="Hash algorithm" ) @click.option( "--secret", prompt="Redeem Password", hide_input=True, confirmation_prompt=True, help="Ascii-text preimage" ) @click.option("--expiration", default=60 * 60, prompt="Expiration (seconds)", help="Duration of HTLC in seconds" ) @click.option( "--length", help="Length of PREIMAGE (not of hash). Generally OK " + "to leave this as 0 for unrestricted. If non-zero, must match length " + "of provided preimage", default=0, show_default=True ) @click.option("--account") @click.pass_context @online @unlock def create_from_secret(ctx, to, amount, symbol, type, secret, expiration, length, account): """Create an HTLC contract from a secret preimage If you are the party choosing the preimage, this version of htlc_create will compute the hash for you from the supplied preimage, and create the HTLC with the resulting hash. """ if length != 0 and length != len(secret): raise ValueError("Length must be zero or agree with actual preimage length") ctx.blockchain.blocking = True tx = ctx.blockchain.htlc_create( Amount(amount, symbol), to, preimage=secret, preimage_length=length, hash_type=type, expiration=expiration, account=account, ) tx.pop("trx", None) print_tx(tx) results = tx.get("operation_results", {}) if results: htlc_id = results[0][1] print("Your htlc_id is: {}".format(htlc_id)) @htlc.command() @click.argument("htlc_id") @click.option( "--secret", prompt="Redeem Password", hide_input=False, confirmation_prompt=False, type=str, help="The preimage, as ascii-text, unless --hex is passed" ) @click.option( "--hex", is_flag=True, help="Interpret preimage as hex-encoded bytes" ) @click.option("--account") @click.pass_context @online @unlock def redeem(ctx, htlc_id, secret, hex, account): """ Redeem an HTLC contract by providing preimage """ encoding = "hex" if hex else "utf-8" print_tx(ctx.blockchain.htlc_redeem(htlc_id, secret, encoding=encoding, account=account) )
xeroc/uptick
uptick/htlc.py
Python
mit
3,974
'use-strict'; var hours = ['6:00am', '7:00am', '8:00am', '9:00am', '10:00am', '11:00am', '12:00pm', '1:00pm', '2:00pm', '3:00pm', '4:00pm', '5:00pm', '6:00pm', '7:00pm']; var allLocations = []; var theTable = document.getElementById('pike'); var el = document.getElementById('moreStores'); // var hourlyTotals = []; // contructor for the Cookie Stores function CookieStore(locationName, minCustomersPerHour, maxCustomersPerHour, avgCookiesPerCustomer) { this.locationName = locationName; this.minCustomersPerHour = minCustomersPerHour; this.maxCustomersPerHour = maxCustomersPerHour; this.avgCookiesPerCustomer = avgCookiesPerCustomer; this.customersEachHour = []; this.cookiesEachHour = []; this.totalDaily = 0; this.calcCustomersThisHour(); this.calcCookiesThisHour(); allLocations.push(this); } // creates total for customers each hour CookieStore.prototype.calcCustomersThisHour = function() { var reference = []; for (var i = 0; i < hours.length; i++) { var numberCustomersPerHour = Math.floor(Math.random() * (this.maxCustomersPerHour - this.minCustomersPerHour + 1)) + this.minCustomersPerHour; reference.push(numberCustomersPerHour); } this.customersEachHour = reference; return numberCustomersPerHour; }; // Creates total for daily cookie sales CookieStore.prototype.calcCookiesThisHour = function() { for (var j = 0; j < hours.length; j++) { var totalCookieSales = Math.ceil(this.customersEachHour[j] * this.avgCookiesPerCustomer); this.cookiesEachHour.push(totalCookieSales); this.totalDaily += this.cookiesEachHour[j]; } this.cookiesEachHour.push(this.totalDaily); }; // creates table elements function makeElement(type, content, parent){ // create var newEl = document.createElement(type); // content newEl.textContent = content; // append parent.appendChild(newEl); } // Push hours to table header var renderHeader = function() { var trEL = document.createElement('tr'); var thEL = document.createElement('th'); thEL.textContent = 'Locations'; trEL.appendChild(thEL); for (var i = 0; i < hours.length; i++) { var thEL = document.createElement('th'); thEL.textContent = hours[i]; trEL.appendChild(thEL); } thEL = document.createElement('th'); thEL.textContent = 'Daily'; trEL.appendChild(thEL); theTable.appendChild(trEL); }; // Push totals to TD's in DOM CookieStore.prototype.render = function() { var trEL = document.createElement('tr'); var tdEL = document.createElement('td'); tdEL.textContent = this.locationName; trEL.appendChild(tdEL); for (var i = 0; i < hours.length + 1; i++) { var tdEL = document.createElement('td'); tdEL.textContent = this.cookiesEachHour[i]; trEL.appendChild(tdEL); } theTable.appendChild(trEL); }; // Footer TOTALLLLL function renderFooter() { var trEL = document.createElement('tr'); var thEL = document.createElement('th'); thEL.textContent = 'Total'; trEL.appendChild(thEL); var totalOfTotals = 0; var hourlyTotal = 0; for (var i = 0; i < hours.length; i++) { hourlyTotal = 0; for (var j = 0; j < allLocations.length; j++) { hourlyTotal += allLocations[j].cookiesEachHour[i]; totalOfTotals += allLocations[j].cookiesEachHour[i]; } thEL = document.createElement('th'); thEL.textContent = hourlyTotal; trEL.appendChild(thEL); } thEL = document.createElement('th'); thEL.textContent = totalOfTotals; trEL.appendChild(thEL); theTable.appendChild(trEL); }; // passing new stores to the cookie store constructor var pikePlace = new CookieStore('Pike Place Market', 23, 65, 6.3); var seaTac = new CookieStore('Seatac', 3, 24, 1.2); var seattleCenter = new CookieStore('Seattle Center', 11, 38, 3.7); var capitolHill = new CookieStore('Capitol Hill', 20, 38, 2.3); var alki = new CookieStore('Alki', 2, 16, 4.6); // Renders the table function renderTable(){ theTable.innerHTML = ''; renderHeader(); for (i = 0; i < allLocations.length; i++) { allLocations[i].render(); } renderFooter(); } renderTable(); // Handler for listener function handleStoreSubmit(event) { event.preventDefault(); var newStoreLocation = event.target.storeLocation.value; var minCustomers = parseInt(event.target.minCustomers.value); var maxCustomers = parseInt(event.target.maxCustomers.value); var avgCookie = parseFloat(event.target.avgCookiesSold.value); console.log('go here'); // prevent empty if(!newStoreLocation || !minCustomers || !maxCustomers || !avgCookie){ return alert('All fields must have a value'); } //validate by type if (typeof minCustomers !== 'number') { return alert('Min customers must be a number'); } // ignore case on store names for(var i = 0; i < allLocations.length; i++){ if(newStoreLocation === allLocations[i].locationName) { allLocations[i].minCustomersPerHour = minCustomers; allLocations[i].maxCustomersPerHour = maxCustomers; allLocations[i].avgCookiesPerCustomer = avgCookie; clearForm(); allLocations[i].totalDaily = 0; allLocations[i].customersEachHour = []; allLocations[i].cookiesEachHour = []; allLocations[i].calcCustomersThisHour(); allLocations[i].calcCookiesThisHour(); console.log('A match was found at index', allLocations[i]); renderTable(); return; } } new CookieStore(newStoreLocation, minCustomers, maxCustomers, avgCookie); function clearForm(){ event.target.storeLocation.value = null; event.target.minCustomers.value = null; event.target.maxCustomers.value = null; event.target.avgCookiesSold.value = null; } clearForm(); // for(var i = allLocations.length - 1; i < allLocations.length; i++){ // allLocations[i].render(); // } renderTable(); }; // Listener code el.addEventListener('submit', handleStoreSubmit);
ianwaites/fish-cookies
JS/app.js
JavaScript
mit
5,853
// Copyright (c) 2009-2012 The Paccoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <map> #include <openssl/ecdsa.h> #include <openssl/obj_mac.h> #include "key.h" #include "util.h" // Generate a private key from just the secret parameter int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key) { int ok = 0; BN_CTX *ctx = NULL; EC_POINT *pub_key = NULL; if (!eckey) return 0; const EC_GROUP *group = EC_KEY_get0_group(eckey); if ((ctx = BN_CTX_new()) == NULL) goto err; pub_key = EC_POINT_new(group); if (pub_key == NULL) goto err; if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx)) goto err; EC_KEY_set_private_key(eckey,priv_key); EC_KEY_set_public_key(eckey,pub_key); ok = 1; err: if (pub_key) EC_POINT_free(pub_key); if (ctx != NULL) BN_CTX_free(ctx); return(ok); } // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields // recid selects which key is recovered // if check is nonzero, additional checks are performed int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check) { if (!eckey) return 0; int ret = 0; BN_CTX *ctx = NULL; BIGNUM *x = NULL; BIGNUM *e = NULL; BIGNUM *order = NULL; BIGNUM *sor = NULL; BIGNUM *eor = NULL; BIGNUM *field = NULL; EC_POINT *R = NULL; EC_POINT *O = NULL; EC_POINT *Q = NULL; BIGNUM *rr = NULL; BIGNUM *zero = NULL; int n = 0; int i = recid / 2; const EC_GROUP *group = EC_KEY_get0_group(eckey); if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; } BN_CTX_start(ctx); order = BN_CTX_get(ctx); if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; } x = BN_CTX_get(ctx); if (!BN_copy(x, order)) { ret=-1; goto err; } if (!BN_mul_word(x, i)) { ret=-1; goto err; } if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; } field = BN_CTX_get(ctx); if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; } if (BN_cmp(x, field) >= 0) { ret=0; goto err; } if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; } if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; } if (check) { if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; } if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; } if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; } } if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; } n = EC_GROUP_get_degree(group); e = BN_CTX_get(ctx); if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; } if (8*msglen > n) BN_rshift(e, e, 8-(n & 7)); zero = BN_CTX_get(ctx); if (!BN_zero(zero)) { ret=-1; goto err; } if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; } rr = BN_CTX_get(ctx); if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; } sor = BN_CTX_get(ctx); if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; } eor = BN_CTX_get(ctx); if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; } if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; } if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; } ret = 1; err: if (ctx) { BN_CTX_end(ctx); BN_CTX_free(ctx); } if (R != NULL) EC_POINT_free(R); if (O != NULL) EC_POINT_free(O); if (Q != NULL) EC_POINT_free(Q); return ret; } void CKey::SetCompressedPubKey() { EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED); fCompressedPubKey = true; } void CKey::Reset() { fCompressedPubKey = false; pkey = EC_KEY_new_by_curve_name(NID_secp256k1); if (pkey == NULL) throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed"); fSet = false; } CKey::CKey() { Reset(); } CKey::CKey(const CKey& b) { pkey = EC_KEY_dup(b.pkey); if (pkey == NULL) throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed"); fSet = b.fSet; } CKey& CKey::operator=(const CKey& b) { if (!EC_KEY_copy(pkey, b.pkey)) throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed"); fSet = b.fSet; return (*this); } CKey::~CKey() { EC_KEY_free(pkey); } bool CKey::IsNull() const { return !fSet; } bool CKey::IsCompressed() const { return fCompressedPubKey; } void CKey::MakeNewKey(bool fCompressed) { if (!EC_KEY_generate_key(pkey)) throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed"); if (fCompressed) SetCompressedPubKey(); fSet = true; } bool CKey::SetPrivKey(const CPrivKey& vchPrivKey) { const unsigned char* pbegin = &vchPrivKey[0]; if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size())) return false; fSet = true; return true; } bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed) { EC_KEY_free(pkey); pkey = EC_KEY_new_by_curve_name(NID_secp256k1); if (pkey == NULL) throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed"); if (vchSecret.size() != 32) throw key_error("CKey::SetSecret() : secret must be 32 bytes"); BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new()); if (bn == NULL) throw key_error("CKey::SetSecret() : BN_bin2bn failed"); if (!EC_KEY_regenerate_key(pkey,bn)) { BN_clear_free(bn); throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed"); } BN_clear_free(bn); fSet = true; if (fCompressed || fCompressedPubKey) SetCompressedPubKey(); return true; } CSecret CKey::GetSecret(bool &fCompressed) const { CSecret vchRet; vchRet.resize(32); const BIGNUM *bn = EC_KEY_get0_private_key(pkey); int nBytes = BN_num_bytes(bn); if (bn == NULL) throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed"); int n=BN_bn2bin(bn,&vchRet[32 - nBytes]); if (n != nBytes) throw key_error("CKey::GetSecret(): BN_bn2bin failed"); fCompressed = fCompressedPubKey; return vchRet; } CPrivKey CKey::GetPrivKey() const { int nSize = i2d_ECPrivateKey(pkey, NULL); if (!nSize) throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed"); CPrivKey vchPrivKey(nSize, 0); unsigned char* pbegin = &vchPrivKey[0]; if (i2d_ECPrivateKey(pkey, &pbegin) != nSize) throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size"); return vchPrivKey; } bool CKey::SetPubKey(const std::vector<unsigned char>& vchPubKey) { const unsigned char* pbegin = &vchPubKey[0]; if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size())) return false; fSet = true; if (vchPubKey.size() == 33) SetCompressedPubKey(); return true; } std::vector<unsigned char> CKey::GetPubKey() const { int nSize = i2o_ECPublicKey(pkey, NULL); if (!nSize) throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed"); std::vector<unsigned char> vchPubKey(nSize, 0); unsigned char* pbegin = &vchPubKey[0]; if (i2o_ECPublicKey(pkey, &pbegin) != nSize) throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size"); return vchPubKey; } bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig) { unsigned int nSize = ECDSA_size(pkey); vchSig.resize(nSize); // Make sure it is big enough if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey)) { vchSig.clear(); return false; } vchSig.resize(nSize); // Shrink to fit actual size return true; } // create a compact signature (65 bytes), which allows reconstructing the used public key // The format is one header byte, followed by two times 32 bytes for the serialized r and s values. // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, // 0x1D = second key with even y, 0x1E = second key with odd y bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig) { bool fOk = false; ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey); if (sig==NULL) return false; vchSig.clear(); vchSig.resize(65,0); int nBitsR = BN_num_bits(sig->r); int nBitsS = BN_num_bits(sig->s); if (nBitsR <= 256 && nBitsS <= 256) { int nRecId = -1; for (int i=0; i<4; i++) { CKey keyRec; keyRec.fSet = true; if (fCompressedPubKey) keyRec.SetCompressedPubKey(); if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) if (keyRec.GetPubKey() == this->GetPubKey()) { nRecId = i; break; } } if (nRecId == -1) throw key_error("CKey::SignCompact() : unable to construct recoverable key"); vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0); BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]); BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]); fOk = true; } ECDSA_SIG_free(sig); return fOk; } // reconstruct public key from a compact signature // This is only slightly more CPU intensive than just verifying it. // If this function succeeds, the recovered public key is guaranteed to be valid // (the signature is a valid signature of the given data for that key) bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig) { if (vchSig.size() != 65) return false; int nV = vchSig[0]; if (nV<27 || nV>=35) return false; ECDSA_SIG *sig = ECDSA_SIG_new(); BN_bin2bn(&vchSig[1],32,sig->r); BN_bin2bn(&vchSig[33],32,sig->s); EC_KEY_free(pkey); pkey = EC_KEY_new_by_curve_name(NID_secp256k1); if (nV >= 31) { SetCompressedPubKey(); nV -= 4; } if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1) { fSet = true; ECDSA_SIG_free(sig); return true; } return false; } bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig) { // -1 = error, 0 = bad sig, 1 = good if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) return false; return true; } bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig) { CKey key; if (!key.SetCompactSignature(hash, vchSig)) return false; if (GetPubKey() != key.GetPubKey()) return false; return true; } bool CKey::IsValid() { if (!fSet) return false; bool fCompr; CSecret secret = GetSecret(fCompr); CKey key2; key2.SetSecret(secret, fCompr); return GetPubKey() == key2.GetPubKey(); }
wmcorless/paccoin-v2
src/key.cpp
C++
mit
11,119
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.ai.textanalytics.implementation.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** The HealthcareEntity model. */ @Fluent public final class HealthcareEntity extends HealthcareEntityProperties { /* * The assertion property. */ @JsonProperty(value = "assertion") private HealthcareAssertion assertion; /* * Preferred name for the entity. Example: 'histologically' would have a * 'name' of 'histologic'. */ @JsonProperty(value = "name") private String name; /* * Entity references in known data sources. */ @JsonProperty(value = "links") private List<HealthcareEntityLink> links; /** * Get the assertion property: The assertion property. * * @return the assertion value. */ public HealthcareAssertion getAssertion() { return this.assertion; } /** * Set the assertion property: The assertion property. * * @param assertion the assertion value to set. * @return the HealthcareEntity object itself. */ public HealthcareEntity setAssertion(HealthcareAssertion assertion) { this.assertion = assertion; return this; } /** * Get the name property: Preferred name for the entity. Example: 'histologically' would have a 'name' of * 'histologic'. * * @return the name value. */ public String getName() { return this.name; } /** * Set the name property: Preferred name for the entity. Example: 'histologically' would have a 'name' of * 'histologic'. * * @param name the name value to set. * @return the HealthcareEntity object itself. */ public HealthcareEntity setName(String name) { this.name = name; return this; } /** * Get the links property: Entity references in known data sources. * * @return the links value. */ public List<HealthcareEntityLink> getLinks() { return this.links; } /** * Set the links property: Entity references in known data sources. * * @param links the links value to set. * @return the HealthcareEntity object itself. */ public HealthcareEntity setLinks(List<HealthcareEntityLink> links) { this.links = links; return this; } }
Azure/azure-sdk-for-java
sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/HealthcareEntity.java
Java
mit
2,567
var express = require('express'); var router = express.Router(); // Play a game from the DB router.get('/games', function (req, res) { res.render('games', data); }); module.exports = router;
jrburga/jsvgdl
routes/games.js
JavaScript
mit
193
import os.path import requests import time from bs4 import BeautifulSoup from geotext import GeoText as gt from string import punctuation from collections import Counter import re import sys reload(sys) sys.setdefaultencoding("utf-8") threats = ['loss', 'fragmentation', 'hunting', 'poaching', 'fishing', 'overfishing', 'environmental', 'environment', 'invasive', 'disease', 'pet', 'pollution'] conservation = ['cites', 'protection law', 'captive breeding', 'protected', 'endangered species act', 'wwf', 'wcs'] conservationString = '' threatString = '' def findConservation(string): consFound = [] string = string.lower() string = string.replace("<p>", "") global conservation for word in conservation: if word in string: consFound.append(word) return consFound def findThreats(string): threatsFound = [] string = string.lower() string = string.replace("<p>", "") global threats for word in threats: if word in string: threatsFound.append(word) index = string.index(word) return threatsFound def parseThrough(string): string = string.replace(',','') s = '<p>' if s in string: string = string.split(s)[1] s = '</p>' if s in string: string = string.split(s)[0] return string def urlNeeded(): global threats global conservationString global threatString allThreats = [] global conservation allCons = [] f = open('output.txt', "w") f.write('Scientific Name, Nickname, Common Name, Kingdom, Phylum, Class, Order, Family, Genus, Size, Threats, Conservation, Threat Keywords, Conservation Keywords, status, countries, country_count' + '\n') with open('test.txt', "rb") as fd: for line in fd: line = line.lstrip().rstrip() url = line r = requests.get(url) soup = BeautifulSoup(r.text.encode('utf-8'), 'html.parser') newName = soup.find('td').text newName = newName.lstrip().rstrip() newName = str(newName) newName = newName.replace(',',';') f.write(newName + ',') for t in soup.findAll('h1'): name = t.text s = '(' if s in name: commonName = name.split(s)[0] scienceName = name.split(s)[1] scienceName = scienceName.replace(')','') f.write(scienceName + ',') print scienceName f.write(name + ',') soupsup = soup.findAll('td', align="left") for node in soupsup: waant = ''.join(node.findAll(text=True)) waant = str(waant) waant = waant.replace('\n', '') f.write(waant + ',') if "(" in node: break items = [] for t in soup.findAll('td'): items.append(t.text) check = 9 badge = len(items) if badge > 6: f.write(items[badge - 1] + ',') else: f.write(',') badges = soup.findAll("p", class_="Threats") ofInterest = str(badges) foundThreats = findThreats(ofInterest) ofInterest = parseThrough(ofInterest) threatString = threatString + ofInterest if ofInterest: f.write(ofInterest) f.write(',') else: f.write(' ,') badges = soup.findAll("p", class_="Conservation") ofInterest = str(badges) foundCons = findConservation(ofInterest) ofInterest = parseThrough(ofInterest) conservationString = conservationString + ofInterest badges = soup.findAll("p", class_="Range") badges = str(badges) countries = gt(badges).country_mentions countries = str(countries) #countries = re.sub('[^A-Z]', '', s) countries = countries.replace(',', '') cCount = sum(c.isdigit() for c in countries) cCount = str(cCount) print cCount status = soup.findAll("p", class_="Status") status = str(status) if 'Critically' in status: status = 'Critically Endangered' else: status = 'Endangered' if ofInterest: f.write(ofInterest) f.write(' ,' + '') else: f.write(' ,') for node in foundThreats: f.write(node) f.write(';') f.write(' ,') for node in foundCons: f.write(node) f.write(';') f.write(' ,') f.write(status) f.write(',') f.write(countries) f.write(',') f.write(cCount) f.write('\n') fd.close() f.close() def main(): urlNeeded() main()
andrewedstrom/cs638project
arkive table analysis/parse.py
Python
mit
5,243
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('stats', '0001_initial'), ] operations = [ migrations.CreateModel( name='Dispensed', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('total_approved', models.IntegerField(help_text='Number of projects approved in any instance.')), ('total_dispensed', models.IntegerField(help_text='Number of projects that did not go to 2nd round of votes.')), ('dispensed_by_plenary', models.IntegerField(help_text='Those projects dispensed due to `acuerdo del pleno`.')), ('dispensed_by_spokesmen', models.IntegerField(help_text='Those projects dispensed due to `junta de portavoces`.')), ('dispensed_others', models.IntegerField(help_text='All other projects dispensed, and those with no specific reason.')), ], options={ }, bases=(models.Model,), ), ]
proyectosdeley/proyectos_de_ley
proyectos_de_ley/stats/migrations/0002_dispensed.py
Python
mit
1,175
module JsonRander # all values types TYPE = ["JsonRander::JHash", "JsonRander::JArray", "JsonRander::JString", "JsonRander::JNum", "JsonRander::JSpecialValue"] class Configuration attr_accessor :string_max_length, :array_max_length, :hash_max_length def initialize @string_max_length = 5 @array_max_length = 5 @hash_max_length = 5 end end end
fdwills/json_rander
lib/json_rander/configuration.rb
Ruby
mit
429
<?php /** * Copyright (C) 2016 Derek J. Lambert * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ namespace CrEOF\Geo\Obj\Validator; use CrEOF\Geo\Obj\Exception\ExceptionInterface; use CrEOF\Geo\Obj\Exception\RangeException; use CrEOF\Geo\Obj\Object; /** * Class DValidator * * @author Derek J. Lambert <dlambert@dereklambert.com> * @license http://dlambert.mit-license.org MIT */ class DValidator extends AbstractValidator { /** * @var int */ private $size = 2; /** * @param int $size * * @throws RangeException */ public function __construct($size) { $this->setExpectedType(Object::T_POINT); if ($size < 2 || $size > 4) { throw new RangeException('Size must be between 2 and 4.'); } $this->size = $size; } /** * @param array &$data * * @throws ExceptionInterface * @throws RangeException * * @TODO compare with expectedDimension also? */ public function validate(array &$data) { parent::validate($data); $size = count($data['value']); if ($this->size !== $size) { throw new RangeException('Invalid size "' . $size . '", size must be '. $this->size . '.'); } } }
creof/geo-obj
lib/Validator/DValidator.php
PHP
mit
2,302
import React from 'react'; import ReactTouchPosition from '../../../dist/ReactTouchPosition'; import TouchPositionLabel from './TouchPositionLabel'; import OnPositionChangedLabel from './OnPositionChangedLabel'; import InstructionsLabel from './InstructionsLabel'; export default class extends React.Component { constructor(props) { super(props); this.state = { isPositionOutside: true, touchPosition: { x: 0, y: 0, } } } render() { return ( <div className="example-container"> <ReactTouchPosition {...{ className: 'example', onPositionChanged: ({ isPositionOutside, touchPosition }) => { this.setState({ isPositionOutside, touchPosition }); }, shouldDecorateChildren: false }}> <TouchPositionLabel /> <InstructionsLabel /> </ReactTouchPosition> <OnPositionChangedLabel {...this.state} /> </div> ); } }
ethanselzer/react-touch-position
example/src/components/ShouldDecorateChildren.js
JavaScript
mit
1,244
#This will be the thread responsible for the matchmaking which operates as follows: #There are four lists where the players are divided into based on their rank. #List 1 is for ranks 0,1,2. #List 2 is for ranks 3,4,5. #List 3 is for ranks 6,7,8. #List 4 is for ranks 9,10. #When a player waits for a match too long, this thread will start looking for #players in adjacent lists, first in the higher category list and then in the #lower one. #Each player has a dictionary associated with him, which will store his info #and some other parameters, like his network info to connect to him. #This thread support only 2 operations: # 1) Add to match making lists # 2) Terminate itself MAX_LOOPS = 10 MAX_WAIT = 10 import Queue,time,random #inputQueue is for getting players from account threads #outputQueue is for sending match tokens to the thread that handles the matches #exitQueue is used for exiting the thread def mmThread(inputQueue,exitQueue,outputQueue): #Lists for all difficulties noviceList = [] apprenticeList = [] adeptList = [] expertList = [] #put them in one list playerList = [noviceList,apprenticeList,adeptList,expertList] #This list contains the players that have waited for too long in their Queue needRematch = [] while True: loopCounter = 0 #Check for exit signal try: exit = exitQueue.get(False) if exit: break except: pass #loop over new entries at most MAX_LOOPS times then do it again while loopCounter < MAX_LOOPS: try: #Get new player and add him to a list according to his rank newPlayer = inputQueue.get(False) playerRank = newPlayer.get('rank') listIndex = playerRank // 3 newPlayer['entryTime'] = time.time() playerList[listIndex].append(newPlayer) print 'MMTHREAD : Got user ' print 'MMTHREAD: USER RANK IS %d ' % playerRank except Queue.Empty: break loopCounter += 1 #First check for players in the rematch Queue for player in needRematch[:]: position = player.get('rank') // 3 foundMatch = False #Check for empty list if len(playerList[position]) == 0 or playerList[position][0] != player: continue #Check for enemy player one list above this player if position + 1 < len(playerList) and len(playerList[position+1]) >= 1: foundMatch = True firstPlayer = playerList[position].pop(0) secondPlayer = playerList[position+1].pop(0) needRematch.remove(player) elif (position - 1 >= 0) and len(playerList[position-1]) >= 1: #Else check for enemy player one list below this player foundMatch = True firstPlayer = playerList[position].pop(0) secondPlayer = playerList[position-1].pop(0) needRematch.remove(player) #Add player tokens to Queue for game play thread if foundMatch: bothPlayers = [firstPlayer,secondPlayer] data = {'turn':0,'players':bothPlayers} print'Add new Player token' outputQueue.put(data) #Match players in same list for category in playerList: while True: try: #Try to pop two players from the list #If successfull, put their token into game play thread Queue firstPlayer = None secondPlayer = None firstPlayer = category.pop(0) secondPlayer = category.pop(0) bothPlayers = [firstPlayer,secondPlayer] turn = random.randint(0,1) data = {'turn':turn,'players':bothPlayers} print'Add new Player token' outputQueue.put(data) except: #Else if only one player is found , but him back if secondPlayer == None and firstPlayer != None: category.insert(0,firstPlayer) break #Check for players that didnt find a match for a long time and alert thread for i in range(0,3): if len(playerList[i]) > 0: if time.time() - playerList[i][0].get('entryTime') >= MAX_WAIT: needRematch.append(playerList[i][0]) print 'match making thread out'
Shalantor/Connect4
server/matchMakingThread.py
Python
mit
4,679
<?php namespace App\Form; use Symfony\Component\Form\{ AbstractType, FormBuilderInterface }; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\{ TextType, TextareaType, FileType }; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Doctrine\ORM\EntityRepository; use App\Entity\{ Company, Category }; class CompanyType extends AbstractType { private $container; public function __construct(ContainerInterface $container) { $this->container = $container; } /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('logo', Type\ImageFileType::class, [ 'required' => false, 'label' => 'front.logo', 'upload_path' => $this->container->getParameter('company_images'), 'attr' => [ 'accept' => 'image/*', 'class' => 'form-control form-control-lg' ] ]) ->add('title', TextType::class, [ 'label' => 'front.name', 'attr' => [ 'class' => 'form-control form-control-lg' ] ]) ->add('description', TextareaType::class, [ 'required' => false, 'label' => 'front.description', 'attr' => [ 'class' => 'form-control form-control-lg' // text-editor ] ]) ->add('categories', EntityType::class, [ 'class' => Category::class, //'required' => false, 'multiple' => true, 'label' => 'front.select.category', 'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('c') ->where('c.parent <> :null') ->setParameter('null', 'null') ->orderBy('c.title', 'ASC'); }, 'attr' => [ 'class' => 'form-control select2' ] ]) ->add('gallery_images', FileType::class, [ "data_class" => null, 'multiple' => true, "mapped" => false, 'required' => false, 'label' => 'front.add.gallery', 'attr' => [ 'class' => 'form-control form-control-lg' ] ]) ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Company::class ]); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'app_company'; } }
lloonnyyaa/reviews
src/Form/CompanyType.php
PHP
mit
3,177
require File.expand_path('../spec_helper', __FILE__) module Pod class Sample extend SpecHelper::Fixture def self.yaml <<-LOCKFILE.strip_heredoc PODS: - BananaLib (1.0): - monkey (< 1.0.9, ~> 1.0.1) - JSONKit (1.4) - monkey (1.0.8) DEPENDENCIES: - BananaLib (~> 1.0) - JSONKit (from `path/JSONKit.podspec`) EXTERNAL SOURCES: JSONKit: :podspec: path/JSONKit.podspec CHECKOUT OPTIONS: JSONKit: :podspec: path/JSONKit.podspec SPEC CHECKSUMS: BananaLib: d46ca864666e216300a0653de197668b12e732a1 JSONKit: 92ae5f71b77c8dec0cd8d0744adab79d38560949 PODFILE CHECKSUM: podfile_checksum COCOAPODS: #{CORE_VERSION} LOCKFILE end def self.quotation_marks_yaml <<-LOCKFILE.strip_heredoc PODS: - BananaLib (1.0): - monkey (< 1.0.9, ~> 1.0.1) - JSONKit (1.4) - monkey (1.0.8) DEPENDENCIES: - BananaLib (~> 1.0) - JSONKit (from `path/JSONKit.podspec`) EXTERNAL SOURCES: JSONKit: :podspec: "path/JSONKit.podspec" CHECKOUT OPTIONS: JSONKit: :podspec: path/JSONKit.podspec SPEC CHECKSUMS: BananaLib: d46ca864666e216300a0653de197668b12e732a1 JSONKit: '92ae5f71b77c8dec0cd8d0744adab79d38560949' PODFILE CHECKSUM: podfile_checksum COCOAPODS: #{CORE_VERSION} LOCKFILE end def self.podfile podfile = Podfile.new do platform :ios pod 'BananaLib', '~>1.0' pod 'JSONKit', :podspec => 'path/JSONKit.podspec' end podfile.stubs(:checksum).returns('podfile_checksum') podfile end def self.specs repo_path = 'spec-repos/test_repo/' bananalib_path = repo_path + 'Specs/BananaLib/1.0/BananaLib.podspec' jsonkit_path = repo_path + 'Specs/JSONKit/1.4/JSONKit.podspec' specs = [ Specification.from_file(fixture(bananalib_path)), Specification.from_file(fixture(jsonkit_path)), Specification.new do |s| s.name = 'monkey' s.version = '1.0.8' end, ] specs end def self.checkout_options { 'JSONKit' => { :podspec => 'path/JSONKit.podspec', }, } end end #---------------------------------------------------------------------------# describe Lockfile do describe 'In general' do extend SpecHelper::TemporaryDirectory before do @tmp_path = temporary_directory + 'Podfile.lock' end it 'stores the initialization hash' do lockfile = Lockfile.new(YAMLHelper.load_string(Sample.yaml)) lockfile.internal_data.should == YAMLHelper.load_string(Sample.yaml) end it 'loads from a file' do File.open(@tmp_path, 'w') { |f| f.write(Sample.yaml) } lockfile = Lockfile.from_file(@tmp_path) lockfile.internal_data.should == YAMLHelper.load_string(Sample.yaml) end it "returns nil if it can't find the initialization file" do lockfile = Lockfile.from_file(temporary_directory + 'Podfile.lock_not_existing') lockfile.should.nil? end it 'returns the file in which is defined' do File.open(@tmp_path, 'w') { |f| f.write(Sample.yaml) } lockfile = Lockfile.from_file(@tmp_path) lockfile.defined_in_file.should == @tmp_path end it "raises if the provided YAML doesn't returns a hash" do File.open(@tmp_path, 'w') { |f| f.write('value') } should.raise Informative do Lockfile.from_file(@tmp_path) end.message.should.match /Invalid Lockfile/ end #--------------------------------------# before do @lockfile = Lockfile.generate(Sample.podfile, Sample.specs, Sample.checkout_options) end it 'returns whether it is equal to another' do podfile = Podfile.new do platform :ios pod 'BananaLib', '~>1.0' end @lockfile.should == @lockfile @lockfile.should.not == Lockfile.generate(podfile, Sample.specs, Sample.checkout_options) end it 'returns the list of the names of the installed pods' do @lockfile.pod_names.should == %w(BananaLib JSONKit monkey) end it 'returns the versions of a given pod' do @lockfile.version('BananaLib').should == Version.new('1.0') @lockfile.version('JSONKit').should == Version.new('1.4') @lockfile.version('monkey').should == Version.new('1.0.8') end it 'returns the versions of a given pod handling the case in which the root spec was not stored' do @lockfile.stubs(:pod_versions).returns('BananaLib/Subspec' => Version.new(1.0)) @lockfile.version('BananaLib').should == Version.new('1.0') end it 'returns the checksum for the given Pod' do @lockfile.checksum('BananaLib').should == 'd46ca864666e216300a0653de197668b12e732a1' end it 'returns the dependencies used for the last installation' do json_dep = Dependency.new('JSONKit') json_dep.external_source = { :podspec => 'path/JSONKit.podspec' } @lockfile.dependencies.should == [ Dependency.new('BananaLib', '~>1.0'), json_dep, ] end it 'includes the external source information in the generated dependencies' do dep = @lockfile.dependencies.find { |d| d.name == 'JSONKit' } dep.external_source.should == { :podspec => 'path/JSONKit.podspec' } end it 'returns the dependency that locks the pod with the given name to the installed version' do json_dep = Dependency.new('JSONKit', '1.4') json_dep.external_source = { :podspec => 'path/JSONKit.podspec' } result = @lockfile.dependencies_to_lock_pod_named('JSONKit') result.should == [json_dep] end it 'raises if there is a request for a locking dependency for a not stored Pod' do should.raise StandardError do @lockfile.dependencies_to_lock_pod_named('Missing') end.message.should.match /without a known dependency/ end it 'returns the version of CocoaPods which generated the lockfile' do @lockfile.cocoapods_version.should == Version.new(CORE_VERSION) end end #-------------------------------------------------------------------------# describe 'Comparison with a Podfile' do before do @podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit' end @specs = [ Specification.new do |s| s.name = 'BlocksKit' s.version = '1.0.0' end, Specification.new do |s| s.name = 'JSONKit' s.version = '1.4' end] @checkout_options = {} @lockfile = Lockfile.generate(@podfile, @specs, @checkout_options) end it 'detects an added Pod' do podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit' pod 'TTTAttributedLabel' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => [], :removed => [], :unchanged => %w(BlocksKit JSONKit), :added => ['TTTAttributedLabel'], } end it 'detects a removed Pod' do podfile = Podfile.new do platform :ios pod 'BlocksKit' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => [], :removed => ['JSONKit'], :unchanged => ['BlocksKit'], :added => [], } end it 'detects Pods whose version changed' do podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit', '> 1.4' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => ['JSONKit'], :removed => [], :unchanged => ['BlocksKit'], :added => [], } end it "it doesn't mark as changed Pods whose version changed but is still compatible with the Podfile" do podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit', '> 1.0' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => [], :removed => [], :unchanged => %w(BlocksKit JSONKit), :added => [], } end it 'detects Pods whose external source changed' do podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit', :git => 'example1.com' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => ['JSONKit'], :removed => [], :unchanged => ['BlocksKit'], :added => [], } @lockfile = Lockfile.generate(podfile, @specs, @checkout_options) podfile = Podfile.new do platform :ios pod 'BlocksKit' pod 'JSONKit', :git => 'example2.com' end @lockfile.detect_changes_with_podfile(podfile).should == { :changed => ['JSONKit'], :removed => [], :unchanged => ['BlocksKit'], :added => [], } end end #-------------------------------------------------------------------------# describe 'Serialization' do before do @lockfile = Lockfile.generate(Sample.podfile, Sample.specs, Sample.checkout_options) end it 'can be store itself at the given path' do path = SpecHelper.temporary_directory + 'Podfile.lock' @lockfile.write_to_disk(path) loaded = Lockfile.from_file(path) loaded.should == @lockfile end it "won't write to disk if the equivalent lockfile is already there" do path = SpecHelper.temporary_directory + 'Podfile.lock' old_yaml = %(---\nhi: "./hi"\n) path.open('w') { |f| f.write old_yaml } @lockfile.stubs(:to_hash).returns('hi' => './hi') @lockfile.stubs(:to_yaml).returns("---\nhi: ./hi\n") path.expects(:open).with('w').never @lockfile.write_to_disk(path) path.read.should == old_yaml end it 'overwrites a different lockfile' do path = SpecHelper.temporary_directory + 'Podfile.lock' path.delete if path.exist? @lockfile.write_to_disk(path) @lockfile = Lockfile.new('COCOAPODS' => '0.0.0') @lockfile.write_to_disk(path) @lockfile.should == Lockfile.from_file(path) end it 'fix strange quotation marks in lockfile' do yaml_string = Sample.quotation_marks_yaml yaml_string = yaml_string.tr("'", '') yaml_string = yaml_string.tr('"', '') yaml_string.should == Sample.yaml end it 'generates a hash representation' do hash = @lockfile.to_hash hash.should == { 'PODS' => [ { 'BananaLib (1.0)' => ['monkey (< 1.0.9, ~> 1.0.1)'] }, 'JSONKit (1.4)', 'monkey (1.0.8)'], 'DEPENDENCIES' => ['BananaLib (~> 1.0)', 'JSONKit (from `path/JSONKit.podspec`)'], 'EXTERNAL SOURCES' => { 'JSONKit' => { :podspec => 'path/JSONKit.podspec' } }, 'CHECKOUT OPTIONS' => { 'JSONKit' => { :podspec => 'path/JSONKit.podspec' } }, 'SPEC CHECKSUMS' => { 'BananaLib' => 'd46ca864666e216300a0653de197668b12e732a1', 'JSONKit' => '92ae5f71b77c8dec0cd8d0744adab79d38560949' }, 'PODFILE CHECKSUM' => 'podfile_checksum', 'COCOAPODS' => CORE_VERSION, } end it 'handles when the podfile has no checksum' do podfile = Sample.podfile podfile.stubs(:checksum).returns(nil) @lockfile = Lockfile.generate(podfile, Sample.specs, Sample.checkout_options) @lockfile.to_hash.should.not.key?('PODFILE CHECKSUM') end it 'generates an ordered YAML representation' do @lockfile.to_yaml.should == Sample.yaml end it 'generates a valid YAML representation' do YAMLHelper.load_string(@lockfile.to_yaml).should == YAMLHelper.load_string(Sample.yaml) end it 'serializes correctly external dependencies' do podfile = Podfile.new do platform :ios pod 'BananaLib', :git => 'www.example.com', :tag => '1.0' end specs = [ Specification.new do |s| s.name = 'BananaLib' s.version = '1.0' end, Specification.new do |s| s.name = 'monkey' s.version = '1.0.8' end, ] checkout_options = { 'BananaLib' => { :git => 'www.example.com', :tag => '1.0' }, } lockfile = Lockfile.generate(podfile, specs, checkout_options) lockfile.internal_data['DEPENDENCIES'][0].should == 'BananaLib (from `www.example.com`, tag `1.0`)' lockfile.internal_data['EXTERNAL SOURCES']['BananaLib'].should == { :git => 'www.example.com', :tag => '1.0' } end end #-------------------------------------------------------------------------# describe 'Generation from a Podfile' do before do @lockfile = Lockfile.generate(Sample.podfile, Sample.specs, Sample.checkout_options) end it 'stores the information of the installed pods and of their dependencies' do @lockfile.internal_data['PODS'].should == [ { 'BananaLib (1.0)' => ['monkey (< 1.0.9, ~> 1.0.1)'] }, 'JSONKit (1.4)', 'monkey (1.0.8)', ] end it 'stores the information of the dependencies of the Podfile' do @lockfile.internal_data['DEPENDENCIES'].should == [ 'BananaLib (~> 1.0)', 'JSONKit (from `path/JSONKit.podspec`)' ] end it 'stores the information of the external sources' do @lockfile.internal_data['EXTERNAL SOURCES'].should == { 'JSONKit' => { :podspec => 'path/JSONKit.podspec' }, } end it 'stores the checksum of the specifications' do @lockfile.internal_data['SPEC CHECKSUMS'].should == { 'BananaLib' => 'd46ca864666e216300a0653de197668b12e732a1', 'JSONKit' => '92ae5f71b77c8dec0cd8d0744adab79d38560949', } end it 'store the version of the CocoaPods Core gem' do @lockfile.internal_data['COCOAPODS'].should == CORE_VERSION end it 'it includes all the information that it is expected to store' do @lockfile.internal_data.should == YAMLHelper.load_string(Sample.yaml) end end #-------------------------------------------------------------------------# describe 'Private helpers' do describe '#generate_pods_data' do it 'groups multiple dependencies for the same pod' do specs = [ Specification.new do |s| s.name = 'BananaLib' s.version = '1.0' s.dependency 'monkey', '< 1.0.9' end, Specification.new do |s| s.name = 'BananaLib' s.version = '1.0' s.dependency 'tree', '~> 1.0.1' end, ] pods_data = Lockfile.send(:generate_pods_data, specs) pods_data.should == [{ 'BananaLib (1.0)' => ['monkey (< 1.0.9)', 'tree (~> 1.0.1)'], }] end end end end end
dacaiguoguogmail/Core
spec/lockfile_spec.rb
Ruby
mit
15,656
/** * Copyright &copy; 2012-2014 <a href="http://www.iwantclick.com">iWantClick</a>iwc.shop All rights reserved. */ package com.iwc.shop.modules.act.web; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.stream.XMLStreamException; import com.iwc.shop.common.utils.StringUtils; import com.iwc.shop.common.web.BaseController; import org.activiti.engine.runtime.ProcessInstance; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.iwc.shop.common.persistence.Page; import com.iwc.shop.modules.act.service.ActProcessService; /** * 流程定义相关Controller * @author Tony Wong * @version 2013-11-03 */ @Controller @RequestMapping(value = "${adminPath}/act/process") public class ActProcessController extends BaseController { @Autowired private ActProcessService actProcessService; /** * 流程定义列表 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = {"list", ""}) public String processList(String category, HttpServletRequest request, HttpServletResponse response, Model model) { /* * 保存两个对象,一个是ProcessDefinition(流程定义),一个是Deployment(流程部署) */ Page<Object[]> page = actProcessService.processList(new Page<Object[]>(request, response), category); model.addAttribute("page", page); model.addAttribute("category", category); return "modules/act/actProcessList"; } /** * 运行中的实例列表 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "running") public String runningList(String procInsId, String procDefKey, HttpServletRequest request, HttpServletResponse response, Model model) { Page<ProcessInstance> page = actProcessService.runningList(new Page<ProcessInstance>(request, response), procInsId, procDefKey); model.addAttribute("page", page); model.addAttribute("procInsId", procInsId); model.addAttribute("procDefKey", procDefKey); return "modules/act/actProcessRunningList"; } /** * 读取资源,通过部署ID * @param processDefinitionId 流程定义ID * @param processInstanceId 流程实例ID * @param resourceType 资源类型(xml|image) * @param response * @throws Exception */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "resource/read") public void resourceRead(String procDefId, String proInsId, String resType, HttpServletResponse response) throws Exception { InputStream resourceAsStream = actProcessService.resourceRead(procDefId, proInsId, resType); byte[] b = new byte[1024]; int len = -1; while ((len = resourceAsStream.read(b, 0, 1024)) != -1) { response.getOutputStream().write(b, 0, len); } } /** * 部署流程 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "/deploy", method=RequestMethod.GET) public String deploy(Model model) { return "modules/act/actProcessDeploy"; } /** * 部署流程 - 保存 * @param file * @return */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "/deploy", method=RequestMethod.POST) public String deploy(@Value("#{APP_PROP['activiti.export.diagram.path']}") String exportDir, String category, MultipartFile file, RedirectAttributes redirectAttributes) { String fileName = file.getOriginalFilename(); if (StringUtils.isBlank(fileName)){ redirectAttributes.addFlashAttribute("message", "请选择要部署的流程文件"); }else{ String message = actProcessService.deploy(exportDir, category, file); redirectAttributes.addFlashAttribute("message", message); } return "redirect:" + adminPath + "/act/process"; } /** * 设置流程分类 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "updateCategory") public String updateCategory(String procDefId, String category, RedirectAttributes redirectAttributes) { actProcessService.updateCategory(procDefId, category); return "redirect:" + adminPath + "/act/process"; } /** * 挂起、激活流程实例 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "update/{state}") public String updateState(@PathVariable("state") String state, String procDefId, RedirectAttributes redirectAttributes) { String message = actProcessService.updateState(state, procDefId); redirectAttributes.addFlashAttribute("message", message); return "redirect:" + adminPath + "/act/process"; } /** * 将部署的流程转换为模型 * @param procDefId * @param redirectAttributes * @return * @throws UnsupportedEncodingException * @throws XMLStreamException */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "convert/toModel") public String convertToModel(String procDefId, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException, XMLStreamException { org.activiti.engine.repository.Model modelData = actProcessService.convertToModel(procDefId); redirectAttributes.addFlashAttribute("message", "转换模型成功,模型ID="+modelData.getId()); return "redirect:" + adminPath + "/act/model"; } /** * 导出图片文件到硬盘 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "export/diagrams") @ResponseBody public List<String> exportDiagrams(@Value("#{APP_PROP['activiti.export.diagram.path']}") String exportDir) throws IOException { List<String> files = actProcessService.exportDiagrams(exportDir);; return files; } /** * 删除部署的流程,级联删除流程实例 * @param deploymentId 流程部署ID */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "delete") public String delete(String deploymentId) { actProcessService.deleteDeployment(deploymentId); return "redirect:" + adminPath + "/act/process"; } /** * 删除流程实例 * @param procInsId 流程实例ID * @param reason 删除原因 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "deleteProcIns") public String deleteProcIns(String procInsId, String reason, RedirectAttributes redirectAttributes) { if (StringUtils.isBlank(reason)){ addMessage(redirectAttributes, "请填写删除原因"); }else{ actProcessService.deleteProcIns(procInsId, reason); addMessage(redirectAttributes, "删除流程实例成功,实例ID=" + procInsId); } return "redirect:" + adminPath + "/act/process/running/"; } }
newmann/shop
src/main/java/com/iwc/shop/modules/act/web/ActProcessController.java
Java
mit
7,103
package net.dckg.daogenerator; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.sql.Types; /** * Denotes a column in database. * <p> * Every DAO property must be public and have this annotation; * <br> - name is it's column name in database * <br> - type is it's column type in database * <br> * <b>The order of properties must be the same as in database table create script.</b> * * @see java.sql.Types */ @Retention(RetentionPolicy.RUNTIME) public @interface Column { String name() default ""; /** * the SQL type (as defined in java.sql.Types) to be sent to the database * <br> * Defaults to INTEGER * * @return java.sql.Types */ int type() default Types.INTEGER; }
dckg/daogenerator
src/main/java/net/dckg/daogenerator/Column.java
Java
mit
743
import { Feature } from 'core/feature'; import * as toolkitHelper from 'helpers/toolkit'; export class TargetBalanceWarning extends Feature { constructor() { super(); } shouldInvoke() { return toolkitHelper.getCurrentRouteName().indexOf('budget') !== -1; } invoke() { $('.budget-table-row.is-sub-category').each((index, element) => { const emberId = element.id; const viewData = toolkitHelper.getEmberView(emberId).data; const { subCategory } = viewData; if (subCategory.get('goalType') === ynab.constants.SubCategoryGoalType.TargetBalance) { const available = viewData.get('available'); const targetBalance = subCategory.get('targetBalance'); const currencyElement = $('.budget-table-cell-available .user-data.currency', element); if (available < targetBalance && !currencyElement.hasClass('cautious')) { if (currencyElement.hasClass('positive')) { currencyElement.removeClass('positive'); } currencyElement.addClass('cautious'); } } }); } observe(changedNodes) { if (!this.shouldInvoke()) return; if (changedNodes.has('budget-table-cell-available-div user-data')) { this.invoke(); } } onRouteChanged() { if (!this.shouldInvoke()) return; this.invoke(); } }
egens/toolkit-for-ynab
sauce/features/budget/target-balance-warning/index.js
JavaScript
mit
1,342
# encoding: utf-8 require 'do_postgres' require 'rom/support/axiom/adapter' require 'rom/support/axiom/adapter/data_objects' module Axiom module Adapter # A Axiom adapter for postgres # class Postgres < DataObjects uri_scheme :postgres end # class Postgres end # module Adapter end # module Axiom
solnic/rom-relation
lib/rom/support/axiom/adapter/postgres.rb
Ruby
mit
329
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form; use Symfony\Component\Form\Event\DataEvent; use Symfony\Component\Form\Event\FilterDataEvent; use Symfony\Component\Form\Exception\FormException; use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * Form represents a form. * * A form is composed of a validator schema and a widget form schema. * * To implement your own form fields, you need to have a thorough understanding * of the data flow within a form field. A form field stores its data in three * different representations: * * (1) the format required by the form's object * (2) a normalized format for internal processing * (3) the format used for display * * A date field, for example, may store a date as "Y-m-d" string (1) in the * object. To facilitate processing in the field, this value is normalized * to a DateTime object (2). In the HTML representation of your form, a * localized string (3) is presented to and modified by the user. * * In most cases, format (1) and format (2) will be the same. For example, * a checkbox field uses a Boolean value both for internal processing as for * storage in the object. In these cases you simply need to set a value * transformer to convert between formats (2) and (3). You can do this by * calling appendClientTransformer(). * * In some cases though it makes sense to make format (1) configurable. To * demonstrate this, let's extend our above date field to store the value * either as "Y-m-d" string or as timestamp. Internally we still want to * use a DateTime object for processing. To convert the data from string/integer * to DateTime you can set a normalization transformer by calling * appendNormTransformer(). The normalized data is then * converted to the displayed data as described before. * * @author Fabien Potencier <fabien@symfony.com> * @author Bernhard Schussek <bernhard.schussek@symfony.com> */ class Form implements \IteratorAggregate, FormInterface { /** * The name of this form * @var string */ private $name; /** * The parent of this form * @var FormInterface */ private $parent; /** * The children of this form * @var array An array of FormInterface instances */ private $children = array(); /** * The mapper for mapping data to children and back * @var DataMapper\DataMapperInterface */ private $dataMapper; /** * The errors of this form * @var array An array of FromError instances */ private $errors = array(); /** * Whether added errors should bubble up to the parent * @var Boolean */ private $errorBubbling; /** * Whether this form is bound * @var Boolean */ private $bound = false; /** * Whether this form may not be empty * @var Boolean */ private $required; /** * The form data in application format * @var mixed */ private $appData; /** * The form data in normalized format * @var mixed */ private $normData; /** * The form data in client format * @var mixed */ private $clientData; /** * Data used for the client data when no value is bound * @var mixed */ private $emptyData = ''; /** * The bound values that don't belong to any children * @var array */ private $extraData = array(); /** * The transformers for transforming from application to normalized format * and back * @var array An array of DataTransformerInterface */ private $normTransformers; /** * The transformers for transforming from normalized to client format and * back * @var array An array of DataTransformerInterface */ private $clientTransformers; /** * Whether the data in application, normalized and client format is * synchronized. Data may not be synchronized if transformation errors * occur. * @var Boolean */ private $synchronized = true; /** * The validators attached to this form * @var array An array of FormValidatorInterface instances */ private $validators; /** * Whether this form may only be read, but not bound * @var Boolean */ private $readOnly = false; /** * The dispatcher for distributing events of this form * @var Symfony\Component\EventDispatcher\EventDispatcherInterface */ private $dispatcher; /** * Key-value store for arbitrary attributes attached to this form * @var array */ private $attributes; /** * The FormTypeInterface instances used to create this form * @var array An array of FormTypeInterface */ private $types; public function __construct($name, EventDispatcherInterface $dispatcher, array $types = array(), array $clientTransformers = array(), array $normTransformers = array(), DataMapperInterface $dataMapper = null, array $validators = array(), $required = false, $readOnly = false, $errorBubbling = false, $emptyData = null, array $attributes = array()) { foreach ($clientTransformers as $transformer) { if (!$transformer instanceof DataTransformerInterface) { throw new UnexpectedTypeException($transformer, 'Symfony\Component\Form\DataTransformerInterface'); } } foreach ($normTransformers as $transformer) { if (!$transformer instanceof DataTransformerInterface) { throw new UnexpectedTypeException($transformer, 'Symfony\Component\Form\DataTransformerInterface'); } } foreach ($validators as $validator) { if (!$validator instanceof FormValidatorInterface) { throw new UnexpectedTypeException($validator, 'Symfony\Component\Form\FormValidatorInterface'); } } $this->name = (string) $name; $this->dispatcher = $dispatcher; $this->types = $types; $this->clientTransformers = $clientTransformers; $this->normTransformers = $normTransformers; $this->dataMapper = $dataMapper; $this->validators = $validators; $this->required = (Boolean) $required; $this->readOnly = (Boolean) $readOnly; $this->errorBubbling = (Boolean) $errorBubbling; $this->emptyData = $emptyData; $this->attributes = $attributes; $this->setData(null); } public function __clone() { foreach ($this->children as $key => $child) { $this->children[$key] = clone $child; } } /** * Returns the name by which the form is identified in forms. * * @return string The name of the form. */ public function getName() { return $this->name; } /** * Returns the types used by this form. * * @return array An array of FormTypeInterface */ public function getTypes() { return $this->types; } /** * Returns whether the form is required to be filled out. * * If the form has a parent and the parent is not required, this method * will always return false. Otherwise the value set with setRequired() * is returned. * * @return Boolean */ public function isRequired() { if (null === $this->parent || $this->parent->isRequired()) { return $this->required; } return false; } /** * Returns whether this form is read only. * * The content of a read-only form is displayed, but not allowed to be * modified. The validation of modified read-only forms should fail. * * Fields whose parents are read-only are considered read-only regardless of * their own state. * * @return Boolean */ public function isReadOnly() { if (null === $this->parent || !$this->parent->isReadOnly()) { return $this->readOnly; } return true; } /** * Sets the parent form. * * @param FormInterface $parent The parent form * * @return Form The current form */ public function setParent(FormInterface $parent = null) { if ('' === $this->getName()) { throw new FormException('Form with empty name can not have parent form.'); } $this->parent = $parent; return $this; } /** * Returns the parent field. * * @return FormInterface The parent field */ public function getParent() { return $this->parent; } /** * Returns whether the form has a parent. * * @return Boolean */ public function hasParent() { return null !== $this->parent; } /** * Returns the root of the form tree. * * @return FormInterface The root of the tree */ public function getRoot() { return $this->parent ? $this->parent->getRoot() : $this; } /** * Returns whether the field is the root of the form tree. * * @return Boolean */ public function isRoot() { return !$this->hasParent(); } /** * Returns whether the form has an attribute with the given name. * * @param string $name The name of the attribute * * @return Boolean */ public function hasAttribute($name) { return isset($this->attributes[$name]); } /** * Returns the value of the attributes with the given name. * * @param string $name The name of the attribute */ public function getAttribute($name) { return $this->attributes[$name]; } /** * Updates the field with default data. * * @param array $appData The data formatted as expected for the underlying object * * @return Form The current form */ public function setData($appData) { $event = new DataEvent($this, $appData); $this->dispatcher->dispatch(FormEvents::PRE_SET_DATA, $event); // Hook to change content of the data $event = new FilterDataEvent($this, $appData); $this->dispatcher->dispatch(FormEvents::SET_DATA, $event); $appData = $event->getData(); // Treat data as strings unless a value transformer exists if (!$this->clientTransformers && !$this->normTransformers && is_scalar($appData)) { $appData = (string) $appData; } // Synchronize representations - must not change the content! $normData = $this->appToNorm($appData); $clientData = $this->normToClient($normData); $this->appData = $appData; $this->normData = $normData; $this->clientData = $clientData; $this->synchronized = true; if ($this->dataMapper) { // Update child forms from the data $this->dataMapper->mapDataToForms($clientData, $this->children); } $event = new DataEvent($this, $appData); $this->dispatcher->dispatch(FormEvents::POST_SET_DATA, $event); return $this; } /** * Returns the data in the format needed for the underlying object. * * @return mixed */ public function getData() { return $this->appData; } /** * Returns the data transformed by the value transformer. * * @return string */ public function getClientData() { return $this->clientData; } /** * Returns the extra data. * * @return array The bound data which do not belong to a child */ public function getExtraData() { return $this->extraData; } /** * Binds data to the field, transforms and validates it. * * @param string|array $clientData The data * * @return Form The current form * * @throws UnexpectedTypeException */ public function bind($clientData) { if ($this->readOnly) { $this->bound = true; return $this; } if (is_scalar($clientData) || null === $clientData) { $clientData = (string) $clientData; } // Initialize errors in the very beginning so that we don't lose any // errors added during listeners $this->errors = array(); $event = new DataEvent($this, $clientData); $this->dispatcher->dispatch(FormEvents::PRE_BIND, $event); $appData = null; $normData = null; $extraData = array(); $synchronized = false; // Hook to change content of the data bound by the browser $event = new FilterDataEvent($this, $clientData); $this->dispatcher->dispatch(FormEvents::BIND_CLIENT_DATA, $event); $clientData = $event->getData(); if (count($this->children) > 0) { if (null === $clientData || '' === $clientData) { $clientData = array(); } if (!is_array($clientData)) { throw new UnexpectedTypeException($clientData, 'array'); } foreach ($this->children as $name => $child) { if (!isset($clientData[$name])) { $clientData[$name] = null; } } foreach ($clientData as $name => $value) { if ($this->has($name)) { $this->children[$name]->bind($value); } else { $extraData[$name] = $value; } } // If we have a data mapper, use old client data and merge // data from the children into it later if ($this->dataMapper) { $clientData = $this->getClientData(); } } if (null === $clientData || '' === $clientData) { $clientData = $this->emptyData; if ($clientData instanceof \Closure) { $clientData = $clientData($this); } } // Merge form data from children into existing client data if (count($this->children) > 0 && $this->dataMapper) { $this->dataMapper->mapFormsToData($this->children, $clientData); } try { // Normalize data to unified representation $normData = $this->clientToNorm($clientData); $synchronized = true; } catch (TransformationFailedException $e) { } if ($synchronized) { // Hook to change content of the data in the normalized // representation $event = new FilterDataEvent($this, $normData); $this->dispatcher->dispatch(FormEvents::BIND_NORM_DATA, $event); $normData = $event->getData(); // Synchronize representations - must not change the content! $appData = $this->normToApp($normData); $clientData = $this->normToClient($normData); } $this->bound = true; $this->appData = $appData; $this->normData = $normData; $this->clientData = $clientData; $this->extraData = $extraData; $this->synchronized = $synchronized; $event = new DataEvent($this, $clientData); $this->dispatcher->dispatch(FormEvents::POST_BIND, $event); foreach ($this->validators as $validator) { $validator->validate($this); } return $this; } /** * Binds a request to the form. * * If the request method is POST, PUT or GET, the data is bound to the form, * transformed and written into the form data (an object or an array). * * @param Request $request The request to bind to the form * * @return Form This form * * @throws FormException if the method of the request is not one of GET, POST or PUT */ public function bindRequest(Request $request) { // Store the bound data in case of a post request switch ($request->getMethod()) { case 'POST': case 'PUT': case 'DELETE': if ('' === $this->getName()) { $data = array_replace_recursive( $request->request->all(), $request->files->all() ); } else { $data = array_replace_recursive( $request->request->get($this->getName(), array()), $request->files->get($this->getName(), array()) ); } break; case 'GET': $data = '' === $this->getName() ? $request->query->all() : $request->query->get($this->getName(), array()); break; default: throw new FormException(sprintf('The request method "%s" is not supported', $request->getMethod())); } return $this->bind($data); } /** * Returns the normalized data of the field. * * @return mixed When the field is not bound, the default data is returned. * When the field is bound, the normalized bound data is * returned if the field is valid, null otherwise. */ public function getNormData() { return $this->normData; } /** * Adds an error to this form. * * @param FormError $error * * @return Form The current form */ public function addError(FormError $error) { if ($this->parent && $this->errorBubbling) { $this->parent->addError($error); } else { $this->errors[] = $error; } return $this; } /** * Returns whether errors bubble up to the parent. * * @return Boolean */ public function getErrorBubbling() { return $this->errorBubbling; } /** * Returns whether the field is bound. * * @return Boolean true if the form is bound to input values, false otherwise */ public function isBound() { return $this->bound; } /** * Returns whether the data in the different formats is synchronized. * * @return Boolean */ public function isSynchronized() { return $this->synchronized; } /** * Returns whether the form is empty. * * @return Boolean */ public function isEmpty() { foreach ($this->children as $child) { if (!$child->isEmpty()) { return false; } } return array() === $this->appData || null === $this->appData || '' === $this->appData; } /** * Returns whether the field is valid. * * @return Boolean */ public function isValid() { if (!$this->isBound()) { throw new \LogicException('You cannot call isValid() on a form that is not bound.'); } if ($this->hasErrors()) { return false; } if (!$this->readOnly) { foreach ($this->children as $child) { if (!$child->isValid()) { return false; } } } return true; } /** * Returns whether or not there are errors. * * @return Boolean true if form is bound and not valid */ public function hasErrors() { // Don't call isValid() here, as its semantics are slightly different // Field groups are not valid if their children are invalid, but // hasErrors() returns only true if a field/field group itself has // errors return count($this->errors) > 0; } /** * Returns all errors. * * @return array An array of FormError instances that occurred during binding */ public function getErrors() { return $this->errors; } /** * Returns a string representation of all form errors (including children errors). * * This method should only be used to help debug a form. * * @param integer $level The indentation level (used internally) * * @return string A string representation of all errors */ public function getErrorsAsString($level = 0) { $errors = ''; foreach ($this->errors as $error) { $errors .= str_repeat(' ', $level).'ERROR: '.$error->getMessage()."\n"; } if ($this->hasChildren()) { foreach ($this->children as $key => $child) { $errors .= str_repeat(' ', $level).$key.":\n"; if ($err = $child->getErrorsAsString($level + 4)) { $errors .= $err; } else { $errors .= str_repeat(' ', $level + 4)."No errors\n"; } } } return $errors; } /** * Returns the DataTransformers. * * @return array An array of DataTransformerInterface */ public function getNormTransformers() { return $this->normTransformers; } /** * Returns the DataTransformers. * * @return array An array of DataTransformerInterface */ public function getClientTransformers() { return $this->clientTransformers; } /** * Returns all children in this group. * * @return array */ public function getChildren() { return $this->children; } /** * Return whether the form has children. * * @return Boolean */ public function hasChildren() { return count($this->children) > 0; } /** * Adds a child to the form. * * @param FormInterface $child The FormInterface to add as a child * * @return Form the current form */ public function add(FormInterface $child) { $this->children[$child->getName()] = $child; $child->setParent($this); if ($this->dataMapper) { $this->dataMapper->mapDataToForm($this->getClientData(), $child); } return $this; } /** * Removes a child from the form. * * @param string $name The name of the child to remove * * @return Form the current form */ public function remove($name) { if (isset($this->children[$name])) { $this->children[$name]->setParent(null); unset($this->children[$name]); } return $this; } /** * Returns whether a child with the given name exists. * * @param string $name * * @return Boolean */ public function has($name) { return isset($this->children[$name]); } /** * Returns the child with the given name. * * @param string $name * * @return FormInterface * * @throws \InvalidArgumentException if the child does not exist */ public function get($name) { if (isset($this->children[$name])) { return $this->children[$name]; } throw new \InvalidArgumentException(sprintf('Field "%s" does not exist.', $name)); } /** * Returns true if the child exists (implements the \ArrayAccess interface). * * @param string $name The name of the child * * @return Boolean true if the widget exists, false otherwise */ public function offsetExists($name) { return $this->has($name); } /** * Returns the form child associated with the name (implements the \ArrayAccess interface). * * @param string $name The offset of the value to get * * @return FormInterface A form instance */ public function offsetGet($name) { return $this->get($name); } /** * Adds a child to the form (implements the \ArrayAccess interface). * * @param string $name Ignored. The name of the child is used. * @param FormInterface $child The child to be added */ public function offsetSet($name, $child) { $this->add($child); } /** * Removes the child with the given name from the form (implements the \ArrayAccess interface). * * @param string $name The name of the child to be removed */ public function offsetUnset($name) { $this->remove($name); } /** * Returns the iterator for this group. * * @return \ArrayIterator */ public function getIterator() { return new \ArrayIterator($this->children); } /** * Returns the number of form children (implements the \Countable interface). * * @return integer The number of embedded form children */ public function count() { return count($this->children); } /** * Creates a view. * * @param FormView $parent The parent view * * @return FormView The view */ public function createView(FormView $parent = null) { if (null === $parent && $this->parent) { $parent = $this->parent->createView(); } $view = new FormView(); $view->setParent($parent); $types = (array) $this->types; foreach ($types as $type) { $type->buildView($view, $this); foreach ($type->getExtensions() as $typeExtension) { $typeExtension->buildView($view, $this); } } $childViews = array(); foreach ($this->children as $key => $child) { $childViews[$key] = $child->createView($view); } $view->setChildren($childViews); foreach ($types as $type) { $type->buildViewBottomUp($view, $this); foreach ($type->getExtensions() as $typeExtension) { $typeExtension->buildViewBottomUp($view, $this); } } return $view; } /** * Normalizes the value if a normalization transformer is set. * * @param mixed $value The value to transform * * @return string */ private function appToNorm($value) { foreach ($this->normTransformers as $transformer) { $value = $transformer->transform($value); } return $value; } /** * Reverse transforms a value if a normalization transformer is set. * * @param string $value The value to reverse transform * * @return mixed */ private function normToApp($value) { for ($i = count($this->normTransformers) - 1; $i >= 0; --$i) { $value = $this->normTransformers[$i]->reverseTransform($value); } return $value; } /** * Transforms the value if a value transformer is set. * * @param mixed $value The value to transform * * @return string */ private function normToClient($value) { if (!$this->clientTransformers) { // Scalar values should always be converted to strings to // facilitate differentiation between empty ("") and zero (0). return null === $value || is_scalar($value) ? (string) $value : $value; } foreach ($this->clientTransformers as $transformer) { $value = $transformer->transform($value); } return $value; } /** * Reverse transforms a value if a value transformer is set. * * @param string $value The value to reverse transform * * @return mixed */ private function clientToNorm($value) { if (!$this->clientTransformers) { return '' === $value ? null : $value; } for ($i = count($this->clientTransformers) - 1; $i >= 0; --$i) { $value = $this->clientTransformers[$i]->reverseTransform($value); } return $value; } }
ttsuru/ecx
vendor/symfony/src/Symfony/Component/Form/Form.php
PHP
mit
28,443
package log type logLevel struct { Level int Prefix string ColorFunc func(...interface{}) string } type logLevels []*logLevel func (l *logLevels) getFunc(Level int) func(...interface{}) string { level := l.getLevel(Level) if level != nil { return level.ColorFunc } return nil } func (l *logLevels) getLevel(Level int) *logLevel { for _, item := range *l { if item.Level == Level { return item } } return nil }
kittuov/go-django
utils/log/structs.go
GO
mit
440
# coding: utf-8 from geventwebsocket.handler import WebSocketHandler from gevent import pywsgi, sleep import json import MySQLdb class JPC: # # 初期化 # def __init__(self, filepath_config): import hashlib # 設定ファイルをロード fp = open(filepath_config, 'r') config = json.load(fp) fp.close() # 設定をクラス変数に格納 self.host = config['host'] self.port = config['port'] self.langlist = json.load(open(config['langfile'], 'r')) self.enckey = hashlib.md5(config['key']).digest() self.db_host = config['db_host'] self.db_name = config['db_name'] self.db_username = config['db_username'] self.db_password = config['db_password'] return # # チェック # def execute(self): import codecs import commands import os import pwd # 情報を取得 code = self.packet['code'] lang = self.packet['lang'] script = self.langlist['compile'][lang] extension = self.langlist['extension'][lang] # 必要なデータを生成 filepath_in = self.randstr(8) + extension filepath_out = self.randstr(8) username = self.randstr(16) # /tmpに移動 os.chdir('/tmp/') # ユーザーを作成する try: os.system("useradd -M {0}".format(username)) pwnam = pwd.getpwnam(username) except Exception: return # コードを生成 fp = codecs.open(filepath_in, 'w', 'utf-8') fp.write(code) fp.close() # コンパイル compile_result = commands.getoutput( script.format(input=filepath_in, output=filepath_out) ) # コードを削除 try: os.remove(filepath_in) except Exception: pass # コンパイル結果を送信 try: self.ws.send(json.dumps({'compile': compile_result})) except Exception: pass # コンパイルできているか if not os.path.exists(filepath_out): print("[INFO] コンパイルに失敗しました。") return # 実行ファイルの権限を変更 try: os.chmod(filepath_out, 0500) os.chown(filepath_out, pwnam.pw_uid, pwnam.pw_gid) # 出力例も一応 os.chown(self.record['output_code'], pwnam.pw_uid, pwnam.pw_gid) except Exception: try: os.remove(filepath_out) os.system("userdel -r {0}".format(username)) except Exception: print("[ERROR] /tmp/{0}の削除に失敗しました。".format(filepath_out)) print("[ERROR] ユーザー{0}の削除に失敗しました。".format(username)) return # チェックする clear = True for n in range(int(self.record['exec_time'])): print("[INFO] {0}回目の試行が開始されました。".format(n + 1)) # 実行開始を宣言 try: self.ws.send(json.dumps({'attempt': n + 1})) except Exception: pass # 入力を生成 self.input_data = commands.getoutput( self.record['input_code'] + " " + str(n) ) # 出力を生成 self.output_data = self.run_command(username, self.record['output_code']) # 実行結果を取得 result = self.run_command(username, './'+filepath_out) #print "Input : ", self.input_data #print "Answer : ", self.output_data #print "Result : ", result # タイムアウト if result == False: self.ws.send(json.dumps({'failure': n + 1})) clear = False print("[INFO] タイムアウトしました。") continue # 結果が違う if self.output_data.rstrip('\n') != result.rstrip('\n'): self.ws.send(json.dumps({'failure': n + 1})) clear = False print("[INFO] 結果に誤りがあります。") continue # 実行結果を宣言 try: self.ws.send(json.dumps({'success': n + 1})) print("[INFO] チェックが成功しました。") except Exception: pass # 成功通知 if clear: self.ws.send('{"complete":"success"}') self.update_db() else: self.ws.send('{"complete":"failure"}') # 実行ファイルを削除 try: os.remove(filepath_out) os.system("userdel -r {0}".format(username)) except Exception: print("[ERROR] /tmp/{0}の削除に失敗しました。".format(filepath_out)) print("[ERROR] ユーザー{0}の削除に失敗しました。".format(username)) return # # コマンドを制限付きで実行 # def run_command(self, username, filepath): import subprocess import time import sys # プロセスを生成 proc = subprocess.Popen( [ 'su', username, '-c', 'ulimit -v {0}; {1}'.format( str(self.record['limit_memory']), filepath ) ], stdout = subprocess.PIPE, stderr = subprocess.PIPE, stdin = subprocess.PIPE, ) # 入力を送る proc.stdin.write(self.input_data.rstrip('\n') + '\n') proc.stdin.close() # 時間制限を設定 deadline = time.time() + float(self.record['limit_time']) / 1000.0 while time.time() < deadline and proc.poll() == None: time.sleep(0.20) # タイムアウト if proc.poll() == None: if float(sys.version[:3]) >= 2.6: proc.terminate() return False # 正常終了 stdout = proc.stdout.read() return stdout # # 点数を追加 # def update_db(self): import time cursor = self.db.cursor(MySQLdb.cursors.DictCursor) # スコアを追加 cursor.execute("UPDATE account SET score=score+{score} WHERE user='{user}';".format(score=int(self.record['score']), user=self.user)) # 解答済み問題を追加 cursor.execute("UPDATE account SET solved=concat('{id},', solved) WHERE user='{user}';".format(id=self.record['id'], user=self.user)) # 解答数をインクリメント cursor.execute("UPDATE problem SET solved=solved+1 WHERE id={id};".format(id=self.record['id'])) # 解答ユーザーを更新 cursor.execute("UPDATE problem SET solved_user='{user}' WHERE id={id};".format(user=self.user, id=self.record['id'])) # 解答時間を更新 cursor.execute("UPDATE problem SET last_date='{date}' WHERE id={id};".format(date=time.strftime('%Y-%m-%d %H:%M:%S'), id=self.record['id'])) cursor.close() self.db.commit() return # # 新規要求を処理 # def handle(self, env, response): self.ws = env['wsgi.websocket'] print("[INFO] 新しい要求を受信しました。") # 要求を取得 self.packet = self.ws.receive() if not self.analyse_packet(): return # 問題を取得 self.get_problem() # 実行 self.execute() return # # 問題の詳細を取得 # def get_problem(self): cursor = self.db.cursor(MySQLdb.cursors.DictCursor) cursor.execute("SELECT * FROM problem WHERE id={id};".format(id=self.packet['id'])) self.record = cursor.fetchall()[0] cursor.close() return # # データを解析 # def analyse_packet(self): from Crypto.Cipher import AES # パケットをJSONとして展開 try: self.packet = json.loads(self.packet) except Exception: print("[ERROR] JSONの展開に失敗しました。") return False # データの整合性を確認 if not self.check_payload(): print("[ERROR] 不正なデータであると判別されました。") self.ws.send('{"error":"無効なデータが送信されました。"}') return False # ユーザー名を復号化 iv = self.packet['iv'].decode('base64') enc_user = self.packet['user'].decode('base64') aes = AES.new(self.enckey, AES.MODE_CBC, iv) self.user = aes.decrypt(enc_user).replace('\x00', '') print("[INFO] この試行のユーザーは{0}です。".format(self.user)) # エスケープ self.user = MySQLdb.escape_string(self.user) self.packet['id'] = int(self.packet['id']) return True # # payloadが有効かを調べる # def check_payload(self): # 最低限の情報が記載されているか if 'lang' not in self.packet : return False if 'code' not in self.packet : return False if 'id' not in self.packet : return False if 'iv' not in self.packet : return False if 'user' not in self.packet : return False # 言語が使用可能か if 'compile' not in self.langlist : return False if 'extension' not in self.langlist : return False if self.packet['lang'] not in self.langlist['compile'] : return False if self.packet['lang'] not in self.langlist['extension'] : return False # データが正しい return True # # ランダムな文字列を生成 # def randstr(self, length): import random import string return ''.join([ random.choice(string.ascii_letters + string.digits) for i in range(length) ]) # # リクエストを受ける # def procon(self, env, response): path = env['PATH_INFO'] if path == "/": return self.handle(env, response) return # # サーバーを稼働させる # def run(self): # サーバー初期化 server = pywsgi.WSGIServer( (self.host, self.port), self.procon, handler_class = WebSocketHandler ) # SQLへの接続 self.db = MySQLdb.connect(host = self.db_host, db = self.db_name, user = self.db_username, passwd = self.db_password, charset = 'utf8', ) # サーバー稼働 server.serve_forever() return
ptr-yudai/JokenPC
server/JPC.py
Python
mit
11,068
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FootPickup : MonoBehaviour { bool glued; void OnTriggerEnter(Collider collider) { if (collider.tag == "Glue") { } } }
denniscarr/VirtualFeet
Assets/Scripts/FootPickup.cs
C#
mit
269
module MixpanelTracker module ControllerHelpers extend ActiveSupport::Concern included do helper_method :mixpanel def mixpanel s = session rescue nil @mixpanel_tracker ||= MixpanelTracker::Tracker.new(s) end end end end
AntonZh/mixpanel_tracker
lib/mixpanel_tracker/controller_helpers.rb
Ruby
mit
271
angular.module('kindly.requests').directive('request', function() { return { restrict: 'E', replace: true, scope: { request: '=' }, controller: function($scope) { $scope.is = function(medium) { return $scope.request.medium === medium; }; }, templateUrl: 'requests/_request.html' }; });
jsvana/WouldYouKindly
app/assets/javascripts/requests/request.directive.js
JavaScript
mit
344
#include <XEEditor/IEditor.hpp> //#include <EditorI/SelectionRectangle.h> //#include "E:/Projekte/Src Game/_Engine/XEngine/TestXE/XETUI/GUI.h" //#include <EditorI/TFViewport.h> #include <XEEditor/Editor.hpp> namespace EI { EI::Editor* gEditor = nullptr; //LNK2005 error Because you enabled STATIC_STD_LIBS (which is not recommended unless you know what you do), you must set the same option in your project, which is /MTd. //http://en.sfml-dev.org/forums/index.php?topic=7071.0 //struct ImplData //{ // Ogre::Root* pRoot; // Ogre::SceneManager* pSceneManager; // Ogre::Camera* pCamera; // Ogre::Viewport* pViewport; // Ogre::RenderWindow* pRenderWindow; // Ogre::RenderSystem* pRenderSystem; // Ogre::SceneNode* pSceneNode; // Ogre::Entity* pEntity; // // CameraNodes* pCameraNodes; // // AnimationSystem* pAnimationSystem; // SelectionRectangle* pSelectionRect; // Ogre::PlaneBoundedVolumeListSceneQuery* pVolumeQuery; // bool mouseBoneSelectionModeEnabled; // // std::vector< BoneInfo > boneInfoList; // // std::vector< BoneDisplayInfo > boneDisplayInfoList; // bool boneSelectionChangedSinceLastCall; // ImplData() // : pRoot(NULL) // , pSceneManager(NULL) // , pCamera(NULL) // , pViewport(NULL) // , pRenderWindow(NULL) // , pRenderSystem(NULL) // , pSceneNode(NULL) // , pEntity(NULL) // // , pCameraNodes(NULL) // // , pAnimationSystem(NULL) // , pSelectionRect(NULL) // , pVolumeQuery(NULL) // , mouseBoneSelectionModeEnabled(false) // , boneSelectionChangedSinceLastCall(true) // { // } //}; //void CreateResourceGroups() //{ // Ogre::ResourceGroupManager::getSingleton().addResourceLocation("TecnoFreak.data", "Zip", "TecnoFreak"); //} //XE::XEngine* engine; //XE::OgreConsole* console; //EI::Editor* gEditor = nullptr; void getStates(char* statesinfo) { //std::cout << "getStates"; // statesinfo->size = 9; //Ogre::String test("hmmm"); // statesinfo = "xxx"; strncpy(statesinfo, "xxx\0", 5); std::cout << "getStates:" << statesinfo; //char temp[51]; //if (strlen(word)>50) // return false; // statesinfo[0] = test.c_str(); // statesinfo->buffer[1] = "1"; // for (int i = 0; i < statesinfo->size; i++) // statesinfo->buffer[i] = "h"; //Ogre::String str(statesinfo->buffer); //Ogre::String* states = new Ogre::String[5]; //str = "asdasd"; //states[0] = "State1"; // states[1] = "State2"; //states[2] = "State3"; //states[3] = "State4"; //statesinfo->buffer = states->c_str(); } unsigned char* command(const char* command, unsigned char* data, int len) { std::cout << "command"; if (gEditor) return gEditor->consoleCmd(command, data, len); return 0; } bool moveToState(const char* stateName) { std::cout << "moveToState"; if (gEditor) { gEditor->moveToState(stateName); return true; } return false; } void renderTargetSize(const char* rtName, Ogre::Real x, Ogre::Real y) { gEditor->renderTargetSize(rtName, x, y); } int pushEvent(sfEvent pushEvent) { //std::cout << "pushEvent"; // return pushEvent.key.code; int test = 0; if (gEditor) { test = gEditor->pushEvent(pushEvent); return test; } /*if (pushEvent.key.code == 23) return true; else*/ return -1; } void* renderOnceTexturePtr(const char* stateName, int width, int height) { void* bbSurface; if (gEditor) { if (gEditor->getEngine()->running()) { gEditor->getEngine()->update(); //Ogre::WindowEventUtilities::messagePump(); } } return bbSurface; } //LPVOID stateInit(sf::WindowHandle hwnd, const char* stateName) void* stateInit(const char* stateName, int width, int height) { std::cout << "initState"; void* bbSurface; if (!gEditor) { gEditor = new EI::Editor(); bbSurface = gEditor->InitState(stateName, width, height); std::cout << "initState OK"; /*bool running = true; while (running) { EI::stateUpdate(); }*/ return bbSurface; } return bbSurface; // std::thread t1(hello); // t1.join(); //Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); //XE::LogManager::getSingleton().logMessage("TecnoFreak: Initialising scene manger"); //g_data.pSceneManager = g_data.pRoot->createSceneManager(Ogre::ST_GENERIC); //g_data.pCamera = g_data.pSceneManager->createCamera("Default"); //g_data.pCamera->setNearClipDistance(0.1f); //g_data.pCamera->setAutoAspectRatio(true); //g_data.pViewport = g_data.pRenderWindow->addViewport(g_data.pCamera); //g_data.pViewport->setBackgroundColour(Ogre::ColourValue::Red); //Ogre::SceneNode* pRootSceneNode = g_data.pSceneManager->getRootSceneNode(); //// g_data.pCameraNodes = new CameraNodes(pRootSceneNode, g_data.pCamera); //g_data.pSelectionRect = new SelectionRectangle("Selection SelectionRectangle"); //pRootSceneNode->attachObject(g_data.pSelectionRect); //g_data.pVolumeQuery = g_data.pSceneManager->createPlaneBoundedVolumeQuery(Ogre::PlaneBoundedVolumeList()); //XE::LogManager::getSingleton().logMessage("TecnoFreak: Finished initialising Ogre viewport"); } bool stateUpdate() { if (gEditor) { if (gEditor->getEngine()->running()) { gEditor->getEngine()->update(); //Ogre::WindowEventUtilities::messagePump(); return true; } } return false; //if (g_data.pRoot == NULL) //{ // return; //} //if (g_data.pRenderWindow == NULL) //{ // return; //} ///*if (g_data.pCameraNodes == NULL) //{ //return; //}*/ //static Ogre::Timer s_frameTimer; //const unsigned long elapsedMilliseconds = s_frameTimer.getMilliseconds(); //const float elapsedSeconds = static_cast< float >(elapsedMilliseconds) / 1000.f; //s_frameTimer.reset(); //g_data.pRenderWindow->windowMovedOrResized(); //g_data.pRoot->renderOneFrame(); //g_data.pCameraNodes->Update(); //UpdateBoneColours(); //if (g_data.pAnimationSystem != NULL) //{ // g_data.pAnimationSystem->update(elapsedSeconds); //} } void quit() { if (gEditor) { gEditor->getEngine()->quit(); delete gEditor; } //ImplData tmp = g_data; //g_data = ImplData(); ////delete tmp.pAnimationSystem; ////delete tmp.pCameraNodes; //delete tmp.pSelectionRect; //delete tmp.pRoot; } //sf::WindowHandle // bool startState(sf::WindowHandle hwnd) // { // // sf::WindowHandle winHandle = reinterpret_cast<sf::WindowHandle>(hwnd); // // sf::Window* window = new sf::Window(hwnd); // // // Create the window // //sfWindow* window = new sfWindow; // //window->This.create(videoMode, title, style, params); // // //sf::Window mWindow(sf::VideoMode(800, 600), "My window"); // // unsigned long winHandle = reinterpret_cast<unsigned long>(window->getSystemHandle()); // // // // // // initialise root // Ogre::NameValuePairList misc; // misc["externalWindowHandle"] = Ogre::StringConverter::toString(winHandle); // // misc["externalGLContext"] = XE::StringConverter::toString(winGlContext); // // misc["externalGLControl"] = Ogre::String("True"); ////#else ////misc["currentGLContext"] = String("True"); ////#endif // //// XE::RenderWindow *renderWindow = root->createRenderWindow("Main", 820, 440, false, &misc); // // return true; // } } // ns EI
devxkh/FrankE
src/src/XEEditor/IEditor.cpp
C++
mit
7,297
""" download a file named filename from the atsc301 downloads directory and save it as a local file with the same name. command line example:: python -m a301utils.a301_readfile photon_data.csv module example:: from a301utils.a301_readfile import download download('photon_data.csv') """ import argparse import requests from pathlib import Path import sys import os import shutil def download(filename): """ copy file filename from http://clouds.eos.ubc.ca/~phil/courses/atsc301/downloads to the local directory Parameters ---------- filename: string name of file to fetch from Returns ------- Side effect: Creates a copy of that file in the local directory """ url = 'https://clouds.eos.ubc.ca/~phil/courses/atsc301/downloads/{}'.format(filename) filepath = Path('./{}'.format(filename)) if filepath.exists(): the_size = filepath.stat().st_size print(('\n{} already exists\n' 'and is {} bytes\n' 'will not overwrite\n').format(filename,the_size)) return None tempfile = str(filepath) + '_tmp' temppath = Path(tempfile) with open(tempfile, 'wb') as localfile: response = requests.get(url, stream=True) if not response.ok: print('response: ',response) raise Exception('Something is wrong, requests.get() failed with filename {}'.format(filename)) for block in response.iter_content(1024): if not block: break localfile.write(block) the_size=temppath.stat().st_size if the_size < 10.e3: print('Warning -- your file is tiny (smaller than 10 Kbyte)\nDid something go wrong?') shutil.move(tempfile,filename) the_size=filepath.stat().st_size print('downloaded {}\nsize = {}'.format(filename,the_size)) return None if __name__ == "__main__": linebreaks=argparse.RawTextHelpFormatter descrip=__doc__.lstrip() parser = argparse.ArgumentParser(formatter_class=linebreaks,description=descrip) parser.add_argument('filename',type=str,help='name of file to download') args=parser.parse_args() download(args.filename)
a301-teaching/a301_code
a301utils/a301_readfile.py
Python
mit
2,239
<?php include 'base.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Blog Home - Start Bootstrap Template</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/blog-home.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Start Bootstrap</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li> <a href="#">About</a> </li> <li> <a href="#">Services</a> </li> <li> <a href="#">Contact</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Page Content --> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8"> <h1 class="page-header"> Page Heading <small>Secondary Text</small> </h1> <?php foreach ($posts as $post) { ?> <!-- Blog Post --> <h2> <a href="#"><?php echo $post->title; ?></a> </h2> <p class="lead"> by <a href="index.php"><?php echo $post->author; ?></a> </p> <p><span class="glyphicon glyphicon-time"></span> Posted on <?php echo $post->date; ?></p> <hr> <img class="img-responsive" src="http://placehold.it/900x300" alt=""> <hr> <p><?php echo $post->short_text; ?></p> <a class="btn btn-primary" href="#">Read More <span class="glyphicon glyphicon-chevron-right"></span></a> <hr> <?php } ?> <!-- Pager --> <ul class="pager"> <li class="previous"> <a href="#">&larr; Older</a> </li> <li class="next"> <a href="#">Newer &rarr;</a> </li> </ul> </div> <!-- Blog Sidebar Widgets Column --> <div class="col-md-4"> <!-- Blog Search Well --> <div class="well"> <h4>Blog Search</h4> <div class="input-group"> <form> <input type="text" name="search" class="form-control"> <span class="input-group-btn"> <button class="btn btn-default" type="submit" value="Submit"> <span class="glyphicon glyphicon-search"></span> </button> </span> </form> </div> <!-- /.input-group --> </div> <!-- Blog Categories Well --> <div class="well"> <h4>Blog Categories</h4> <div class="row"> <div class="col-lg-6"> <ul class="list-unstyled"> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> </ul> </div> <!-- /.col-lg-6 --> <div class="col-lg-6"> <ul class="list-unstyled"> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> </ul> </div> <!-- /.col-lg-6 --> </div> <!-- /.row --> </div> <!-- Side Widget Well --> <div class="well"> <h4>Side Widget Well</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, perspiciatis adipisci accusamus laudantium odit aliquam repellat tempore quos aspernatur vero.</p> </div> </div> </div> <!-- /.row --> <hr> <!-- Footer --> <footer> <div class="row"> <div class="col-lg-12"> <p>Copyright &copy; Your Website 2016</p> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> </footer> </div> <!-- /.container --> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> </body> </html>
jamisonj/ds_assignments
application_project/form.php
PHP
mit
6,483
<?php namespace Kraken\Config; use Dazzle\Util\Factory\SimpleFactoryInterface; interface ConfigFactoryInterface extends SimpleFactoryInterface {}
kraken-php/framework
src/Config/src/ConfigFactoryInterface.php
PHP
mit
149
package com.example.myloading; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void buttonMethod(View v){ ProgressBar p = (ProgressBar) findViewById(R.id.progressBar1); p.setVisibility(View.VISIBLE); // 表示 } public void buttonMethod2(View v){ ProgressBar p = (ProgressBar) findViewById(R.id.progressBar1); p.setVisibility(View.GONE); // 非表示 } }
android-samples/loading-show-hide
src/com/example/myloading/MainActivity.java
Java
mit
705
package collection.mutable; import java.util.AbstractMap; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; public class HashMultimap<K,V> { Map<K, List<V>> map = new HashMap<K, List<V>>(); int total = 0; public HashMultimap() { } /** * Returns the total number of entries in the multimap. * @return */ public int size() { return total; } /** * Tests whether if the multimap is empty. * @return */ public boolean isEmpty() { return size() == 0; } /** * Returns a (possibly empty) iteration of all values associated wiht the key. * @param key * @return */ Iterable<V> get(K key) { List<V> secondary = map.get(key); if (secondary != null) return secondary; return new ArrayList<V>(); } /** * Adds a new entry associating key with value. * @param key * @param value */ public void put(K key, V value) { List<V> secondary = map.get(key); if (secondary == null) { secondary = new ArrayList<V>(); map.put(key, secondary); } secondary.add(value); total++; } /** * Removes the (key, value) entry, if exists. * @param key * @param value * @return */ public boolean remove(K key, V value) { boolean wasRemoved = false; List<V> secondary = map.get(key); if (secondary != null) { wasRemoved = secondary.remove(value); if (wasRemoved) { total--; if (secondary.isEmpty()) map.remove(key); } } return wasRemoved; } /** * Removes all entries with given key. * @param key * @return */ Iterable<V> removeAll(K key) { List<V> secondary = map.get(key); if (secondary != null) { total -= secondary.size(); map.remove(key); } else secondary = new ArrayList<V>(); return secondary; } /** * Returns an iteration of all entries in the multimap. * @return */ Iterable<Map.Entry<K,V>> entries() { List<Map.Entry<K,V>> result = new ArrayList<Map.Entry<K, V>>(); for (Map.Entry<K,List<V>> secondary: map.entrySet()) { K key = secondary.getKey(); for (V value: secondary.getValue()) result.add(new AbstractMap.SimpleEntry<K, V>(key, value)); } return result; } }
zitudu/scala-like-collection-and-sort
src/main/java/collection/mutable/HashMultimap.java
Java
mit
2,578
using System; using UIKit; using SlideMenuControllerXamarin; namespace SlideMenuControllerExample { public partial class ViewController2 : UIViewController { protected ViewController2(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } public ViewController2() : base("ViewController2", null) { } public override void ViewDidLoad() { base.ViewDidLoad(); this.AddLeftBarButtonWithImage(UIImage.FromBundle("menu")); // Perform any additional setup after loading the view, typically from a nib. } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } } }
bastianX6/SlideMenuControllerXamarin
SlideMenuControllerExample/ViewController2.cs
C#
mit
742