repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Winterbraid/ffmpeg_progress | lib/ffmpeg_progress/theme.rb | 4930 | module FFmpegProgress
# This is the class that handles progress bar themes and converting them into
# visual elements. {FFmpegProgress} expects a 256-color capable terminal.
class Theme
# The default theme.
DEFAULT_THEME = {
bars: 63, head_chr: '[', full_chr: '=', empty_chr: '-', tail_chr: ']',
end_fg: 202, full_fg: 214, empty_fg: 202,
time_fg: 214, block_fg: 214, finish_fg: 40, cancel_fg: 1
}
# The length of the progress bar.
#
# @return [Integer]
attr_accessor :bars
# The string to be used as the start of a section.
#
# @return [String]
attr_accessor :head_chr
# The string to be used to draw the filled part of the bar.
#
# @return [String]
attr_accessor :full_chr
# The string to be used to draw the remaining part of the bar.
#
# @return [String]
attr_accessor :empty_chr
# The string to be used as the end of a section.
#
# @return [String]
attr_accessor :tail_chr
# The color of the beginning and end of a section.
#
# @return [Integer]
attr_accessor :end_fg
# The color of the filled part of the bar.
#
# @return [Integer]
attr_accessor :full_fg
# The color of the remaining part of the bar.
#
# @return [Integer]
attr_accessor :empty_fg
# The color of the current time position info.
#
# @return [Integer]
attr_accessor :time_fg
# The color of the optional block return value.
#
# @return [Integer]
attr_accessor :block_fg
# The color of the time position info on a completed task.
#
# @return [Integer]
attr_accessor :finish_fg
# The color of the time position info on an interrupted task.
#
# @return [Integer]
attr_accessor :cancel_fg
# Generates a new instance of Theme. Returns the argument if the argument
# is a Theme.
#
# @param [Hash, Theme] object
# @return [Theme]
def self.from(object)
return object if object.is_a? Theme
return new(object) if object.is_a? Hash
fail "Argument must be either Theme or Hash. #{object.class.name}"
end
# Generates a new instance of Theme from a theme hash.
#
# @param [Hash] theme_hash
# @return [Theme]
def initialize(theme_hash = DEFAULT_THEME)
DEFAULT_THEME.merge(theme_hash).each_pair do |key, value|
method("#{key}=").call(value) if DEFAULT_THEME.key? key
end
end
# Returns a progress bar given a fractional position, a time string,
# and an optional block output string.
#
# @param [Float] position
# @param [String] time_string
# @param [Hash] option_hash
# @option option_hash [String] :block_output the output from the optional
# block passed to {FFmpeg#run}, if any.
# @option option_hash [Boolean] :interrupted has the task been canceled?
# @option option_hash [Boolean] :finished has the task finished?
# @return [String]
def bar(position, time_string = '00:00:00.00', option_hash = {})
output = "#{head}#{full(position)}#{empty(position)}#{tail}" \
"#{head}#{time(time_string, option_hash)}#{tail}"
if option_hash.fetch :block_output, false
output << "#{head}#{colorize(option_hash[:block_output], @block_fg)}" \
"#{tail}"
end
output
end
private
# Returns the contents of the time section.
#
# @param [String] time_string
# @param [Hash] option_hash
# @option option_hash [Boolean] :interrupted has the task been canceled?
# @option option_hash [Boolean] :finished has the task finished?
# @return [String]
def time(time_string, option_hash = {})
fg_color =
if option_hash.fetch :interrupted, false
@cancel_fg
elsif option_hash.fetch :finished, false
@finish_fg
else
@time_fg
end
colorize(time_string, fg_color)
end
# Returns the filled part of the progress bar given a fractional position.
#
# @param [Float] position
# @return [String]
def full(position)
colorize(@full_chr * (position * @bars).round, @full_fg)
end
# Returns the empty part of the progress bar given a fractional position.
#
# @param [Float] position
# @return [String]
def empty(position)
colorize(@empty_chr * (@bars - (position * @bars).round), @empty_fg)
end
# Returns a colorized section start element.
#
# @return [String]
def head
colorize(@head_chr, @end_fg)
end
# Returns a colorized section end element.
#
# @return [String]
def tail
colorize(@tail_chr, @end_fg)
end
# Colorize a string for the terminal (256-color mode).
#
# @param [String] string
# @param [Integer] color
# @return [String]
def colorize(string, color)
"\x1b[38;5;#{color}m#{string}\x1b[0m"
end
end
end
| mit |
vaj25/SICBAF | assets/js/validate/reporte/activofijo/bunidadenlace.js | 648 |
var reglas = {
rules: {
"autocomplete": {
required: true,
checkautocomplete: 'seccion'
},
},
messages: {
"autocomplete": {
required: "La seccion es obligatoria."
},
},
};
var iseccion;
$(document).ready(function() {
//empleado
$.autocomplete({
elemet: $('input[name=autocomplete3]'),
url: 'index.php/ActivoFijo/Reportes/Bienes_por_unidad_enlace/autocompleteEmpleadoSeccion',
name: 'empleado',
siguiente: 'button',
content: 'suggestions2',
ajaxdata: {seccion: $('input[name=seccion]').val()},
});
});
| mit |
jeikerxiao/SpringBootStudy | spring-boot-multi-datasource/src/main/java/com/jeiker/demo/config/DynamicDataSource.java | 579 | package com.jeiker.demo.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* @author : xiao
* @date : 2018/3/9 上午10:47
* @description :
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
protected Object determineCurrentLookupKey() {
logger.info("数据源为{}",JdbcContextHolder.getDataSource());
return JdbcContextHolder.getDataSource();
}
}
| mit |
escribano/code | lib/code/ancestors/browser-det.js | 1524 | <script type="text/javascript">
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
if (ffversion>=5)
document.write(" FF 5.x or above")
else if (ffversion>=4)
document.write(" FF 4.x or above")
else if (ffversion>=3)
document.write(" FF 3.x or above")
else if (ffversion>=2)
document.write(" FF 2.x")
else if (ffversion>=1)
document.write(" FF 1.x")
}
else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
if (ieversion>=9)
document.write(" IE9 or above")
else if (ieversion>=8)
document.write(" IE8 or above")
else if (ieversion>=7)
document.write(" IE7.x")
else if (ieversion>=6)
document.write(" IE6.x")
else if (ieversion>=5)
document.write(" IE5.x")
}
else if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Opera/x.x or Opera x.x (ignoring remaining decimal places);
var oprversion=new Number(RegExp.$1) // capture x.x portion and store as a number
if (oprversion>=10)
document.write("You're using Opera 10.x or above")
else if (oprversion>=9)
document.write("You're using Opera 9.x")
else if (oprversion>=8)
document.write("You're using Opera 8.x")
else if (oprversion>=7)
document.write("You're using Opera 7.x")
else
document.write("")
}
else
document.write(navigator.appVersion)
</script> | mit |
SlateFoundation/slate | sencha-workspace/SlateAdmin/app/view/Main.js | 617 | /*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.view.Main', {
extend: 'Ext.container.Container',
xtype: 'slateadmin-main',
requires: [
'SlateAdmin.view.Navigation',
'Ext.layout.container.Card'
],
autoEl: 'main',
componentCls: 'slateadmin-main',
layout: 'border',
items: [{
region: 'west',
xtype: 'slateadmin-navigation',
split: true,
collapsible: false
},{
region: 'center',
xtype: 'container',
itemId: 'cardCt',
layout: 'card',
cls: 'slate-empty-view'
}]
});
| mit |
HandyCodeJob/mikeandzoey-site | src/rsvp/migrations/0008_auto_20150906_0714.py | 680 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('rsvp', '0007_auto_20150906_0354'),
]
operations = [
migrations.RemoveField(
model_name='person',
name='attending',
),
migrations.AlterField(
model_name='person',
name='food_choice',
field=models.CharField(choices=[('not_attending', 'Not Attending'), ('hamburger', 'Hamburger'), ('chicken', 'Chicken'), ('veggie', 'Veggie Burger')], max_length=31, verbose_name='Choice of Food', blank=True),
),
]
| mit |
DanielJRaine/employee-forms-auth | tmp/broccoli_persistent_filterbabel__babel_employee_forms_auth-output_path-QkVqzlHt.tmp/employee-forms-auth/routes/users.js | 259 | define('employee-forms-auth/routes/users', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports['default'] = _ember['default'].Route.extend({
model: function model() {
return this.get('store').findAll('user');
}
});
}); | mit |
learncode/Sublime | SublimeDal/SublimeDal.Core/Mapper/Mapper.cs | 815 | using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace SublimeDal.Library {
public class Mapper {
public static List<T> GetList<T>(DataTable dataTable) where T : new() {
List<T> entities = new List<T>();
foreach (DataRow row in dataTable.Rows) {
T obj = new T();
foreach (PropertyInfo propertyInfo in new T().GetType().GetProperties()) {
var column = (Column)propertyInfo.GetCustomAttribute(typeof(Column));
if (column == null)
continue;
propertyInfo.SetValue(obj, row[column.Name] == DBNull.Value ? null : row[column.Name]);
}
entities.Add(obj);
}
return entities;
}
}
}
| mit |
benjaminleetmaa/hsOemV3 | src/app/shared/pipes/gridRow.pipe.ts | 2703 | import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'gridRowPipe'
})
export class GridRowPipe implements PipeTransform {
transform(value: any, args: any) {
// console.log(args[2])
// console.log(value);
if (typeof value === 'object' && value) {
let expandObj = value[args[0]];
// console.log(expandObj)
if (expandObj && typeof expandObj === 'object') {
expandObj = expandObj[args[1]];
}
if (expandObj && args[2] === 'ErrorDescriptionDim') {
return expandObj.slice(0, 10) + ' ...'
// return expandObj
}
if (expandObj && args[0] === 'ERRORDESCRIPTIONDIMID') {
return expandObj === 660 ? 'external':'internal'
// return expandObj
}
// console.log(expandObj)
return expandObj ? expandObj : '';
}
// parse values for grid view
if (value && (args[2] === 'CLAIMDATE' || args[2] === 'CREATED')) {
var formattedDate = value.substr(0, 10);
// var formattedDate = value.substr(0, 10);
return formattedDate;
}
if (value && args[2] === 'NUMBER') {
// to get decimals only when decimals exists.
return value.toLocaleString();
}
// expand usernickname if col are CREATEDBY or USERID
if (value && args[3] && (args[2] === 'CREATEDBY' || args[2] === 'USERID')) {
// console.log(value);
for (let users of args[3]) {
// console.log(users.email)
// console.log(value)
if (users.user_id === value && users.user_metadata) {
return users.user_metadata.nickname
}
}
}
return value;
}
}
@Pipe({
name: 'customerEmailFilter'
})
export class CustomerEmailFilter implements PipeTransform {
transform(items: Array<any>, query): Array<any> {
console.log(query[0])
let splitQuery;
query[0] ? splitQuery = query[0].split(',') : splitQuery = null;
let result = splitQuery && splitQuery[0] && splitQuery[1] && items ? items.filter(k => k['POSITION'] === splitQuery[0] && k['PRODID'] === splitQuery[1]):null
console.log(result)
return result && result.length !== 0 ? [result[0]] : null;
}
}
@Pipe({
name: 'searchItemId'
})
export class SearchItemId implements PipeTransform {
transform(items: Array<any>, query): Array<any> {
console.log(query[0])
let hits = items ? items.filter(f => f.itemid.startsWith(query)):null;
return hits ? hits : null;
}
}
| mit |
briandavidwetzel/rapid_api | test/integration/ams_ar_test.rb | 1528 | require File.expand_path '../../test_helper.rb', __FILE__
class AmsArTest < ActionController::TestCase
class AmsArIntegrationController < ActionController::Base
include RapidApi::ActionController::Errors
rapid_actions model: Brick, serializer: BrickSerializer
scope_by :user_id do
params['user_id']
end
permit_params :color, :weight, :material
end
tests AmsArIntegrationController
def setup
super
DatabaseCleaner.start
Brick.delete_all
@user1 = User.create
@user2 = User.create
end
def teardown
DatabaseCleaner.clean
end
def test_index
Brick.destroy_all
brick1 = @user1.bricks.create color: 'yellow', weight: 10, material: 'gold'
brick2 = @user1.bricks.create color: 'red', weight: 1, material: 'clay'
brick3 = @user2.bricks.create color: 'magenta', weight: 0, material: 'feathers'
get :index, params: { user_id: @user1.id }
assert_equal "{\"data\":[{\"id\":\"#{brick1.id}\",\"type\":\"bricks\",\"attributes\":{\"color\":\"yellow\",\"weight\":\"10.0\",\"material\":\"gold\"}},{\"id\":\"#{brick2.id}\",\"type\":\"bricks\",\"attributes\":{\"color\":\"red\",\"weight\":\"1.0\",\"material\":\"clay\"}}]}", response.body
end
def test_show
brick = Brick.create color: 'red', weight: 1, material: 'clay'
get :show, params: { id: brick.id }
assert_equal "{\"data\":{\"id\":\"#{brick.id}\",\"type\":\"bricks\",\"attributes\":{\"color\":\"red\",\"weight\":\"1.0\",\"material\":\"clay\"}}}", response.body
end
end
| mit |
rohansen/Code-Examples | Public Web Services/Microsoft Text Analytics API/Microsoft Text Analytics API/Form1.Designer.cs | 3580 | namespace Microsoft_Text_Analytics_API
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lbBooking = new System.Windows.Forms.ListBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// lbBooking
//
this.lbBooking.FormattingEnabled = true;
this.lbBooking.ItemHeight = 16;
this.lbBooking.Location = new System.Drawing.Point(12, 33);
this.lbBooking.Name = "lbBooking";
this.lbBooking.Size = new System.Drawing.Size(269, 164);
this.lbBooking.TabIndex = 0;
this.lbBooking.SelectedIndexChanged += new System.EventHandler(this.lbBooking_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 10);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(66, 17);
this.label1.TabIndex = 1;
this.label1.Text = "Bookings";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(173, 13);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(46, 17);
this.label2.TabIndex = 2;
this.label2.Text = "label2";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(288, 33);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(273, 164);
this.textBox1.TabIndex = 3;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(840, 545);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.lbBooking);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListBox lbBooking;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox1;
}
}
| mit |
icaromagnago/tcc-ddd-scrum | src/main/java/br/icc/ddd/scrum/application/ApplicationService.java | 957 | package br.icc.ddd.scrum.application;
import java.io.Serializable;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import br.icc.ddd.scrum.domain.Entidade;
import br.icc.ddd.scrum.domain.ValidacaoException;
public interface ApplicationService extends Serializable {
/**
* Valida as entidades através do bean validation
* @param entidade a ser validada
* @throws IllegalArgumentException, ValidacaoException
*/
default public void validarEntidade(Entidade entidade) {
if(entidade == null) {
throw new IllegalArgumentException("entidade não pode ser null");
}
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Set<ConstraintViolation<Entidade>> violacoes = factory.getValidator().validate(entidade);
if(!violacoes.isEmpty()) {
throw new ValidacaoException(violacoes);
}
}
}
| mit |
amutylo/IB-d8-migration | migrate_infob/src/Plugin/migrate/source/TermFunctions.php | 1791 | <?php
namespace Drupal\migrate_infob\Plugin\migrate\source;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
/**
* Taxonomy term source from database.
*
*
* @MigrateSource(
* id = "taxonomy_term_functions",
* source_provider = "taxonomy"
* )
*/
class TermFunctions extends DrupalSqlBase {
protected $vocabularyName = 'Functions';
protected $vocVid;
protected $termsToMigrate = [
'Call Centers',
'Logistics',
'Marketing',
'Mid-sized Companies',
'Operations',
'Sales',
'Supply Chain Management',
'HR'
];
/**
* {@inheritdoc}
*/
public function query() {
if (empty($this->topicsVid)) {
$vid = $this->select('vocabulary', 'v')
->fields('v', ['vid'])
->condition('name', $this->vocabularyName)
->distinct()
->execute()
->fetchCol();
$this->vocVid = $vid;
}
$query = $this->select('term_data', 'td')
->fields('td')
->distinct()
->orderBy('td.tid');
if (isset($this->vocVid)) {
$query->condition('td.vid', $this->vocVid);
}
$query->condition('name', $this->termsToMigrate, 'IN');
return $query;
}
/**
* {@inheritdoc}
*/
public function fields() {
$fields = [
'tid' => $this->t('The term ID.'),
'vid' => $this->t('Existing term VID'),
'name' => $this->t('The name of the term.'),
'description' => $this->t('The term description.'),
'weight' => $this->t('Weight'),
];
return $fields;
}
/**
* {@inheritdoc}
*/
public function prepareRow(Row $row) {
return parent::prepareRow($row);
}
/**
* {@inheritdoc}
*/
public function getIds() {
$ids['tid']['type'] = 'integer';
return $ids;
}
}
| mit |
sazze/node-pm | test/main.test.js | 19245 | var expect = require('chai').expect;
var path = require('path');
var child = require('child_process');
var _ = require('underscore');
var fs = require('fs');
var ps;
describe('Worker Manager', function() {
"use strict";
describe('during startup', function() {
it('should require a start script', function(done) {
spawn('', function(out) {
expect(out).to.match(/.*app start script must be specified/);
done();
});
});
it('should require an existing start script', function(done) {
spawn('fake.js', function(out) {
expect(out).to.match(/.*cannot find application start script: fake.js/);
done();
});
});
it('should set default timeouts', function() {
var config = require('../lib/config');
expect(config).to.have.property('timeouts');
expect(config.timeouts).to.have.property('start').and.to.equal(30000);
expect(config.timeouts).to.have.property('stop').and.to.equal(30000);
expect(config.timeouts).to.have.property('maxAge').and.to.equal(1800000);
});
it('should override default timeouts', function (done) {
spawn('httpServer.js -n 1 -vvv --tStart 15000 --tStop 10000 --tMaxAge 900000', function(out) {
var matches;
if ((matches = out.match(/.*node-pm options: (\{.*\})/))) {
var options = JSON.parse(matches[1]);
expect(options).to.have.property('timeouts');
expect(options.timeouts).to.have.property('start').and.to.equal(15000);
expect(options.timeouts).to.have.property('stop').and.to.equal(10000);
expect(options.timeouts).to.have.property('maxAge').and.to.equal(900000);
expect(options).to.not.have.property('tStart');
expect(options).to.not.have.property('tStop');
expect(options).to.not.have.property('tMaxAge');
ps.once('exit', function () {
done();
});
ps.kill();
}
});
});
it('should work with an relative path', function(done) {
spawn('httpServer.js -n 1');
ps.on('cluster:listening', function(worker) {
ps.kill();
});
ps.once('exit', function() {
done();
});
});
it('should work with an absolute path', function(done) {
spawn(__dirname + '/scripts/httpServer.js -n 1');
ps.on('cluster:listening', function(worker) {
ps.kill();
});
ps.once('exit', function() {
done();
});
});
it('should run as a daemon', function (done) {
this.timeout(5000);
var parentExit = false;
spawn('httpServer.js -n 1 -vvv -d --pidFile ' + path.join(__dirname, 'daemon.pid'));
ps.once('exit', function () {
parentExit = true;
});
setTimeout(function () {
expect(parentExit).to.equal(true, 'parent did not exit');
expect(fs.existsSync(path.join(__dirname, 'daemon.pid'))).to.equal(true, path.join(__dirname, 'daemon.pid') + ' does not exist');
child.exec('cat ' + path.join(__dirname, 'daemon.pid'), function (err, stdout, stderr) {
expect(err).to.equal(null);
expect(stderr.length).to.equal(0);
expect(stdout.length).to.be.gt(0);
process.kill(parseInt(stdout.toString()), 'SIGTERM');
setTimeout(function () {
expect(fs.existsSync(path.join(__dirname, 'daemon.pid'))).to.equal(false, path.join(__dirname, 'daemon.pid') + ' not cleaned up');
done();
}, 500);
});
}, 1500);
});
});
describe('event listening', function() {
it('should send the start event', function(done) {
var started = true;
spawn('httpServer.js -n 1 -vvv');
ps.on('start', function() {
started = true;
});
ps.on('cluster:listening', function() {
expect(started).to.equal(true);
ps.kill();
done();
});
});
it('should re-spawn child process if it is killed hard', function(done) {
var pid;
spawn('pid.js -n 1');
ps.once('cluster:online', function(worker) {
pid = worker.process.pid;
});
ps.once('cluster:listening', function(worker) {
expect(worker.process.pid).to.equal(pid);
ps.once('cluster:listening', function(worker) {
expect(worker.process.pid).not.to.equal(pid);
ps.kill();
ps.once('exit', function() {
done();
});
});
setTimeout(function () {
process.kill(worker.process.pid, 'SIGKILL');
}, 50);
});
});
it('should call exit when child process exits', function(done) {
var pid;
spawn('childExit.js -n 1');
ps.once('cluster:online', function(worker) {
pid = worker.process.pid;
});
ps.once('cluster:exit', function(worker) {
expect(worker.suicide).to.equal(false);
expect(worker.process.pid).to.equal(pid);
ps.kill();
done();
});
});
it('should kill the forked processes', function(done) {
spawn('pid.js -n 1');
ps.once('exit', function(worker) {
setTimeout(function() {
try {
process.kill(worker.process.pid);
done('child must no longer run');
} catch (e) {
done();
}
}, 500);
});
ps.once('cluster:listening', function() {
ps.kill();
});
});
});
describe('while running', function() {
it('should spawn 4 workers', function(done) {
var listenCount = 0;
spawn('httpServer.js -n 4');
ps.on('cluster:listening', function(worker) {
listenCount++;
if (listenCount == 4) {
ps.kill();
}
});
ps.once('exit', function() {
expect(listenCount).to.equal(4);
done();
});
});
it('should listen on more than one port', function(done) {
var listenObjects = [];
var pid;
spawn('multipleHttpServers.js -n 1');
ps.once('cluster:online', function(worker) {
pid = worker.process.pid;
});
ps.on('cluster:listening', function(worker, address) {
expect(worker.process.pid).to.equal(pid);
if (listenObjects.length < 1) {
listenObjects.push(address);
return;
}
expect(listenObjects).to.not.include.members([address]);
listenObjects.push(address);
if (listenObjects.length == 2) {
ps.kill();
}
});
ps.once('cluster:exit', function(worker) {
expect(worker.process.pid).to.equal(pid);
expect(listenObjects.length).to.equal(2);
done();
})
});
it('should restart workers after lifecycle timeout', function(done) {
this.timeout(5000);
var pids = [];
spawn('restart.js -n 4 --tMaxAge 800 --tStart 400 --tStop 400 -vvv');
ps.on('cluster:online', function(worker) {
pids.push(worker.process.pid);
});
ps.on('restart', function() {
ps.kill();
ps.once('exit', function() {
expect(pids.length).to.equal(8);
done();
});
});
});
it('should re-register the lifecycle timeout', function (done) {
this.timeout(5000);
var pids = [];
var restartCount = 0;
spawn('restart.js -n 4 --tMaxAge 800 --tStart 400 --tStop 400');
ps.on('cluster:online', function (worker) {
pids.push(worker.process.pid);
});
ps.on('restart', function () {
restartCount++;
if (restartCount == 2) {
ps.kill();
ps.once('exit', function () {
expect(pids.length).to.equal(12);
expect(restartCount).to.equal(2);
done();
});
}
});
});
it('should shutdown when fork loop is detected', function(done) {
var shutdown = false;
var forkLoop = false;
spawn('childCrash.js -n 1 --tStart 100 --tStop 100');
ps.once('forkLoop', function() {
forkLoop = true;
});
ps.on('shutdown', function() {
shutdown = true;
});
ps.on('exit', function() {
expect(forkLoop).to.equal(true);
expect(shutdown).to.equal(true);
done();
});
});
it('should allow inter-process communication', function (done) {
var messageCount = 0;
spawn('httpServer.js -n 2 --workerMessageHandler ' + path.join(__dirname, 'scripts', 'workerMessageHandlerPubSub.js'), function (line) {
var msg = JSON.parse(line);
expect(msg).to.have.property('pid');
expect(msg).to.have.property('message');
expect(msg.message).to.not.contain(msg.pid);
messageCount++;
if (messageCount >= 2) {
return 'kill';
}
});
ps.once('exit', function () {
expect(messageCount).to.equal(2);
done();
});
});
it('should re-open log files on SIGHUP', function (done) {
this.timeout(5000);
var out = fs.createWriteStream('./out.log', {flags: 'w+'});
var err = fs.createWriteStream('./out.err', {flags: 'w+'});
out.write('start test', function () {
err.write('start test', function () {
runTest();
});
});
function runTest() {
expect(out.fd).to.not.equal(null);
expect(err.fd).to.not.equal(null);
expect(fs.existsSync('./out.log')).to.equal(true);
expect(fs.existsSync('./out.err')).to.equal(true);
expect(fs.existsSync('./out.log.1')).to.equal(false);
expect(fs.existsSync('./out.err.1')).to.equal(false);
spawn('logger.js -n 1 -vvv', [null, out, err, 'ipc']);
ps.once('start', function () {
setTimeout(function () {
fs.renameSync('./out.log', './out.log.1');
fs.renameSync('./out.err', './out.err.1');
expect(fs.existsSync('./out.log')).to.equal(false);
expect(fs.existsSync('./out.err')).to.equal(false);
expect(fs.existsSync('./out.log.1')).to.equal(true);
expect(fs.existsSync('./out.err.1')).to.equal(true);
ps.kill('SIGHUP');
setTimeout(function () {
expect(fs.existsSync('./out.log')).to.equal(true);
expect(fs.existsSync('./out.err')).to.equal(true);
expect(fs.existsSync('./out.log.1')).to.equal(true);
expect(fs.existsSync('./out.err.1')).to.equal(true);
setTimeout(function () {
ps.kill();
}, 1000);
}, 1000);
}, 1000);
});
ps.once('exit', function () {
out.close(function () {
err.close(function () {
fs.unlink('./out.log.1', function (err) {
fs.unlink('./out.err.1', function (err) {
fs.unlink('./out.log', function (err) {
fs.unlink('./out.err', function (err) {
done();
});
});
});
});
});
});
});
}
});
it('should re-open log files on SIGUSR2', function (done) {
this.timeout(5000);
var out = fs.createWriteStream('./out.log', {flags: 'w+'});
var err = fs.createWriteStream('./out.err', {flags: 'w+'});
out.write('start test', function () {
err.write('start test', function () {
runTest();
});
});
function runTest() {
expect(out.fd).to.not.equal(null);
expect(err.fd).to.not.equal(null);
expect(fs.existsSync('./out.log')).to.equal(true);
expect(fs.existsSync('./out.err')).to.equal(true);
expect(fs.existsSync('./out.log.1')).to.equal(false);
expect(fs.existsSync('./out.err.1')).to.equal(false);
spawn('logger.js -n 1 -vvv', [null, out, err, 'ipc']);
ps.once('start', function () {
setTimeout(function () {
fs.renameSync('./out.log', './out.log.1');
fs.renameSync('./out.err', './out.err.1');
expect(fs.existsSync('./out.log')).to.equal(false);
expect(fs.existsSync('./out.err')).to.equal(false);
expect(fs.existsSync('./out.log.1')).to.equal(true);
expect(fs.existsSync('./out.err.1')).to.equal(true);
ps.kill('SIGUSR2');
setTimeout(function () {
expect(fs.existsSync('./out.log')).to.equal(true);
expect(fs.existsSync('./out.err')).to.equal(true);
expect(fs.existsSync('./out.log.1')).to.equal(true);
expect(fs.existsSync('./out.err.1')).to.equal(true);
setTimeout(function () {
ps.kill();
}, 1000);
}, 1000);
}, 1000);
});
ps.once('exit', function () {
out.close(function () {
err.close(function () {
fs.unlink('./out.log.1', function (err) {
fs.unlink('./out.err.1', function (err) {
fs.unlink('./out.log', function (err) {
fs.unlink('./out.err', function (err) {
done();
});
});
});
});
});
});
});
}
});
it('should restart workers on SIGHUP', function (done) {
var restart = false;
spawn('httpServer.js -n 1 -vvv');
ps.once('cluster:listening', function () {
setTimeout(function () {
ps.once('cluster:listening', function () {
setTimeout(function () {
ps.kill();
}, 100);
});
ps.kill('SIGHUP');
}, 500);
});
ps.once('restart', function () {
restart = true;
});
ps.once('exit', function () {
expect(restart).to.equal(true);
done();
});
});
it('should kill high cpu processes', function (done) {
this.timeout(5000);
var listening = 0;
var exits = 0;
spawn('highCpu.js -n 2 -vvv --tStop 1000');
ps.on('cluster:listening', function () {
listening++;
if (listening == 2) {
ps.on('cluster:exit', function () {
exits++;
});
setTimeout(function () {
ps.kill();
}, 2000);
}
});
ps.once('exit', function () {
expect(listening).to.equal(2);
expect(exits).to.equal(2);
done();
});
});
});
describe('during shutdown', function() {
it('should call shutdown', function(done) {
var shutdown = 0;
spawn('httpServer.js -n 1');
ps.on('shutdown', function() {
shutdown++;
});
ps.once('cluster:listening', function() {
setTimeout(function() {
ps.kill();
}, 50);
});
ps.once('exit', function() {
expect(shutdown).to.equal(1);
done();
});
});
it('should kill long living connections', function(done) {
var pid;
spawn('longLive.js -vvv --tStop 100 -n 1');
ps.once('cluster:listening', function(worker) {
pid = worker.process.pid;
ps.kill();
});
ps.once('cluster:exit', function(worker) {
expect(worker.process.pid).to.equal(pid);
});
ps.once('exit', function() {
done();
});
});
it('should check that forked processes are running', function (done) {
var pid;
var killed = false;
var outObj = {};
spawn('pid.js -n 1 -vvv', function (out) {
var matches;
if (!pid && (matches = out.match(/.*pid: (\d+)/i))) {
pid = matches[1];
}
if (!pid) {
return;
}
outObj.out = out;
if (!killed) {
killed = true;
this.on('exit', function () {
expect(outObj.out).to.match(new RegExp('worker ' + pid + ' is running'));
done();
});
setTimeout(function () {
process.kill(ps.pid, 'SIGTERM');
}, 500);
}
});
});
it('should handle processes that don\'t exit', function (done) {
var pid;
var killed = false;
var outObj = {};
spawn('childNoExit.js -n 1 -vvv --tStop 100');
ps.once('cluster:listening', function(worker) {
pid = worker.process.pid;
ps.kill();
});
ps.once('cluster:exit', function (worker) {
expect(pid).to.be.gt(0);
expect(worker.process.pid).to.equal(pid);
});
ps.once('exit', function () {
try {
killed = !process.kill(pid, 0);
} catch (e) {
killed = e.code !== 'EPERM';
}
expect(killed).to.equal(true);
done();
});
});
});
afterEach(function() {
try {
if (ps) {
ps.kill();
ps = null;
}
} catch (e) {
//ignore these errors
ps = null;
}
});
});
/**
* Spawn a new process with cmd. Will call callback on
* data from stdout. To kill spawn return 'kill' from
* callback function. if you return a function it will call
* that function on next output.
*
* @param cmd the command to run
* @param [stdio] the stdio array to use for the spawned process
* @param [cb] the callback function with either a out or line parameter
*
* @returns {child_process}
*/
function spawn(cmd, stdio, cb) {
if (typeof stdio === 'function') {
cb = stdio;
stdio = undefined;
}
if (!stdio) {
stdio = [null, null, null, 'ipc'];
}
ps = child.spawn(__dirname + '/../bin/node-pm', cmd.split(' '), { cwd: __dirname + '/scripts', stdio: stdio });
var out = '';
ps.on('message', function(json) {
var args = JSON.parse(json);
if (ps) {
ps.emit.apply(ps, args);
}
});
// ps.stderr.on('data', function(data) {
// console.log(data.toString());
// });
//
// ps.stdout.on('data', function(data) {
// console.log(data.toString());
// });
if (typeof cb === 'function') {
ps.stdout.on('data', function(data) {
var line = data.toString();
out += line;
if (!cb) {
return;
}
// Determine which output they want
var paramNames = getParameterName(cb);
var param = out;
if (paramNames.length == 1 && paramNames[0] == 'line') {
param = line;
}
// Call the callback since we are done spawning
var response = cb.call(ps, param);
if (typeof response === 'function') {
cb = response;
} else if (response == 'kill') {
cb = null;
process.kill(ps.pid);
} else if (response === false) {
cb = null;
}
});
}
return ps
}
/**
* Returns the parameter names of a function
*
* @param fn
* @returns {Array}
*/
function getParameterName(fn) {
"use strict";
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var fnStr = fn.toString().replace(STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(/([^\s,]+)/g);
return result === null ? [] : result;
} | mit |
neyko5/balistos | models/playlist.js | 620 | var sequelize = require('../database');
var Sequelize = require('sequelize');
var User = require('./user');
var Chat = require('./chat');
var PlaylistVideo = require('./playlistVideo');
var Playlist = sequelize.define('playlist', {
id: {
type: Sequelize.INTEGER,
field: 'id',
primaryKey: true,
autoIncrement: true
},
title: {
type: Sequelize.STRING,
field: 'title'
},
description: {
type: Sequelize.TEXT,
field: 'description'
},
}, {
tableName: 'playlists'
});
Playlist.belongsTo(User);
Playlist.hasMany(PlaylistVideo);
Playlist.hasMany(Chat);
module.exports = Playlist;
| mit |
CoandaCMS/coanda-core | src/views/admin/modules/history/emails/dailydigest.blade.php | 5713 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 0; padding: 0;">
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Daily Digest</title>
</head>
<body bgcolor="#f6f6f6" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; width: 100% !important; height: 100%; margin: 0; padding: 0;">
<table style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; width: 100%; margin: 0; padding: 20px;">
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 0; padding: 0;">
<td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 0; padding: 0;"></td>
<td bgcolor="#FFFFFF" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; display: block !important; max-width: 600px !important; clear: both !important; margin: 0 auto; padding: 20px; border: 1px solid #f0f0f0;">
<div style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; max-width: 600px; display: block; margin: 0 auto; padding: 0;">
<table style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; width: 100%; margin: 0; padding: 0;">
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 0; padding: 0;">
<td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 0; padding: 0;">
<p style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.6; font-weight: normal; margin: 0 0 10px; padding: 0;">Hi,</p>
<p style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.6; font-weight: normal; margin: 0 0 10px; padding: 0;">Below is a summary of activity on the site.</p>
<table width="100%">
<tr>
<td width="25%" align="center" style="background: #f6f6f6; font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 0; padding: 10px 0; font-size: 24px; font-weight: bold;">{{ $summary_figures['yesterday'] }}</td>
<td width="25%" align="center" style="background: #f6f6f6; font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 0; padding: 10px 0; font-size: 24px; font-weight: bold;">{{ $summary_figures['week'] }}</td>
<td width="25%" align="center" style="background: #f6f6f6; font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 0; padding: 10px 0; font-size: 24px; font-weight: bold;">{{ $summary_figures['month'] }}</td>
<td width="25%" align="center" style="background: #f6f6f6; font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 0; padding: 10px 0; font-size: 24px; font-weight: bold;">{{ $summary_figures['year'] }}</td>
</tr>
<tr>
<td align="center">Yesterday</td>
<td align="center">This week</td>
<td align="center">This month</td>
<td align="center">This year</td>
</tr>
</table>
@if ($history_list->count() > 0)
<h2 style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 10px 0 10px 0; padding: 0; font-size: 16px; font-weight: bold;">Recent activity</h2>
<table width="100%" border="0" cellspacing="0" cellpadding="0" style="border-top: 1px solid #ccc;">
@foreach ($history_list as $history)
<tr>
<td valign="top" class="tight" style="border-bottom: 1px solid #ccc; font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; line-height: 1.6; margin: 0; padding: 5px; font-size: 12px;">
<span style="white-space: nowrap;">{{ $history->created_at->format(\Config::get('coanda::coanda.datetime_format')) }}</span>
<br>
<small>{{ $history->user->full_name }}</small>
</td>
<td valign="top" style="border-bottom: 1px solid #ccc; font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; line-height: 1.6; margin: 0; padding: 5px; font-size: 12px;">{{ $history->display_text }}</td>
</tr>
@endforeach
</table>
@if ($history_list->getTotal() > 50)
<p>Total <strong>{{ number_format($history_list->getTotal()) }}</strong>, <a href="{{ Coanda::adminUrl('history') . '?from=' . $from->format('d/m/Y') . '&to=' . $to->format('d/m/Y') }}">view all online</a></p>
@endif
@endif
</td>
</tr>
</table>
</div>
</td>
<td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 100%; line-height: 1.6; margin: 0; padding: 0;"></td>
</tr>
</table>
</body>
</html> | mit |
marknmel/telegraf | plugins/inputs/statsd/statsd.go | 14775 | package statsd
import (
"errors"
"fmt"
"log"
"net"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/influxdata/telegraf/plugins/parsers/graphite"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
)
const (
UDP_PACKET_SIZE int = 1500
defaultFieldName = "value"
)
var dropwarn = "ERROR: Message queue full. Discarding line [%s] " +
"You may want to increase allowed_pending_messages in the config\n"
type Statsd struct {
// Address & Port to serve from
ServiceAddress string
// Number of messages allowed to queue up in between calls to Gather. If this
// fills up, packets will get dropped until the next Gather interval is ran.
AllowedPendingMessages int
// Percentiles specifies the percentiles that will be calculated for timing
// and histogram stats.
Percentiles []int
PercentileLimit int
DeleteGauges bool
DeleteCounters bool
DeleteSets bool
DeleteTimings bool
ConvertNames bool
// UDPPacketSize is the size of the read packets for the server listening
// for statsd UDP packets. This will default to 1500 bytes.
UDPPacketSize int `toml:"udp_packet_size"`
sync.Mutex
// Channel for all incoming statsd packets
in chan []byte
done chan struct{}
// Cache gauges, counters & sets so they can be aggregated as they arrive
// gauges and counters map measurement/tags hash -> field name -> metrics
// sets and timings map measurement/tags hash -> metrics
gauges map[string]cachedgauge
counters map[string]cachedcounter
sets map[string]cachedset
timings map[string]cachedtimings
// bucket -> influx templates
Templates []string
}
func NewStatsd() *Statsd {
s := Statsd{}
// Make data structures
s.done = make(chan struct{})
s.in = make(chan []byte, s.AllowedPendingMessages)
s.gauges = make(map[string]cachedgauge)
s.counters = make(map[string]cachedcounter)
s.sets = make(map[string]cachedset)
s.timings = make(map[string]cachedtimings)
s.ConvertNames = true
s.UDPPacketSize = UDP_PACKET_SIZE
return &s
}
// One statsd metric, form is <bucket>:<value>|<mtype>|@<samplerate>
type metric struct {
name string
field string
bucket string
hash string
intvalue int64
floatvalue float64
mtype string
additive bool
samplerate float64
tags map[string]string
}
type cachedset struct {
name string
fields map[string]map[int64]bool
tags map[string]string
}
type cachedgauge struct {
name string
fields map[string]interface{}
tags map[string]string
}
type cachedcounter struct {
name string
fields map[string]interface{}
tags map[string]string
}
type cachedtimings struct {
name string
fields map[string]RunningStats
tags map[string]string
}
func (_ *Statsd) Description() string {
return "Statsd Server"
}
const sampleConfig = `
## Address and port to host UDP listener on
service_address = ":8125"
## Delete gauges every interval (default=false)
delete_gauges = false
## Delete counters every interval (default=false)
delete_counters = false
## Delete sets every interval (default=false)
delete_sets = false
## Delete timings & histograms every interval (default=true)
delete_timings = true
## Percentiles to calculate for timing & histogram stats
percentiles = [90]
## convert measurement names, "." to "_" and "-" to "__"
convert_names = true
## Statsd data translation templates, more info can be read here:
## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md#graphite
# templates = [
# "cpu.* measurement*"
# ]
## Number of UDP messages allowed to queue up, once filled,
## the statsd server will start dropping packets
allowed_pending_messages = 10000
## Number of timing/histogram values to track per-measurement in the
## calculation of percentiles. Raising this limit increases the accuracy
## of percentiles but also increases the memory usage and cpu time.
percentile_limit = 1000
## UDP packet size for the server to listen for. This will depend on the size
## of the packets that the client is sending, which is usually 1500 bytes.
udp_packet_size = 1500
`
func (_ *Statsd) SampleConfig() string {
return sampleConfig
}
func (s *Statsd) Gather(acc telegraf.Accumulator) error {
s.Lock()
defer s.Unlock()
now := time.Now()
for _, metric := range s.timings {
// Defining a template to parse field names for timers allows us to split
// out multiple fields per timer. In this case we prefix each stat with the
// field name and store these all in a single measurement.
fields := make(map[string]interface{})
for fieldName, stats := range metric.fields {
var prefix string
if fieldName != defaultFieldName {
prefix = fieldName + "_"
}
fields[prefix+"mean"] = stats.Mean()
fields[prefix+"stddev"] = stats.Stddev()
fields[prefix+"upper"] = stats.Upper()
fields[prefix+"lower"] = stats.Lower()
fields[prefix+"count"] = stats.Count()
for _, percentile := range s.Percentiles {
name := fmt.Sprintf("%s%v_percentile", prefix, percentile)
fields[name] = stats.Percentile(percentile)
}
}
acc.AddFields(metric.name, fields, metric.tags, now)
}
if s.DeleteTimings {
s.timings = make(map[string]cachedtimings)
}
for _, metric := range s.gauges {
acc.AddFields(metric.name, metric.fields, metric.tags, now)
}
if s.DeleteGauges {
s.gauges = make(map[string]cachedgauge)
}
for _, metric := range s.counters {
acc.AddFields(metric.name, metric.fields, metric.tags, now)
}
if s.DeleteCounters {
s.counters = make(map[string]cachedcounter)
}
for _, metric := range s.sets {
fields := make(map[string]interface{})
for field, set := range metric.fields {
fields[field] = int64(len(set))
}
acc.AddFields(metric.name, fields, metric.tags, now)
}
if s.DeleteSets {
s.sets = make(map[string]cachedset)
}
return nil
}
func (s *Statsd) Start(_ telegraf.Accumulator) error {
// Make data structures
s.done = make(chan struct{})
s.in = make(chan []byte, s.AllowedPendingMessages)
s.gauges = make(map[string]cachedgauge)
s.counters = make(map[string]cachedcounter)
s.sets = make(map[string]cachedset)
s.timings = make(map[string]cachedtimings)
// Start the UDP listener
go s.udpListen()
// Start the line parser
go s.parser()
log.Printf("Started the statsd service on %s\n", s.ServiceAddress)
return nil
}
// udpListen starts listening for udp packets on the configured port.
func (s *Statsd) udpListen() error {
address, _ := net.ResolveUDPAddr("udp", s.ServiceAddress)
listener, err := net.ListenUDP("udp", address)
if err != nil {
log.Fatalf("ERROR: ListenUDP - %s", err)
}
defer listener.Close()
log.Println("Statsd listener listening on: ", listener.LocalAddr().String())
for {
select {
case <-s.done:
return nil
default:
buf := make([]byte, s.UDPPacketSize)
n, _, err := listener.ReadFromUDP(buf)
if err != nil {
log.Printf("ERROR: %s\n", err.Error())
}
select {
case s.in <- buf[:n]:
default:
log.Printf(dropwarn, string(buf[:n]))
}
}
}
}
// parser monitors the s.in channel, if there is a packet ready, it parses the
// packet into statsd strings and then calls parseStatsdLine, which parses a
// single statsd metric into a struct.
func (s *Statsd) parser() error {
for {
select {
case <-s.done:
return nil
case packet := <-s.in:
lines := strings.Split(string(packet), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
s.parseStatsdLine(line)
}
}
}
}
}
// parseStatsdLine will parse the given statsd line, validating it as it goes.
// If the line is valid, it will be cached for the next call to Gather()
func (s *Statsd) parseStatsdLine(line string) error {
s.Lock()
defer s.Unlock()
// Validate splitting the line on ":"
bits := strings.Split(line, ":")
if len(bits) < 2 {
log.Printf("Error: splitting ':', Unable to parse metric: %s\n", line)
return errors.New("Error Parsing statsd line")
}
// Extract bucket name from individual metric bits
bucketName, bits := bits[0], bits[1:]
// Add a metric for each bit available
for _, bit := range bits {
m := metric{}
m.bucket = bucketName
// Validate splitting the bit on "|"
pipesplit := strings.Split(bit, "|")
if len(pipesplit) < 2 {
log.Printf("Error: splitting '|', Unable to parse metric: %s\n", line)
return errors.New("Error Parsing statsd line")
} else if len(pipesplit) > 2 {
sr := pipesplit[2]
errmsg := "Error: parsing sample rate, %s, it must be in format like: " +
"@0.1, @0.5, etc. Ignoring sample rate for line: %s\n"
if strings.Contains(sr, "@") && len(sr) > 1 {
samplerate, err := strconv.ParseFloat(sr[1:], 64)
if err != nil {
log.Printf(errmsg, err.Error(), line)
} else {
// sample rate successfully parsed
m.samplerate = samplerate
}
} else {
log.Printf(errmsg, "", line)
}
}
// Validate metric type
switch pipesplit[1] {
case "g", "c", "s", "ms", "h":
m.mtype = pipesplit[1]
default:
log.Printf("Error: Statsd Metric type %s unsupported", pipesplit[1])
return errors.New("Error Parsing statsd line")
}
// Parse the value
if strings.ContainsAny(pipesplit[0], "-+") {
if m.mtype != "g" {
log.Printf("Error: +- values are only supported for gauges: %s\n", line)
return errors.New("Error Parsing statsd line")
}
m.additive = true
}
switch m.mtype {
case "g", "ms", "h":
v, err := strconv.ParseFloat(pipesplit[0], 64)
if err != nil {
log.Printf("Error: parsing value to float64: %s\n", line)
return errors.New("Error Parsing statsd line")
}
m.floatvalue = v
case "c", "s":
var v int64
v, err := strconv.ParseInt(pipesplit[0], 10, 64)
if err != nil {
v2, err2 := strconv.ParseFloat(pipesplit[0], 64)
if err2 != nil {
log.Printf("Error: parsing value to int64: %s\n", line)
return errors.New("Error Parsing statsd line")
}
v = int64(v2)
}
// If a sample rate is given with a counter, divide value by the rate
if m.samplerate != 0 && m.mtype == "c" {
v = int64(float64(v) / m.samplerate)
}
m.intvalue = v
}
// Parse the name & tags from bucket
m.name, m.field, m.tags = s.parseName(m.bucket)
switch m.mtype {
case "c":
m.tags["metric_type"] = "counter"
case "g":
m.tags["metric_type"] = "gauge"
case "s":
m.tags["metric_type"] = "set"
case "ms":
m.tags["metric_type"] = "timing"
case "h":
m.tags["metric_type"] = "histogram"
}
// Make a unique key for the measurement name/tags
var tg []string
for k, v := range m.tags {
tg = append(tg, fmt.Sprintf("%s=%s", k, v))
}
sort.Strings(tg)
m.hash = fmt.Sprintf("%s%s", strings.Join(tg, ""), m.name)
s.aggregate(m)
}
return nil
}
// parseName parses the given bucket name with the list of bucket maps in the
// config file. If there is a match, it will parse the name of the metric and
// map of tags.
// Return values are (<name>, <field>, <tags>)
func (s *Statsd) parseName(bucket string) (string, string, map[string]string) {
tags := make(map[string]string)
bucketparts := strings.Split(bucket, ",")
// Parse out any tags in the bucket
if len(bucketparts) > 1 {
for _, btag := range bucketparts[1:] {
k, v := parseKeyValue(btag)
if k != "" {
tags[k] = v
}
}
}
var field string
name := bucketparts[0]
p, err := graphite.NewGraphiteParser(".", s.Templates, nil)
if err == nil {
p.DefaultTags = tags
name, tags, field, _ = p.ApplyTemplate(name)
}
if s.ConvertNames {
name = strings.Replace(name, ".", "_", -1)
name = strings.Replace(name, "-", "__", -1)
}
if field == "" {
field = defaultFieldName
}
return name, field, tags
}
// Parse the key,value out of a string that looks like "key=value"
func parseKeyValue(keyvalue string) (string, string) {
var key, val string
split := strings.Split(keyvalue, "=")
// Must be exactly 2 to get anything meaningful out of them
if len(split) == 2 {
key = split[0]
val = split[1]
} else if len(split) == 1 {
val = split[0]
}
return key, val
}
// aggregate takes in a metric. It then
// aggregates and caches the current value(s). It does not deal with the
// Delete* options, because those are dealt with in the Gather function.
func (s *Statsd) aggregate(m metric) {
switch m.mtype {
case "ms", "h":
// Check if the measurement exists
cached, ok := s.timings[m.hash]
if !ok {
cached = cachedtimings{
name: m.name,
fields: make(map[string]RunningStats),
tags: m.tags,
}
}
// Check if the field exists. If we've not enabled multiple fields per timer
// this will be the default field name, eg. "value"
field, ok := cached.fields[m.field]
if !ok {
field = RunningStats{
PercLimit: s.PercentileLimit,
}
}
if m.samplerate > 0 {
for i := 0; i < int(1.0/m.samplerate); i++ {
field.AddValue(m.floatvalue)
}
} else {
field.AddValue(m.floatvalue)
}
cached.fields[m.field] = field
s.timings[m.hash] = cached
case "c":
// check if the measurement exists
_, ok := s.counters[m.hash]
if !ok {
s.counters[m.hash] = cachedcounter{
name: m.name,
fields: make(map[string]interface{}),
tags: m.tags,
}
}
// check if the field exists
_, ok = s.counters[m.hash].fields[m.field]
if !ok {
s.counters[m.hash].fields[m.field] = int64(0)
}
s.counters[m.hash].fields[m.field] =
s.counters[m.hash].fields[m.field].(int64) + m.intvalue
case "g":
// check if the measurement exists
_, ok := s.gauges[m.hash]
if !ok {
s.gauges[m.hash] = cachedgauge{
name: m.name,
fields: make(map[string]interface{}),
tags: m.tags,
}
}
// check if the field exists
_, ok = s.gauges[m.hash].fields[m.field]
if !ok {
s.gauges[m.hash].fields[m.field] = float64(0)
}
if m.additive {
s.gauges[m.hash].fields[m.field] =
s.gauges[m.hash].fields[m.field].(float64) + m.floatvalue
} else {
s.gauges[m.hash].fields[m.field] = m.floatvalue
}
case "s":
// check if the measurement exists
_, ok := s.sets[m.hash]
if !ok {
s.sets[m.hash] = cachedset{
name: m.name,
fields: make(map[string]map[int64]bool),
tags: m.tags,
}
}
// check if the field exists
_, ok = s.sets[m.hash].fields[m.field]
if !ok {
s.sets[m.hash].fields[m.field] = make(map[int64]bool)
}
s.sets[m.hash].fields[m.field][m.intvalue] = true
}
}
func (s *Statsd) Stop() {
s.Lock()
defer s.Unlock()
log.Println("Stopping the statsd service")
close(s.done)
close(s.in)
}
func init() {
inputs.Add("statsd", func() telegraf.Input {
return &Statsd{
ConvertNames: true,
UDPPacketSize: UDP_PACKET_SIZE,
}
})
}
| mit |
rehanarroihan/PerpustakaanCI | application/views/transaksi/peminjaman_view.php | 13920 | <script src="<?php echo base_url() ?>assets/vendors/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#slcAgta").change(function(){
var agt = $(this).val();
$.ajax({
url:"<?php echo base_url() ?>peminjaman/searchAgtName",
type: "POST",
data: {"id" : agt},
cache: false,
success: function(huh){
$("#tbNama").val(huh);
}
})
})
//Buku 1
$("#slcBookCode1").change(function() {
if(this.value != ''){
$('#row2').css('display','block');
//Get Data
$.ajax({
url: "<?php echo base_url() ?>peminjaman/searchBookTitle",
type: "POST",
data: "id="+this.value,
cache: false,
success: function(data){
$("#tbJudul1").val(data);
}
})
$.ajax({
url: "<?php echo base_url() ?>peminjaman/searchBookAuthor",
type: "POST",
data: "id="+this.value,
cache: false,
success: function(data){
$("#tbPenulis1").val(data);
}
})
}
if(this.value == ''){
$('#tbJudul1').val('');
$('#tbPenulis1').val('');
$('#row2').css('display','none');
$('#slcBookCode2').prop('selectedIndex',0);
$('#tbJudul2').val('');
$('#tbPenulis2').val('');
//3
$('#row3').css('display','none');
$('#slcBookCode3').prop('selectedIndex',0);
$('#tbJudul3').val('');
$('#tbPenulis3').val('');
}
})
//Buku 2
$("#slcBookCode2").change(function() {
if(this.value != ''){
$('#row3').css('display','block');
//Get Data
$.ajax({
url: "<?php echo base_url() ?>peminjaman/searchBookTitle",
type: "POST",
data: "id="+this.value,
cache: false,
success: function(data){
$("#tbJudul2").val(data);
}
})
$.ajax({
url: "<?php echo base_url() ?>peminjaman/searchBookAuthor",
type: "POST",
data: "id="+this.value,
cache: false,
success: function(data){
$("#tbPenulis2").val(data);
}
})
}
if(this.value == ''){
$('#tbJudul2').val('');
$('#tbPenulis2').val('');
$('#row3').css('display','none');
$('#slcBookCode3').prop('selectedIndex',0);
$('#tbJudul3').val('');
$('#tbPenulis3').val('');
}
})
//Buku 3
$("#slcBookCode3").change(function() {
if(this.value != ''){
//Get Data
$.ajax({
url: "<?php echo base_url() ?>peminjaman/searchBookTitle",
type: "POST",
data: "id="+this.value,
cache: false,
success: function(data){
$("#tbJudul3").val(data);
}
})
$.ajax({
url: "<?php echo base_url() ?>peminjaman/searchBookAuthor",
type: "POST",
data: "id="+this.value,
cache: false,
success: function(data){
$("#tbPenulis3").val(data);
}
})
}
if(this.value == ''){
$('#tbJudul3').val('');
$('#tbPenulis3').val('');
}
})
})
</script>
<div class="">
<div class="page-title" style="padding: 8px">
<div class="title_left">
<h1><i class="fa fa-arrow-up"></i> Peminjaman</h1>
</div>
</div>
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Masukkan data peminjaman</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<!-- Notif -->
<?php $announce = $this->session->userdata('announce') ?>
<?php if(!empty($announce)): ?>
<?php if($announce == 'Berhasil menyimpan data'): ?>
<div class="alert alert-success fade in">
<?php echo $announce; ?>
</div>
<?php else: ?>
<div class="alert alert-danger">
<?php echo $announce; ?>
</div>
<?php endif; ?>
<?php endif; ?>
<form method="post" action="<?php echo base_url(); ?>peminjaman/submit" role="form" enctype="multipart/form-data">
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Kode Peminjaman</label>
<input type="text" name="tbBrwCode" class="form-control" value="<?php echo $kode ?>" readonly="readonly">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>ID Anggota</label>
<select class="form-control" id="slcAgta" name="slcAgta">
<option value="">Pilih ID Anggota</option>
<?php foreach ($anggota as $agt): ?>
<option><?php echo $agt->ID_ANGGOTA ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Tanggal Peminjaman</label>
<?php
$plus = date('Y-m-d',strtotime("+7 day",strtotime(date('Y-m-d'))));
?>
<input name="tbDateStart" class="form-control" value="<?php echo date("Y-m-d"); ?>" readonly="readonly">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Tanggal Pengembalian</label>
<input name="tbDateEnd" class="form-control" value="<?php echo $plus ?>" readonly="readonly">
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Nama Peminjam</label>
<input type="text" name="tbNama" id="tbNama" class="form-control" placeholder="Pilih Kolom ID Anggota" readonly="readonly">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Nama Petugas</label>
<input readonly="readonly" name="tbPetugas" class="form-control" value="<?php echo $petugas ?>">
</div>
</div>
</div>
<hr/>
<!-- Buku 1 -->
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Kode Buku</label>
<select class="form-control" name="slcBookCode1" id="slcBookCode1">
<option value="">Pilih Kode Buku</option>
<?php foreach ($buku as $kode): ?>
<option><?php echo $kode->ID_BUKU?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Judul Buku</label>
<input type="text" name="tbJudul" id="tbJudul1" class="form-control" placeholder="Judul Buku" readonly="readonly">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Penulis Buku</label>
<input type="text" name="tbPenulis" id="tbPenulis1" class="form-control" placeholder="Penulis Buku" readonly="readonly">
</div>
</div>
</div>
<!-- Buku 2 -->
<div class="row" id="row2" style="display:none">
<div class="col-md-4">
<div class="form-group">
<select class="form-control" name="slcBookCode2" id="slcBookCode2">
<option value="">Pilih Kode Buku</option>
<?php foreach ($buku as $kode): ?>
<option><?php echo $kode->ID_BUKU?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" name="tbJudul" id="tbJudul2" class="form-control" placeholder="Judul Buku" readonly="readonly">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" name="tbPenulis" id="tbPenulis2" class="form-control" placeholder="Penulis Buku" readonly="readonly">
</div>
</div>
</div>
<!-- Buku 3 -->
<div class="row" id="row3" style="display:none">
<div class="col-md-4">
<div class="form-group">
<select class="form-control" name="slcBookCode3" id="slcBookCode3">
<option value="">Pilih Kode Buku</option>
<?php foreach ($buku as $kode): ?>
<option><?php echo $kode->ID_BUKU?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" name="tbJudul" id="tbJudul3" class="form-control" placeholder="Judul Buku" readonly="readonly">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" name="tbPenulis" id="tbPenulis3" class="form-control" placeholder="Penulis Buku" readonly="readonly">
</div>
</div>
</div>
<hr/>
<div class="row">
<div class="col-md-12">
<input type="submit" name="submit" class="btn btn-primary" value="Simpan">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div> | mit |
jlmeeker/Aura | src/org/meekers/plugins/aura/AuraPluginListener.java | 2698 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.meekers.plugins.aura;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.util.Vector;
/**
*
* @author jaredm
*/
class AuraPluginListener implements Listener {
Aura plugin;
public AuraPluginListener(Aura plugin) {
this.plugin = plugin;
}
@EventHandler
public void onEntityTarget(EntityTargetEvent event) {
boolean repel = false;
Entity e = event.getEntity();
Entity t = event.getTarget();
// If an entity dies, e may be null
if (e == null) {
return;
}
if (t.getType() == EntityType.PLAYER && e instanceof LivingEntity) {
Player p = (Player) event.getTarget();
int playerxp = p.getLevel();
double speed = plugin.getConfig().getDouble("repelspeed");
int zoxp = plugin.getConfig().getInt("zoxp");
int spxp = plugin.getConfig().getInt("spxp");
int skxp = plugin.getConfig().getInt("skxp");
int crxp = plugin.getConfig().getInt("crxp");
int enxp = plugin.getConfig().getInt("enxp");
// Zombie
if (zoxp > 0 && playerxp >= zoxp && e.getType() == EntityType.ZOMBIE) {
repel = true;
}
// Spider
if (spxp > 0 && playerxp >= spxp && e.getType() == EntityType.SPIDER) {
repel = true;
}
// Skeleton
if (skxp > 0 && playerxp >= skxp && e.getType() == EntityType.SKELETON) {
repel = true;
}
// Creeper
if (crxp > 0 && playerxp >= crxp && e.getType() == EntityType.CREEPER) {
repel = true;
}
// Enderman
if (enxp > 0 && playerxp >= enxp && e.getType() == EntityType.ENDERMAN) {
repel = true;
}
if (repel == true) {
// Get velocity unit vector:
Vector unitVector = e.getLocation().toVector().subtract(p.getLocation().toVector()).normalize();
// Set speed and push entity:
e.setVelocity(unitVector.multiply(speed));
//p.sendMessage("Your XP just repelled a " + e.getType().getName());
event.setCancelled(true);
}
}
}
}
| mit |
pablosproject/FuzzyBrain-Release | src/input_providers/InputStreamProvider.cpp | 301 | /*
* InputStreamProvider.cpp
*
* Created on: Dec 6, 2012
* Author: igloo
*/
#include "InputStreamProvider.h"
InputStreamProvider::InputStreamProvider() {
// TODO Auto-generated constructor stub
}
InputStreamProvider::~InputStreamProvider() {
// TODO Auto-generated destructor stub
}
| mit |
cosbycoin/cosbycoin | src/qt/locale/bitcoin_it.ts | 89945 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="it" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="14"/>
<source>About CosbyCoin</source>
<translation>Info su CosbyCoin</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="53"/>
<source><b>CosbyCoin</b> version</source>
<translation>Versione di <b>CosbyCoin</b></translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="85"/>
<source>Copyright © 2011-2013 CosbyCoin Developers
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file license.txt 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>Copyright © 2011-2013 CosbyCoin Developers
Questo è un software sperimentale.
Distribuito sotto la licenza software MIT/X11, vedi il file license.txt incluso oppure su http://www.opensource.org/licenses/mit-license.php.
Questo prodotto include software sviluppato dal progetto OpenSSL per l'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>Rubrica</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="20"/>
<source>These are your CosbyCoin 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>Questi sono i tuoi indirizzi CosbyCoin per ricevere pagamenti. Potrai darne uno diverso ad ognuno per tenere così traccia di chi ti sta pagando.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="33"/>
<source>Double-click to edit address or label</source>
<translation>Fai doppio click per modificare o cancellare l'etichetta</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="57"/>
<source>Create a new address</source>
<translation>Crea un nuovo indirizzo</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="60"/>
<source>&New Address...</source>
<translation>&Nuovo indirizzo...</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="71"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copia l'indirizzo attualmente selezionato nella clipboard</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="74"/>
<source>&Copy to Clipboard</source>
<translation>&Copia nella clipboard</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="85"/>
<source>Show &QR Code</source>
<translation>Mostra il codice &QR</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="96"/>
<source>Sign a message to prove you own this address</source>
<translation>Firma un messaggio per dimostrare di possedere questo indirizzo</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="99"/>
<source>&Sign Message</source>
<translation>&Firma il messaggio</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="110"/>
<source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source>
<translation>Cancella l'indirizzo attualmente selezionato dalla lista. Solo indirizzi d'invio possono essere cancellati.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="113"/>
<source>&Delete</source>
<translation>&Cancella</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="61"/>
<source>Copy address</source>
<translation>Copia l'indirizzo</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="62"/>
<source>Copy label</source>
<translation>Copia l'etichetta</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="63"/>
<source>Edit</source>
<translation>Modifica</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="64"/>
<source>Delete</source>
<translation>Cancella</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="281"/>
<source>Export Address Book Data</source>
<translation>Esporta gli indirizzi della rubrica</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="282"/>
<source>Comma separated file (*.csv)</source>
<translation>Testo CSV (*.csv)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="295"/>
<source>Error exporting</source>
<translation>Errore nell'esportazione</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="295"/>
<source>Could not write to file %1.</source>
<translation>Impossibile scrivere sul file %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="77"/>
<source>Label</source>
<translation>Etichetta</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="77"/>
<source>Address</source>
<translation>Indirizzo</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="113"/>
<source>(no label)</source>
<translation>(nessuna etichetta)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="26"/>
<source>Dialog</source>
<translation>Dialogo</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="32"/>
<location filename="../forms/askpassphrasedialog.ui" line="97"/>
<source>TextLabel</source>
<translation>Etichetta</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="50"/>
<source>Enter passphrase</source>
<translation>Inserisci la passphrase</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="64"/>
<source>New passphrase</source>
<translation>Nuova passphrase</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="78"/>
<source>Repeat new passphrase</source>
<translation>Ripeti la passphrase</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="34"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Inserisci la passphrase per il portamonete.<br/>Per piacere usare unapassphrase di <b>10 o più caratteri casuali</b>, o <b>otto o più parole</b>.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="35"/>
<source>Encrypt wallet</source>
<translation>Cifra il portamonete</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="38"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Quest'operazione necessita della passphrase per sbloccare il portamonete.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="43"/>
<source>Unlock wallet</source>
<translation>Sblocca il portamonete</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="46"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Quest'operazione necessita della passphrase per decifrare il portamonete,</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="51"/>
<source>Decrypt wallet</source>
<translation>Decifra il portamonete</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="54"/>
<source>Change passphrase</source>
<translation>Cambia la passphrase</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="55"/>
<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 filename="../askpassphrasedialog.cpp" line="101"/>
<source>Confirm wallet encryption</source>
<translation>Conferma la cifratura del portamonete</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="102"/>
<source>WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR CBCoinS</b>!
Are you sure you wish to encrypt your wallet?</source>
<translation>ATTENZIONE: se si cifra il portamonete e si perde la frase d'ordine, <b>SI PERDERANNO TUTTI I PROPRI CosbyCoin</b>!
Si è sicuri di voler cifrare il portamonete?</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="111"/>
<location filename="../askpassphrasedialog.cpp" line="160"/>
<source>Wallet encrypted</source>
<translation>Portamonete cifrato</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="112"/>
<source>CosbyCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your CBCoins from being stolen by malware infecting your computer.</source>
<translation>CosbyCoin verrà ora chiuso per finire il processo di crittazione. Ricorda che criptare il tuo portamonete non può fornire una protezione totale contro furti causati da malware che dovessero infettare il tuo computer.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="208"/>
<location filename="../askpassphrasedialog.cpp" line="232"/>
<source>Warning: The Caps Lock key is on.</source>
<translation>Attenzione: tasto Blocco maiuscole attivo.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="117"/>
<location filename="../askpassphrasedialog.cpp" line="124"/>
<location filename="../askpassphrasedialog.cpp" line="166"/>
<location filename="../askpassphrasedialog.cpp" line="172"/>
<source>Wallet encryption failed</source>
<translation>Cifratura del portamonete fallita</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="118"/>
<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 filename="../askpassphrasedialog.cpp" line="125"/>
<location filename="../askpassphrasedialog.cpp" line="173"/>
<source>The supplied passphrases do not match.</source>
<translation>Le passphrase inserite non corrispondono.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="136"/>
<source>Wallet unlock failed</source>
<translation>Sblocco del portamonete fallito</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="137"/>
<location filename="../askpassphrasedialog.cpp" line="148"/>
<location filename="../askpassphrasedialog.cpp" line="167"/>
<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 filename="../askpassphrasedialog.cpp" line="147"/>
<source>Wallet decryption failed</source>
<translation>Decifrazione del portamonete fallita</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="161"/>
<source>Wallet passphrase was succesfully changed.</source>
<translation>Passphrase del portamonete modificata con successo.</translation>
</message>
</context>
<context>
<name>CBCoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="69"/>
<source>CosbyCoin Wallet</source>
<translation>Portamonete di CosbyCoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="142"/>
<location filename="../bitcoingui.cpp" line="464"/>
<source>Synchronizing with network...</source>
<translation>Sto sincronizzando con la rete...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="145"/>
<source>Block chain synchronization in progress</source>
<translation>sincronizzazione della catena di blocchi in corso</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="176"/>
<source>&Overview</source>
<translation>&Sintesi</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="177"/>
<source>Show general overview of wallet</source>
<translation>Mostra lo stato generale del portamonete</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="182"/>
<source>&Transactions</source>
<translation>&Transazioni</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="183"/>
<source>Browse transaction history</source>
<translation>Cerca nelle transazioni</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="188"/>
<source>&Address Book</source>
<translation>&Rubrica</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="189"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Modifica la lista degli indirizzi salvati e delle etichette</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="194"/>
<source>&Receive coins</source>
<translation>&Ricevi monete</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="195"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Mostra la lista di indirizzi su cui ricevere pagamenti</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="200"/>
<source>&Send coins</source>
<translation>&Invia monete</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="201"/>
<source>Send coins to a CosbyCoin address</source>
<translation>Invia monete ad un indirizzo CosbyCoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="206"/>
<source>Sign &message</source>
<translation>Firma il &messaggio</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="207"/>
<source>Prove you control an address</source>
<translation>Dimostra di controllare un indirizzo</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="226"/>
<source>E&xit</source>
<translation>&Esci</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="227"/>
<source>Quit application</source>
<translation>Chiudi applicazione</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="230"/>
<source>&About %1</source>
<translation>&Informazioni su %1</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="231"/>
<source>Show information about CosbyCoin</source>
<translation>Mostra informazioni su CosbyCoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="233"/>
<source>About &Qt</source>
<translation>Informazioni su &Qt</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="234"/>
<source>Show information about Qt</source>
<translation>Mostra informazioni su Qt</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="236"/>
<source>&Options...</source>
<translation>&Opzioni...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="237"/>
<source>Modify configuration options for CosbyCoin</source>
<translation>Modifica configurazione opzioni per CosbyCoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="239"/>
<source>Open &CosbyCoin</source>
<translation>Apri &CosbyCoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="240"/>
<source>Show the CosbyCoin window</source>
<translation>Mostra la finestra CosbyCoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="241"/>
<source>&Export...</source>
<translation>&Esporta...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="242"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="243"/>
<source>&Encrypt Wallet</source>
<translation>&Cifra il portamonete</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="244"/>
<source>Encrypt or decrypt wallet</source>
<translation>Cifra o decifra il portamonete</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="246"/>
<source>&Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="247"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="248"/>
<source>&Change Passphrase</source>
<translation>&Cambia la passphrase</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="249"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cambia la passphrase per la cifratura del portamonete</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="272"/>
<source>&File</source>
<translation>&File</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="281"/>
<source>&Settings</source>
<translation>&Impostazioni</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="287"/>
<source>&Help</source>
<translation>&Aiuto</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="294"/>
<source>Tabs toolbar</source>
<translation>Barra degli strumenti "Tabs"</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="305"/>
<source>Actions toolbar</source>
<translation>Barra degli strumenti "Azioni"</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="317"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="407"/>
<source>CosbyCoin-qt</source>
<translation>CosbyCoin-qt</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="449"/>
<source>%n active connection(s) to CosbyCoin network</source>
<translation><numerusform>%n connessione attiva alla rete CosbyCoin</numerusform><numerusform>%n connessioni attive alla rete CosbyCoin</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="475"/>
<source>Downloaded %1 of %2 blocks of transaction history.</source>
<translation>Scaricati %1 dei %2 blocchi dello storico transazioni.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="487"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Scaricati %1 blocchi dello storico transazioni.</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="502"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n secondo fa</numerusform><numerusform>%n secondi fa</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="506"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n minuto fa</numerusform><numerusform>%n minuti fa</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="510"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n ora fa</numerusform><numerusform>%n ore fa</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="514"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n giorno fa</numerusform><numerusform>%n giorni fa</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="520"/>
<source>Up to date</source>
<translation>Aggiornato</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="525"/>
<source>Catching up...</source>
<translation>In aggiornamento...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="533"/>
<source>Last received block was generated %1.</source>
<translation>L'ultimo blocco ricevuto è stato generato %1</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="597"/>
<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>Questa transazione è superiore al limite di dimensione. È comunque possibile inviarla con una commissione di %1, che va ai nodi che processano la tua transazione e contribuisce a sostenere la rete. Vuoi pagare la commissione?</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="602"/>
<source>Sending...</source>
<translation>Invio...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="629"/>
<source>Sent transaction</source>
<translation>Transazione inviata</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="630"/>
<source>Incoming transaction</source>
<translation>Transazione ricevuta</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="631"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Quantità: %2
Tipo: %3
Indirizzo: %4
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="751"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Il portamonete è <b>cifrato</b> e attualmente <b>sbloccato</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="759"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Il portamonete è <b>cifrato</b> e attualmente <b>bloccato</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="782"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="782"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="785"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="785"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>DisplayOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="270"/>
<source>&Unit to show amounts in: </source>
<translation>&Unità di misura degli importi in: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="274"/>
<source>Choose the default subdivision unit to show in the interface, and when sending coins</source>
<translation>Scegli l'unità di suddivisione di default per l'interfaccia e per l'invio di monete</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="281"/>
<source>Display addresses in transaction list</source>
<translation>Mostra gli indirizzi nella lista delle transazioni</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="14"/>
<source>Edit Address</source>
<translation>Modifica l'indirizzo</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="25"/>
<source>&Label</source>
<translation>&Etichetta</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="35"/>
<source>The label associated with this address book entry</source>
<translation>L'etichetta associata a questo indirizzo nella rubrica</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="42"/>
<source>&Address</source>
<translation>&Indirizzo</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="52"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>L'indirizzo associato a questa voce della rubrica. Si può modificare solo negli indirizzi di spedizione.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="20"/>
<source>New receiving address</source>
<translation>Nuovo indirizzo di ricezione</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="24"/>
<source>New sending address</source>
<translation>Nuovo indirizzo d'invio</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="27"/>
<source>Edit receiving address</source>
<translation>Modifica indirizzo di ricezione</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="31"/>
<source>Edit sending address</source>
<translation>Modifica indirizzo d'invio</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="91"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>L'indirizzo inserito "%1" è già in rubrica.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="96"/>
<source>The entered address "%1" is not a valid CosbyCoin address.</source>
<translation>L'indirizzo inserito "%1" non è un indirizzo CosbyCoin valido.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="101"/>
<source>Could not unlock wallet.</source>
<translation>Impossibile sbloccare il portamonete.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="106"/>
<source>New key generation failed.</source>
<translation>Generazione della nuova chiave non riuscita.</translation>
</message>
</context>
<context>
<name>MainOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="170"/>
<source>&Start CosbyCoin on window system startup</source>
<translation>&Fai partire CosbyCoin all'avvio del sistema</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="171"/>
<source>Automatically start CosbyCoin after the computer is turned on</source>
<translation>Avvia automaticamente CosbyCoin all'accensione del computer</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="175"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizza sul tray invece che sulla barra delle applicazioni</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="176"/>
<source>Show only a tray icon after minimizing the window</source>
<translation>Mostra solo un'icona nel tray quando si minimizza la finestra</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="180"/>
<source>Map port using &UPnP</source>
<translation>Mappa le porte tramite l'&UPnP</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="181"/>
<source>Automatically open the CosbyCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Apri automaticamente la porta del client CosbyCoin sul router. Questo funziona solo se il router supporta UPnP ed è abilitato.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="185"/>
<source>M&inimize on close</source>
<translation>M&inimizza alla chiusura</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="186"/>
<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'applicazione quando la finestra viene chiusa. Quando questa opzione è attivata, l'applicazione verrà chiusa solo dopo aver selezionato Esci nel menu.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="190"/>
<source>&Connect through SOCKS4 proxy:</source>
<translation>&Collegati tramite SOCKS4 proxy:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="191"/>
<source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source>
<translation>Connettiti alla rete Bitcon attraverso un proxy SOCKS4 (ad esempio quando ci si collega via Tor)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="196"/>
<source>Proxy &IP: </source>
<translation>&IP del proxy: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="202"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Indirizzo IP del proxy (ad esempio 127.0.0.1)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="205"/>
<source>&Port: </source>
<translation>&Porta: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="211"/>
<source>Port of the proxy (e.g. 1234)</source>
<translation>Porta del proxy (es. 1234)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="217"/>
<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>Commissione di transazione per kB; è opzionale e contribuisce ad assicurare che le transazioni siano elaborate velocemente. Le transazioni sono per la maggior parte da 1 kB. Commissione raccomandata 0,01.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="223"/>
<source>Pay transaction &fee</source>
<translation>Paga la &commissione</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="226"/>
<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>Commissione di transazione per kB; è opzionale e contribuisce ad assicurare che le transazioni siano elaborate velocemente. Le transazioni sono per la maggior parte da 1 kB. Commissione raccomandata 0,01.</translation>
</message>
</context>
<context>
<name>MessagePage</name>
<message>
<location filename="../forms/messagepage.ui" line="14"/>
<source>Message</source>
<translation>Messaggio</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="20"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="38"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>L'indirizzo del beneficiario cui inviare il pagamento (ad esempio 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="48"/>
<source>Choose adress from address book</source>
<translation>Scegli l'indirizzo dalla rubrica</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="58"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="71"/>
<source>Paste address from clipboard</source>
<translation>Incollare l'indirizzo dagli appunti</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="81"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="93"/>
<source>Enter the message you want to sign here</source>
<translation>Inserisci qui il messaggio che vuoi firmare</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="105"/>
<source>Click "Sign Message" to get signature</source>
<translation>Clicca "Firma il messaggio" per ottenere la firma</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="117"/>
<source>Sign a message to prove you own this address</source>
<translation>Firma un messaggio per dimostrare di possedere questo indirizzo</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="120"/>
<source>&Sign Message</source>
<translation>&Firma il messaggio</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="131"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copia l'indirizzo attualmente selezionato nella clipboard</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="134"/>
<source>&Copy to Clipboard</source>
<translation>&Copia nella clipboard</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="74"/>
<location filename="../messagepage.cpp" line="89"/>
<location filename="../messagepage.cpp" line="101"/>
<source>Error signing</source>
<translation>Errore nel firmare</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="74"/>
<source>%1 is not a valid address.</source>
<translation>%1 non è un indirizzo valido.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="89"/>
<source>Private key for %1 is not available.</source>
<translation>La chiave privata per %1 non è disponibile.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="101"/>
<source>Sign failed</source>
<translation>Firma non riuscita</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../optionsdialog.cpp" line="79"/>
<source>Main</source>
<translation>Principale</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="84"/>
<source>Display</source>
<translation>Mostra</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="104"/>
<source>Options</source>
<translation>Opzioni</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="14"/>
<source>Form</source>
<translation>Modulo</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="40"/>
<source>Balance:</source>
<translation>Saldo</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="47"/>
<source>123.456 BTC</source>
<translation>123,456 BTC</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="54"/>
<source>Number of transactions:</source>
<translation>Numero di transazioni:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="61"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="68"/>
<source>Unconfirmed:</source>
<translation>Non confermato:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="75"/>
<source>0 BTC</source>
<translation>0 BTC</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="82"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Wallet</span></p></body></html></source>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">⏎
<html><head><meta name="qrichtext" content="1" /><style type="text/css">⏎
p, li { white-space: pre-wrap; }⏎
</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;">⏎
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Wallet</span></p></body></html></translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="122"/>
<source><b>Recent transactions</b></source>
<translation><b>Transazioni recenti</b></translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="103"/>
<source>Your current balance</source>
<translation>Saldo attuale</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Totale delle transazioni in corso di conferma, che non sono ancora incluse nel saldo attuale</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="111"/>
<source>Total number of transactions in wallet</source>
<translation>Numero delle transazioni effettuate</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="14"/>
<source>Dialog</source>
<translation>Dialogo</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="32"/>
<source>QR Code</source>
<translation>Codice QR</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="52"/>
<source>Request Payment</source>
<translation>Richiedi pagamento</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="67"/>
<source>Amount:</source>
<translation>Importo:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="102"/>
<source>BTC</source>
<translation>BTC</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="118"/>
<source>Label:</source>
<translation>Etichetta:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="141"/>
<source>Message:</source>
<translation>Messaggio:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="183"/>
<source>&Save As...</source>
<translation>&Salva come...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="101"/>
<source>Save Image...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="101"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="14"/>
<location filename="../sendcoinsdialog.cpp" line="122"/>
<location filename="../sendcoinsdialog.cpp" line="127"/>
<location filename="../sendcoinsdialog.cpp" line="132"/>
<location filename="../sendcoinsdialog.cpp" line="137"/>
<location filename="../sendcoinsdialog.cpp" line="143"/>
<location filename="../sendcoinsdialog.cpp" line="148"/>
<location filename="../sendcoinsdialog.cpp" line="153"/>
<source>Send Coins</source>
<translation>Spedisci CosbyCoin</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="64"/>
<source>Send to multiple recipients at once</source>
<translation>Spedisci a diversi beneficiari in una volta sola</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="67"/>
<source>&Add recipient...</source>
<translation>&Aggiungi beneficiario...</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="84"/>
<source>Remove all transaction fields</source>
<translation>Rimuovi tutti i campi della transazione</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="87"/>
<source>Clear all</source>
<translation>Cancella tutto</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="106"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="113"/>
<source>123.456 BTC</source>
<translation>123,456 BTC</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="144"/>
<source>Confirm the send action</source>
<translation>Conferma la spedizione</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="147"/>
<source>&Send</source>
<translation>&Spedisci</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="94"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="99"/>
<source>Confirm send coins</source>
<translation>Conferma la spedizione di CosbyCoin</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source>Are you sure you want to send %1?</source>
<translation>Si è sicuri di voler spedire %1?</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source> and </source>
<translation> e </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="123"/>
<source>The recepient address is not valid, please recheck.</source>
<translation>L'indirizzo del beneficiario non è valido, per cortesia controlla.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="128"/>
<source>The amount to pay must be larger than 0.</source>
<translation>L'importo da pagare dev'essere maggiore di 0.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="133"/>
<source>Amount exceeds your balance</source>
<translation>L'importo è superiore al saldo attuale</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="138"/>
<source>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 filename="../sendcoinsdialog.cpp" line="144"/>
<source>Duplicate address found, can only send to each address once in one 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 filename="../sendcoinsdialog.cpp" line="149"/>
<source>Error: Transaction creation failed </source>
<translation>Errore: creazione della transazione fallita </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="154"/>
<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>Errore: la transazione è stata rifiutata. Ciò accade se alcuni CosbyCoin nel portamonete sono stati già spesi, ad esempio se è stata usata una copia del file wallet.dat e i CosbyCoin sono stati spesi dalla copia ma non segnati come spesi qui.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="14"/>
<source>Form</source>
<translation>Modulo</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="29"/>
<source>A&mount:</source>
<translation>&Importo:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="42"/>
<source>Pay &To:</source>
<translation>Paga &a:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="66"/>
<location filename="../sendcoinsentry.cpp" line="26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Inserisci un'etichetta per questo indirizzo, per aggiungerlo nella rubrica</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="75"/>
<source>&Label:</source>
<translation>&Etichetta</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="93"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>L'indirizzo del beneficiario cui inviare il pagamento (ad esempio 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="103"/>
<source>Choose address from address book</source>
<translation>Scegli l'indirizzo dalla rubrica</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="113"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="120"/>
<source>Paste address from clipboard</source>
<translation>Incollare l'indirizzo dagli appunti</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="130"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="137"/>
<source>Remove this recipient</source>
<translation>Rimuovere questo beneficiario</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="25"/>
<source>Enter a CosbyCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Inserisci un indirizzo CosbyCoin (ad esempio 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="18"/>
<source>Open for %1 blocks</source>
<translation>Aperto per %1 blocchi</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="20"/>
<source>Open until %1</source>
<translation>Aperto fino a %1</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="26"/>
<source>%1/offline?</source>
<translation>%1/offline?</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="28"/>
<source>%1/unconfirmed</source>
<translation>%1/non confermato</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="30"/>
<source>%1 confirmations</source>
<translation>%1 conferme</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="47"/>
<source><b>Status:</b> </source>
<translation><b>Stato:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="52"/>
<source>, has not been successfully broadcast yet</source>
<translation>, non è stato ancora trasmesso con successo</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="54"/>
<source>, broadcast through %1 node</source>
<translation>, trasmesso attraverso %1 nodo</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="56"/>
<source>, broadcast through %1 nodes</source>
<translation>, trasmesso attraverso %1 nodi</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="60"/>
<source><b>Date:</b> </source>
<translation><b>Data:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="67"/>
<source><b>Source:</b> Generated<br></source>
<translation><b>Fonte:</b> Generato<br></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="73"/>
<location filename="../transactiondesc.cpp" line="90"/>
<source><b>From:</b> </source>
<translation><b>Da:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="90"/>
<source>unknown</source>
<translation>sconosciuto</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="91"/>
<location filename="../transactiondesc.cpp" line="114"/>
<location filename="../transactiondesc.cpp" line="173"/>
<source><b>To:</b> </source>
<translation><b>Per:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="94"/>
<source> (yours, label: </source>
<translation> (vostro, etichetta: </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="96"/>
<source> (yours)</source>
<translation> (vostro)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="131"/>
<location filename="../transactiondesc.cpp" line="145"/>
<location filename="../transactiondesc.cpp" line="190"/>
<location filename="../transactiondesc.cpp" line="207"/>
<source><b>Credit:</b> </source>
<translation><b>Credito:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="133"/>
<source>(%1 matures in %2 more blocks)</source>
<translation>(%1 matura in altri %2 blocchi)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="137"/>
<source>(not accepted)</source>
<translation>(non accettate)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="181"/>
<location filename="../transactiondesc.cpp" line="189"/>
<location filename="../transactiondesc.cpp" line="204"/>
<source><b>Debit:</b> </source>
<translation><b>Debito:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="195"/>
<source><b>Transaction fee:</b> </source>
<translation><b>Commissione:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="211"/>
<source><b>Net amount:</b> </source>
<translation><b>Importo netto:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="217"/>
<source>Message:</source>
<translation>Messaggio:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="219"/>
<source>Comment:</source>
<translation>Commento:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="221"/>
<source>Transaction ID:</source>
<translation>ID della transazione:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="224"/>
<source>Generated coins must wait 120 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, it will change to "not accepted" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Bisogna attendere 120 blocchi prima di spendere I CosbyCoin generati. Quando è stato generato questo blocco, è stato trasmesso alla rete per aggiungerlo alla catena di blocchi. Se non riesce a entrare nella catena, verrà modificato in "non accettato" e non sarà spendibile. Questo può accadere a volte, se un altro nodo genera un blocco entro pochi secondi del tuo.</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 filename="../forms/transactiondescdialog.ui" line="20"/>
<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="213"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Address</source>
<translation>Indirizzo</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Amount</source>
<translation>Importo</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="274"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Aperto per %n blocco</numerusform><numerusform>Aperto per %n blocchi</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="277"/>
<source>Open until %1</source>
<translation>Aperto fino a %1</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="280"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 conferme)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="283"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Non confermati (%1 su %2 conferme)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="286"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confermato (%1 conferme)</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="295"/>
<source>Mined balance will be available in %n more blocks</source>
<translation><numerusform>Il saldo generato sarà disponibile tra %n altro blocco</numerusform><numerusform>Il saldo generato sarà disponibile tra %n altri blocchi</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="301"/>
<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 filename="../transactiontablemodel.cpp" line="304"/>
<source>Generated but not accepted</source>
<translation>Generati, ma non accettati</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="347"/>
<source>Received with</source>
<translation>Ricevuto tramite</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="349"/>
<source>Received from</source>
<translation>Ricevuto da</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="352"/>
<source>Sent to</source>
<translation>Spedito a</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="354"/>
<source>Payment to yourself</source>
<translation>Pagamento a te stesso</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="356"/>
<source>Mined</source>
<translation>Ottenuto dal mining</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="394"/>
<source>(n/a)</source>
<translation>(N / a)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="593"/>
<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 filename="../transactiontablemodel.cpp" line="595"/>
<source>Date and time that the transaction was received.</source>
<translation>Data e ora in cui la transazione è stata ricevuta.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="597"/>
<source>Type of transaction.</source>
<translation>Tipo di transazione.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="599"/>
<source>Destination address of transaction.</source>
<translation>Indirizzo di destinazione della transazione.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="601"/>
<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 filename="../transactionview.cpp" line="71"/>
<source>All</source>
<translation>Tutti</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="56"/>
<source>Today</source>
<translation>Oggi</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="57"/>
<source>This week</source>
<translation>Questa settimana</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="58"/>
<source>This month</source>
<translation>Questo mese</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="59"/>
<source>Last month</source>
<translation>Il mese scorso</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="60"/>
<source>This year</source>
<translation>Quest'anno</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="61"/>
<source>Range...</source>
<translation>Intervallo...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="72"/>
<source>Received with</source>
<translation>Ricevuto tramite</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="74"/>
<source>Sent to</source>
<translation>Spedito a</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="76"/>
<source>To yourself</source>
<translation>A te</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="77"/>
<source>Mined</source>
<translation>Ottenuto dal mining</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="78"/>
<source>Other</source>
<translation>Altro</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="84"/>
<source>Enter address or label to search</source>
<translation>Inserisci un indirizzo o un'etichetta da cercare</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="90"/>
<source>Min amount</source>
<translation>Importo minimo</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="124"/>
<source>Copy address</source>
<translation>Copia l'indirizzo</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="125"/>
<source>Copy label</source>
<translation>Copia l'etichetta</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="126"/>
<source>Copy amount</source>
<translation>Copia l'importo</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="127"/>
<source>Edit label</source>
<translation>Modifica l'etichetta</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="128"/>
<source>Show details...</source>
<translation>Mostra i dettagli...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="268"/>
<source>Export Transaction Data</source>
<translation>Esporta i dati della transazione</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="269"/>
<source>Comma separated file (*.csv)</source>
<translation>Testo CSV (*.csv)</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="277"/>
<source>Confirmed</source>
<translation>Confermato</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="278"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="279"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="280"/>
<source>Label</source>
<translation>Etichetta</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="281"/>
<source>Address</source>
<translation>Indirizzo</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="282"/>
<source>Amount</source>
<translation>Importo</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="283"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="287"/>
<source>Error exporting</source>
<translation>Errore nell'esportazione</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="287"/>
<source>Could not write to file %1.</source>
<translation>Impossibile scrivere sul file %1.</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="382"/>
<source>Range:</source>
<translation>Intervallo:</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="390"/>
<source>to</source>
<translation>a</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="145"/>
<source>Sending...</source>
<translation>Invio...</translation>
</message>
</context>
<context>
<name>CosbyCoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="3"/>
<source>CosbyCoin version</source>
<translation>Versione di CosbyCoin</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="4"/>
<source>Usage:</source>
<translation>Utilizzo:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="5"/>
<source>Send command to -server or cosbycoind</source>
<translation>Manda il comando a -server o cosbycoind
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="6"/>
<source>List commands</source>
<translation>Lista comandi
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="7"/>
<source>Get help for a command</source>
<translation>Aiuto su un comando
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="8"/>
<source>Options:</source>
<translation>Opzioni:
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="9"/>
<source>Specify configuration file (default: CosbyCoin.conf)</source>
<translation>Specifica il file di configurazione (di default: CosbyCoin.conf)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="10"/>
<source>Specify pid file (default: cosbycoind.pid)</source>
<translation>Specifica il file pid (default: cosbycoind.pid)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="11"/>
<source>Generate coins</source>
<translation>Genera CosbyCoin
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="12"/>
<source>Don't generate coins</source>
<translation>Non generare CosbyCoin
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="13"/>
<source>Start minimized</source>
<translation>Parti in icona
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="14"/>
<source>Specify data directory</source>
<translation>Specifica la cartella dati
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="15"/>
<source>Specify connection timeout (in milliseconds)</source>
<translation>Specifica il timeout di connessione (in millisecondi)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="16"/>
<source>Connect through socks4 proxy</source>
<translation>Connessione tramite socks4 proxy
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="17"/>
<source>Allow DNS lookups for addnode and connect</source>
<translation>Consenti ricerche DNS per aggiungere nodi e collegare
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="18"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>Ascolta le connessioni JSON-RPC su <porta> (default: 8333 o testnet: 18333)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="19"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Mantieni al massimo <n> connessioni ai peer (default: 125)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="20"/>
<source>Add a node to connect to</source>
<translation>Aggiungi un nodo e connetti a
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="21"/>
<source>Connect only to the specified node</source>
<translation>Connetti solo al nodo specificato
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="22"/>
<source>Don't accept connections from outside</source>
<translation>Non accettare connessioni dall'esterno
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="23"/>
<source>Don't bootstrap list of peers using DNS</source>
<translation>Non avviare la lista dei peer usando il DNS</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="24"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Soglia di disconnessione dei peer di cattiva qualità (default: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="25"/>
<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 (default: 86400)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="28"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)</source>
<translation>Buffer di ricezione massimo per connessione, <n>*1000 byte (default: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="29"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)</source>
<translation>Buffer di invio massimo per connessione, <n>*1000 byte (default: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="30"/>
<source>Don't attempt to use UPnP to map the listening port</source>
<translation>Non usare l'UPnP per mappare la porta
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="31"/>
<source>Attempt to use UPnP to map the listening port</source>
<translation>Prova ad usare l'UPnp per mappare la porta
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="32"/>
<source>Fee per kB to add to transactions you send</source>
<translation>Commissione per kB da aggiungere alle transazioni in uscita</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="33"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accetta da linea di comando e da comandi JSON-RPC
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="34"/>
<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 filename="../bitcoinstrings.cpp" line="35"/>
<source>Use the test network</source>
<translation>Utilizza la rete di prova
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="36"/>
<source>Output extra debugging information</source>
<translation>Produci informazioni extra utili al debug</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="37"/>
<source>Prepend debug output with timestamp</source>
<translation>Anteponi all'output di debug una marca temporale</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="38"/>
<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 filename="../bitcoinstrings.cpp" line="39"/>
<source>Send trace/debug info to debugger</source>
<translation>Invia le informazioni di trace/debug al debugger</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="40"/>
<source>Username for JSON-RPC connections</source>
<translation>Nome utente per connessioni JSON-RPC
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="41"/>
<source>Password for JSON-RPC connections</source>
<translation>Password per connessioni JSON-RPC
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="42"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332)</source>
<translation>Attendi le connessioni JSON-RPC su <porta> (default: 8332)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="43"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Consenti connessioni JSON-RPC dall'indirizzo IP specificato
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="44"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Inviare comandi al nodo in esecuzione su <ip> (default: 127.0.0.1)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="45"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Impostare la quantità di chiavi di riserva a <n> (default: 100)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="46"/>
<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 filename="../bitcoinstrings.cpp" line="47"/>
<source>
SSL options: (see the CosbyCoin Wiki for SSL setup instructions)</source>
<translation>
Opzioni SSL: (vedi il wiki di CosbyCoin per le istruzioni di configurazione SSL)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="50"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Utilizzare OpenSSL (https) per le connessioni JSON-RPC
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="51"/>
<source>Server certificate file (default: server.cert)</source>
<translation>File certificato del server (default: server.cert)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="52"/>
<source>Server private key (default: server.pem)</source>
<translation>Chiave privata del server (default: server.pem)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="53"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Cifrari accettabili (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="56"/>
<source>This help message</source>
<translation>Questo messaggio di aiuto
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="57"/>
<source>Cannot obtain a lock on data directory %s. CosbyCoin is probably already running.</source>
<translation>Non è possibile ottenere i dati sulla directory %s. Probabilmente CosbyCoin è già in esecuzione.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="60"/>
<source>Loading addresses...</source>
<translation>Caricamento indirizzi...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="61"/>
<source>Error loading addr.dat</source>
<translation>Errore caricamento addr.dat</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="63"/>
<source>Error loading blkindex.dat</source>
<translation>Errore caricamento blkindex.dat</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="65"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Errore caricamento wallet.dat: Wallet corrotto</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="66"/>
<source>Error loading wallet.dat: Wallet requires newer version of CosbyCoin</source>
<translation>Errore caricamento wallet.dat: il wallet richiede una versione nuova di CosbyCoin</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="67"/>
<source>Wallet needed to be rewritten: restart CosbyCoin to complete</source>
<translation>Il portamonete deve essere riscritto: riavviare CosbyCoin per completare</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="68"/>
<source>Error loading wallet.dat</source>
<translation>Errore caricamento wallet.dat</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="62"/>
<source>Loading block index...</source>
<translation>Caricamento dell'indice del blocco...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="64"/>
<source>Loading wallet...</source>
<translation>Caricamento portamonete...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="69"/>
<source>Rescanning...</source>
<translation>Ripetere la scansione...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="70"/>
<source>Done loading</source>
<translation>Caricamento completato</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="71"/>
<source>Invalid -proxy address</source>
<translation>Indirizzo -proxy non valido</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="72"/>
<source>Invalid amount for -paytxfee=<amount></source>
<translation>Importo non valido per -paytxfee=<amount></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="73"/>
<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 filename="../bitcoinstrings.cpp" line="76"/>
<source>Error: CreateThread(StartNode) failed</source>
<translation>Errore: CreateThread(StartNode) non riuscito</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="77"/>
<source>Warning: Disk space is low </source>
<translation>Attenzione: lo spazio su disco è scarso </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="78"/>
<source>Unable to bind to port %d on this computer. CosbyCoin is probably already running.</source>
<translation>Impossibile collegarsi alla porta %d su questo computer. Probabilmente CosbyCoin è già in esecuzione.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="81"/>
<source>Warning: Please check that your computer's date and time are correct. If your clock is wrong CosbyCoin will not work properly.</source>
<translation>Attenzione: si prega di controllare che la data del computer e l'ora siano corrette. Se il vostro orologio è sbagliato CosbyCoin non funziona correttamente.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="84"/>
<source>beta</source>
<translation>beta</translation>
</message>
</context>
</TS> | mit |
pgte/fugue | test/test_one_worker.js | 897 | //Testing to see if I can get data from 1 worker...
var path = require('path'),
net = require('net'),
assert = require('assert');
var fugue = require(path.join(__dirname, '..', 'lib', 'fugue.js'));
var expected_data = 'here is some data';
server = net.createServer(function(conn) {
conn.end(expected_data);
});
var port = 4001;
exports.setup = function() {
fugue.start(server, port, null, 1, {verbose: false} );
}
exports.run = function(next) {
var client = net.createConnection(port);
var timeout_id = setTimeout(function() {
assert.ok(got_some_data, "Couldn't get data from server");
if(next) next();
}, 3000);
var got_some_data = false;
client.on('data', function(what) {
got_some_data = true;
assert.equal(what.toString(), expected_data);
clearTimeout(timeout_id);
next();
});
}
exports.teardown = function() {
fugue.stop();
} | mit |
Caldis/react-image-slideshow | webpack.config.js | 814 | var path = require('path');
var config = {
entry: path.resolve(__dirname, './src/main.js'),
output: {
path: path.resolve(__dirname, './example'),
filename: 'bundle.js'
},
devServer: {
historyApiFallback: true
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
noParse: [],
loaders: [
{
test: /\.js$|\.jsx$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react', 'stage-1']
}
},
{
test: /\.css$/,
loader: "style!css?modules&localIdentName=[local]-[hash:base64:5]"
}
]
}
};
module.exports = config; | mit |
wfalkwallace/TAFS | src/Element.java | 4954 | import java.util.ArrayList;
/**
*
*/
/**
* @author wgf2104
*
*/
public class Element {
private String name;
private String type;
private String contents;
private Element parent;
private ArrayList<Element> children;
/**
* Drive constructor
* @param name drive name
*/
public Element(String name) {
this.name = name;
this.type = "drive";
parent = null;
contents = "";
children = new ArrayList<Element>();
}
/**
* Folder, Zip, and Text File constructor
* @param name element name
* @param type element type
* @param parent file system hierarchy parent
*/
//folders, zips, and apparently text files? guidelines are a bit
//ambiguous here - are drives supposed to be created with a null-parent/path?
public Element(String name, String type, Element parent) {
this.name = name;
this.type = type.toLowerCase();
this.parent = parent;
contents = "";
if(type.equals("text"))
children = null;
else
children = new ArrayList<Element>();
}
/**
* Populated text file constructor
* @param name text file name
* @param parent hierarchy parent
* @param contents initial text file contents
*/
//text files
public Element(String name, Element parent, String contents) {
type = "text";
this.name = name;
this.parent = parent;
this.contents = contents;
//maybe a little bloated for text files to all have children at all, but so
//much simpler to just check type in addChild instead of both here and there.
children = null;
}
/**
* Get Element path as a string
* @return path from root
*/
public String getPath() {
//calculating dynamically is easier than updating on all changes, maybe a bit bloated.
if(parent != null)
return parent.getPath() + "/" + name;
return name;
}
/**
* Element Name
* @return name string
*/
public String getName() {
return name;
}
/**
* modify element name
* @param name new name
*/
public void setName(String name) {
this.name = name;
}
/**
* element size calculator
* @return element size (sum of size of all children, recursively; content string length for text files; and half calculated size for zip files)
*/
public int getSize() {
int size = contents.length();
if(size == 0)
for(Element e:children)
size += e.getSize();
if(type.equals("zip"))
size /= 2;
return size;
}
/**
* Get's an elements children
* @return set of element's children
* @throws TAFSException if textfile, operation is illegal
*/
public ArrayList<Element> getChildren() throws TAFSException {
if(children != null)
return children;
else
throw new TAFSException("Illegal File System Operation");
}
/**
* Get element container - only valid for non-drive elements
* @return element's container
*/
public Element getParent() {
return parent;
}
/**
* Modify element parent
* @param parent new parent
* @throws TAFSException nonvalid operation for drive entities
*/
public void setParent(Element parent) throws TAFSException {
if(type.equals("drive"))
this.parent = parent;
else
throw new TAFSException("Illegal File System Operation");
}
/**
* Add a child element to a container element
* @param child child to add
* @throws TAFSException preexisting path/duplicate element name; illegal operation
*/
public void addChild(Element child) throws TAFSException {
if(!type.equals("text"))
for(Element e:children) {
if(!e.getName().equals(child.getName()))
children.add(child);
else
throw new TAFSException("Path already exists");
}
else
throw new TAFSException("Illegal File System Operation");
}
/**
* Remove an element from its container
* @param child element to remove
* @throws TAFSException non-existing child
*/
public void removeChild(Element child) throws TAFSException {
if(children.indexOf(child) > -1)
children.remove(child);
else
throw new TAFSException("Path Not Found");
}
/**
*Recursively print subsequent file system hierarchy
* @param depth indentation guideline
*/
public void print(int depth) {
for(int i = 0; i < depth; i++)
System.out.print(" |_");
System.out.println(name);
for(Element e:children) {
e.print(depth + 1);
}
}
/**
* Element Type accessor
* @return Element Type
*/
public String getType() {
return type;
}
/**
* text file content accessor
* @return Text file content string
* @throws TAFSException not a text file
*/
public String getContents() throws TAFSException {
if(type.equals("text"))
return contents;
else
throw new TAFSException("Illegal File System Operation");
}
/**
* Modify text file contents
* @param contents new content string (overwrites old)
* @throws TAFSException not a text file
*/
public void setContents(String contents) throws TAFSException {
if(type.equals("text"))
this.contents = contents;
else
throw new TAFSException("Not a text File");
}
}
| mit |
Orkestro/Orkestro | src/Orkestro/Bundle/CategoryBundle/Entity/CategoryRepository.php | 302 | <?php
namespace Orkestro\Bundle\CategoryBundle\Entity;
use Gedmo\Tree\Entity\Repository\NestedTreeRepository;
/**
* CategoryRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class CategoryRepository extends NestedTreeRepository
{
}
| mit |
lozga/spaceracegame | src/spaceracegame/LaunchWindows.java | 4642 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package spaceracegame;
import java.awt.Stroke;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
*
* @author Terekhov F.V. <fterekhov@gmail.com>
*/
public class LaunchWindows {
public static ArrayList<StoreObject> listLaunchWindows = new ArrayList<StoreObject>();
public static ArrayList<PlanetSinodicPeriod> listPlanetPeriods = new ArrayList<PlanetSinodicPeriod>();
public static void generateLaunchWindows() {
listLaunchWindows.clear();
for (PlanetSinodicPeriod planet : listPlanetPeriods) {
Calendar tempcalendar = GregorianCalendar.getInstance();
tempcalendar.setTime(planet.anchordate);
//rewind to 1956
while (tempcalendar.get(Calendar.YEAR) > 1956) {
tempcalendar.add(Calendar.DATE, -planet.synodicperiod);
}
//then start from 1957 to 1985
while (tempcalendar.get(Calendar.YEAR) < 1986) {
Calendar writecalendar = GregorianCalendar.getInstance();
writecalendar.setTime(tempcalendar.getTime());
writecalendar.set(Calendar.DAY_OF_MONTH, 1);
writecalendar.set(Calendar.HOUR, 1);
writecalendar.set(Calendar.MINUTE, 1);
writecalendar.set(Calendar.SECOND, 1);
//then write 3 windows for current, previous and following months
StoreObject window = new StoreObject();
window.objectcode = planet.code;
window.objectdate = writecalendar.getTime();
listLaunchWindows.add(window);
if (planet.code != 1) {
writecalendar.add(Calendar.MONTH, -1);
window = new StoreObject();
window.objectcode = planet.code;
window.objectdate = writecalendar.getTime();
listLaunchWindows.add(window);
writecalendar.add(Calendar.MONTH, +2);
window = new StoreObject();
window.objectcode = planet.code;
window.objectdate = writecalendar.getTime();
listLaunchWindows.add(window);
}
tempcalendar.add(Calendar.DATE, planet.synodicperiod);
}
}
}
public static String searchWindowsforMonth(Date givendate) {
String returnString = "";
for (StoreObject tempObject : listLaunchWindows) {
if (isEqualByMonthandYear(tempObject.objectdate, givendate)) {
if (returnString.length() > 0) {
returnString = returnString + ", ";
}
returnString = returnString + getPlanetNameByCode(tempObject.objectcode);
}
}
return returnString;
}
private static String getPlanetNameByCode(int code) {
String returnString = "";
for (PlanetSinodicPeriod period : listPlanetPeriods) {
if (period.code == code) {
returnString = period.name;
}
}
return returnString;
}
private static boolean isEqualByMonthandYear(Date date1, Date date2) {
boolean result = false;
Calendar calendar1 = GregorianCalendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = GregorianCalendar.getInstance();
calendar2.setTime(date2);
if ((calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)) & (calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR))) {
result = true;
}
return result;
}
public static boolean isLaunchWindowFor(Date date, String planet) {
boolean result = false;
if (!((planet.equals("Earth")) | (planet.equals("Moon")))) {
for (StoreObject window : listLaunchWindows) {
if (isEqualByMonthandYear(window.objectdate, date)) {
if (findPlanetbyCode(window.objectcode).equals(planet)) {
result = true;
}
}
}
} else {
result = true;
}
return result;
}
private static String findPlanetbyCode(int code) {
String returnString = "";
for (PlanetSinodicPeriod planet : listPlanetPeriods) {
if (planet.code == code) {
returnString = planet.name;
}
}
return returnString;
}
}
| mit |
npetzall/http-double | server/src/test/java/npetzall/httpdouble/doubles/ServiceDoubleRegistryDouble.java | 826 | package npetzall.httpdouble.doubles;
import npetzall.httpdouble.api.ServiceDouble;
import npetzall.httpdouble.server.registry.ServiceDoubleRef;
import npetzall.httpdouble.server.registry.ServiceDoubleRegistry;
import java.util.Collections;
import java.util.Map;
public class ServiceDoubleRegistryDouble implements ServiceDoubleRegistry {
private ServiceDoubleRef serviceDoubleRef;
public ServiceDoubleRegistryDouble(ServiceDouble serviceDouble, String name) {
serviceDoubleRef = new ServiceDoubleRef(name,serviceDouble);
}
@Override
public ServiceDoubleRef getServiceDoubleByURLPath(String urlPath) {
return serviceDoubleRef;
}
@Override
public Map<String, ServiceDoubleRef> getAllServiceDoubles() {
return Collections.singletonMap("*",serviceDoubleRef);
}
}
| mit |
mash1t/tcpchat | TcpChat/src/de/mash1t/chat/client/gui/ClientGuiThread.java | 4534 | /*
* The MIT License
*
* Copyright 2015 Manuel Schmid.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.mash1t.chat.client.gui;
import de.mash1t.networklib.packets.*;
import de.mash1t.chat.client.gui.tabs.TabController;
import de.mash1t.chat.logging.Counters;
import java.io.IOException;
/**
* This class serves as an outsourced thread, as the gui can only handle one thread (itself)
*
* @author Manuel Schmid
*/
public class ClientGuiThread implements Runnable {
// Current gui thread
protected ClientGui gui = null;
protected boolean exitListening = false;
/**
* Constructor
*
* @param gui
*/
public ClientGuiThread(ClientGui gui) {
this.gui = gui;
}
/*
* Create a thread to read messages asynchronous from the server
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
try {
while (!TabController.isInitialized()) {
Thread.sleep(100);
}
} catch (InterruptedException ex) {
// TODO handle Exception
Counters.exception();
}
/*
* Keep on reading from the socket untill "Bye" is received from the
* server
*/
Packet responsePacket;
PacketType ptype;
String message, sender, receiver;
do {
responsePacket = null;
responsePacket = gui.networkObj.read();
ptype = responsePacket.getType();
switch (ptype) {
case Disconnect:
exitListening = true;
break;
case GM:
GroupMessagePacket gm = ((GroupMessagePacket) responsePacket);
message = gm.getMessage();
sender = gm.getSender();
// Always output groupmessage on first tab ("Group Chat")
gui.tabController.outputLineOnGui("<" + sender + "> " + message, 0);
break;
case Kick:
// TODO dialog?
gui.tabController.outputLineOnGui(((KickPacket) responsePacket).getMessage());
exitListening = true;
break;
case PM:
PrivateMessagePacket pm = ((PrivateMessagePacket) responsePacket);
message = pm.getMessage();
sender = pm.getSender();
receiver = pm.getReceiver();
// Get name of other person
String person = (gui.clientName.equals(receiver)) ? sender : receiver;
// TODO fix bug where sender is this client
if (gui.tabController.outputLineOnGui("<" + sender + "> " + message, person)) {
if (gui.clientName.equals(sender)) {
gui.tabController.setFocusAt(receiver);
}
}
break;
case Userlist:
UserListPacket ulPacket = (UserListPacket) responsePacket;
gui.userListController.updateUserList(ulPacket);
break;
case Info:
gui.tabController.outputLineOnGui(((MessagePacket) responsePacket).getMessage());
}
} while (!exitListening);
// Close the connection as it is no longer needed
gui.closeConnection();
}
}
| mit |
ajgassner/fireparty | src/main/java/at/agsolutions/fireparty/FirePartyApplication.java | 1746 | package at.agsolutions.fireparty;
import at.agsolutions.fireparty.ui.RootPane;
import com.google.inject.Guice;
import com.google.inject.Injector;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
public class FirePartyApplication extends Application {
private static final Logger LOGGER = LoggerFactory.getLogger(FirePartyApplication.class);
private static Stage stage;
private static Injector injector;
private static final String APP_TITLE = "FireParty Planner";
private static final String THREAD_NAME = "UI thread";
private static final int APP_WIDTH = 800;
private static final int APP_HEIGHT = 600;
private static final String[] APP_ICONS = new String[]{
"calendar_16.png",
"calendar_24.png",
"calendar_32.png",
"calendar_64.png",
"calendar_128.png"
};
public static void main(String[] args) {
launch(args);
}
@Override
public void start(final Stage primaryStage) throws Exception {
Thread.currentThread().setName(THREAD_NAME);
LOGGER.info("Starting application");
stage = primaryStage;
primaryStage.setTitle(APP_TITLE);
Arrays.stream(APP_ICONS).forEach(iconName -> primaryStage.getIcons().add(new Image(FirePartyApplication.class.getResourceAsStream
(iconName))));
injector = Guice.createInjector(new FirePartyModule());
primaryStage.setScene(new Scene(injector.getInstance(RootPane.class), APP_WIDTH, APP_HEIGHT));
primaryStage.show();
}
public static Stage getStage() {
return stage;
}
public static Injector getInjector() {
return injector;
}
}
| mit |
JNK/node-confim | example/config.js | 1362 | /**
* Created by jnk on 05.03.16.
*/
module.exports = {
modules: {
'web-server-one': {
default: {
port: 3000,
host: '127.0.0.1'
},
development: {
host: '0.0.0.0'
}
},
'web-server-two': {
default: {
port: 4000,
host: '127.0.0.1'
},
development: {
host: '0.0.0.0'
}
},
'database': {
default: {
logLevel: 'info',
username: 'foo',
database: 'bar',
password: '__CONFIM_REQUIRED__'
},
development: {
host: 'localhost',
password: 'weakPassFoLocal'
},
integration: {
host: 'db.integration.example.org'
},
production: {
host: 'db.production.example.org'
}
}
},
shared: {
default: {
logLevel: 'info'
},
development: {
logLevel: 'debug'
},
integration: {
logLevel: 'error'
},
production: {
logLevel: 'warn'
}
},
aliases: {
'primary-server': 'web-server-two'
}
}; | mit |
skazhy/blake | blake/core.py | 14055 | #
# blake.core 0.2.1
# Do cool things with your Markdown docs
# skazhy / sept-dec 2012
#
import copy
import os
import re
import unicodedata
import yaml
from datetime import datetime
from markdown import markdown
EXTENSIONS = [".md", ".markdown"]
class QueryDict(object):
def __init__(self, d=None):
if d is not None:
self._dict = d
else:
self._dict = {}
def __getitem__(self, key):
return self._dict.get(key, None)
def __setitem__(self, key, value):
self._dict[key] = value
def __delitem__(self, key):
if key in self._dict:
self._dict.pop(key)
def __iter__(self):
for key in self._dict:
yield key
def keys(self):
return self._dict.keys()
class AttrList(object):
# TODO: blake0.2.2 should add more functions to both of these
# classes
def __init__(self):
self._list = []
def __getitem__(self, key):
return self._list[key]
def __setitem__(self, key, value):
self._list[key] = value
def __iter__(self):
for item in self._list:
yield item
def __contains__(self, item):
return item in self._list
def __str__(self):
return ",".join(self._list)
def __unicode__(self):
return ",".join(self._list)
def append(self, item):
self._list.append(item)
def islocal(path):
if path[:7] == "http://" or path[:8] == "https://" or path[:2] == "//":
return False
return True
def _validate_path(path, filename=None, extensions=EXTENSIONS):
"""Checks if given path contains a valid Markdown document."""
# If no filename is given, assume that it is given in path
if filename is None:
path, filename = os.path.split(path)
name, extension = os.path.splitext(filename)
extension = extension.lower()
if not os.path.exists(path):
return False
# Ignore hidden files
if not len(name) or name[0] == '.':
return False
# If given file has a proper extension, return the full path
for t in extensions:
if extension == t:
return os.path.join(path, filename)
return False
def _relative_subdirectories(src, path):
""" Gets the relative subdirectory part from 2 given paths."""
return filter(lambda x: len(x) > 0, path.replace(src, "").split("/"))
def slugify(text, delim='-', escape_html=False):
"""Generates an ASCII-only slug."""
if type(text) is list:
text = delim.join(text)
text = text.decode("UTF-8")
text = unicodedata.normalize("NFKD", text) # transform to normalforms
text = text.encode("ascii", "ignore").decode("ascii")
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
if escape_html:
text = re.sub('<[^<]+?>', '', text)
result = []
for word in _punct_re.split(text.lower()):
if word:
result.append(word)
return delim.join(result)
class Blake(object):
@property
def slug(self):
"""Returns slug of the document."""
if self._slug is not None:
return self._slug
if "subdirectory" in self.head and self.head["subdirectory"]:
subdir = self.head["subdirectory"]
dir_slug = "-".join(map(lambda x: slugify(x), subdir))
return "-".join([dir_slug, slugify(self.filename)])
if self.filename is not None:
return self.filename
return None
@slug.setter
def slug(self, value):
self._slug = slugify(value)
@property
def title(self):
if self._title is not None:
return self._title
return self.filename
@title.setter
def title(self, value):
self._title = value
class Document(Blake):
def __init__(self, filename=None, parse=True, static_prefix=""):
self.head = QueryDict({
"full_path": filename,
"subdirectory": []
})
self._slug = None
self._title = None
self._content = ""
self.static_prefix = static_prefix
if parse:
self.create()
def __hash__(self):
# Unique identifier for 2 newly created docs will work?
return self.slug.__hash__()
def __eq__(self, other):
return hash(self) == hash(other)
def _path_split(self, index=0):
if self.head["full_path"] is not None:
path, filename = os.path.split(self.head["full_path"])
filename, extension = os.path.splitext(filename)
return [path, filename, extension][index]
return None
@property
def filename(self):
return self._path_split(1)
@property
def extension(self):
return self._path_split(2)
@property
def images(self):
pattern = '!\[.*\]\((.*)\)'
seen = set()
seen_add = seen.add
return [x for x in [i for i in re.findall(pattern, self._content)]
if x not in seen and not seen_add(x)]
# Override the following methods to define custom
# rendering and content generation process
def render(self, renderable, context):
md = markdown(renderable)
for img in filter(lambda x: islocal(x), self.images):
md = md.replace(img, self.static_prefix + img)
return md
def context(self):
# Default context returns everything except content
return self.to_dict(exclude=["content"])
@property
def content(self):
return self.render(self._content, self.context())
@content.setter
def content(self, c):
self._content = c
def create(self, head=None):
"""Parses the raw document."""
if self.head["full_path"] is not None:
blakefile = open(self.head["full_path"], "r")
cont = ""
yaml_present = False
blakefile.readline() # This line should always contain "---"
line = blakefile.readline()
while line:
if line[0] == "-":
yaml_present = True
break
cont += line
line = blakefile.readline()
if yaml_present:
# The following line is the bottleneck of #create(), should
# investigate how to boost YAML parsing
h = yaml.load(cont)
for key in h:
if key == "title":
self._title = h["title"]
elif key == "tags":
if not isinstance(h["tags"], list):
h["tags"] = h["tags"].split(",")
self.head["tags"] = AttrList()
[self.head["tags"].append(t.strip()) for t in h["tags"]]
else:
self.head[key] = h[key]
line = blakefile.readline()
while line:
self._content += line
line = blakefile.readline()
else:
self._content = cont
blakefile.close()
self._content = self._content.decode("UTF-8")
# Extra params in head argument override those found in yaml (if any)
if head is not None:
for key in head:
self.head[key] = head[key]
if "published" in self.head:
try:
self.head['published'].now()
except AttributeError:
self.head['published'] = datetime.now()
def to_dict(self, include=[], exclude=[]):
""" Return a dict representing attributes. """
d = {}
if exclude is None:
exclude = []
for key in self.head.keys():
if key not in exclude:
d[key] = self.head[key].__str__()
if "slug" not in exclude:
d["slug"] = self.slug
if "filename" not in exclude:
d["filename"] = self.filename
if "title" not in exclude:
d["title"] = self.title
if "content" not in exclude:
d["content"] = self.content
# If include is present - leave only given keys
# This is kinda dangerous -as is-
if include:
for key in d.keys():
if key not in include:
d.pop(key)
if "subdirectory" in d:
d["subdirectory"] = "/".join(self.head["subdirectory"])
return d
def slugify(self, attr):
""" Slugify a head attr."""
if attr in self.head:
return slugify(self.head[attr])
return None
def add_slug(self, *args, **kwargs):
for arg in args:
if arg in self.head:
self.head["%s_slug" % arg] = slugify(self.head[arg])
def dump(self):
yield "---\n"
exc = ["full_path", "subdirectory", "content", "filename", "slug"]
dct = self.to_dict(exclude=exc)
for key in dct:
yield "%s: %s\n" % (key, dct[key])
yield "---\n"
yield self._content.encode("utf-8")
def replace(self, old, new, count=-1):
""" Merely a wrapper for str.replace. """
self._content = self._content.replace(old, new, count)
class DocumentList(Blake):
document = Document
extensions = EXTENSIONS
properties = ("filename", "title", "slug", "bug")
def __init__(self, src=None, static_prefix="", recursive=True):
self._documents = []
self._slug = None
self.static_prefix = static_prefix
self.subdirectory = []
if src:
self.add(src, recursive=recursive)
def __getitem__(self, i):
if isinstance(i, slice):
a = copy.copy(self)
a._documents = self._documents[i]
return a
else:
return self._documents[i]
def __iter__(self):
for doc in self._documents:
yield doc
def __len__(self):
return len(self._documents)
# documentlist += document
def __iadd__(self, doc):
if isinstance(doc, Document):
self._documents.append(doc)
return self
@property
def documents(self):
return self._documents
@documents.setter
def documents(self, docs):
self._documents = docs
def add(self, filename=None, parse=True, static_prefix="", recursive=True):
# TODO: nested documentlists
if not os.path.exists(filename):
return False
if os.path.isdir(filename):
valid_documents(filename, parse=parse,
instance=self,
static_prefix=static_prefix,
recursive=recursive)
else:
self += self.document(filename=filename,
parse=parse,
static_prefix=static_prefix)
return True
def exclude(self, *args, **kwargs):
new_kw = {}
for key in kwargs:
new_kw[key + "__ne"] = kwargs[key]
return self.find(self, *args, **new_kw)
def find(self, *args, **kwargs):
""" Query the documentlist. Return a DL with fewer results."""
if kwargs:
a = copy.copy(self)
while kwargs:
key, value = kwargs.popitem()
key_arr = key.split("__")
# TODO: __has on self.properties attribute that is iterable
# TODO: Improve to add more __ options, see how Django ORM
# implements __ option parsing
if len(key_arr) == 2 and key_arr[1] == "has":
key = key_arr[0]
a.documents = filter(lambda x: x.head[key] and value in x.head[key], a)
else:
if len(key_arr) == 2 and key_arr[1] == "ne":
key = key_arr[0]
comp = value.__ne__
else:
comp = value.__eq__
if key in self.properties:
a.documents = filter(lambda x: comp(getattr(x, key)), a)
else:
a.documents = filter(lambda x: comp(x.head[key]), a)
return a
return self
def get(self, *args, **kwargs):
""" Retrieve a single document. """
doc = self.find(*args, **kwargs).documents
if not len(doc):
return None
return doc[0]
def distinct(self, key, sparse=True):
""" Get distinct values of an attribute. """
values = []
if key in self.properties:
[values.append(getattr(doc, key, None)) for doc in self]
else:
[values.append(doc.head[key]) for doc in self]
s = set(values)
if sparse and None in s:
s.remove(None)
return s
def to_list(self, include=[], exclude=[]):
""" Returns list of to_dict for each of the elements. """
return map(lambda d: d.to_dict(include=include, exclude=exclude), self)
def count(self):
return len(self)
def valid_documents(src, parse=True, instance=None, static_prefix="", recursive=True):
# This allows to populate the DL from customized instances
if instance is not None:
d = instance
else:
d = DocumentList()
if recursive:
for (path, dirs, files) in os.walk(src):
for filename in files:
doc_path = _validate_path(path, filename, d.extensions)
if doc_path:
d.add(filename=doc_path, parse=parse, static_prefix=static_prefix)
d[-1].head["subdirectory"] = _relative_subdirectories(src, path)
else:
for filename in os.listdir(src):
doc_path = _validate_path(src, filename)
if doc_path:
d.add(doc_path, parse, static_prefix=static_prefix)
if instance is not None:
return True
return d
| mit |
WuliHole/hole | src/routers/index.tsx | 1060 | import App from '../containers/app'
import Reading from './reading'
import Verify from './verify'
import Editing from './editing'
import Profile from './profile'
import Post from './post'
import Login from './login'
import Signup from './signup'
import Home from './home'
import Logout from './loggedOut'
import DashBoard from './dashboard'
import isLogin from '../store/isLogin'
import store from '../store/configure-store'
import toJS from '../utils/immutable-to-js'
/* istanbul ignore next */
export const rootRoute = {
childRoutes: [{
path: '/',
component: App,
indexRoute: {
onEnter: (nextState, replace) => {
const jsStore = toJS(store.getState()) as any
if (!isLogin()) {
replace(`/welcome`)
} else {
const user = jsStore.session.user
replace(`/dashboard/recent-post?public=true`)
}
}
},
childRoutes: [
Home,
Login,
Signup,
Logout,
Reading,
Verify,
Editing,
Profile,
Post,
DashBoard
]
}]
}
| mit |
alonecoder1337/Dos-Attack-Detection-using-Machine-Learning | App.py | 1271 | from Classifier import Classififer
import pandas as pd
import numpy as np
from Dataset import Dataset
class App:
def __init__(self):
self.classifier = Classififer().get_classifier();
def train(self):
df = pd.read_csv('data/train.csv', header=None)
data = np.array(df)
self.x_train = data[:, :-1]
self.y_train = data[:, -1:]
self.classifier.fit(self.x_train,self.y_train)
def test(self):
self.ds_obj = Dataset()
ds = self.ds_obj.read_dataset()
new_ds = []
for row in ds:
new_ds.append(row[1:])
self.x_test = np.array(new_ds)
self.results = self.classifier.predict(self.x_test)
def post_test(self):
client_ip_ids = []
total_test,_ = self.x_test.shape
for i in range(total_test):
if self.results[i]==1 :
if self.x_test[i,1] not in client_ip_ids:
client_ip_ids.append(self.x_test[i,1])
dos_ips = self.ds_obj.detransform_client_ip(np.array(client_ip_ids,dtype="int64"))
for ip in dos_ips:
print ip
def run(self):
self.train()
self.test()
self.post_test()
if __name__ == '__main__':
app = App()
app.run()
| mit |
ZingModelChecker/Zing | Microsoft.Zing/ZLooker.cs | 16015 | using System.Collections;
using System.Compiler;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Zing
{
/// <summary>
/// Walks an IR, mutuating it by replacing identifier nodes with the members/locals they resolve to
/// </summary>
internal sealed class Looker : System.Compiler.Looker
{
internal Looker(Scope scope, Microsoft.Zing.ErrorHandler errorHandler, TrivialHashtable scopeFor, TypeSystem typeSystem) // LJW: added typeSystem parameter
: this(scope, errorHandler, scopeFor, typeSystem, null, null, null)
{
}
internal Looker(Scope scope, ErrorHandler errorHandler, TrivialHashtable scopeFor, TypeSystem typeSystem, TrivialHashtable ambiguousTypes, // LJW: added typeSystem parameter
TrivialHashtable referencedLabels, Hashtable exceptionNames)
: base(scope, errorHandler, scopeFor, typeSystem, ambiguousTypes, referencedLabels)
{
this.exceptionNames = exceptionNames;
}
private void HandleError(Node errorNode, Error error, params string[] messageParameters)
{
ErrorNode enode = new ZingErrorNode(error, messageParameters);
enode.SourceContext = errorNode.SourceContext;
this.ErrorHandler.Errors.Add(enode);
}
public override System.Compiler.Declarer GetDeclarer()
{
return new Declarer((Zing.ErrorHandler)this.ErrorHandler);
}
private Hashtable exceptionNames;
private void AddExceptionName(string exceptionName)
{
if (exceptionNames != null)
{
if (!exceptionNames.Contains(exceptionName))
exceptionNames.Add(exceptionName, exceptionName);
}
}
public override Node Visit(Node node)
{
if (node == null) return null;
switch (((ZingNodeType)node.NodeType))
{
case ZingNodeType.Array:
return this.VisitArray((ZArray)node);
case ZingNodeType.Accept:
return this.VisitAccept((AcceptStatement)node);
case ZingNodeType.Assert:
return this.VisitAssert((AssertStatement)node);
case ZingNodeType.Assume:
return this.VisitAssume((AssumeStatement)node);
case ZingNodeType.Async:
return this.VisitAsync((AsyncMethodCall)node);
case ZingNodeType.Atomic:
return this.VisitAtomic((AtomicBlock)node);
case ZingNodeType.AttributedStatement:
return this.VisitAttributedStatement((AttributedStatement)node);
case ZingNodeType.Chan:
return this.VisitChan((Chan)node);
case ZingNodeType.Choose:
return this.VisitChoose((UnaryExpression)node);
case ZingNodeType.Event:
return this.VisitEventStatement((EventStatement)node);
case ZingNodeType.EventPattern:
return this.VisitEventPattern((EventPattern)node);
case ZingNodeType.In:
return this.VisitIn((BinaryExpression)node);
case ZingNodeType.JoinStatement:
return this.VisitJoinStatement((JoinStatement)node);
case ZingNodeType.InvokePlugin:
return this.VisitInvokePlugin((InvokePluginStatement)node);
case ZingNodeType.InvokeSched:
return this.VisitInvokeSched((InvokeSchedulerStatement)node);
case ZingNodeType.Range:
return this.VisitRange((Range)node);
case ZingNodeType.ReceivePattern:
return this.VisitReceivePattern((ReceivePattern)node);
case ZingNodeType.Select:
return this.VisitSelect((Select)node);
case ZingNodeType.Send:
return this.VisitSend((SendStatement)node);
case ZingNodeType.Set:
return this.VisitSet((Set)node);
case ZingNodeType.Self:
return this.VisitSelf((SelfExpression)node);
case ZingNodeType.Trace:
return this.VisitTrace((TraceStatement)node);
case ZingNodeType.TimeoutPattern:
return this.VisitTimeoutPattern((TimeoutPattern)node);
case ZingNodeType.Try:
return this.VisitZTry((ZTry)node);
case ZingNodeType.WaitPattern:
return this.VisitWaitPattern((WaitPattern)node);
case ZingNodeType.With:
return this.VisitWith((With)node);
case ZingNodeType.Yield:
return this.VisitYield((YieldStatement)node);
default:
return base.Visit(node);
}
}
// Override the Looker base to build a list of locals on the current method
public override Statement VisitVariableDeclaration(VariableDeclaration variableDeclaration)
{
if (variableDeclaration == null) return null;
Statement result = base.VisitVariableDeclaration(variableDeclaration);
ZMethod zMethod = this.currentMethod as ZMethod;
Debug.Assert(zMethod != null);
Field f = variableDeclaration.Field;
zMethod.LocalVars.Add(f);
return result;
}
#region Handle ambiguous type/expression scenarios
//
// For "choose" and "sizeof", the operand may be a type reference or a general
// expression. If the operand is a single, unqualified identifier, the parser
// can't distinguish types from expressions and assumes it's looking at a type.
// Here in the looker, we need to gracefully handle the case where the parser
// guessed wrong and we're actually looking at an expression. To do this, we
// override a couple of methods in the base class and reconsider the operand
// as an expression if it doesn't look like a type.
//
private bool ignoreTypeRefErrors;
private bool encounteredTypeRefError;
public override Expression VisitUnaryExpression(UnaryExpression unaryExpression)
{
if ((unaryExpression.NodeType != NodeType.Sizeof && ((ZingNodeType)unaryExpression.NodeType) != ZingNodeType.Choose)
|| !(unaryExpression.Operand is MemberBinding))
return base.VisitUnaryExpression(unaryExpression);
Debug.Assert(unaryExpression.Operand is MemberBinding);
MemberBinding mb = (MemberBinding)unaryExpression.Operand;
Debug.Assert(mb.BoundMember is TypeExpression);
TypeExpression te = (TypeExpression)mb.BoundMember;
if (te.Expression is Identifier)
{
Identifier id = (Identifier)te.Expression;
this.encounteredTypeRefError = false;
this.ignoreTypeRefErrors = true;
unaryExpression.Operand = this.VisitExpression(unaryExpression.Operand);
this.ignoreTypeRefErrors = false;
if (encounteredTypeRefError)
{
// If this didn't resolve to a type, then treat it as an expression and let
// the resolver deal with it (or report an error).
unaryExpression.Operand = this.VisitExpression(id);
NameBinding nb = unaryExpression.Operand as NameBinding;
if (nb != null && nb.BoundMembers.Count == 0)
{
this.HandleTypeExpected(nb.Identifier);
return null;
}
}
}
return unaryExpression;
}
public override void HandleTypeExpected(Node offendingNode)
{
encounteredTypeRefError = true;
if (ignoreTypeRefErrors)
return;
base.HandleTypeExpected(offendingNode);
}
#endregion Handle ambiguous type/expression scenarios
private ZArray VisitArray(ZArray array)
{
array.domainType = this.VisitTypeReference(array.domainType);
EnumNode en = array.domainType as EnumNode;
if (en != null)
{
array.Sizes = new int[] { en.Members.Count - 1 };
}
array.ElementType = this.VisitTypeReference(array.ElementType);
return (ZArray)base.VisitTypeNode((TypeNode)array);
}
private AssertStatement VisitAssert(AssertStatement assert)
{
assert.booleanExpr = this.VisitExpression(assert.booleanExpr);
return assert;
}
private AcceptStatement VisitAccept(AcceptStatement accept)
{
accept.booleanExpr = this.VisitExpression(accept.booleanExpr);
return accept;
}
private AssumeStatement VisitAssume(AssumeStatement assume)
{
assume.booleanExpr = this.VisitExpression(assume.booleanExpr);
return assume;
}
private EventStatement VisitEventStatement(EventStatement Event)
{
Event.channelNumber = this.VisitExpression(Event.channelNumber);
Event.messageType = this.VisitExpression(Event.messageType);
Event.direction = this.VisitExpression(Event.direction);
return Event;
}
private TraceStatement VisitTrace(TraceStatement trace)
{
trace.Operands = this.VisitExpressionList(trace.Operands);
return trace;
}
private InvokePluginStatement VisitInvokePlugin(InvokePluginStatement InvokePlugin)
{
InvokePlugin.Operands = this.VisitExpressionList(InvokePlugin.Operands);
return InvokePlugin;
}
private InvokeSchedulerStatement VisitInvokeSched(InvokeSchedulerStatement InvokeSched)
{
InvokeSched.Operands = this.VisitExpressionList(InvokeSched.Operands);
return InvokeSched;
}
private AsyncMethodCall VisitAsync(AsyncMethodCall async)
{
return (AsyncMethodCall)this.VisitExpressionStatement((ExpressionStatement)async);
}
private AtomicBlock VisitAtomic(AtomicBlock atomic)
{
return (AtomicBlock)this.VisitBlock((Block)atomic);
}
private AttributedStatement VisitAttributedStatement(AttributedStatement attributedStmt)
{
attributedStmt.Attributes = this.VisitAttributeList(attributedStmt.Attributes);
attributedStmt.Statement = (Statement)this.Visit(attributedStmt.Statement);
return attributedStmt;
}
private Chan VisitChan(Chan chan)
{
TypeNode tNode = this.VisitTypeExpression((TypeExpression)chan.ChannelType);
chan.ChannelType = tNode;
return chan;
}
private UnaryExpression VisitChoose(UnaryExpression expr)
{
return (UnaryExpression)this.VisitUnaryExpression(expr);
}
private EventPattern VisitEventPattern(EventPattern ep)
{
ep.channelNumber = this.VisitExpression(ep.channelNumber);
ep.messageType = this.VisitExpression(ep.messageType);
ep.direction = this.VisitExpression(ep.direction);
return ep;
}
private BinaryExpression VisitIn(BinaryExpression expr)
{
return (BinaryExpression)base.VisitBinaryExpression(expr);
}
private JoinStatement VisitJoinStatement(JoinStatement joinstmt)
{
JoinPatternList newJoinPatternList = new JoinPatternList();
for (int i = 0, n = joinstmt.joinPatternList.Length; i < n; i++)
newJoinPatternList.Add((JoinPattern)this.Visit(joinstmt.joinPatternList[i]));
joinstmt.joinPatternList = newJoinPatternList;
joinstmt.statement = (Statement)this.Visit(joinstmt.statement);
joinstmt.attributes = this.VisitAttributeList(joinstmt.attributes);
return joinstmt;
}
private Range VisitRange(Range range)
{
range.Min = this.VisitExpression(range.Min);
range.Max = this.VisitExpression(range.Max);
return (Range)this.VisitConstrainedType((ConstrainedType)range);
}
private ReceivePattern VisitReceivePattern(ReceivePattern rp)
{
rp.channel = this.VisitExpression(rp.channel);
rp.data = this.VisitExpression(rp.data);
return rp;
}
private Select VisitSelect(Select select)
{
JoinStatementList newJoinStatementList = new JoinStatementList();
for (int i = 0, n = select.joinStatementList.Length; i < n; i++)
{
JoinStatement js = this.VisitJoinStatement(select.joinStatementList[i]);
js.visible = select.visible;
newJoinStatementList.Add(js);
}
select.joinStatementList = newJoinStatementList;
return select;
}
private SendStatement VisitSend(SendStatement send)
{
send.channel = this.VisitExpression(send.channel);
send.data = this.VisitExpression(send.data);
return send;
}
private YieldStatement VisitYield(YieldStatement yield)
{
return yield;
}
private SelfExpression VisitSelf(SelfExpression self)
{
return self;
}
private Set VisitSet(Set @set)
{
@set.SetType = this.VisitTypeExpression((TypeExpression)@set.SetType);
return @set;
}
[SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")]
private TimeoutPattern VisitTimeoutPattern(TimeoutPattern tp)
{
return tp;
}
private WaitPattern VisitWaitPattern(WaitPattern wp)
{
wp.expression = this.VisitExpression(wp.expression);
return wp;
}
private ZTry VisitZTry(ZTry Try)
{
Try.Body = this.VisitBlock(Try.Body);
WithList newCatchers = new WithList();
for (int i = 0, n = Try.Catchers.Length; i < n; i++)
newCatchers.Add(this.VisitWith(Try.Catchers[i]));
Try.Catchers = newCatchers;
return Try;
}
private With VisitWith(With with)
{
if (with.Name != null)
AddExceptionName(with.Name.Name);
with.Block = this.VisitBlock(with.Block);
return with;
}
public override Statement VisitThrow(Throw Throw)
{
if (Throw == null) return null;
if (!(Throw.Expression is Identifier))
{
this.HandleError(Throw.Expression, Error.InvalidExceptionExpression);
return null;
}
AddExceptionName(((Identifier)Throw.Expression).Name);
return Throw;
}
public override Field VisitField(Field field)
{
Field result = base.VisitField(field);
return result;
}
public override Expression VisitParameter(Parameter parameter)
{
Parameter result = (Parameter)base.VisitParameter(parameter);
Reference pRefType = result.Type as Reference;
return result;
}
public override Method VisitMethod(Method method)
{
method = base.VisitMethod(method);
return method;
}
}
} | mit |
MrAntix/antix | source/Antix.Services/Validation/Predicates/StringNullOrWhiteSpacePredicate.cs | 312 | using System.Threading.Tasks;
namespace Antix.Services.Validation.Predicates
{
public class StringNullOrWhiteSpacePredicate : ValidationPredicateBase<string>
{
public override async Task<bool> IsAsync(string model)
{
return string.IsNullOrWhiteSpace(model);
}
}
} | mit |
ramisg85/oueslatirami | src/BackOffice/RO/CategorieBundle/Entity/categorie.php | 1928 | <?php
namespace BackOffice\RO\CategorieBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use APY\DataGridBundle\Grid\Mapping as GRID;
/**
* BackOffice\RO\CategorieBundle\Entity\categorie
*
* @ORM\Table(name="categorie")
* @ORM\Entity(repositoryClass="BackOffice\RO\CategorieBundle\Entity\categorieRepository")
*
* @GRID\Source(columns="id, nomCategorie")
* @GRID\Column(id="nom_categorie", title="Nom", size="255", type="text", operatorsVisible=false)
*/
class Categorie {
/**
* @var integer
* @GRID\Column(visible=false)
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nom_categorie", type="string", length=250, nullable=false)
* @GRID\Column(title="Nom catégorie", size="255", type="text", operatorsVisible=false)
*/
private $nomCategorie;
/**
* @var string
*
* @ORM\Column(name="desc_categorie", type="text", nullable=false)
*/
private $descCategorie;
/**
* @var ArrayCollection $vehicules
*
* @ORM\OneToMany(targetEntity="BackOffice\RO\VehiculeBundle\Entity\Vehicule", mappedBy="categorie", cascade={"persist", "remove", "merge"})
*/
protected $vehicules;
function getId() {
return $this->id;
}
function getNomCategorie() {
return $this->nomCategorie;
}
function getDescCategorie() {
return $this->descCategorie;
}
function getVehicules() {
return $this->vehicules;
}
function setId($id) {
$this->id = $id;
}
function setNomCategorie($nomCategorie) {
$this->nomCategorie = $nomCategorie;
}
function setDescCategorie($descCategorie) {
$this->descCategorie = $descCategorie;
}
function setVehicules($vehicules) {
$this->vehicules = $vehicules;
}
}
| mit |
dcunited001/minitest-reporters-ws | lib/minitest/reporters/ws/formatting.rb | 2201 | module Minitest::Reporters::Ws
module Formatting
INFO_PADDING = 8
def get_description(runner, test)
"#{test.suite}: <b>#{test.test}</b>"
end
def print_time(test)
total_time = Time.now - (runner.test_start_time || Time.now)
" (%.2fs)" % total_time
end
def print_info(e)
e.message.each_line { |line| print_with_info_padding(line) }
trace = filter_backtrace(e.backtrace)
trace.each { |line| print_with_info_padding(line) }
end
# TODO: fix printing
def print_pass(suite, test, test_runner)
unless @client.connected?
# do nothing
end
end
def print_skip(suite, test, test_runner)
puts @emoji['S'] + yellow { " SKIP #{suite}" }
puts yellow { " #{print_time(test)} #{test}" }
puts print_info(test_runner.exception) unless @client.connected?
end
def print_fail(suite, test, test_runner)
puts @emoji['F'] + red { " FAIL #{suite}" }
puts red { " #{print_time(test)} #{test}" }
puts print_info(test_runner.exception) unless @client.connected?
end
def print_err(suite, test, test_runner)
puts @emoji['E'] + red { " ERROR #{suite}" }
puts red { " #{print_time(test)} #{test}" }
puts print_info(test_runner.exception) unless @client.connected?
end
def print_after_suite(suite)
puts "#{@test_count} Tests - #{suite}"
%w(P E F S).each do |status|
print("#{@emoji[status]} => " + @emoji[status]*@results[status] + " #{@results[status]}")
puts;
end
puts;
end
def print_after_suites
puts "FINISHED - #{runner.test_count} tests ran"
%w(P E F S).each do |status|
print("#{@emoji[status]} => " + @emoji[status]*@suites_results[status] + " #{@suites_results[status]}")
puts;
end
end
def err_info(e)
err = ""
e.message.each_line { |line| err += "<p>#{line}</p>" }
trace = filter_backtrace(e.backtrace)
trace.each { |line| err += "<p>#{line}</p>" }
err
end
def pad(str, size)
' ' * size + str
end
def print_with_info_padding(line)
puts pad(line, INFO_PADDING)
end
end
end
| mit |
absolute8511/nsq | consistence/nsqd_coordinator_rpc_helper.go | 3754 | package consistence
func (self *NsqdCoordinator) requestJoinCatchup(topic string, partition int) *CoordErr {
coordLog.Infof("try to join catchup for topic: %v-%v", topic, partition)
c, err := self.getLookupRemoteProxy()
if err != nil {
coordLog.Infof("get lookup failed: %v", err)
return err
}
//defer self.putLookupRemoteProxy(c)
err = c.RequestJoinCatchup(topic, partition, self.myNode.GetID())
if err != nil {
coordLog.Infof("request join catchup failed: %v", err)
}
return err
}
func (self *NsqdCoordinator) requestCheckTopicConsistence(topic string, partition int) {
c, err := self.getLookupRemoteProxy()
if err != nil {
coordLog.Infof("get lookup failed: %v", err)
return
}
//defer self.putLookupRemoteProxy(c)
c.RequestCheckTopicConsistence(topic, partition)
}
func (self *NsqdCoordinator) requestNotifyNewTopicInfo(topic string, partition int) {
c, err := self.getLookupRemoteProxy()
if err != nil {
coordLog.Infof("get lookup failed: %v", err)
return
}
//defer self.putLookupRemoteProxy(c)
c.RequestNotifyNewTopicInfo(topic, partition, self.myNode.GetID())
}
func (self *NsqdCoordinator) requestJoinTopicISR(topicInfo *TopicPartitionMetaInfo) *CoordErr {
// request change catchup to isr list and wait for nsqlookupd response to temp disable all new write.
c, err := self.getLookupRemoteProxy()
if err != nil {
return err
}
//defer self.putLookupRemoteProxy(c)
err = c.RequestJoinTopicISR(topicInfo.Name, topicInfo.Partition, self.myNode.GetID())
return err
}
func (self *NsqdCoordinator) notifyReadyForTopicISR(topicInfo *TopicPartitionMetaInfo, leaderSession *TopicLeaderSession, joinSession string) *CoordErr {
// notify myself is ready for isr list for current session and can accept new write.
// leader session should contain the (isr list, current leader session, leader epoch), to identify the
// the different session stage.
c, err := self.getLookupRemoteProxy()
if err != nil {
return err
}
//defer self.putLookupRemoteProxy(c)
return c.ReadyForTopicISR(topicInfo.Name, topicInfo.Partition, self.myNode.GetID(), leaderSession, joinSession)
}
// only move from isr to catchup, if restart, we can catchup directly.
func (self *NsqdCoordinator) requestLeaveFromISR(topic string, partition int) *CoordErr {
c, err := self.getLookupRemoteProxy()
if err != nil {
return err
}
//defer self.putLookupRemoteProxy(c)
return c.RequestLeaveFromISR(topic, partition, self.myNode.GetID())
}
func (self *NsqdCoordinator) requestLeaveFromISRFast(topic string, partition int) *CoordErr {
c, err := self.getLookupRemoteProxy()
if err != nil {
return err
}
if realC, ok := c.(*NsqLookupRpcClient); ok {
return realC.RequestLeaveFromISRFast(topic, partition, self.myNode.GetID())
}
return c.RequestLeaveFromISR(topic, partition, self.myNode.GetID())
}
// this should only be called by leader to remove slow node in isr.
// Be careful to avoid removing most of the isr nodes, should only remove while
// only small part of isr is slow.
// TODO: If most of nodes is slow, the leader should check the leader itself and
// maybe giveup the leadership.
func (self *NsqdCoordinator) requestLeaveFromISRByLeader(topic string, partition int, nid string) *CoordErr {
topicCoord, err := self.getTopicCoordData(topic, partition)
if err != nil {
return err
}
if topicCoord.GetLeaderSessionID() != self.myNode.GetID() || topicCoord.GetLeader() != self.myNode.GetID() {
return ErrNotTopicLeader
}
// send request with leader session, so lookup can check the valid of session.
c, err := self.getLookupRemoteProxy()
if err != nil {
return err
}
//defer self.putLookupRemoteProxy(c)
return c.RequestLeaveFromISRByLeader(topic, partition, nid, &topicCoord.topicLeaderSession)
}
| mit |
jinchen92/JavaBasePractice | src/com/jinwen/thread/multithread/supplement/example2/Run2_threadRunSyn.java | 762 | package com.jinwen.thread.multithread.supplement.example2;
/**
* P291
* 使线程具有有序性
*/
public class Run2_threadRunSyn {
public static void main(String[] args) {
Object lock = new Object();
MyThread a = new MyThread(lock, "A", 1);
MyThread b = new MyThread(lock, "B", 2);
MyThread c = new MyThread(lock, "C", 0);
a.start();
b.start();
c.start();
}
}
/*
输出:
ThreadName=Thread-0 runCount = 1 A
ThreadName=Thread-1 runCount = 2 B
ThreadName=Thread-2 runCount = 3 C
ThreadName=Thread-0 runCount = 4 A
ThreadName=Thread-1 runCount = 5 B
ThreadName=Thread-2 runCount = 6 C
ThreadName=Thread-0 runCount = 7 A
ThreadName=Thread-1 runCount = 8 B
ThreadName=Thread-2 runCount = 9 C
*/ | mit |
Condors/TunisiaMall | vendor/nomaya/social-bundle/Nomaya/SocialBundle/Twig/Extension/NomayaTwigSocialLinks.php | 3607 | <?php
/*
Copyright (c) 2014 Yann Chauvel - Nomaya.net - yann@nomaya.net
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 Nomaya\SocialBundle\Twig\Extension;
class NomayaTwigSocialLinks extends \Twig_Extension{
protected $container;
/**
* Constructor.
*
* @param ContainerInterface $container
*/
public function __construct($container)
{
$this->container = $container;
}
public function getName()
{
return 'nomaya_social_links';
}
public function getFunctions()
{
return array(
'socialLinks' => new \Twig_Function_Method($this, 'getSocialLinks' ,array('is_safe' => array('html'))),
'socialLink' => new \Twig_Function_Method($this, 'getSocialLink' ,array('is_safe' => array('html')))
);
}
public function getSocialLinks($parameters = array())
{
$networks = array('facebook', 'twitter', 'googleplus', 'linkedin', 'tumblr', 'pinterest', 'youtube', 'instagram');
foreach ($networks as $network)
{
// no parameters were defined, keeps default values
if (!array_key_exists($network, $parameters)){
$render_parameters[$network] = array();
// parameters are defined, overrides default values
} else if (is_array($parameters[$network])){
$render_parameters[$network] = $parameters[$network];
// the button is not displayed
} else {
$render_parameters[$network] = false;
}
}
// get the helper service and display the template
return $this->container->get('nomaya.socialLinksHelper')->socialLinks($render_parameters);
}
// https://developers.facebook.com/docs/reference/plugins/like/
public function getSocialLink($network, $parameters = array())
{
// default values, you can override the values by setting them
$otherParameters = $this->container->hasParameter('links.'.$network) ? $this->container->getParameter('links.'.$network) : array();
$parameters = $parameters + $otherParameters;
if (!array_key_exists('network', $parameters)) { $parameters = $parameters + array('network' => $network); }
if (!array_key_exists('theme', $parameters)) { $parameters = $parameters + array('theme' => $this->container->getParameter('social.theme')); }
return !empty($parameters) && array_key_exists('url', $parameters) ? $this->container->get('nomaya.socialLinksHelper')->socialLink($parameters): false;
}
} | mit |
nyc-nighthawks-2016/Linken-Jarale-StackOverflow | app/controllers/answers.rb | 414 | post '/answers' do
# binding.pry
@post = Post.find(params[:post_id])
@answer = @post.answers.new(body:params[:body], user_id:current_user.id)
if @answer.save
if request.xhr?
erb :'/partials/_answer',layout: false, locals: {answer: @answer, post: @post}
else
redirect "/posts/#{params[:post_id]}"
end
else
@errors = answer.errors.full_messages
erb :'posts/show'
end
end
| mit |
Neofonie/gonzo | http/principal.go | 286 | package gonzo
import "net/http"
type Principal struct {
next ContextHandler
}
func (p Principal) ServeHTTP(w http.ResponseWriter, r *http.Request, c *Context) {
if pr := r.Header.Get("X-Principal"); pr != "" {
p.next(w, r, c)
} else {
w.WriteHeader(http.StatusForbidden)
}
}
| mit |
binghuo365/SiteGroupCms | src/SiteGroupCms.Utils/Cookie.cs | 17420 | /*
* 程序中文名称: 站群内容管理系统
*
* 程序英文名称: SiteGroupCms
*
* 程序版本: 5.2.X
*
* 程序作者: 高伟 ( 合作请联系:254860396#qq.com)
*
*
*
*
*
*/
using System;
using System.Web;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
namespace SiteGroupCms.Utils
{
/// <summary>
/// Cookie操作类
/// </summary>
public static class Cookie
{
/// <summary>
/// 创建COOKIE对象并赋Value值,修改COOKIE的Value值也用此方法,因为对COOKIE修改必须重新设Expires
/// </summary>
/// <param name="strCookieName">COOKIE对象名</param>
/// <param name="strValue">COOKIE对象Value值</param>
public static void SetObj(string strCookieName, string strValue)
{
SetObj(strCookieName, 1, strValue, "", "/");
}
/// <summary>
/// 创建COOKIE对象并赋Value值,修改COOKIE的Value值也用此方法,因为对COOKIE修改必须重新设Expires
/// </summary>
/// <param name="strCookieName">COOKIE对象名</param>
/// <param name="iExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365),</param>
/// <param name="strValue">COOKIE对象Value值</param>
public static void SetObj(string strCookieName, int iExpires, string strValue)
{
SetObj(strCookieName, iExpires, strValue, "", "/");
}
/// <summary>
/// 创建COOKIE对象并赋Value值,修改COOKIE的Value值也用此方法,因为对COOKIE修改必须重新设Expires
/// </summary>
/// <param name="strCookieName">COOKIE对象名</param>
/// <param name="iExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365),</param>
/// <param name="strValue">COOKIE对象Value值</param>
/// <param name="strDomains">作用域,多个域名用;隔开</param>
public static void SetObj(string strCookieName, int iExpires, string strValue, string strDomains)
{
SetObj(strCookieName, iExpires, strValue, strDomains, "/");
}
/// <summary>
/// 创建COOKIE对象并赋Value值,修改COOKIE的Value值也用此方法,因为对COOKIE修改必须重新设Expires
/// </summary>
/// <param name="strCookieName">COOKIE对象名</param>
/// <param name="iExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365),</param>
/// <param name="strValue">COOKIE对象Value值</param>
/// <param name="strDomains">作用域,多个域名用;隔开</param>
/// <param name="strPath">作用路径</param>
public static void SetObj(string strCookieName, int iExpires, string strValue, string strDomains, string strPath)
{
string _strDomain = SelectDomain(strDomains);
HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
objCookie.Value = HttpUtility.UrlEncode(strValue.Trim());
if (_strDomain.Length > 0)
objCookie.Domain = _strDomain;
if (iExpires > 0)
{
if (iExpires == 1)
objCookie.Expires = DateTime.MaxValue;
else
objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
}
HttpContext.Current.Response.Cookies.Add(objCookie);
}
/// <summary>
/// 创建COOKIE对象并赋多个KEY键值
/// 设键/值如下:
/// NameValueCollection myCol = new NameValueCollection();
/// myCol.Add("red", "rojo");
/// myCol.Add("green", "verde");
/// myCol.Add("blue", "azul");
/// myCol.Add("red", "rouge"); 结果“red:rojo,rouge;green:verde;blue:azul”
/// </summary>
/// <param name="strCookieName">COOKIE对象名</param>
/// <param name="iExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365),</param>
/// <param name="KeyValue">键/值对集合</param>
public static void SetObj(string strCookieName, int iExpires, NameValueCollection KeyValue)
{
SetObj(strCookieName, iExpires, KeyValue, "", "/");
}
public static void SetObj(string strCookieName, int iExpires, NameValueCollection KeyValue, string strDomains)
{
SetObj(strCookieName, iExpires, KeyValue, strDomains, "/");
}
/// <summary>
/// 创建COOKIE对象并赋多个KEY键值
/// 设键/值如下:
/// NameValueCollection myCol = new NameValueCollection();
/// myCol.Add("red", "rojo");
/// myCol.Add("green", "verde");
/// myCol.Add("blue", "azul");
/// myCol.Add("red", "rouge"); 结果“red:rojo,rouge;green:verde;blue:azul”
/// </summary>
/// <param name="strCookieName">COOKIE对象名</param>
/// <param name="iExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365),</param>
/// <param name="KeyValue">键/值对集合</param>
/// <param name="strDomains">作用域,多个域名用;隔开</param>
/// <param name="strPath">作用路径</param>
public static void SetObj(string strCookieName, int iExpires, NameValueCollection KeyValue, string strDomains, string strPath)
{
string _strDomain = SelectDomain(strDomains);
HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
foreach (String key in KeyValue.AllKeys)
{
objCookie[key] = HttpUtility.UrlEncode(KeyValue[key].Trim());
}
if (_strDomain.Length > 0)
objCookie.Domain = _strDomain;
objCookie.Path = strPath.Trim();
if (iExpires > 0)
{
if (iExpires == 1)
objCookie.Expires = DateTime.MaxValue;
else
objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
}
HttpContext.Current.Response.Cookies.Add(objCookie);
}
/// <summary>
/// 读取Cookie某个对象的Value值,返回Value值,如果对象本就不存在,则返回字符串null
/// </summary>
/// <param name="strCookieName">Cookie对象名称</param>
/// <returns>Value值,如果对象本就不存在,则返回字符串null</returns>
public static string GetValue(string strCookieName)
{
if (HttpContext.Current.Request.Cookies[strCookieName] == null)
{
return null;
}
else
{
string _value = HttpContext.Current.Request.Cookies[strCookieName].Value;
return HttpUtility.UrlDecode(_value);
}
}
/// <summary>
/// 读取Cookie某个对象的某个Key键的键值,返回Key键值,如果对象本就不存在,则返回字符串null,如果Key键不存在,则返回字符串"KeyNonexistence"
/// </summary>
/// <param name="strCookieName">Cookie对象名称</param>
/// <param name="strKeyName">Key键名</param>
/// <returns>Key键值,如果对象本就不存在,则返回字符串null,如果Key键不存在,则返回字符串"KeyNonexistence"</returns>
public static string GetValue(string strCookieName, string strKeyName)
{
if (HttpContext.Current.Request.Cookies[strCookieName] == null)
{
return null;
}
else
{
string strObjValue = HttpContext.Current.Request.Cookies[strCookieName].Value;
string strKeyName2 = strKeyName + "=";
//if (strObjValue.IndexOf(strKeyName2) == -1)
if (!strObjValue.Contains(strKeyName2))
return null;
else
{
string _value = HttpContext.Current.Request.Cookies[strCookieName][strKeyName];
return HttpUtility.UrlDecode(_value);
}
}
}
/// <summary>
/// 修改某个COOKIE对象某个Key键的键值 或 给某个COOKIE对象添加Key键 都调用本方法,操作成功返回字符串"success",如果对象本就不存在,则返回字符串null。
/// </summary>
/// <param name="strCookieName">Cookie对象名称</param>
/// <param name="strKeyName">Key键名</param>
/// <param name="KeyValue">Key键值</param>
/// <param name="iExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365)。注意:虽是修改功能,实则重建覆盖,所以时间也要重设,因为没办法获得旧的有效期</param>
/// <returns>如果对象本就不存在,则返回字符串null,如果操作成功返回字符串"success"。</returns>
public static string Edit(string strCookieName, string strKeyName, string KeyValue, int iExpires)
{
return Edit(strCookieName, strKeyName, KeyValue, iExpires, "", "/");
}
/// <summary>
/// 修改某个COOKIE对象某个Key键的键值 或 给某个COOKIE对象添加Key键 都调用本方法,操作成功返回字符串"success",如果对象本就不存在,则返回字符串null。
/// </summary>
/// <param name="strCookieName">Cookie对象名称</param>
/// <param name="strKeyName">Key键名</param>
/// <param name="KeyValue">Key键值</param>
/// <param name="iExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365)。注意:虽是修改功能,实则重建覆盖,所以时间也要重设,因为没办法获得旧的有效期</param>
/// <param name="strPath">作用路径</param>
/// <returns>如果对象本就不存在,则返回字符串null,如果操作成功返回字符串"success"。</returns>
public static string Edit(string strCookieName, string strKeyName, string KeyValue, int iExpires, string strPath)
{
return Edit(strCookieName, strKeyName, KeyValue, iExpires, "", strPath);
}
/// <summary>
/// 修改某个COOKIE对象某个Key键的键值 或 给某个COOKIE对象添加Key键 都调用本方法,操作成功返回字符串"success",如果对象本就不存在,则返回字符串null。
/// </summary>
/// <param name="strCookieName">Cookie对象名称</param>
/// <param name="strKeyName">Key键名</param>
/// <param name="KeyValue">Key键值</param>
/// <param name="iExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365)。注意:虽是修改功能,实则重建覆盖,所以时间也要重设,因为没办法获得旧的有效期</param>
/// <param name="strDomains">作用域,多个域名用;隔开</param>
/// <param name="strPath">作用路径</param>
/// <returns>如果对象本就不存在,则返回字符串null,如果操作成功返回字符串"success"。</returns>
public static string Edit(string strCookieName, string strKeyName, string KeyValue, int iExpires, string strDomains, string strPath)
{
if (HttpContext.Current.Request.Cookies[strCookieName] == null)
return null;
else
{
HttpCookie objCookie = HttpContext.Current.Request.Cookies[strCookieName];
objCookie[strKeyName] = HttpUtility.UrlEncode(KeyValue.Trim());
if (iExpires > 0)
{
if (iExpires == 1)
objCookie.Expires = DateTime.MaxValue;
else
objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
}
HttpContext.Current.Response.Cookies.Add(objCookie);
return "success";
}
}
/// <summary>
/// 删除COOKIE对象
/// </summary>
/// <param name="strCookieName">Cookie对象名称</param>
public static void Del(string strCookieName)
{
Del(strCookieName, "", "/");
}
/// <summary>
/// 删除COOKIE对象
/// </summary>
/// <param name="strCookieName">Cookie对象名称</param>
/// <param name="strDomains">作用域,多个域名用;隔开</param>
public static void Del(string strCookieName, string strDomains)
{
Del(strCookieName, strDomains, "/");
}
/// <summary>
/// 删除COOKIE对象
/// </summary>
/// <param name="strCookieName">Cookie对象名称</param>
/// <param name="strDomains">作用域,多个域名用;隔开</param>
/// <param name="strPath">作用路径</param>
public static void Del(string strCookieName, string strDomains, string strPath)
{
string _strDomain = SelectDomain(strDomains);
HttpCookie objCookie = new HttpCookie(strCookieName.Trim());
if (_strDomain.Length > 0)
objCookie.Domain = _strDomain;
objCookie.Path = strPath.Trim();
objCookie.Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.Response.Cookies.Add(objCookie);
}
/// <summary>
/// 删除某个COOKIE对象某个Key子键,操作成功返回字符串"success",如果对象本就不存在,则返回字符串null
/// </summary>
/// <param name="strCookieName">Cookie对象名称</param>
/// <param name="strKeyName">Key键名</param>
/// <param name="iExpires">COOKIE对象有效时间(秒数),1表示永久有效,0和负数都表示不设有效时间,大于等于2表示具体有效秒数,31536000秒=1年=(60*60*24*365)。注意:虽是修改功能,实则重建覆盖,所以时间也要重设,因为没办法获得旧的有效期</param>
/// <returns>如果对象本就不存在,则返回字符串null,如果操作成功返回字符串"success"。</returns>
public static string DelKey(string strCookieName, string strKeyName, int iExpires)
{
if (HttpContext.Current.Request.Cookies[strCookieName] == null)
{
return null;
}
else
{
HttpCookie objCookie = HttpContext.Current.Request.Cookies[strCookieName];
objCookie.Values.Remove(strKeyName);
if (iExpires > 0)
{
if (iExpires == 1)
objCookie.Expires = DateTime.MaxValue;
else
objCookie.Expires = DateTime.Now.AddSeconds(iExpires);
}
HttpContext.Current.Response.Cookies.Add(objCookie);
return "success";
}
}
/// <summary>
/// 定位到正确的域
/// </summary>
/// <param name="strDomains"></param>
/// <returns></returns>
private static string SelectDomain(string strDomains)
{
bool _isLocalServer = false;
if (strDomains.Trim().Length == 0)
return "";
string _thisDomain = HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString();
//if (_thisDomain.IndexOf(".") < 0)//说明是计算机名,而不是域名
if (!_thisDomain.Contains("."))
_isLocalServer = true;
string _strDomain = "www.abc.com";//这个域名是瞎扯
string[] _strDomains = strDomains.Split(';');
for (int i = 0; i < _strDomains.Length; i++)
{
//if (_thisDomain.IndexOf(_strDomains[i].Trim()) < 0)//判断当前域名是否在作用域内
if (!_thisDomain.Contains(_strDomains[i].Trim()))
continue;
else
{
//区分真实域名(或IP)与计算机名
if (_isLocalServer)
_strDomain = "";//作用域留空,否则Cookie不能写入
else
_strDomain = _strDomains[i].Trim();
break;
}
}
return _strDomain;
}
}
}
| mit |
evertharmeling/brouwkuyp-control | src/Brouwkuyp/Bundle/LogicBundle/Traits/ExecutableTrait.php | 709 | <?php
namespace Brouwkuyp\Bundle\LogicBundle\Traits;
use Brouwkuyp\Bundle\LogicBundle\Model\ExecutableInterface;
/**
* ExecutableTrait
*/
trait ExecutableTrait
{
/**
* Flag indicating that this object is started.
*
* @var bool
*/
protected $started;
/**
* Flag indicating that this object is performed and finished.
*
* @var bool
*/
protected $finished;
/**
*
* @see ExecutableInterface::isStarted()
*/
public function isStarted()
{
return $this->started;
}
/**
*
* @see ExecutableInterface::isFinished()
*/
public function isFinished()
{
return $this->finished;
}
}
| mit |
zporky/langs-and-paradigms | projects/EJULOK/Java/prognyelvek/src/main/java/bence/prognyelvek/contexts/SimpleContext.java | 881 | package bence.prognyelvek.contexts;
import java.util.ArrayList;
import java.util.List;
public class SimpleContext<T, O> implements Context<T, O> {
private final List<T> tokens = new ArrayList<T>();
private final List<O> output = new ArrayList<O>();
private int pointer = 0;
public SimpleContext(final List<T> tokens) {
this.tokens.addAll(tokens);
}
@Override
public T popToken() {
final T result = peakToken();
pointer++;
return result;
}
@Override
public T peakToken() {
return tokens.get(pointer);
}
@Override
public boolean hasNextToken() {
return tokens.size() > pointer;
}
@Override
public void writeOutput(final O token) {
output.add(token);
}
@Override
public List<O> getOutput() {
return new ArrayList<O>(output);
}
}
| mit |
dvajs/dva | packages/dva-loading/test/index.test.js | 7362 | import expect from 'expect';
import dva from 'dva';
import createLoading from '../src/index';
const delay = timeout => new Promise(resolve => setTimeout(resolve, timeout));
describe('dva-loading', () => {
it('normal', done => {
const app = dva();
app.use(createLoading());
app.model({
namespace: 'count',
state: 0,
reducers: {
add(state) {
return state + 1;
},
},
effects: {
*addRemote(action, { put }) {
yield delay(100);
yield put({ type: 'add' });
},
},
});
app.router(() => 1);
app.start();
expect(app._store.getState().loading).toEqual({
global: false,
models: {},
effects: {},
});
app._store.dispatch({ type: 'count/addRemote' });
expect(app._store.getState().loading).toEqual({
global: true,
models: { count: true },
effects: { 'count/addRemote': true },
});
setTimeout(() => {
expect(app._store.getState().loading).toEqual({
global: false,
models: { count: false },
effects: { 'count/addRemote': false },
});
done();
}, 200);
});
it('opts.effects', done => {
const app = dva();
app.use(
createLoading({
effects: true,
}),
);
app.model({
namespace: 'count',
state: 0,
reducers: {
add(state) {
return state + 1;
},
},
effects: {
*addRemote(action, { put }) {
yield delay(100);
yield put({ type: 'add' });
},
},
});
app.router(() => 1);
app.start();
expect(app._store.getState().loading).toEqual({
global: false,
models: {},
effects: {},
});
app._store.dispatch({ type: 'count/addRemote' });
expect(app._store.getState().loading).toEqual({
global: true,
models: { count: true },
effects: { 'count/addRemote': true },
});
setTimeout(() => {
expect(app._store.getState().loading).toEqual({
global: false,
models: { count: false },
effects: { 'count/addRemote': false },
});
done();
}, 200);
});
it('opts.namespace', () => {
const app = dva();
app.use(
createLoading({
namespace: 'fooLoading',
}),
);
app.model({
namespace: 'count',
state: 0,
});
app.router(() => 1);
app.start();
expect(app._store.getState().fooLoading).toEqual({
global: false,
models: {},
effects: {},
});
});
it('opts.only', () => {
const app = dva();
app.use(
createLoading({
only: ['count/a'],
}),
);
app.model({
namespace: 'count',
state: 0,
effects: {
*a(action, { call }) {
yield call(delay, 500);
},
*b(action, { call }) {
yield call(delay, 500);
},
},
});
app.router(() => 1);
app.start();
expect(app._store.getState().loading).toEqual({
global: false,
models: {},
effects: {},
});
app._store.dispatch({ type: 'count/a' });
setTimeout(() => {
expect(app._store.getState().loading).toEqual({
global: true,
models: { count: true },
effects: { 'count/a': true },
});
app._store.dispatch({ type: 'count/b' });
setTimeout(() => {
expect(app._store.getState().loading).toEqual({
global: false,
models: { count: false },
effects: { 'count/a': false },
});
}, 300);
}, 300);
});
it('opts.except', () => {
const app = dva();
app.use(
createLoading({
except: ['count/a'],
}),
);
app.model({
namespace: 'count',
state: 0,
effects: {
*a(action, { call }) {
yield call(delay, 500);
},
*b(action, { call }) {
yield call(delay, 500);
},
},
});
app.router(() => 1);
app.start();
expect(app._store.getState().loading).toEqual({
global: false,
models: {},
effects: {},
});
app._store.dispatch({ type: 'count/a' });
setTimeout(() => {
expect(app._store.getState().loading).toEqual({
global: false,
models: {},
effects: {},
});
app._store.dispatch({ type: 'count/b' });
setTimeout(() => {
expect(app._store.getState().loading).toEqual({
global: true,
models: { count: true },
effects: { 'count/b': true },
});
}, 300);
}, 300);
});
it('opts.only and opts.except ambiguous', () => {
expect(() => {
const app = dva();
app.use(
createLoading({
only: ['count/a'],
except: ['count/b'],
}),
);
}).toThrow('ambiguous');
});
it('takeLatest', done => {
const app = dva();
app.use(createLoading());
app.model({
namespace: 'count',
state: 0,
reducers: {
add(state) {
return state + 1;
},
},
effects: {
addRemote: [
function*(action, { put }) {
yield delay(100);
yield put({ type: 'add' });
},
{ type: 'takeLatest' },
],
},
});
app.router(() => 1);
app.start();
expect(app._store.getState().loading).toEqual({
global: false,
models: {},
effects: {},
});
app._store.dispatch({ type: 'count/addRemote' });
app._store.dispatch({ type: 'count/addRemote' });
expect(app._store.getState().loading).toEqual({
global: true,
models: { count: true },
effects: { 'count/addRemote': true },
});
setTimeout(() => {
expect(app._store.getState().loading).toEqual({
global: false,
models: { count: false },
effects: { 'count/addRemote': false },
});
done();
}, 200);
});
it('multiple effects', done => {
const app = dva();
app.use(createLoading());
app.model({
namespace: 'count',
state: 0,
effects: {
*a(action, { call }) {
yield call(delay, 100);
},
*b(action, { call }) {
yield call(delay, 500);
},
},
});
app.router(() => 1);
app.start();
app._store.dispatch({ type: 'count/a' });
app._store.dispatch({ type: 'count/b' });
setTimeout(() => {
expect(app._store.getState().loading.models.count).toEqual(true);
}, 200);
setTimeout(() => {
expect(app._store.getState().loading.models.count).toEqual(false);
done();
}, 800);
});
it('error catch', done => {
const app = dva({
onError(err) {
err.preventDefault();
console.log('failed', err.message);
},
});
app.use(createLoading());
app.model({
namespace: 'count',
state: 0,
effects: {
*throwError(action, { call }) {
yield call(delay, 100);
throw new Error('haha');
},
},
});
app.router(() => 1);
app.start();
app._store.dispatch({ type: 'count/throwError' });
expect(app._store.getState().loading.global).toEqual(true);
setTimeout(() => {
expect(app._store.getState().loading.global).toEqual(false);
done();
}, 200);
});
});
| mit |
beardgame/utilities | Bearded.Utilities/SpaceTime/2d/Velocity2.cs | 7320 | using System;
using System.Globalization;
using Bearded.Utilities.Geometry;
using OpenTK.Mathematics;
namespace Bearded.Utilities.SpaceTime;
/// <summary>
/// A type-safe representation of a 2d directed velocity vector.
/// </summary>
public readonly struct Velocity2 : IEquatable<Velocity2>, IFormattable
{
private readonly Vector2 value;
#region construction
public Velocity2(Vector2 value)
{
this.value = value;
}
public Velocity2(float x, float y)
: this(new Vector2(x, y))
{
}
public Velocity2(Speed x, Speed y)
: this(new Vector2(x.NumericValue, y.NumericValue))
{
}
/// <summary>
/// Creates a new instance of the Velocity2 type with a given direction and magnitude.
/// </summary>
public static Velocity2 In(Direction2 direction, Speed s) => direction * s;
#endregion
#region properties
/// <summary>
/// Returns the numeric vector value of the velocity vector.
/// </summary>
public Vector2 NumericValue => value;
/// <summary>
/// Returns the X component of the velocity vector.
/// </summary>
public Speed X => new Speed(value.X);
/// <summary>
/// Returns the Y component of the velocity vector.
/// </summary>
public Speed Y => new Speed(value.Y);
/// <summary>
/// Returns the direction of the velocity vector.
/// </summary>
public Direction2 Direction => Direction2.Of(value);
/// <summary>
/// Returns the typed magnitude of the velocity vector.
/// </summary>
public Speed Length => new Speed(value.Length);
/// <summary>
/// Returns the typed square of the magnitude of the velocity vector.
/// </summary>
public Squared<Speed> LengthSquared => new Squared<Speed>(value.LengthSquared);
/// <summary>
/// Returns a Velocity2 type with value 0.
/// </summary>
public static Velocity2 Zero => new Velocity2(0, 0);
#endregion
#region methods
#region lerp
/// <summary>
/// Linearly interpolates between two typed velocity vectors.
/// </summary>
/// <param name="v0">The velocity vector at t = 0.</param>
/// <param name="v1">The velocity vector at t = 1.</param>
/// <param name="t">The interpolation scalar.</param>
public static Velocity2 Lerp(Velocity2 v0, Velocity2 v1, float t) => v0 + (v1 - v0) * t;
/// <summary>
/// Linearly interpolates towards another typed velocity vector.
/// </summary>
/// <param name="v">The velocity vector at t = 1.</param>
/// <param name="t">The interpolation scalar.</param>
public Velocity2 LerpTo(Velocity2 v, float t) => Lerp(this, v, t);
#endregion
#region projection
/// <summary>
/// Projects the velocity vector onto an untyped vector, returning the speed component in that vector's direction.
/// </summary>
public Speed ProjectedOn(Vector2 vector) => projectedOn(vector.NormalizedSafe());
/// <summary>
/// Projects the velocity vector onto a difference vector, returning the speed component in that vector's direction.
/// </summary>
public Speed ProjectedOn(Difference2 vector) => projectedOn(vector.NumericValue.NormalizedSafe());
/// <summary>
/// Projects the velocity vector onto a direction, returning the speed component in that direction.
/// </summary>
public Speed ProjectedOn(Direction2 direction) => projectedOn(direction.Vector);
private Speed projectedOn(Vector2 normalisedVector) => new Speed(Vector2.Dot(value, normalisedVector));
#endregion
#region equality and hashcode
public bool Equals(Velocity2 other) => value == other.value;
public override bool Equals(object? obj) => obj is Velocity2 velocity2 && Equals(velocity2);
public override int GetHashCode() => value.GetHashCode();
#endregion
#region tostring
public override string ToString() => ToString(null, CultureInfo.CurrentCulture);
public string ToString(string? format, IFormatProvider? formatProvider)
=> $"({value.X.ToString(format, formatProvider)}, {value.Y.ToString(format, formatProvider)}) u/t";
public string ToString(string? format)
=> ToString(format, CultureInfo.CurrentCulture);
#endregion
#endregion
#region operators
#region algebra
/// <summary>
/// Adds two velocity vectors.
/// </summary>
public static Velocity2 operator +(Velocity2 v0, Velocity2 v1) => new Velocity2(v0.value + v1.value);
/// <summary>
/// Subtracts a velocity vector from another.
/// </summary>
public static Velocity2 operator -(Velocity2 v0, Velocity2 v1) => new Velocity2(v0.value - v1.value);
#endregion
#region scaling
/// <summary>
/// Inverts the velocity vector.
/// </summary>
public static Velocity2 operator -(Velocity2 v) => new Velocity2(-v.value);
/// <summary>
/// Multiplies the velocity vector with a scalar.
/// </summary>
public static Velocity2 operator *(Velocity2 v, float scalar) => new Velocity2(v.value * scalar);
/// <summary>
/// Multiplies the velocity vector with a scalar.
/// </summary>
public static Velocity2 operator *(float scalar, Velocity2 v) => new Velocity2(v.value * scalar);
/// <summary>
/// Divides the velocity vector by a divisor.
/// </summary>
public static Velocity2 operator /(Velocity2 v, float divisor) => new Velocity2(v.value / divisor);
#endregion
#region ratio
/// <summary>
/// Divides a velocity vector by a speed, returning an untyped vector.
/// </summary>
public static Vector2 operator /(Velocity2 v, Speed divisor) => v.value / divisor.NumericValue;
#endregion
#region differentiate
/// <summary>
/// Divides a velocity vector by a timespan, returning an acceleration vector.
/// </summary>
public static Acceleration2 operator /(Velocity2 v, TimeSpan t) => new Acceleration2(v.value / (float)t.NumericValue);
public static Acceleration2 operator *(Velocity2 v, Frequency f) => new Acceleration2(v.value * (float)f.NumericValue);
public static Acceleration2 operator *(Frequency f, Velocity2 v) => new Acceleration2(v.value * (float)f.NumericValue);
#endregion
#region integrate
/// <summary>
/// Multiplies a velocity vector by a timespan, returning a difference vector.
/// </summary>
public static Difference2 operator *(Velocity2 v, TimeSpan t) => new Difference2(v.value * (float)t.NumericValue);
/// <summary>
/// Multiplies a velocity vector by a timespan, returning a difference vector.
/// </summary>
public static Difference2 operator *(TimeSpan t, Velocity2 v) => new Difference2(v.value * (float)t.NumericValue);
public static Difference2 operator /(Velocity2 v, Frequency f) => new Difference2(v.value / (float)f.NumericValue);
#endregion
#region comparision
/// <summary>
/// Compares two velocity vectors for equality.
/// </summary>
public static bool operator ==(Velocity2 v0, Velocity2 v1) => v0.Equals(v1);
/// <summary>
/// Compares two velocity vectors for inequality.
/// </summary>
public static bool operator !=(Velocity2 v0, Velocity2 v1) => !(v0 == v1);
#endregion
#endregion
}
| mit |
GestionSystemesTelecom/gst-library | src/GST.Library.Helper/Type/IsTypeHelper.cs | 4683 | using System;
using System.Globalization;
using System.Reflection;
namespace GST.Library.Helper.Type
{
/// <summary>
/// IsTypeHelper
/// </summary>
public static class IsTypeHelper
{
private static string[] dateFormats = {
"yyyy-MM",
"yyyy-MM-dd",
"dd/MM/yyyy"
};
/// <summary>
/// Check if a value is a numeric one
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static bool IsNumeric(this System.Object obj)
{
if (obj is PropertyInfo)
{
return IsNumericType(((PropertyInfo)obj).PropertyType);
}
if (IsNumericType(obj.GetType()))
{
return true;
}
try
{
Convert.ToInt64(obj);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Determines if a type is numeric. Nullable numeric types are considered numeric.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsNumericType(this System.Type type)
{
if (type == null)
{
return false;
}
switch (System.Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
case TypeCode.Object:
return false;
}
return false;
}
/// <summary>
/// Check if the object is a string
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static bool IsString(this System.Object obj)
{
if (obj is PropertyInfo)
{
return IsStringType(((PropertyInfo)obj).PropertyType);
}
return IsStringType(obj.GetType());
}
/// <summary>
/// Determines if a type is string.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsStringType(this System.Type type)
{
if (type == null)
{
return false;
}
switch (System.Type.GetTypeCode(type))
{
case TypeCode.Char:
case TypeCode.String:
return true;
case TypeCode.Object:
return false;
}
return false;
}
/// <summary>
/// Check if the object is a date or a date time
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static bool IsDate(this System.Object obj)
{
if (obj is PropertyInfo)
{
return IsDateType(((PropertyInfo)obj).PropertyType);
}
if (IsDateType(obj.GetType()))
{
return true;
}
DateTime dateValue;
if (DateTime.TryParseExact(obj.ToString(), dateFormats,
new CultureInfo("fr-FR"),
DateTimeStyles.None,
out dateValue))
{
return true;
}
return false;
}
/// <summary>
/// Determines if a type is date.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsDateType(this System.Type type)
{
if (type == null)
{
return false;
}
switch (System.Type.GetTypeCode(type))
{
case TypeCode.DateTime:
return true;
case TypeCode.Object:
return false;
}
return false;
}
}
}
| mit |
tommy351/warehouse | test/scripts/model.js | 32755 | 'use strict';
const should = require('chai').use(require('chai-as-promised')).should();
const sortBy = require('lodash/sortBy');
const Promise = require('bluebird');
const sinon = require('sinon');
const cuid = require('cuid');
describe('Model', () => {
const Database = require('../..');
const Schema = Database.Schema;
const SchemaType = Database.SchemaType;
const db = new Database();
const userSchema = new Schema({
name: {
first: String,
last: String
},
email: String,
age: Number,
posts: [{type: Schema.Types.CUID, ref: 'Post'}]
});
userSchema.virtual('name.full').get(function() {
return `${this.name.first} ${this.name.last}`;
});
const postSchema = new Schema({
title: String,
content: String,
user_id: {type: Schema.Types.CUID, ref: 'User'},
created: Date
});
const User = db.model('User', userSchema);
const Post = db.model('Post', postSchema);
it('new()', () => {
const user = User.new({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
});
user._id.should.exist;
user.name.first.should.eql('John');
user.name.last.should.eql('Doe');
user.name.full.should.eql('John Doe');
user.email.should.eql('abc@example.com');
user.age.should.eql(20);
user.posts.should.eql([]);
});
it('findById()', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => {
User.findById(data._id).should.eql(data);
return data;
}).then(data => User.removeById(data._id)));
it('findById() - lean', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => {
User.findById(data._id, {lean: true}).name.should.not.ownProperty('full');
return data;
}).then(data => User.removeById(data._id)));
it('insert()', () => {
const listener = sinon.spy(data => {
User.findById(data._id).should.exist;
});
User.once('insert', listener);
return User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => {
User.findById(data._id).should.exist;
User.should.to.have.length(1);
listener.calledOnce.should.be.true;
return data;
}).then(data => User.removeById(data._id));
});
it('insert() - no id', () => {
const doc = User.new();
delete doc._id;
return User.insert(doc).should.eventually.be.rejected;
});
it('insert() - already existed', () => {
let user;
return User.insert({}).then(data => {
user = data;
return User.insert(data);
}).finally(() => User.removeById(user._id)).should.eventually.be.rejected;
});
it('insert() - hook', () => {
const db = new Database();
const testSchema = new Schema();
let Test;
const preHook = sinon.spy(data => {
should.not.exist(Test.findById(data._id));
data.foo.should.eql('bar');
});
const postHook = sinon.spy(data => {
Test.findById(data._id).should.exist;
data.foo.should.eql('bar');
});
testSchema.pre('save', preHook);
testSchema.post('save', postHook);
Test = db.model('Test', testSchema);
return Test.insert({foo: 'bar'}).then(() => {
preHook.calledOnce.should.be.true;
postHook.calledOnce.should.be.true;
});
});
it('insert() - array', () => User.insert([
{
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
},
{
name: {first: 'Andy', last: 'Baker'},
email: 'andy@example.com',
age: 30
}
]).then(data => {
data.length = 2;
return data;
}).map(item => User.removeById(item._id)));
it('insert() - sync problem', () => {
const db = new Database();
const testSchema = new Schema();
let Test;
testSchema.pre('save', data => {
const item = Test.findOne({id: data.id});
if (item) throw new Error(`ID "${data.id}" has been used.`);
});
Test = db.model('Test', testSchema);
return Promise.all([
Test.insert({id: 1}),
Test.insert({id: 1})
]).should.eventually.be.rejected;
});
it('save() - insert', () => User.save({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => {
User.findById(data._id).should.exist;
return data;
}).then(data => User.removeById(data._id)));
it('save() - replace', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => {
data.age = 30;
return User.save(data);
}).then(data => {
data.age.should.eql(30);
return data;
}).then(data => User.removeById(data._id)));
it('save() - sync problem', () => {
const id = cuid();
return Promise.all([
User.save({_id: id, age: 1}),
User.save({_id: id, age: 2})
]).then(() => {
const user = User.findById(id);
user.age.should.eql(2);
User.should.to.have.length(1);
return User.removeById(id);
});
});
it('updateById()', () => {
const listener = sinon.spy(data => {
User.findById(data._id).age.should.eql(30);
});
User.once('update', listener);
return User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.updateById(data._id, {age: 30})).then(data => {
data.age.should.eql(30);
listener.calledOnce.should.be.true;
return data;
}).then(data => User.removeById(data._id));
});
it('updateById() - object', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.updateById(data._id, {name: {first: 'Jerry'}})).then(data => {
data.name.first.should.eql('Jerry');
data.name.last.should.eql('Doe');
return data;
}).then(data => User.removeById(data._id)));
it('updateById() - dot notation', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.updateById(data._id, {'name.last': 'Smith'})).then(data => {
data.name.first.should.eql('John');
data.name.last.should.eql('Smith');
return data;
}).then(data => User.removeById(data._id)));
it('updateById() - operator', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.updateById(data._id, {age: {$inc: 5}})).then(data => {
data.age.should.eql(25);
return data;
}).then(data => User.removeById(data._id)));
it('updateById() - operator in first class', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.updateById(data._id, {$inc: {age: 5}})).then(data => {
data.age.should.eql(25);
return data;
}).then(data => User.removeById(data._id)));
it('updateById() - $set', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.updateById(data._id, {$set: {age: 25}})).then(data => {
data.age.should.eql(25);
return data;
}).then(data => User.removeById(data._id)));
it('updateById() - $unset', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.updateById(data._id, {$unset: {email: true}})).then(data => {
should.not.exist(data.email);
return data;
}).then(data => User.removeById(data._id)));
it('updateById() - $unset false', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.updateById(data._id, {$unset: {email: false}})).then(data => {
data.email.should.eql('abc@example.com');
return data;
}).then(data => User.removeById(data._id)));
it('updateById() - $rename', () => User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.updateById(data._id, {$rename: {email: 'address'}})).then(data => {
data.address.should.eql('abc@example.com');
should.not.exist(data.email);
return data;
}).then(data => User.removeById(data._id)));
it('updateById() - id not exist', () => User.updateById('foo', {}).should.eventually.be.rejected);
it('updateById() - hook', () => {
const db = new Database();
const testSchema = new Schema();
const Test = db.model('Test', testSchema);
const preHook = sinon.spy(data => {
should.not.exist(Test.findById(data._id).baz);
});
const postHook = sinon.spy(data => {
Test.findById(data._id).baz.should.eql(1);
});
return Test.insert({
foo: 'bar'
}).then(data => {
testSchema.pre('save', preHook);
testSchema.post('save', postHook);
return Test.updateById(data._id, {baz: 1});
}).then(() => {
preHook.calledOnce.should.be.true;
postHook.calledOnce.should.be.true;
});
});
it('update()', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 20},
{age: 40}
]).then(data => User.update({age: 20}, {email: 'A'}).then(updated => {
updated[0]._id.should.eql(data[1]._id);
updated[1]._id.should.eql(data[3]._id);
updated[0].email.should.eql('A');
updated[1].email.should.eql('A');
return data;
})).map(item => User.removeById(item._id)));
it('replaceById()', () => {
function validate(data) {
data.name.first.should.eql('Mary');
data.name.last.should.eql('White');
data.age.should.eql(40);
data.should.not.ownProperty('email');
}
const listener = sinon.spy(data => {
validate(User.findById(data._id));
});
User.once('update', listener);
return User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.replaceById(data._id, {
name: {first: 'Mary', last: 'White'},
age: 40
})).then(data => {
validate(data);
listener.calledOnce.should.be.true;
return data;
}).then(data => User.removeById(data._id));
});
it('replaceById() - id not exist', () => User.replaceById('foo', {}).should.eventually.be.rejected);
it('replaceById() - pre-hook', () => {
const db = new Database();
const testSchema = new Schema();
const Test = db.model('Test', testSchema);
const preHook = sinon.spy(data => {
Test.findById(data._id).foo.should.eql('bar');
});
const postHook = sinon.spy(data => {
Test.findById(data._id).foo.should.eql('baz');
});
return Test.insert({
foo: 'bar'
}).then(data => {
testSchema.pre('save', preHook);
testSchema.post('save', postHook);
return Test.replaceById(data._id, {foo: 'baz'});
}).then(() => {
preHook.calledOnce.should.be.true;
postHook.calledOnce.should.be.true;
});
});
it('replace()', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 20},
{age: 40}
]).then(data => User.replace({age: 20}, {email: 'A'}).then(updated => {
updated[0]._id.should.eql(data[1]._id);
updated[1]._id.should.eql(data[3]._id);
updated[0].email.should.eql('A');
updated[1].email.should.eql('A');
return data;
})).map(item => User.removeById(item._id)));
it('removeById()', () => {
const listener = sinon.spy(data => {
should.not.exist(User.findById(data._id));
});
User.once('remove', listener);
return User.insert({
name: {first: 'John', last: 'Doe'},
email: 'abc@example.com',
age: 20
}).then(data => User.removeById(data._id)).then(data => {
listener.calledOnce.should.be.true;
should.not.exist(User.findById(data._id));
});
});
it('removeById() - id not exist', () => User.removeById('foo', {}).should.eventually.be.rejected);
it('removeById() - hook', () => {
const db = new Database();
const testSchema = new Schema();
const Test = db.model('Test', testSchema);
const preHook = sinon.spy(data => {
Test.findById(data._id).should.exist;
});
const postHook = sinon.spy(data => {
should.not.exist(Test.findById(data._id));
});
testSchema.pre('remove', preHook);
testSchema.post('remove', postHook);
return Test.insert({
foo: 'bar'
}).then(data => Test.removeById(data._id)).then(() => {
preHook.calledOnce.should.be.true;
postHook.calledOnce.should.be.true;
});
});
it('remove()', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 20},
{age: 40}
]).then(data => User.remove({age: 20}).then(removed => {
should.not.exist(User.findById(data[1]._id));
should.not.exist(User.findById(data[3]._id));
return [data[0], data[2], data[4]];
})).map(item => User.removeById(item._id)));
it('destroy()', () => {
const Test = db.model('Test');
Test.destroy();
should.not.exist(db._models.Test);
});
it('count()', () => {
Post.should.to.have.length(Post.count());
});
it('forEach()', () => {
let count = 0;
return Post.insert(Array(10).fill({})).then(data => {
Post.forEach((item, i) => {
item.should.eql(data[i]);
i.should.eql(count++);
});
count.should.eql(data.length);
return data;
}).map(item => Post.removeById(item._id));
});
it('toArray()', () => Post.insert(Array(10).fill({})).then(data => {
Post.toArray().should.eql(data);
return data;
}).map(item => Post.removeById(item._id)));
it('find()', () => User.insert([
{age: 10},
{age: 20},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
const query = User.find({age: 20});
query.data.should.eql(data.slice(1, 3));
return data;
}).map(item => User.removeById(item._id)));
it('find() - blank', () => User.insert([
{age: 10},
{age: 20},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
const query = User.find({});
query.data.should.eql(data);
return data;
}).map(item => User.removeById(item._id)));
it('find() - operator', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
const query = User.find({age: {$gt: 20}});
query.data.should.eql(data.slice(2));
return data;
}).map(item => User.removeById(item._id)));
it('find() - limit', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
const query = User.find({age: {$gte: 20}}, {limit: 2});
query.data.should.eql(data.slice(1, 3));
return data;
}).map(item => User.removeById(item._id)));
it('find() - skip', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
let query = User.find({age: {$gte: 20}}, {skip: 1});
query.data.should.eql(data.slice(2));
// with limit
query = User.find({age: {$gte: 20}}, {limit: 1, skip: 1});
query.data.should.eql(data.slice(2, 3));
return data;
}).map(item => User.removeById(item._id)));
it('find() - lean', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
const query = User.find({age: {$gt: 20}}, {lean: true});
query.should.be.a('array');
return data;
}).map(item => User.removeById(item._id)));
it('find() - $and', () => User.insert([
{name: {first: 'John', last: 'Doe'}, age: 20},
{name: {first: 'Jane', last: 'Doe'}, age: 25},
{name: {first: 'Jack', last: 'White'}, age: 30}
]).then(data => {
const query = User.find({
$and: [
{'name.last': 'Doe'},
{age: {$gt: 20}}
]
});
query.toArray().should.eql([data[1]]);
return data;
}).map(item => User.removeById(item._id)));
it('find() - $or', () => User.insert([
{name: {first: 'John', last: 'Doe'}, age: 20},
{name: {first: 'Jane', last: 'Doe'}, age: 25},
{name: {first: 'Jack', last: 'White'}, age: 30}
]).then(data => {
const query = User.find({
$or: [
{'name.last': 'White'},
{age: {$gt: 20}}
]
});
query.toArray().should.eql(data.slice(1));
return data;
}).map(item => User.removeById(item._id)));
it('find() - $nor', () => User.insert([
{name: {first: 'John', last: 'Doe'}, age: 20},
{name: {first: 'Jane', last: 'Doe'}, age: 25},
{name: {first: 'Jack', last: 'White'}, age: 30}
]).then(data => {
const query = User.find({
$nor: [
{'name.last': 'White'},
{age: {$gt: 20}}
]
});
query.toArray().should.eql([data[0]]);
return data;
}).map(item => User.removeById(item._id)));
it('find() - $not', () => User.insert([
{name: {first: 'John', last: 'Doe'}, age: 20},
{name: {first: 'Jane', last: 'Doe'}, age: 25},
{name: {first: 'Jack', last: 'White'}, age: 30}
]).then(data => {
const query = User.find({
$not: {'name.last': 'Doe'}
});
query.toArray().should.eql(data.slice(2));
return data;
}).map(item => User.removeById(item._id)));
it('find() - $where', () => User.insert([
{name: {first: 'John', last: 'Doe'}, age: 20},
{name: {first: 'Jane', last: 'Doe'}, age: 25},
{name: {first: 'Jack', last: 'White'}, age: 30}
]).then(data => {
const query = User.find({
$where: function() {
return this.name.last === 'Doe';
}
});
query.toArray().should.eql(data.slice(0, 2));
return data;
}).map(item => User.removeById(item._id)));
it('findOne()', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
User.findOne({age: {$gt: 20}}).should.eql(data[2]);
return data;
}).map(item => User.removeById(item._id)));
it('findOne() - lean', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
User.findOne({age: {$gt: 20}}, {lean: true})._id.should.eql(data[2]._id);
return data;
}).map(item => User.removeById(item._id)));
it('sort()', () => User.insert([
{age: 15},
{age: 35},
{age: 10}
]).then(data => {
const query = User.sort('age');
query.data[0].should.eql(data[2]);
query.data[1].should.eql(data[0]);
query.data[2].should.eql(data[1]);
return data;
}).map(item => User.removeById(item._id)));
it('sort() - descending', () => User.insert([
{age: 15},
{age: 35},
{age: 10}
]).then(data => {
const query = User.sort('age', -1);
query.data[0].should.eql(data[1]);
query.data[1].should.eql(data[0]);
query.data[2].should.eql(data[2]);
return data;
}).map(item => User.removeById(item._id)));
it('sort() - multi', () => User.insert([
{age: 15, email: 'A'},
{age: 30, email: 'B'},
{age: 20, email: 'C'},
{age: 20, email: 'D'}
]).then(data => {
const query = User.sort('age email');
query.data[0].should.eql(data[0]);
query.data[1].should.eql(data[2]);
query.data[2].should.eql(data[3]);
query.data[3].should.eql(data[1]);
return data;
}).map(item => User.removeById(item._id)));
it('eq()', () => Post.insert(Array(5).fill({})).then(data => {
for (let i = 0, len = data.length; i < len; i++) {
Post.eq(i).should.eql(data[i]);
}
return data;
}).map(item => Post.removeById(item._id)));
it('eq() - negative index', () => Post.insert(Array(5).fill({})).then(data => {
for (let i = 1, len = data.length; i <= len; i++) {
Post.eq(-i).should.eql(data[len - i]);
}
return data;
}).map(item => Post.removeById(item._id)));
it('first()', () => Post.insert(Array(5).fill({})).then(data => {
Post.first().should.eql(data[0]);
return data;
}).map(item => Post.removeById(item._id)));
it('last()', () => Post.insert(Array(5).fill({})).then(data => {
Post.last().should.eql(data[data.length - 1]);
return data;
}).map(item => Post.removeById(item._id)));
it('slice() - no arguments', () => Post.insert(Array(5).fill({})).then(data => {
Post.slice().data.should.eql(data);
return data;
}).map(item => Post.removeById(item._id)));
it('slice() - one argument', () => Post.insert(Array(5).fill({})).then(data => {
Post.slice(2).data.should.eql(data.slice(2));
return data;
}).map(item => Post.removeById(item._id)));
it('slice() - one negative argument', () => Post.insert(Array(5).fill({})).then(data => {
Post.slice(-2).data.should.eql(data.slice(-2));
return data;
}).map(item => Post.removeById(item._id)));
it('slice() - two arguments', () => Post.insert(Array(5).fill({})).then(data => {
Post.slice(2, 4).data.should.eql(data.slice(2, 4));
return data;
}).map(item => Post.removeById(item._id)));
it('slice() - start + negative end index', () => Post.insert(Array(5).fill({})).then(data => {
Post.slice(1, -1).data.should.eql(data.slice(1, -1));
return data;
}).map(item => Post.removeById(item._id)));
it('slice() - two negative arguments', () => Post.insert(Array(5).fill({})).then(data => {
Post.slice(-3, -1).data.should.eql(data.slice(-3, -1));
return data;
}).map(item => Post.removeById(item._id)));
it('slice() - start > end', () => Post.insert(Array(5).fill({})).then(data => {
Post.slice(-1, -3).data.should.eql(data.slice(-1, -3));
return data;
}).map(item => Post.removeById(item._id)));
it('slice() - index overflow', () => Post.insert(Array(5).fill({})).then(data => {
Post.slice(1, 100).data.should.eql(data.slice(1, 100));
return data;
}).map(item => Post.removeById(item._id)));
it('slice() - index overflow 2', () => Post.insert(Array(5).fill({})).then(data => {
Post.slice(100, 200).data.should.eql(data.slice(100, 200));
return data;
}).map(item => Post.removeById(item._id)));
it('limit()', () => Post.insert(Array(5).fill({})).then(data => {
Post.limit(2).data.should.eql(data.slice(0, 2));
return data;
}).map(item => Post.removeById(item._id)));
it('skip()', () => Post.insert(Array(5).fill({})).then(data => {
Post.skip(2).data.should.eql(data.slice(2));
return data;
}).map(item => Post.removeById(item._id)));
it('reverse()', () => Post.insert(Array(5).fill({})).then(data => {
const query = Post.reverse();
for (let i = 0, len = data.length; i < len; i++) {
query.data[i].should.eql(data[len - i - 1]);
}
return data;
}).map(item => Post.removeById(item._id)));
it('shuffle()', () => Post.insert(Array(5).fill({})).then(data => {
const query = Post.shuffle();
sortBy(query.data, '_id').should.eql(sortBy(data, '_id'));
return data;
}).map(item => Post.removeById(item._id)));
it('map()', () => Post.insert(Array(5).fill({})).then(data => {
let num = 0;
const d1 = Post.map((item, i) => {
i.should.eql(num++);
return item._id;
});
const d2 = data.map(item => item._id);
d1.should.eql(d2);
return data;
}).map(item => Post.removeById(item._id)));
it('reduce()', () => Post.insert([
{email: 'A'},
{email: 'B'},
{email: 'C'}
]).then(data => {
let num = 1;
const sum = Post.reduce((sum, item, i) => {
i.should.eql(num++);
return {email: sum.email + item.email};
});
sum.email.should.eql('ABC');
return data;
}).map(item => Post.removeById(item._id)));
it('reduce() - with initial', () => Post.insert([
{email: 'A'},
{email: 'B'},
{email: 'C'}
]).then(data => {
let num = 0;
const sum = Post.reduce((sum, item, i) => {
i.should.eql(num++);
return sum + item.email;
}, '_');
sum.should.eql('_ABC');
return data;
}).map(item => Post.removeById(item._id)));
it('reduceRight()', () => Post.insert([
{email: 'A'},
{email: 'B'},
{email: 'C'}
]).then(data => {
let num = 1;
const sum = Post.reduceRight((sum, item, i) => {
i.should.eql(num--);
return {email: sum.email + item.email};
});
sum.email.should.eql('CBA');
return data;
}).map(item => Post.removeById(item._id)));
it('reduceRight() - with initial', () => Post.insert([
{email: 'A'},
{email: 'B'},
{email: 'C'}
]).then(data => {
let num = 2;
const sum = Post.reduceRight((sum, item, i) => {
i.should.eql(num--);
return sum + item.email;
}, '_');
sum.should.eql('_CBA');
return data;
}).map(item => Post.removeById(item._id)));
it('filter()', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
let num = 0;
const query = User.filter((data, i) => {
i.should.eql(num++);
return data.age > 20;
});
query.data.should.eql(data.slice(2));
return data;
}).map(item => User.removeById(item._id)));
it('every()', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
let num = 0;
User.every((data, i) => {
i.should.eql(num++);
return data.age;
}).should.be.true;
User.every((data, i) => data.age > 10).should.be.false;
return data;
}).map(item => User.removeById(item._id)));
it('some()', () => User.insert([
{age: 10},
{age: 20},
{age: 30},
{age: 40}
]).then(data => {
let num = 0;
User.some((data, i) => data.age > 10).should.be.true;
User.some((data, i) => {
i.should.eql(num++);
return data.age < 0;
}).should.be.false;
return data;
}).map(item => User.removeById(item._id)));
it('populate() - object', () => {
let user, post;
return User.insert({}).then(user_ => {
user = user_;
return Post.insert({
user_id: user_._id
});
}).then(post_ => {
post = post_;
return Post.populate('user_id');
}).then(result => {
result.first().user_id.should.eql(user);
return Promise.all([
User.removeById(user._id),
Post.removeById(post._id)
]);
});
});
it('populate() - array', () => {
let posts, user;
return Post.insert([
{title: 'ABCD'},
{title: 'ACD'},
{title: 'CDE'},
{title: 'XYZ'}
]).then(posts_ => {
posts = posts_;
return User.insert({
posts: posts.map(post => post._id)
});
}).then(user_ => {
user = user_;
return User.populate('posts');
}).then(result => {
const query = result.first().posts;
query.should.be.an.instanceOf(Post.Query);
query.toArray().should.eql(posts);
return Promise.all([
User.removeById(user._id),
Post.removeById(posts[0]._id),
Post.removeById(posts[1]._id),
Post.removeById(posts[2]._id),
Post.removeById(posts[3]._id)
]);
});
});
it('populate() - match', () => {
let posts, user;
return Post.insert([
{title: 'ABCD'},
{title: 'ACD'},
{title: 'CDE'},
{title: 'XYZ'}
]).then(posts_ => {
posts = posts_;
return User.insert({
posts: posts.map(post => post._id)
});
}).then(user_ => {
user = user_;
return User.populate({
path: 'posts',
match: {title: /^A/}
});
}).then(result => {
result.first().posts.toArray().should.eql(posts.slice(0, 2));
return Promise.all([
User.removeById(user._id),
Post.removeById(posts[0]._id),
Post.removeById(posts[1]._id),
Post.removeById(posts[2]._id),
Post.removeById(posts[3]._id)
]);
});
});
it('populate() - sort', () => {
let posts, user;
return Post.insert([
{title: 'XYZ'},
{title: 'ABCD'},
{title: 'CDE'},
{title: 'ACD'}
]).then(posts_ => {
posts = posts_;
return User.insert({
posts: posts.map(post => post._id)
});
}).then(user_ => {
user = user_;
return User.populate({
path: 'posts',
sort: 'title'
});
}).then(result => {
result.first().posts.toArray().should.eql([
posts[1],
posts[3],
posts[2],
posts[0]
]);
return Promise.all([
User.removeById(user._id),
Post.removeById(posts[0]._id),
Post.removeById(posts[1]._id),
Post.removeById(posts[2]._id),
Post.removeById(posts[3]._id)
]);
});
});
it('populate() - limit', () => {
let posts, user;
return Post.insert([
{title: 'XYZ'},
{title: 'ABCD'},
{title: 'CDE'},
{title: 'ACD'}
]).then(posts_ => {
posts = posts_;
return User.insert({
posts: posts.map(post => post._id)
});
}).then(user_ => {
user = user_;
return User.populate({
path: 'posts',
limit: 2
});
}).then(result => {
result.first().posts.toArray().should.eql(posts.slice(0, 2));
// with match
return User.populate({
path: 'posts',
match: {title: /D/},
limit: 2
});
}).then(result => {
result.first().posts.toArray().should.eql(posts.slice(1, 3));
return Promise.all([
User.removeById(user._id),
Post.removeById(posts[0]._id),
Post.removeById(posts[1]._id),
Post.removeById(posts[2]._id),
Post.removeById(posts[3]._id)
]);
});
});
it('populate() - skip', () => {
let posts, user;
return Post.insert([
{title: 'XYZ'},
{title: 'ABCD'},
{title: 'CDE'},
{title: 'ACD'}
]).then(posts_ => {
posts = posts_;
return User.insert({
posts: posts.map(post => post._id)
});
}).then(user_ => {
user = user_;
return User.populate({
path: 'posts',
skip: 2
});
}).then(result => {
result.first().posts.toArray().should.eql(posts.slice(2));
// with match
return User.populate({
path: 'posts',
match: {title: /D/},
skip: 2
});
}).then(result => {
result.first().posts.toArray().should.eql(posts.slice(3));
// with limit
return User.populate({
path: 'posts',
limit: 2,
skip: 1
});
}).then(result => {
result.first().posts.toArray().should.eql(posts.slice(1, 3));
// with match & limit
return User.populate({
path: 'posts',
match: {title: /D/},
limit: 2,
skip: 1
});
}).then(result => {
result.first().posts.toArray().should.eql(posts.slice(2));
return Promise.all([
User.removeById(user._id),
Post.removeById(posts[0]._id),
Post.removeById(posts[1]._id),
Post.removeById(posts[2]._id),
Post.removeById(posts[3]._id)
]);
});
});
it('static method', () => {
const schema = new Schema();
schema.static('add', function(value) {
return this.insert(value);
});
const Test = db.model('Test', schema);
Test.add({name: 'foo'}).then(data => {
data.name.should.eql('foo');
});
Test.destroy();
});
it('instance method', () => {
const schema = new Schema();
schema.method('getName', function() {
return this.name;
});
const Test = db.model('Test', schema);
Test.insert({name: 'foo'}).then(data => {
data.getName().should.eql('foo');
});
Test.destroy();
});
it('_import()', () => {
const schema = new Schema({
_id: {type: String, required: true},
bool: Boolean
});
const Test = db.model('Test', schema);
Test._import([
{_id: 'A', bool: 1},
{_id: 'B', bool: 0}
]);
Test.should.to.have.length(2);
Test.toArray().should.eql([
Test.new({_id: 'A', bool: true}),
Test.new({_id: 'B', bool: false})
]);
Test.destroy();
});
it('_export()', () => {
const schema = new Schema({
_id: {type: String, required: true},
bool: Boolean
});
const Test = db.model('Test', schema);
return Test.insert([
{_id: 'A', bool: true},
{_id: 'B', bool: false}
]).then(data => {
Test._export().should.eql(JSON.stringify([
{_id: 'A', bool: 1},
{_id: 'B', bool: 0}
]));
return Test.destroy();
});
});
it('_export() - should not save undefined value', () => {
class CacheType extends SchemaType {
value() {}
}
const schema = new Schema({
cache: CacheType
});
const Test = db.model('Test', schema);
return Test.insert({
cache: 'test'
}).then(data => {
data.cache.should.exist;
should.not.exist(JSON.parse(Test._export())[0].cache);
return Test.destroy();
});
});
});
| mit |
vassildinev/CSharp-Part-2 | 03.MethodsHomework/08.NumberAsArray/Properties/AssemblyInfo.cs | 1408 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("08.NumberAsArray")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("08.NumberAsArray")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("972c3623-f12c-4dd7-8e73-625472f9f8a8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
ComputerArchitectureGroupPWr/JGenerilo | src/main/java/edu/byu/ece/rapidSmith/bitstreamTools/bitstream/DummySyncData.java | 4846 | /*
* Copyright (c) 2010-2011 Brigham Young University
*
* This file is part of the BYU RapidSmith Tools.
*
* BYU RapidSmith Tools is free software: you may redistribute it
* and/or modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 2 of
* the License, or (at your option) any later version.
*
* BYU RapidSmith Tools is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* A copy of the GNU General Public License is included with the BYU
* RapidSmith Tools. It can be found at doc/gpl2.txt. You may also
* get a copy of the license at <http://www.gnu.org/licenses/>.
*
*/
package edu.byu.ece.rapidSmith.bitstreamTools.bitstream;
import java.util.ArrayList;
import java.util.List;
/**
* Represents the dummy sync data found in Xilinx bitstreams. This object contains
* a List<Byte> member that holds all of the sync data. This class contains two
* prebuilt static DummySyncData objects for V5 and V6.
* <p/>
* TODO: Create separate classes for V4 sync data vs. v5/v6 sync data
*/
public class DummySyncData extends ConfigurationData {
/**
* A static DummySyncData object for V4.
*/
public static final DummySyncData V4_STANDARD_DUMMY_SYNC_DATA = new DummySyncData(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xAA, (byte) 0x99, (byte) 0x55, (byte) 0x66});
/**
* A static DummySyncData object for V5 and V6.
*/
public static final DummySyncData V5_V6_STANDARD_DUMMY_SYNC_DATA = new DummySyncData(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xBB, (byte) 0x11, (byte) 0x22, (byte) 0x00, (byte) 0x44, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xAA, (byte) 0x99, (byte) 0x55, (byte) 0x66});
/**
* dummy syncronization data for v5 and v6 ICAP. Note: does not need as much sync data is the regular bitstream
*/
public static final DummySyncData V5_V6_ICAP_DUMMY_SYNC_DATA = new DummySyncData(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xBB, (byte) 0x11, (byte) 0x22, (byte) 0x00, (byte) 0x44, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xAA, (byte) 0x99, (byte) 0x55, (byte) 0x66});
public static final byte[] SYNC_DATA = new byte[]{(byte) 0xAA, (byte) 0x99, (byte) 0x55, (byte) 0x66};
public DummySyncData(byte[] bytes) {
_data = new ArrayList<Byte>(bytes.length);
for (Byte b : bytes) {
_data.add(b);
}
}
public DummySyncData(List<Byte> bytes) {
_data = new ArrayList<Byte>(bytes);
}
/**
* Find the dummy/sync data in the bitstream starting at the given index and
* return it as a DummySyncData object. If no sync word (0xaa995566) is found,
* null is returned. The startIndex is assumed to be the beginning of the dummy
* data and the dummy/sync data ends after the sync word is found.
*
* @param data The data to search through.
* @param startIndex The starting index in the data given.
* @return The dummy sync data if found or null otherwise.
*/
public static DummySyncData findDummySyncData(List<Byte> data, int startIndex) {
int numMatched = 0;
int index = startIndex;
int dataLength = data.size();
while (index < dataLength) {
if (data.get(index) == SYNC_DATA[numMatched]) {
numMatched++;
} else {
numMatched = 0;
}
if (numMatched == SYNC_DATA.length) {
return new DummySyncData(data.subList(startIndex, index + 1));
}
index++;
}
return null;
}
public boolean matchesData(List<Byte> data) {
return _data.equals(data);
}
public List<Byte> getData() {
return new ArrayList<Byte>(_data);
}
public int getDataSize() {
return _data.size();
}
/**
* The bytes that make up the dummy sync data of the bitstream.
*/
protected List<Byte> _data;
@Override
public List<Byte> toByteArray() {
return this.getData();
}
}
| mit |
xissburg/XDefrac | XDefrac/btMaterial.cpp | 1166 |
#include "btMaterial.h"
btMaterial::btMaterial(btScalar youngModulus, btScalar poissonRatio):
m_e(youngModulus),
m_nu(poissonRatio),
m_E(6, 6)
{
computeE();
}
void btMaterial::computeE()
{
const btScalar c = m_e/((1+m_nu)*(1-2*m_nu));
m_E.setZero();
m_E(0,0)=c*(1-m_nu), m_E(0,1)=c*m_nu, m_E(0,2)=c*m_nu, m_E(0,3)=0, m_E(0,4)=0, m_E(0,5)=0;
m_E(1,0)=c*m_nu, m_E(1,1)=c*(1-m_nu), m_E(1,2)=c*m_nu, m_E(1,3)=0, m_E(1,4)=0, m_E(1,5)=0;
m_E(2,0)=c*m_nu, m_E(2,1)=c*m_nu, m_E(2,2)=c*(1-m_nu), m_E(2,3)=0, m_E(2,4)=0, m_E(2,5)=0;
m_E(3,0)=0, m_E(3,1)=0, m_E(3,2)=0, m_E(3,3)=c*(0.5f-m_nu), m_E(3,4)=0, m_E(3,5)=0;
m_E(4,0)=0, m_E(4,1)=0, m_E(4,2)=0, m_E(4,3)=0, m_E(4,4)=c*(0.5f-m_nu), m_E(4,5)=0;
m_E(5,0)=0, m_E(5,1)=0, m_E(5,2)=0, m_E(5,3)=0, m_E(5,4)=0, m_E(5,5)=c*(0.5f-m_nu);
}
void btMaterial::setYoungModulus(btScalar e)
{
m_e = e;
computeE();
}
void btMaterial::setPoissonRatio(btScalar nu)
{
m_nu = nu;
computeE();
}
void btMaterial::setYoungModulusAndPoissonRatio(btScalar youngModulus, btScalar poissonRatio)
{
m_e = youngModulus;
m_nu = poissonRatio;
computeE();
} | mit |
enow-dev/enow | front/src/Views/Components/EventBox.js | 8176 | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Card, { CardContent } from 'material-ui/Card';
import List, {
ListItem,
ListItemIcon,
ListItemText,
ListItemSecondaryAction,
} from 'material-ui/List';
import EventIcon from 'material-ui-icons/Event';
import LocationONIcon from 'material-ui-icons/LocationOn';
import SupervisorAccount from 'material-ui-icons/SupervisorAccount';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';
import Divider from 'material-ui/Divider';
import { grey, blue, orange } from 'material-ui/colors';
import dateFormat from 'dateformat';
import KeyboardArrowUp from 'material-ui-icons/KeyboardArrowUp';
import Typography from 'material-ui/Typography';
import IconButton from 'material-ui/IconButton';
import FavoriteIcon from 'material-ui-icons/Favorite';
import propviderInfo from '../../Constants/Provider';
const styles = theme => ({
cardTitle: {
width: '100%',
padding: 10,
margin: 0,
},
cardTitleHover: {
padding: 10,
color: blue[500],
},
button: {
border: `solid 1px ${grey[300]}`,
borderRadius: '10px',
backgroundColor: `${grey[300]}`,
color: `${grey[700]}`,
},
noFavoriteButton: {
minWidth: 200,
border: `solid 1px ${orange[500]}`,
borderRadius: 10,
backgroundColor: '#fff',
padding: '15px 30px',
color: orange[500],
},
favoriteButton: {
minWidth: 200,
border: `solid 1px ${orange[500]}`,
borderRadius: 10,
backgroundColor: `${orange[500]}`,
padding: '15px 30px',
color: '#fff',
},
favoriteIcon : {
width: 25,
height: 25,
position: 'absolute',
left: 10,
top: 10,
fill: '#fff',
zIndex: 1,
},
noFavoriteIcon: {
width: 25,
height: 25,
position: 'absolute',
left: 5,
top: 10,
fill: orange[500],
zIndex: 1,
}
});
class EventBox extends React.Component {
constructor(props) {
super(props);
this.state = {
isOpenDrawer: false,
isOpenedDrawer: false,
favorite: null,
isTitleHover: false,
isFavorite: props.event.item.isFavorite ? props.event.item.isFavorite : false,
};
}
handleCloseDrawer = () => {
this.setState({ isOpenDrawer: false });
};
handleOpenDrawer() {
if (this.state.isOpenDrawer) {
this.setState({ isOpenDrawer: false });
return;
}
this.setState({ isOpenDrawer: true });
const { event, onClickEdit } = this.props;
if (onClickEdit) {
onClickEdit(event);
}
}
renderDrawer() {
const { event } = this.props;
return (
<div>
<ListItem>
<div dangerouslySetInnerHTML={{ __html: `${event.item.description ? event.item.description : '' }` }} />
</ListItem>
<ListItem button onClick={this.handleCloseDrawer}>
<Grid container align="center" direction="row" justify="center">
<Grid item>
<KeyboardArrowUp />
</Grid>
</Grid>
</ListItem>
</div>
);
}
render() {
const { classes, event, handleProviderJump, onClickDeleteFavorite, onClickPutFavorite } = this.props;
const startDate = new Date(event.item.startAt);
const endDate = new Date(event.item.endAt);
let title = String(event.item.title);
if (title.length > 36) {
title =`${ title.substr(0,36)}...`
}
let logoUrl = null;
propviderInfo.some(item => {
if (event.item['api_id'] === item.id) {
logoUrl = item.logoUrl;
return true;
}
return false;
});
return (
<Card>
<Grid
container
className={classes.cardTitle}
align="center"
direction="row"
justify="space-between"
spacing={24}
>
<Grid item>
<Typography
className={this.state.isTitleHover ? classes.cardTitleHover : classes.cardTitle}
type="headline"
component="a"
href="#"
align="left"
onClick={() => {
handleProviderJump(event);
return false;
}}
onMouseEnter={() => {
this.setState({ isTitleHover: true });
}}
onMouseLeave={() => {
this.setState({ isTitleHover: false });
}}
>
{title}
</Typography>
</Grid>
<Grid item>
<div style={{ width: '100%', position: 'relative', display: 'inline-block' }}>
<FavoriteIcon className={
this.state.isFavorite ? classes.favoriteIcon : classes.noFavoriteIcon
}
/>
<Button
className={
this.state.isFavorite ? classes.favoriteButton : classes.noFavoriteButton
}
dense
onClick={() => {
const { isFavorite } = this.state;
this.setState({ isFavorite: !isFavorite });
if (isFavorite) {
onClickDeleteFavorite(event);
} else {
onClickPutFavorite(event);
}
}}
>
{this.state.isFavorite ? 'お気に入り中' : 'お気に入りに追加する'}
</Button>
</div>
</Grid>
</Grid>
<CardContent>
<List>
<ListItem>
<ListItemIcon>
<EventIcon />
</ListItemIcon>
<ListItemText
primary={`${dateFormat(startDate, 'yyyy/mm/dd')} ~ ${dateFormat(endDate, 'mm/dd')}`}
/>
</ListItem>
<ListItem>
<ListItemIcon>
<LocationONIcon />
</ListItemIcon>
<ListItemText primary={`${event.item.area}`} />
</ListItem>
<ListItem>
<ListItemIcon>
<SupervisorAccount />
</ListItemIcon>
<ListItemText primary={`${event.item.accepted}人/定員${event.item.limit}人`} />
</ListItem>
<ListItem>
<Grid container direction="row" justify="flex-start" align="center">
{event.item.tags.map((item, index) =>
<Grid item key={index}>
<Button dense className={classes.button}>
{item}
</Button>
</Grid>,
)}
</Grid>
</ListItem>
<Divider />
<ListItem>
<Grid container direction="row" justify="space-between" align="center">
<Grid item>
<Button
dense
className={classes.button}
onClick={() => {
this.handleOpenDrawer();
}}
>
{this.state.isOpenDrawer ? '閉じる' : '詳細を見る'}
</Button>
</Grid>
<Grid item>
<ListItemSecondaryAction>
<IconButton
style={{ width: 100 }}
onClick={() => {
handleProviderJump(event);
}}
>
<img style={{ width: 100 }} src={`${logoUrl}`} alt="提供元ロゴ"/>
</IconButton>
</ListItemSecondaryAction>
</Grid>
</Grid>
</ListItem>
{this.state.isOpenDrawer ? this.renderDrawer() : null}
</List>
</CardContent>
</Card>
);
}
}
EventBox.propTypes = {
classes: PropTypes.object.isRequired,
event: PropTypes.shape({
accepted: PropTypes.number,
limit: PropTypes.number,
}),
};
EventBox.defaultProps = {
classes: Object,
event: PropTypes.shape({
accepted: 0,
limit: 0,
}),
};
export default withStyles(styles)(EventBox);
| mit |
technohippy/ruby-wave-robot-api | examples/ruby-kitchen-sinky.rb | 1846 | require 'rubygems'
require 'sinatra'
require 'waveapi'
robot = Waveapi::Robot.new(
'Ruby Ketchensinky',
:base_url => '/sample-robot',
:image_url => 'http://ruby-wave-robot.heroku.com/images/icon.png',
:profile_url => 'http://ruby-wave-robot-api.heroku.com'
)
robot.register_handler(Waveapi::WaveletSelfAddedEvent) do |event, wavelet|
blip = event.blip
wavelet.title = 'A wavelet title'
blip.append(Waveapi::Image.new('http://www.google.com/logos/clickortreat1.gif', 320, 118))
wavelet.proxy_for('douwe').reply().append('hi from douwe')
inline_blip = blip.insert_inline_blip(5)
inline_blip.append('hello again!')
new_wave = robot.new_wave(wavelet.domain, wavelet.participants, wavelet)
new_wave.root_blip.append('A new day and a new wave')
new_wave.root_blip.append_markup('<p>Some stuff!</p><p>Not the <b>beautiful</b></p>')
new_wave.submit_with(wavelet)
end
robot.register_handler(Waveapi::WaveletCreatedEvent) do |event, wavelet|
org_wavelet = wavelet.robot.blind_wavelet(event.message)
gadget = Waveapi::Gadget.new('http://kitchensinky.appspot.com/public/embed.xml')
gadget.waveid = wavelet.wave_id
org_wavelet.root_blip.append(gadget)
org_wavelet.root_blip.append("\nInserted a gadget: hello")
org_wavelet.submit_with(wavelet)
end
robot.register_handler(Waveapi::BlipSubmittedEvent) do |event, wavelet|
blip = event.blip
gadget = blip.first(Waveapi::Gadget, :url => 'http://kitchensinky.appspot.com/public/embed.xml')
if (gadget and gadget.get('loaded', 'no') == 'yes' and gadget.get('seen', 'no') == 'no')
gadget.update_element('seen' => 'yes')
blip.append("\nThe gadget worked.")
image = blip.first(Waveapi::Image)
image.update_element('url' => 'http://www.google.com/logos/poppy09.gif')
blip.append("\nThe image worked -look for a poppy.")
end
end
robot.start
| mit |
rinat-enikeev/ReliabilityImitation | javafx/src/main/java/pro/enikeev/imitation/JFXImitationApp.java | 562 | package pro.enikeev.imitation;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class JFXImitationApp extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("/fxml/imitationView.fxml"));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| mit |
flightlog/flsweb | src/masterdata/flightTypes/FlightTypesEditDirective.js | 287 | import FlightTypesEditController from './FlightTypesEditController';
export default class FlightTypesEditDirective {
static factory() {
return {
template: require("./flight-types-table.html"),
controller: FlightTypesEditController
}
}
}
| mit |
EmilPopov/C-Sharp | C# OOP/Exam Preparation OOP/Academy Ecosystem/AcademyEcosystem/AcademyEcosystem/Zombie.cs | 408 |
namespace AcademyEcosystem
{
public class Zombie : Animal
{
private const int MeatFromZombie = 10;
private const int ZombieSize = 0;
public Zombie(string name, Point location)
: base(name, location,ZombieSize)
{
}
public override int GetMeatFromKillQuantity()
{
return MeatFromZombie;
}
}
}
| mit |
ponycoin/ponycoin | src/qt/locale/bitcoin_ja.ts | 99027 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="ja" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About PonyCoin</source>
<translation>PonyCoinについて</translation>
</message>
<message>
<location line="+39"/>
<source><b>PonyCoin</b> version</source>
<translation><b>PonyCoin</b> バージョン</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The PonyCoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>アドレス帳</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>アドレスまたはラベルを編集するにはダブルクリック</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>新規アドレスの作成</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>現在選択されているアドレスをシステムのクリップボードにコピーする</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your PonyCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a PonyCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified PonyCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>削除(&D)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your PonyCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>アドレス帳データをエクスポートする</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>CSVファイル (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>エクスポートエラー</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1のファイルに書き込めませんでした。</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>ラベル</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>アドレス</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ラベル無し)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>パスフレーズを入力</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>新しいパスフレーズ</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>新しいパスフレーズをもう一度</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>ウォレットの新しいパスフレーズを入力してください。<br/><b>8個以上の単語か10個以上のランダムな文字</b>を使ってください。</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>ウォレットを暗号化する</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>この操作はウォレットをアンロックするためにパスフレーズが必要です。</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>ウォレットをアンロックする</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>この操作はウォレットの暗号化解除のためにパスフレーズが必要です。</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>ウォレットの暗号化を解除する</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>パスフレーズの変更</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>新旧両方のパスフレーズを入力してください。</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>ウォレットの暗号化を確認する</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR PonyCoinS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>ウォレットは暗号化されました</translation>
</message>
<message>
<location line="-56"/>
<source>PonyCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your PonyCoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>ウォレットの暗号化に失敗しました</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>内部エラーによりウォレットの暗号化が失敗しました。ウォレットは暗号化されませんでした。</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>パスフレーズが同じではありません。</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>ウォレットのアンロックに失敗しました</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>ウォレットの暗号化解除のパスフレーズが正しくありません。</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>ウォレットの暗号化解除に失敗しました</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>ネットワークに同期中……</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>概要(&O)</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>ウォレットの概要を見る</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>取引(&T)</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>取引履歴を閲覧</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>保存されたアドレスとラベルのリストを編集</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>支払い受け取り用アドレスのリストを見る</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>アプリケーションを終了</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about PonyCoin</source>
<translation>PonyCoinに関する情報を見る</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>オプション(&O)</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a PonyCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for PonyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>ウォレット暗号化用パスフレーズの変更</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>PonyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About PonyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your PonyCoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified PonyCoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>ファイル(&F)</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>設定(&S)</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>ヘルプ(&H)</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>タブツールバー</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>PonyCoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to PonyCoin network</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>バージョンは最新です</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>送金取引</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>着金取引</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid PonyCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>ウォレットは<b>暗号化され、アンロックされています</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>ウォレットは<b>暗号化され、ロックされています</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. PonyCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>アドレスの編集</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>ラベル(&L)</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>このアドレス帳の入った事と関係のレーベル</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&アドレス</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>アドレス帳の入った事の関係のアドレスです。これは遅れるのアドレスのためだけに編集出来ます。</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>新しいの受け入れのアドレス</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>新しいの送るのアドレス</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>受け入れのアドレスを編集する</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>送るのアドレスを編集する</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>入ったのアドレス「%1」はもうアドレス帳にあります。</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid PonyCoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>財布をアンロックするのは出来ませんでした。</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>新しいのキーの生成は失敗しました。</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>PonyCoin-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 "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>オプションズ</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start PonyCoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start PonyCoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the PonyCoin 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 &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the PonyCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting PonyCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show PonyCoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting PonyCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>フォーム</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the PonyCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>残高:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>未確認:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>最近の取引</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>今の残高</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start PonyCoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation 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>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the PonyCoin-Qt help message to get a list with possible PonyCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>PonyCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>PonyCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the PonyCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the PonyCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>コインを送る</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>残高:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</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="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>フォーム</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a PonyCoin address (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</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 type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this PonyCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified PonyCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a PonyCoin address (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter PonyCoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The PonyCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 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 "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Helbidea</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>テキスト CSV (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>レーベル</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Helbidea</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>エラー輸出</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1のファイルに書き込めませんでした。</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation 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>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>PonyCoin version</source>
<translation>PonyCoin Bertsio</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or ponycoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: PonyCoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: ponycoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 6933 or testnet: 16933)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 6933 or testnet: 16933)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=PonyCoinrpc
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 "PonyCoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. PonyCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong PonyCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the PonyCoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of PonyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart PonyCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. PonyCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS>
| mit |
737/sun.js | src/sun.loading.js | 4640 | var sun = sun || {};
var _loadingbar = function(){
var self = {},
settings = {
direction: "right"
};
function _start(){
if ($("#sun_loadingbar").length === 0) {
$("body").append("<div id='sun_loadingbar'></div>");
$("#sun_loadingbar").addClass("waiting").append($("<dt/><dd/>"));
switch (settings.direction) {
case 'right':
$("#sun_loadingbar").width((50 + Math.random() * 30) + "%");
break;
case 'left':
$("#sun_loadingbar").addClass("left").animate({
right: 0,
left: 100 - (50 + Math.random() * 30) + "%"
}, 200);
break;
case 'down':
$("#sun_loadingbar").addClass("down").animate({
left: 0,
height: (50 + Math.random() * 30) + "%"
}, 200);
break;
case 'up':
$("#sun_loadingbar").addClass("up").animate({
left: 0,
top: 100 - (50 + Math.random() * 30) + "%"
}, 200);
break;
}
}
}
function _end(){
switch (settings.direction) {
case 'right':
$("#sun_loadingbar").width("101%").delay(200).fadeOut(400, function() {
$(this).remove();
});
break;
case 'left':
$("#sun_loadingbar").css("left","0").delay(200).fadeOut(400, function() {
$(this).remove();
});
break;
case 'down':
$("#sun_loadingbar").height("101%").delay(200).fadeOut(400, function() {
$(this).remove();
});
break;
case 'up':
$("#sun_loadingbar").css("top", "0").delay(200).fadeOut(400, function() {
$(this).remove();
});
break;
}
}
self.start = function() {
var _url = sun.loading.config.cssPath + 'sun_loadingbar.css';
sun.load.css(_url, function() {
setTimeout(_start, 1000);
});
};
self.end = function() {
setTimeout(_end, 1200);
};
return self;
}();
var _loadCircle = function(){
var self = {},
settings = {
direction: "right"
};
function _start(){
if ($("#sun_loadCircle").length > 0) {
var html = '<div id="sun_loadCircle">' +
'<div class="spinner">' +
'<div class="spinner-container container1">' +
'<div class="circle1"></div>' +
'<div class="circle2"></div>' +
'<div class="circle3"></div>' +
'<div class="circle4"></div>' +
' </div>' +
'<div class="spinner-container container2">' +
'<div class="circle1"></div>' +
'<div class="circle2"></div>' +
'<div class="circle3"></div>' +
'<div class="circle4"></div>' +
'</div>' +
'<div class="spinner-container container3">' +
'<div class="circle1"></div>' +
'<div class="circle2"></div>' +
'<div class="circle3"></div>' +
'<div class="circle4"></div>' +
' </div>' +
' </div>' +
' </div>';
$("body").append(html);
}
}
function _end(){
if ($("#sun_loadCircle").length === 0) {
$("#sun_loadCircle").remove();
}
}
self.start = function() {
var _url = sun.loading.config.cssPath + 'sun_loadcircle.css';
sun.load.css(_url, function() {
setTimeout(_start, 1000);
});
};
self.end = function() {
setTimeout(_end, 1200);
};
return self;
}();
sun.loading = {
config : {
isWorking : true,
type : 'loadingbar',
cssPath : '/include/css/'
},
loadingbar : _loadingbar,
loadCircle : _loadCircle
};
| mit |
kuroneko1996/cyberlab | triggers/message.py | 6530 | import settings
import pygame as pg
from settings import J_BUTTONS, TYPING_SPEED
import re
import collections
def get_message(text, picture=None):
if text and text[0] == "#":
pass
elif text and text[0] == "$":
return ControlMessage(text, picture)
else:
return TextMessage(text, picture)
MessageStyle = collections.namedtuple("MessageStyle", "frame text picture")
# frame is the position of the text box
# text is the position of the text
# picture is the picture of the text box
class Message:
ICON_TEXT_BOX = None
NARRATOR_TEXT_BOX = None
BIG_TEXT_BOX = None
FONT = None
FONT_SMALLER = None
FONT_BIGGER = None
messages = []
text_box = None
speaker = "1"
def __init__(self):
if not Message.messages:
Message.FONT = pg.font.Font(*settings.FONT)
Message.FONT_SMALLER = pg.font.Font(*settings.FONT_SMALLER)
Message.FONT_BIGGER = pg.font.Font(*settings.FONT_BIGGER)
Message.ICON_TEXT_BOX = MessageStyle((0, 360),
(130, 370),
pg.image.load(settings.ICON_TEXT_BOX).convert_alpha())
Message.NARRATOR_TEXT_BOX = MessageStyle((0, 360),
(20, 370),
pg.image.load(settings.NARRATOR_TEXT_BOX).convert_alpha())
Message.BIG_TEXT_BOX = MessageStyle((5, 5),
(10, 10),
self.get_rectangle_picture())
Message.text_box = Message.ICON_TEXT_BOX
Message.messages.append(self)
@staticmethod
def get_rectangle_picture():
big_box_picture = pg.Surface((settings.SCREEN_WIDTH - 10,
settings.SCREEN_HEIGHT - 10))
big_box_picture.fill((24, 191, 60),
pg.Rect(2, 2,
big_box_picture.get_width() - 4,
big_box_picture.get_height() - 4))
return big_box_picture
@property
def complete(self):
return True
def update(self, game):
pass
def render(self, display):
pass
def close(self):
pass
def update(game):
"""
Handles user input regarding messages
:return: nothing
"""
if Message.messages:
Message.messages[0].update(game)
if Message.messages[0].complete and type(Message.messages[0]) == ControlMessage:
Message.messages.pop(0)
if (game.get_vbutton_jp('next') or
game.get_joystick_jp(J_BUTTONS['A'])):
if Message.messages:
Message.messages[0].close()
if (game.get_vbutton_jp('close') or
game.get_joystick_jp(J_BUTTONS['B'])):
Message.messages = []
class TextMessage(Message):
"""
Text messages simply display text
"""
def __init__(self, text, picture):
super().__init__()
self.__text = text
self.__text_typed = 0
self.__picture = picture
def __str__(self):
return self.__text[:self.__text_typed]
def close(self):
"""
Either finish typing this messages or switch to the next screen
"""
if self.completed:
Message.messages.pop(0)
else:
self.__text_typed = len(self.__text)
@property
def completed(self):
"""
Returns true if message is complete
:return: true if the messages is typed
"""
return len(self.__text) == self.__text_typed
def update(self, game):
if game.global_time % TYPING_SPEED < game.dt:
self.__text_typed = min(self.__text_typed + 1,
len(self.__text))
def __put_text_on_screen(self, display):
display.blit(Message.text_box.picture, Message.text_box.frame)
if Message.text_box == Message.ICON_TEXT_BOX:
display.blit(pg.transform.scale(
pg.image.load("assets/messages/avatars/{0}.png".format(Message.speaker))
.convert_alpha(),
(105, 105)),
(5, 367))
line_num = 0
for line in re.split("\n", self.__str__()):
display.blit(self.FONT.render(line, True, (255, 255, 255)),
(Message.text_box.text[0],
Message.text_box.text[1] + 20 * line_num))
line_num += 1
display.blit(self.FONT_SMALLER.render("[RETURN]", True, (255, 255, 255)), (565, 455))
pg.display.flip()
def render(self, display):
"""
Renders self onto given display
:param display: display on which to render the messages
:return: nothing
"""
self.__put_text_on_screen(display)
class ControlMessage(Message):
"""
Control messages can execute arbitrary code
$style icon
$style narrator
^-- change the messages style
"""
def __init__(self, text, picture):
super().__init__()
self.__code = re.split(" ", text[1:])
def update(self, game):
if self.__code[0] == "style":
if self.__code[1] == "icon":
Message.text_box = Message.ICON_TEXT_BOX
elif self.__code[1] == "narrator":
Message.text_box = Message.NARRATOR_TEXT_BOX
elif self.__code[1] == "big":
Message.text_box = Message.BIG_TEXT_BOX
else:
raise ValueError("Unexpected message style")
if self.__code[0] == "speaker":
Message.speaker = self.__code[1]
def render(self, display):
pass
def close(self):
Message.messages.remove(self)
def is_a_line_comment(line):
"""
Returns true if given line is a comment
:param line: line to be checked
:return: true if the line is a comment, false otherwise
"""
return re.fullmatch("^#.*", line)
def is_code(line):
"""
Returns true if given line is a code
:param line: line to be checked
:return: true if the line is a code, false otherwise
"""
return re.fullmatch("^\$.*", line)
def is_text(line):
"""
Return true if given line is plain text
:param line: line to be checked
:return: true if the line is a text, false otherwise
"""
return not (is_a_line_comment(line) or is_code(line)) | mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highstock/config/PlotOptionsPolygonStatesSelectMarkerStatesHoverAnimation.scala | 1053 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highstock]]
*/
package com.highstock.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>plotOptions-polygon-states-select-marker-states-hover-animation</code>
*/
@js.annotation.ScalaJSDefined
class PlotOptionsPolygonStatesSelectMarkerStatesHoverAnimation extends com.highcharts.HighchartsGenericObject {
val duration: js.UndefOr[Double] = js.undefined
}
object PlotOptionsPolygonStatesSelectMarkerStatesHoverAnimation {
/**
*/
def apply(duration: js.UndefOr[Double] = js.undefined): PlotOptionsPolygonStatesSelectMarkerStatesHoverAnimation = {
val durationOuter: js.UndefOr[Double] = duration
com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsPolygonStatesSelectMarkerStatesHoverAnimation {
override val duration: js.UndefOr[Double] = durationOuter
})
}
}
| mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highmaps/config/PlotOptionsBubblePathfinderStartMarker.scala | 5765 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highmaps]]
*/
package com.highmaps.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>plotOptions-bubble-pathfinder-startMarker</code>
*/
@js.annotation.ScalaJSDefined
class PlotOptionsBubblePathfinderStartMarker extends com.highcharts.HighchartsGenericObject {
/**
* <p>Set the symbol of the pathfinder start markers.</p>
* @since 6.2.0
*/
val symbol: js.UndefOr[String] = js.undefined
/**
* <p>Enable markers for the connectors.</p>
* @since 6.2.0
*/
val enabled: js.UndefOr[Boolean] = js.undefined
/**
* <p>Horizontal alignment of the markers relative to the points.</p>
* @since 6.2.0
*/
val align: js.UndefOr[String] = js.undefined
/**
* <p>Vertical alignment of the markers relative to the points.</p>
* @since 6.2.0
*/
val verticalAlign: js.UndefOr[String] = js.undefined
/**
* <p>Whether or not to draw the markers inside the points.</p>
* @since 6.2.0
*/
val inside: js.UndefOr[Boolean] = js.undefined
/**
* <p>Set the line/border width of the pathfinder markers.</p>
* @since 6.2.0
*/
val lineWidth: js.UndefOr[Double] = js.undefined
/**
* <p>Set the radius of the pathfinder markers. The default is
* automatically computed based on the algorithmMargin setting.</p>
* <p>Setting marker.width and marker.height will override this
* setting.</p>
* @since 6.2.0
*/
val radius: js.UndefOr[Double] = js.undefined
/**
* <p>Set the width of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.</p>
* @since 6.2.0
*/
val width: js.UndefOr[Double] = js.undefined
/**
* <p>Set the height of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.</p>
* @since 6.2.0
*/
val height: js.UndefOr[Double] = js.undefined
/**
* <p>Set the color of the pathfinder markers. By default this is the
* same as the connector color.</p>
* @since 6.2.0
*/
val color: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>Set the line/border color of the pathfinder markers. By default
* this is the same as the marker color.</p>
* @since 6.2.0
*/
val lineColor: js.UndefOr[String | js.Object] = js.undefined
}
object PlotOptionsBubblePathfinderStartMarker {
/**
* @param symbol <p>Set the symbol of the pathfinder start markers.</p>
* @param enabled <p>Enable markers for the connectors.</p>
* @param align <p>Horizontal alignment of the markers relative to the points.</p>
* @param verticalAlign <p>Vertical alignment of the markers relative to the points.</p>
* @param inside <p>Whether or not to draw the markers inside the points.</p>
* @param lineWidth <p>Set the line/border width of the pathfinder markers.</p>
* @param radius <p>Set the radius of the pathfinder markers. The default is. automatically computed based on the algorithmMargin setting.</p>. <p>Setting marker.width and marker.height will override this. setting.</p>
* @param width <p>Set the width of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p>
* @param height <p>Set the height of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p>
* @param color <p>Set the color of the pathfinder markers. By default this is the. same as the connector color.</p>
* @param lineColor <p>Set the line/border color of the pathfinder markers. By default. this is the same as the marker color.</p>
*/
def apply(symbol: js.UndefOr[String] = js.undefined, enabled: js.UndefOr[Boolean] = js.undefined, align: js.UndefOr[String] = js.undefined, verticalAlign: js.UndefOr[String] = js.undefined, inside: js.UndefOr[Boolean] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, radius: js.UndefOr[Double] = js.undefined, width: js.UndefOr[Double] = js.undefined, height: js.UndefOr[Double] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined): PlotOptionsBubblePathfinderStartMarker = {
val symbolOuter: js.UndefOr[String] = symbol
val enabledOuter: js.UndefOr[Boolean] = enabled
val alignOuter: js.UndefOr[String] = align
val verticalAlignOuter: js.UndefOr[String] = verticalAlign
val insideOuter: js.UndefOr[Boolean] = inside
val lineWidthOuter: js.UndefOr[Double] = lineWidth
val radiusOuter: js.UndefOr[Double] = radius
val widthOuter: js.UndefOr[Double] = width
val heightOuter: js.UndefOr[Double] = height
val colorOuter: js.UndefOr[String | js.Object] = color
val lineColorOuter: js.UndefOr[String | js.Object] = lineColor
com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsBubblePathfinderStartMarker {
override val symbol: js.UndefOr[String] = symbolOuter
override val enabled: js.UndefOr[Boolean] = enabledOuter
override val align: js.UndefOr[String] = alignOuter
override val verticalAlign: js.UndefOr[String] = verticalAlignOuter
override val inside: js.UndefOr[Boolean] = insideOuter
override val lineWidth: js.UndefOr[Double] = lineWidthOuter
override val radius: js.UndefOr[Double] = radiusOuter
override val width: js.UndefOr[Double] = widthOuter
override val height: js.UndefOr[Double] = heightOuter
override val color: js.UndefOr[String | js.Object] = colorOuter
override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter
})
}
}
| mit |
bolatov/contests | codeforces.ru/cf119/a.cpp | 614 | #include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
<<<<<<< HEAD
int n, a, b, c;
cin >> n >> a >> b >> c;
int ans = -1;
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= n; ++j) {
int ab = a * i + b * j;
int k = (n - ab) / c;
if (ab + k * c == n && k > 0) {
ans = max(ans, i + j + k);
// printf("%d %d %d\n", i, j, k);
}
}
}
cout << ans << endl;
return 0;
}
| mit |
shaunmahony/seqcode | src/edu/psu/compbio/seqcode/gse/tools/rnaseq/DifferentialExpression.java | 7583 | package edu.psu.compbio.seqcode.gse.tools.rnaseq;
import java.util.*;
import java.io.IOException;
import java.sql.SQLException;
import cern.jet.random.Gamma;
import cern.jet.random.Binomial;
import cern.jet.random.engine.DRand;
import edu.psu.compbio.seqcode.gse.datasets.general.*;
import edu.psu.compbio.seqcode.gse.datasets.seqdata.*;
import edu.psu.compbio.seqcode.gse.datasets.species.*;
import edu.psu.compbio.seqcode.gse.ewok.verbs.*;
import edu.psu.compbio.seqcode.gse.tools.utils.Args;
import edu.psu.compbio.seqcode.gse.utils.NotFoundException;
/**
* DifferentialExpression --species "$SC;Sigmav6" --one "Sigma polyA RNA, haploid from 2/9/09;3/17/09;bowtie --best -m 100 -k 100" \
* --two "Sigma polyA RNA, tetraploid from 2/9/09;3/17/09;bowtie --best -m 100 -k 100" --genes sgdGene \
* [--bothstrands] [--byweight] [--flipgenetrands] [--exons] [--lengthnorm]
*
* Output columns are
* - gene name
* - count one
* - count two
* - frequency in sample count (count / total count)
* - frequency two
* - pval of count two given frequency one
* - pval of count one given frequency two
*/
public class DifferentialExpression {
SeqDataLoader loader;
List<SeqAlignment> one, two;
RefGeneGenerator genes;
Genome genome;
boolean bothstrands, byweight, exons, lengthnorm;
public static void main(String args[]) throws Exception {
DifferentialExpression d = new DifferentialExpression();
d.parseArgs(args);
d.run();
d.loader.close();
}
public DifferentialExpression() throws SQLException, IOException {
loader = new SeqDataLoader();
one = new ArrayList<SeqAlignment>();
two = new ArrayList<SeqAlignment>();
}
public void parseArgs(String args[]) throws SQLException, NotFoundException {
genome = Args.parseGenome(args).cdr();
List<SeqLocator> locators = Args.parseSeqExpt(args,"one");
for (SeqLocator locator : locators) {
one.addAll(loader.loadAlignments(locator,genome));
}
locators = Args.parseSeqExpt(args,"two");
for (SeqLocator locator : locators) {
two.addAll(loader.loadAlignments(locator,genome));
}
// parseGenes returns a list of genes; just take the first one
genes = Args.parseGenes(args).get(0);
if (one.size() == 0) {
throw new NotFoundException("--one didn't match any alignments");
}
if (two.size() == 0) {
throw new NotFoundException("--two didn't match any alignments");
}
bothstrands = Args.parseFlags(args).contains("bothstrands");
byweight = Args.parseFlags(args).contains("byweight");
exons = Args.parseFlags(args).contains("exons");
lengthnorm = Args.parseFlags(args).contains("lengthnorm");
if (exons) {
genes.retrieveExons(true);
}
}
public void run() throws SQLException, IOException {
ChromRegionIterator chroms = new ChromRegionIterator(genome);
double totalweightone = getWeight(one), totalweighttwo = getWeight(two);
double totalcountone, totalcounttwo;
if (byweight) {
totalcountone = getWeight(one);
totalcounttwo = getWeight(two);
} else {
totalcountone = getCount(one);
totalcounttwo = getCount(two);
}
System.err.println("Total weight one is " + totalweightone + " hits one is " + totalcountone);
System.err.println("Total weight two is " + totalweighttwo + " hits two is " + totalcounttwo);
Binomial binomial = new Binomial(100,.1,new DRand((int)(System.currentTimeMillis() % 0xFFFFFFFF)));
List<StrandedRegion> geneRegions = new ArrayList<StrandedRegion>();
while (chroms.hasNext()) {
Region chrom = chroms.next();
Iterator<Gene> geneiter = genes.execute(chrom);
while (geneiter.hasNext()) {
Gene g = geneiter.next();
double countone = 0, counttwo = 0;
int length = 0;
geneRegions.clear();
if (exons && g instanceof ExonicGene) {
Iterator<Region> exoniter = ((ExonicGene)g).getExons();
while (exoniter.hasNext()) {
geneRegions.add(new StrandedRegion(exoniter.next(), g.getStrand()));
}
} else {
geneRegions.add(g);
}
for (StrandedRegion r : geneRegions) {
length += r.getWidth();
try {
if (bothstrands) {
if (byweight) {
countone += loader.weightByRegion(one,(Region)r);
counttwo += loader.weightByRegion(two,(Region)r);
} else {
countone += loader.countByRegion(one,(Region)r);
counttwo += loader.countByRegion(two,(Region)r);
}
} else {
if (byweight) {
countone += loader.weightByRegion(one,r);
counttwo += loader.weightByRegion(two,r);
} else {
countone += loader.countByRegion(one,r);
counttwo += loader.countByRegion(two,r);
}
}
} catch (IllegalArgumentException e) {
// this is just it complaining about invalid chromosomes
}
}
if (countone < 2 && counttwo < 2) { continue; }
if (countone < 2) {countone = 2;}
if (counttwo < 2) {counttwo = 2;}
if (lengthnorm) {
countone = countone * 1000.0 / length;
counttwo = counttwo * 1000.0 / length;
}
double pone = countone / totalcountone;
double ptwo = counttwo / totalcounttwo;
binomial.setNandP((int)totalcountone, ptwo);
double cdf = binomial.cdf((int)countone);
double pvalonegiventwo = Math.min(cdf, 1 - cdf);
binomial.setNandP((int)totalcounttwo, pone);
cdf = binomial.cdf((int)counttwo);
double pvaltwogivenone = Math.min(cdf, 1 - cdf);
System.out.println(String.format("%s\t%.0f\t%.0f\t%.4e\t%.4e\t%.4e\t%.4e", g.toString(),
countone,
counttwo,
pone, ptwo,
pvaltwogivenone,
pvalonegiventwo));
}
}
}
private double getWeight(Collection<SeqAlignment> alignments) throws SQLException, IOException {
double weight = 0;
for (SeqAlignment a : alignments) {
weight += loader.weighAllHits(a);
}
return weight;
}
private int getCount(Collection<SeqAlignment> alignments) throws SQLException, IOException {
int count = 0;
for (SeqAlignment a : alignments) {
count += loader.countAllHits(a);
}
return count;
}
} | mit |
jacobhyphenated/PokerServer | src/main/java/com/hyphenated/card/domain/BlindLevel.java | 2721 | /*
The MIT License (MIT)
Copyright (c) 2013 Jacob Kanipe-Illig
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.hyphenated.card.domain;
/**
*
* Data structure for Blind Level. This enum has all possible Blind Levels
* that can occur for any game type.
*
* @author jacobhyphenated
*/
public enum BlindLevel {
BLIND_10_20(10,20),
BLIND_15_30(15,30),
BLIND_20_40(20,40),
BLIND_25_50(25,50),
BLIND_30_60(30,60),
BLIND_40_80(40,80),
BLIND_50_100(50,100),
BLIND_60_120(60,120),
BLIND_75_150(75,150),
BLIND_80_160(80,160),
BLIND_100_200(100,200),
BLIND_120_240(120,240),
BLIND_150_300(150,300),
BLIND_200_400(200,400),
BLIND_250_500(250,500),
BLIND_300_600(300,600),
BLIND_400_800(400,800),
BLIND_500_1000(500,1000),
BLIND_600_1200(600,1200),
BLIND_700_1400(700,1400),
BLIND_800_1600(800,1600),
BLIND_900_1800(900,1800),
BLIND_1000_2000(1000,2000),
BLIND_1200_2400(1200,2400),
BLIND_1500_3000(1500,3000),
BLIND_1600_3200(1600,3200),
BLIND_1800_3600(1800,3600),
BLIND_2000_4000(2000,4000),
BLIND_2500_5000(2500,5000),
BLIND_3000_6000(3000,6000),
BLIND_4000_8000(4000,8000),
BLIND_5000_10K(5000,10000),
BLIND_6000_12K(6000,12000),
BLIND_7000_14K(7000,14000),
BLIND_8000_16K(8000,16000),
BLIND_9000_18K(9000,18000),
BLIND_10K_20K(10000,20000),
BLIND_12K_24K(12000,24000),
BLIND_14K_28K(14000,28000),
BLIND_16K_32K(16000,32000),
BLIND_18K_36K(18000,36000),
BLIND_20K_40K(20000,40000),
BLIND_25K_50K(25000,50000);
private int smallBlind;
private int bigBlind;
private BlindLevel(int smallBlind, int bigBlind){
this.smallBlind = smallBlind;
this.bigBlind = bigBlind;
}
public int getSmallBlind(){
return smallBlind;
}
public int getBigBlind(){
return bigBlind;
}
}
| mit |
emartech/cranium | lib/cranium/profiling.rb | 332 | BEGIN {
require 'ruby-prof'
RubyProf.start
}
END {
profile = RubyProf.stop
printer = RubyProf::CallStackPrinter.new profile
profile_path = "/tmp/" + File.basename($0).gsub(".", "_") + "_profile.html"
printer.print File.open(profile_path, "w"), min_percent: 1
puts "Profiling information saved to: " + profile_path
}
| mit |
blachlylab/gff3 | tests/gff3_test.go | 4860 | package unit_tests
import (
"os"
"reflect"
"strings"
"testing"
"../../gff3"
)
var fakeGff3Line = "chr1\tHAVANA\tgene\t11869\t14409\t.\t+\t.\tID=ENSG00000223972.5;gene_id=ENSG00000223972.5;gene_type=transcribed_unprocessed_pseudogene;gene_status=KNOWN;gene_name=DDX11L1;level=2;havana_gene=OTTHUMG00000000961.2"
func TestSimpleParseLineWithReader(t *testing.T) {
myReader := gff3.NewReader(strings.NewReader(fakeGff3Line))
myRecord, err := myReader.Read()
if err != nil {
t.Errorf("record was not correctly parsed and returned an error")
}
// file opened fine, but is the content correct?
var fakeGff3Solution = gff3.Record{
Complete: true,
SeqidField: "chr1",
SourceField: "HAVANA",
TypeField: "gene",
StartField: 11869,
EndField: 14409,
ScoreField: 0,
StrandField: '+',
PhaseField: 0,
AttributesField: map[string]string{
"ID": "ENSG00000223972.5",
"gene_id": "ENSG00000223972.5",
"gene_type": "transcribed_unprocessed_pseudogene",
"gene_status": "KNOWN",
"gene_name": "DDX11L1",
"level": "2",
"havana_gene": "OTTHUMG00000000961.2",
},
}
// deep equal will recursively compare all attributes and values of the structs
// a simple equal "==" doesn't suffice because keys in the attributes map may be reordered
if !reflect.DeepEqual(myRecord, &fakeGff3Solution) {
t.Errorf("record was not correctly parsed, but did not throw an error")
}
fakeGff3Solution.StartField = 1
if reflect.DeepEqual(myRecord, &fakeGff3Solution) {
t.Errorf("records are different and should not be equal")
}
}
func TestParseTwoLinesWithReader(t *testing.T) {
fakeGff3Line := "chr1\tHAVANA\tgene\t11869\t14409\t.\t+\t.\tID=ENSG00000223972.5;gene_id=ENSG00000223972.5;gene_type=transcribed_unprocessed_pseudogene;gene_status=KNOWN;gene_name=DDX11L1;level=2;havana_gene=OTTHUMG00000000961.2\nchr1\tHAVANA\tgene\t69091\t70008\t.\t+\t.\tID=ENSG00000186092.4;gene_id=ENSG00000186092.4;gene_type=protein_coding;gene_status=KNOWN;gene_name=OR4F5;level=2;havana_gene=OTTHUMG00000001094.2"
myReader := gff3.NewReader(strings.NewReader(fakeGff3Line))
if myRecord, err := myReader.Read(); err != nil {
t.Errorf("first record was not correctly parsed and returned an error")
} else if !myRecord.Complete {
t.Errorf("first record was not correctly parsed, but did not throw an error")
}
if myRecord, err := myReader.Read(); err != nil {
t.Errorf("second record was not correctly parsed and returned an error")
} else if !myRecord.Complete {
t.Errorf("second record was not correctly parsed, but did not throw an error")
}
}
func TestParseSeveralCommentsBeforeLine(t *testing.T) {
fakeGff3Line := "#GFF3 file\n#header information\n#file version\nchr1\tHAVANA\tgene\t11869\t14409\t.\t+\t.\tID=ENSG00000223972.5;gene_id=ENSG00000223972.5;gene_type=transcribed_unprocessed_pseudogene;gene_status=KNOWN;gene_name=DDX11L1;level=2;havana_gene=OTTHUMG00000000961.2"
myReader := gff3.NewReader(strings.NewReader(fakeGff3Line))
if myRecord, err := myReader.Read(); err != nil {
t.Errorf("record was not correctly parsed and returned an error")
} else if !myRecord.Complete {
t.Errorf("record was not correctly parsed, but did not throw an error")
}
}
func TestRecordFilterStrand(t *testing.T) {
myReader := gff3.NewReader(strings.NewReader(fakeGff3Line))
myRecord, _ := myReader.Read()
filtRecord := myRecord.FilterByField("strand", "+")
if !filtRecord.Complete {
t.Errorf("record did not successfully pass filter")
}
filtRecord = myRecord.FilterByField("strand", "-")
if filtRecord.Complete {
t.Errorf("record did not appropriately fail filter")
}
}
func TestRecordFilterAttribute(t *testing.T) {
myReader := gff3.NewReader(strings.NewReader(fakeGff3Line))
myRecord, _ := myReader.Read()
filtRecord := myRecord.FilterByAttribute("level", "2")
if !filtRecord.Complete {
t.Errorf("record did not successfully pass filter")
}
filtRecord = myRecord.FilterByAttribute("gene", "GAPDH")
if filtRecord.Complete {
t.Errorf("record did not appropriately fail fitler")
}
}
func TestChainedRecordFilters(t *testing.T) {
myReader := gff3.NewReader(strings.NewReader(fakeGff3Line))
myRecord, _ := myReader.Read()
filtRecord := myRecord.FilterByAttribute("level", "2").FilterByField("strand", "+").FilterByField("type", "gene")
if !filtRecord.Complete {
t.Errorf("record did not successfully pass filter")
}
filtRecord = myRecord.FilterByAttribute("level", "2").FilterByField("strand", "+").FilterByField("type", "exon")
if filtRecord.Complete {
t.Errorf("record did not appropriately fail filter")
}
filtRecord = myRecord.FilterByAttribute("level", "2").FilterByField("strand", "-").FilterByField("type", "gene")
if filtRecord.Complete {
t.Errorf("record did not appropriately fail filter")
}
}
func TestMain(m *testing.M) {
os.Exit(m.Run())
}
| mit |
cs3b/electron-multiwindow-notification-app | app/router.js | 257 | import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('external-screen');
});
export default Router;
| mit |
tkgospodinov/omniauth-fitbit | example/example.rb | 422 | require 'sinatra'
require 'omniauth-fitbit'
use Rack::Session::Cookie
use OmniAuth::Builder do
provider :fitbit, '', '', { :scope => 'profile', :redirect_uri => 'http://localhost:4567/auth/fitbit/callback' }
end
get '/' do
<<-HTML
<a href='/auth/fitbit'>Sign in with Fitbit</a>
HTML
end
get '/auth/fitbit/callback' do
# Do whatever you want with the data
MultiJson.encode(request.env['omniauth.auth'])
end | mit |
anchour/portland-vineyard | web/app/themes/portland-vineyard/lib/taxonomy-fields.php | 2992 | <?php
/**
* Custom fields for taxonomy terms. In the case of this website, they'll be used for categories.
*
* @author Matt Robitaille <matt@anchour.com>
*/
// Set up the field when adding the category
function pv_add_category_fields()
{
?>
<div class="form-field">
<p>To upload a banner image to the category page, edit the category on the right after saving it.</p>
</div>
<?php
}
add_action('category_add_form_fields', 'pv_add_category_fields', 10, 2);
// Set up the field for when editing the category
function pv_edit_category_fields($term)
{
$key = '_taxonomy_image_term_' . $term->term_id;
$term_meta = get_option( $key );
$meta_value = esc_attr( $term_meta['category_image'] ) ? esc_attr( $term_meta['category_image'] ) : '';
?>
<?php setEnctype('edittag'); ?>
<table class="form-table">
<tr class="form-field">
<th scope="row">
<label for="category_image"><?php __('Category Image', 'portlandvineyard'); ?>Category Featured Image</label>
</th>
<td>
<?php if ($meta_value) : ?>
<img src="<?php echo $meta_value; ?>" alt="" style="max-width: 100%;display: block; width:320px; height: auto;">
<?php endif; ?>
<input type="file" name="category_image" name="category_image" value=""/>
</td>
</tr>
</table>
<?php
}
add_action('category_edit_form_fields', 'pv_edit_category_fields', 10, 2);
// Save extra taxonomy fields callback function.
function save_taxonomy_custom_meta( $term_id ) {
if ( array_key_exists('category_image', $_FILES) ) {
// Handle the file uploads.
$file = $_FILES['category_image'];
$file = filterFileType($file);
if ($file) {
$overrides = array( 'test_form' => false );
$fileData = wp_handle_upload( $file, $overrides );
$url = $fileData['url'];
$key = '_taxonomy_image_term_' . $term_id;
// Get the meta for the term.
$term_meta = get_option( $key );
// Set the new category image meta.
$term_meta['category_image'] = $url;
// Save the option array.
update_option( $key, $term_meta );
}
}
}
function setEnctype($id)
{
if ( ! $id) return;
echo "
<script>
jQuery(document).ready(function($) {
$('#{$id}').attr('enctype', 'multipart/form-data');
});
</script>
";
}
function filterFileType(array $file)
{
if ( count($file) === 0) return false;
$allowedValues = array(
'image/png',
'image/gif',
'image/jpeg',
'image/jpg',
);
// Return the file if the image is one of the allowed types.
return in_array($file['type'], $allowedValues) ? $file : false;
}
add_action( 'edited_category', 'save_taxonomy_custom_meta', 10, 2 );
add_action( 'create_category', 'save_taxonomy_custom_meta', 10, 2 ); | mit |
trustify/oroplatform | src/Oro/Bundle/ActionBundle/DependencyInjection/CompilerPass/AbstractPass.php | 1501 | <?php
namespace Oro\Bundle\ActionBundle\DependencyInjection\CompilerPass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
abstract class AbstractPass implements CompilerPassInterface
{
/**
* @param ContainerBuilder $container
* @param string $serviceId
* @param string $tag
*/
public function processTypes(ContainerBuilder $container, $serviceId, $tag)
{
if (!$container->hasDefinition($serviceId)) {
return;
}
$types = [];
$conditions = $container->findTaggedServiceIds($tag);
foreach ($conditions as $id => $attributes) {
$this->prepareDefinition($container->getDefinition($id));
foreach ($attributes as $eachTag) {
$aliases = empty($eachTag['alias']) ? [$id] : explode('|', $eachTag['alias']);
foreach ($aliases as $alias) {
$types[$alias] = $id;
}
}
}
$extensionDef = $container->getDefinition($serviceId);
$extensionDef->replaceArgument(1, $types);
}
/**
* @param Definition $definition
*/
protected function prepareDefinition(Definition $definition)
{
$definition->setScope(ContainerInterface::SCOPE_PROTOTYPE)->setPublic(false);
}
}
| mit |
wtnabe/activerecord-simple_explain | lib/active_record/simple_explain/version.rb | 74 | module ActiveRecord
class SimpleExplain
VERSION = "0.0.2"
end
end
| mit |
tpoikela/battles | lib/rot-js/display/types.ts | 663 | type LayoutType = 'hex' | 'rect' | 'tile' | 'tile-gl' | 'term';
export interface DisplayOptions {
width: number;
height: number;
transpose: boolean;
layout: LayoutType;
fontSize: number;
spacing: number;
border: number;
forceSquareRatio: boolean;
fontFamily: string;
fontStyle: string;
fg: string;
bg: string;
tileWidth: number;
tileHeight: number;
tileMap: { [key: string]: [number, number] };
tileSet: null | HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | ImageBitmap;
tileColorize: Boolean;
}
export type DisplayData = [number, number, string | string[] | null, string, string];
| mit |
fahad19/firenze | src/Functions.js | 655 | export default class Functions {
constructor(...args) {
this.query = args[0];
this.column = args[1];
this.funcs = [];
}
addFunction(funcName) {
this.funcs.push(funcName);
return this;
}
getFunctions() {
return this.funcs;
}
setColumn(column) {
this.column = column;
return this;
}
getColumn() {
return this.column;
}
upper() { return this; }
lower() { return this; }
concat() { return null; }
sum() { return this; }
avg() { return this; }
min() { return this; }
max() { return this; }
count() { return this; }
now() { return null; }
toString() { return null; }
}
| mit |
IonicaBizau/arc-assembler | clients/Semantic-UI-1.1.2/dist/components/visit.min.js | 8082 | "use strict";
/*
* # Semantic UI
* https://github.com/Semantic-Org/Semantic-UI
* http://www.semantic-ui.com/
*
* Copyright 2014 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
!function (e, t, i, n) {
e.visit = e.fn.visit = function (i) {
var o,
r = e(e.isFunction(this) ? t : this),
s = r.selector || "",
a = new Date().getTime(),
c = [],
u = arguments[0],
d = "string" == typeof u,
l = [].slice.call(arguments, 1);return r.each(function () {
var g,
m = e.extend(!0, {}, e.fn.visit.settings, i),
f = m.error,
p = m.namespace,
v = p + "-module",
h = e(this),
y = e(),
b = this,
k = h.data(v);g = { initialize: function initialize() {
m.count ? g.store(m.key.count, m.count) : m.id ? g.add.id(m.id) : m.increment && "increment" !== d && g.increment(), g.add.display(h), g.instantiate();
}, instantiate: function instantiate() {
g.verbose("Storing instance of visit module", g), k = g, h.data(v, g);
}, destroy: function destroy() {
g.verbose("Destroying instance"), h.removeData(v);
}, increment: function increment(e) {
var t = g.get.count(),
i = +t + 1;e ? g.add.id(e) : (i > m.limit && !m.surpass && (i = m.limit), g.debug("Incrementing visits", i), g.store(m.key.count, i));
}, decrement: function decrement(e) {
var t = g.get.count(),
i = +t - 1;e ? g.remove.id(e) : (g.debug("Removing visit"), g.store(m.key.count, i));
}, get: { count: function count() {
return +g.retrieve(m.key.count) || 0;
}, idCount: function idCount(e) {
return e = e || g.get.ids(), e.length;
}, ids: function ids(e) {
var t = [];return e = e || g.retrieve(m.key.ids), "string" == typeof e && (t = e.split(m.delimiter)), g.verbose("Found visited ID list", t), t;
}, storageOptions: function storageOptions() {
var e = {};return m.expires && (e.expires = m.expires), m.domain && (e.domain = m.domain), m.path && (e.path = m.path), e;
} }, has: { visited: function visited(t, i) {
var o = !1;return i = i || g.get.ids(), t !== n && i && e.each(i, function (e, i) {
i == t && (o = !0);
}), o;
} }, set: { count: function count(e) {
g.store(m.key.count, e);
}, ids: function ids(e) {
g.store(m.key.ids, e);
} }, reset: function reset() {
g.store(m.key.count, 0), g.store(m.key.ids, null);
}, add: { id: function id(e) {
var t = g.retrieve(m.key.ids),
i = t === n || "" === t ? e : t + m.delimiter + e;g.has.visited(e) ? g.debug("Unique content already visited, not adding visit", e, t) : e === n ? g.debug("ID is not defined") : (g.debug("Adding visit to unique content", e), g.store(m.key.ids, i)), g.set.count(g.get.idCount());
}, display: function display(t) {
var i = e(t);i.size() > 0 && !e.isWindow(i[0]) && (g.debug("Updating visit count for element", i), y = y.size() > 0 ? y.add(i) : i);
} }, remove: { id: function id(t) {
var i = g.get.ids(),
o = [];t !== n && i !== n && (g.debug("Removing visit to unique content", t, i), e.each(i, function (e, i) {
i !== t && o.push(i);
}), o = o.join(m.delimiter), g.store(m.key.ids, o)), g.set.count(g.get.idCount());
} }, check: { limit: function limit(t) {
t = t || g.get.count(), m.limit && (t >= m.limit && (g.debug("Pages viewed exceeded limit, firing callback", t, m.limit), e.proxy(m.onLimit, this)(t)), g.debug("Limit not reached", t, m.limit), e.proxy(m.onChange, this)(t)), g.update.display(t);
} }, update: { display: function display(e) {
e = e || g.get.count(), y.size() > 0 && (g.debug("Updating displayed view count", y), y.html(e));
} }, store: function store(i, o) {
var r = g.get.storageOptions(o);if ("localstorage" == m.storageMethod && t.localStorage !== n) t.localStorage.setItem(i, o), g.debug("Value stored using local storage", i, o);else {
if (e.cookie === n) return void g.error(f.noCookieStorage);e.cookie(i, o, r), g.debug("Value stored using cookie", i, o, r);
}i == m.key.count && g.check.limit(o);
}, retrieve: function retrieve(i) {
var o;return "localstorage" == m.storageMethod && t.localStorage !== n ? o = t.localStorage.getItem(i) : e.cookie !== n ? o = e.cookie(i) : g.error(f.noCookieStorage), ("undefined" == o || "null" == o || o === n || null === o) && (o = n), o;
}, setting: function setting(t, i) {
if (e.isPlainObject(t)) e.extend(!0, m, t);else {
if (i === n) return m[t];m[t] = i;
}
}, internal: function internal(t, i) {
return g.debug("Changing internal", t, i), i === n ? g[t] : void (e.isPlainObject(t) ? e.extend(!0, g, t) : g[t] = i);
}, debug: function debug() {
m.debug && (m.performance ? g.performance.log(arguments) : (g.debug = Function.prototype.bind.call(console.info, console, m.name + ":"), g.debug.apply(console, arguments)));
}, verbose: function verbose() {
m.verbose && m.debug && (m.performance ? g.performance.log(arguments) : (g.verbose = Function.prototype.bind.call(console.info, console, m.name + ":"), g.verbose.apply(console, arguments)));
}, error: function error() {
g.error = Function.prototype.bind.call(console.error, console, m.name + ":"), g.error.apply(console, arguments);
}, performance: { log: function log(e) {
var t, i, n;m.performance && (t = new Date().getTime(), n = a || t, i = t - n, a = t, c.push({ Name: e[0], Arguments: [].slice.call(e, 1) || "", Element: b, "Execution Time": i })), clearTimeout(g.performance.timer), g.performance.timer = setTimeout(g.performance.display, 100);
}, display: function display() {
var t = m.name + ":",
i = 0;a = !1, clearTimeout(g.performance.timer), e.each(c, function (e, t) {
i += t["Execution Time"];
}), t += " " + i + "ms", s && (t += " '" + s + "'"), r.size() > 1 && (t += " (" + r.size() + ")"), (console.group !== n || console.table !== n) && c.length > 0 && (console.groupCollapsed(t), console.table ? console.table(c) : e.each(c, function (e, t) {
console.log(t.Name + ": " + t["Execution Time"] + "ms");
}), console.groupEnd()), c = [];
} }, invoke: function invoke(t, i, r) {
var s,
a,
c,
u = k;return i = i || l, r = b || r, "string" == typeof t && u !== n && (t = t.split(/[\. ]/), s = t.length - 1, e.each(t, function (i, o) {
var r = i != s ? o + t[i + 1].charAt(0).toUpperCase() + t[i + 1].slice(1) : t;if (e.isPlainObject(u[r]) && i != s) u = u[r];else {
if (u[r] !== n) return a = u[r], !1;if (!e.isPlainObject(u[o]) || i == s) return u[o] !== n ? (a = u[o], !1) : !1;u = u[o];
}
})), e.isFunction(a) ? c = a.apply(r, i) : a !== n && (c = a), e.isArray(o) ? o.push(c) : o !== n ? o = [o, c] : c !== n && (o = c), a;
} }, d ? (k === n && g.initialize(), g.invoke(u)) : (k !== n && g.destroy(), g.initialize());
}), o !== n ? o : this;
}, e.fn.visit.settings = { name: "Visit", debug: !1, verbose: !0, performance: !0, namespace: "visit", increment: !1, surpass: !1, count: !1, limit: !1, delimiter: "&", storageMethod: "localstorage", key: { count: "visit-count", ids: "visit-ids" }, expires: 30, domain: !1, path: "/", onLimit: function onLimit() {}, onChange: function onChange() {}, error: { method: "The method you called is not defined", missingPersist: "Using the persist setting requires the inclusion of PersistJS", noCookieStorage: "The default storage cookie requires $.cookie to be included." } };
}(jQuery, window, document); | mit |
goghcrow/php-minimalism | test/#GameOfLife/Calc.php | 118 | <?php
function idx($i, $limit)
{
while ($i < 0) {
$i += $limit;
}
$i %= $limit;
return $i;
} | mit |
Azure/azure-sdk-for-java | sdk/synapse/azure-resourcemanager-synapse/src/main/java/com/azure/resourcemanager/synapse/models/WorkspaceAadAdminInfo.java | 1712 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.synapse.models;
import com.azure.resourcemanager.synapse.fluent.models.WorkspaceAadAdminInfoInner;
/** An immutable client-side representation of WorkspaceAadAdminInfo. */
public interface WorkspaceAadAdminInfo {
/**
* Gets the id property: Fully qualified resource Id for the resource.
*
* @return the id value.
*/
String id();
/**
* Gets the name property: The name of the resource.
*
* @return the name value.
*/
String name();
/**
* Gets the type property: The type of the resource.
*
* @return the type value.
*/
String type();
/**
* Gets the tenantId property: Tenant ID of the workspace active directory administrator.
*
* @return the tenantId value.
*/
String tenantId();
/**
* Gets the login property: Login of the workspace active directory administrator.
*
* @return the login value.
*/
String login();
/**
* Gets the administratorType property: Workspace active directory administrator type.
*
* @return the administratorType value.
*/
String administratorType();
/**
* Gets the sid property: Object ID of the workspace active directory administrator.
*
* @return the sid value.
*/
String sid();
/**
* Gets the inner com.azure.resourcemanager.synapse.fluent.models.WorkspaceAadAdminInfoInner object.
*
* @return the inner object.
*/
WorkspaceAadAdminInfoInner innerModel();
}
| mit |
jscanlon77/angular-admin | src/app/pages/maps/components/googleMaps/googleMaps.component.ts | 755 | import {Component, ElementRef} from '@angular/core';
import {GoogleMapsLoader} from './googleMaps.loader';
@Component({
selector: 'google-maps',
pipes: [],
providers: [],
styles: [require('./googleMaps.scss')],
template: require('./googleMaps.html'),
})
export class GoogleMaps {
constructor(private _elementRef:ElementRef) {
}
ngAfterViewInit() {
let el = this._elementRef.nativeElement.querySelector('.google-maps');
// TODO: do not load this each time as we already have the library after first attempt
GoogleMapsLoader.load((google) => {
new google.maps.Map(el, {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
});
}
}
| mit |
likerRr/urf-battleground | app/Managers/LolApi/Api/Response/Dto/ListDto.php | 944 | <?php namespace URFBattleground\Managers\LolApi\Api\Response\Dto;
use URFBattleground\Managers\LolApi\Api\Response\Response;
use URFBattleground\Managers\LolApi\Api\Response\ResponseDto;
use URFBattleground\Managers\LolApi\Engine\Support\Collection;
class ListDto extends ResponseDto {
/** @var \ArrayIterator */
private $list;
/**
* @param Response $response
*/
public function __construct(Response $response)
{
parent::__construct($response);
$this->list = new Collection((array) $this->response()->getData());
}
/**
* Returns list of game ids or gets exactly game id by key in array
* @param null $index
* @param null $default
* @return \ArrayIterator|mixed
*/
public function getList($index = null, $default = null)
{
if ($index !== null && is_int($index)) {
if (!$this->list->offsetExists($index)) {
return $default;
}
return $this->list->offsetGet($index);
}
return $this->list;
}
}
| mit |
MrEfrem/TestApp | config/index.js | 2375 | import path from 'path'
import fs from 'fs'
import url from 'url'
const config = { path: {} }
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
config.path.project = fs.realpathSync(process.cwd())
config.resolve = (relativePath = '') => path.resolve(config.path.project, relativePath)
config.path.build = config.resolve('build')
config.path.buildTemplate = config.resolve('build/index.html')
config.path.entry = config.resolve('src/index.js'),
config.path.packageJSON = config.resolve('package.json'),
config.path.public = config.resolve('public')
config.path.rawTemplate = config.resolve('public/index.html')
config.path.src = config.resolve('src')
config.path.yarnLockFile = config.resolve('yarn.lock')
config.node = {
host: process.env.HOST || 'localhost',
port: process.env.PORT || 3000
}
config.webpack = {
publicPath: '/static/',
fileName: 'js/bundle.js'
}
const ensureSlash = (path, needsSlash) => {
const hasSlash = path.endsWith('/')
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1)
} else if (!hasSlash && needsSlash) {
return path + '/'
} else {
return path
}
}
config.publicUrl = ''
if (process.env.NODE_ENV === 'production') {
// We use "homepage" field to infer "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
const homepagePath = require(config.path.packageJSON).homepage
const homepagePathname = homepagePath ? url.parse(homepagePath).pathname : '/'
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
config.webpack.publicPath = ensureSlash(homepagePathname, true)
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
config.publicUrl = ensureSlash(homepagePathname, false)
}
export default config
| mit |
gustavoguichard/qrshirts | app/controllers/admin/reports/overviews_controller.rb | 946 | class Admin::Reports::OverviewsController < Admin::Reports::BaseController
before_filter :set_time_range
def show
@accounting_report = RorEReports::Accounting.new(start_time, end_time)
@orders_report = RorEReports::Orders.new(start_time, end_time)
@customers_report = RorEReports::Customers.new(start_time, end_time)
end
private
def set_time_range
if params[:start_date].present?
@start_time = Time.parse(params[:start_date])
else
@start_time = Chronic.parse('last week').beginning_of_week
end
set_end_time
end
def set_end_time
@end_time = case params[:commit]
when 'Daily'
start_time + 1.day
when 'Weekly'
start_time + 1.week
when 'Monthly'
start_time + 1.month
else
start_time + 1.week
end
end
def start_time
@start_time
end
def end_time
@end_time
end
end
| mit |
DaDiaoShuai/vue-mixin-information | src/main.js | 547 | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vux from 'vux'
import 'normalize.css/normalize.css'
import 'nprogress/nprogress.css'
import 'font-awesome/css/font-awesome.css'
import './style/app.styl'
Vue.config.productionTip = false
// Vue.use(Vux)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
}) | mit |
jurgendl/swing-easy | src/main/java/org/swingeasy/EToolBarButtonConfig.java | 1614 | package org.swingeasy;
import javax.swing.Action;
import javax.swing.Icon;
/**
* @author Jurgen
*/
public class EToolBarButtonConfig extends EComponentConfig<EToolBarButtonConfig> {
protected EToolBarButtonCustomizer buttonCustomizer;
protected Action action;
protected Icon icon;
public EToolBarButtonConfig() {
super();
}
public EToolBarButtonConfig(Action a) {
this.action = a;
}
public EToolBarButtonConfig(EToolBarButtonCustomizer ebc) {
this.buttonCustomizer = ebc;
}
public EToolBarButtonConfig(EToolBarButtonCustomizer ebc, Action a) {
this.buttonCustomizer = ebc;
this.action = a;
}
public EToolBarButtonConfig(EToolBarButtonCustomizer ebc, Icon icon) {
this.buttonCustomizer = ebc;
this.icon = icon;
}
public EToolBarButtonConfig(Icon icon) {
this.icon = icon;
}
public Action getAction() {
return this.action;
}
public EButtonCustomizer getButtonCustomizer() {
return this.buttonCustomizer;
}
public Icon getIcon() {
return this.icon;
}
public EToolBarButtonConfig setAction(Action action) {
this.lockCheck();
this.action = action;
return this;
}
public EToolBarButtonConfig setButtonCustomizer(EToolBarButtonCustomizer buttonCustomizer) {
this.lockCheck();
this.buttonCustomizer = buttonCustomizer;
return this;
}
public EToolBarButtonConfig setIcon(Icon icon) {
this.lockCheck();
this.icon = icon;
return this;
}
}
| mit |
kyokomi/AndEngineSRPGQuest | src/com/kyokomi/srpgquest/layer/CutInLayer.java | 2633 | package com.kyokomi.srpgquest.layer;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.FadeInModifier;
import org.andengine.entity.modifier.IEntityModifier;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.sprite.Sprite;
import org.andengine.util.color.Color;
import org.andengine.util.modifier.IModifier;
import com.kyokomi.core.scene.KeyListenScene;
import com.kyokomi.srpgquest.constant.LayerZIndexType;
import com.kyokomi.srpgquest.constant.MapBattleCutInLayerType;
/**
* 自動的に消えるカットイン.
* @author kyokomi
*
*/
public class CutInLayer extends Rectangle {
private final MapBattleCutInLayerType mapBattleCutInLayerType;
/**
* カットインのコールバック.
* @author kyokomi
*
*/
public interface ICutInCallback {
public void doAction();
}
/**
* コンストラクタ
* @param pBaseScene
*/
public CutInLayer(float pX, float pY, float pWidth, float pHeight, KeyListenScene pBaseScene, MapBattleCutInLayerType mapBattleCutInLayerType) {
super(pX, pY, pWidth, pHeight, pBaseScene.getBaseActivity().getVertexBufferObjectManager());
this.mapBattleCutInLayerType = mapBattleCutInLayerType;
setTag(mapBattleCutInLayerType.getValue());
setAlpha(0.0f);
setColor(Color.TRANSPARENT);
setVisible(false);
setZIndex(LayerZIndexType.CUTIN_LAYER.getValue());
attachWithCreateMapBattleCutIn(pBaseScene, mapBattleCutInLayerType);
}
public MapBattleCutInLayerType getMapBattleCutInLayerType() {
return mapBattleCutInLayerType;
}
private final static int SPRITE_TAG = 1;
private void attachWithCreateMapBattleCutIn(KeyListenScene pBaseScene, MapBattleCutInLayerType mapBattleCutInLayerType) {
Sprite sprite = pBaseScene.getResourceSprite(getMapBattleCutInLayerType().getFileName());
if (mapBattleCutInLayerType.isWindowSize()) {
sprite.setSize(pBaseScene.getWindowWidth(), pBaseScene.getWindowHeight());
}
pBaseScene.placeToCenter(sprite);
sprite.setTag(SPRITE_TAG);
attachChild(sprite);
}
public void showCutInSprite(final float pDuration, final ICutInCallback cutInCallback) {
final Sprite sprite = (Sprite) getChildByTag(SPRITE_TAG);
sprite.registerEntityModifier(new FadeInModifier(pDuration, new IEntityModifier.IEntityModifierListener() {
@Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
setVisible(true);
}
@Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
cutInCallback.doAction(); // コールバック呼び出し
sprite.setAlpha(0.0f);
setVisible(false);
}
}));
}
}
| mit |
DailyActie/Surrogate-Model | 01-codes/scipy-master/scipy/sparse/sputils.py | 12267 | """ Utility functions for sparse matrix module
"""
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
__all__ = ['upcast', 'getdtype', 'isscalarlike', 'isintlike',
'isshape', 'issequence', 'isdense', 'ismatrix', 'get_sum_dtype']
supported_dtypes = ['bool', 'int8', 'uint8', 'short', 'ushort', 'intc',
'uintc', 'longlong', 'ulonglong', 'single', 'double',
'longdouble', 'csingle', 'cdouble', 'clongdouble']
supported_dtypes = [np.typeDict[x] for x in supported_dtypes]
_upcast_memo = {}
def upcast(*args):
"""Returns the nearest supported sparse dtype for the
combination of one or more types.
upcast(t0, t1, ..., tn) -> T where T is a supported dtype
Examples
--------
>>> upcast('int32')
<type 'numpy.int32'>
>>> upcast('bool')
<type 'numpy.bool_'>
>>> upcast('int32','float32')
<type 'numpy.float64'>
>>> upcast('bool',complex,float)
<type 'numpy.complex128'>
"""
t = _upcast_memo.get(hash(args))
if t is not None:
return t
upcast = np.find_common_type(args, [])
for t in supported_dtypes:
if np.can_cast(upcast, t):
_upcast_memo[hash(args)] = t
return t
raise TypeError('no supported conversion for types: %r' % (args,))
def upcast_char(*args):
"""Same as `upcast` but taking dtype.char as input (faster)."""
t = _upcast_memo.get(args)
if t is not None:
return t
t = upcast(*map(np.dtype, args))
_upcast_memo[args] = t
return t
def upcast_scalar(dtype, scalar):
"""Determine data type for binary operation between an array of
type `dtype` and a scalar.
"""
return (np.array([0], dtype=dtype) * scalar).dtype
def downcast_intp_index(arr):
"""
Down-cast index array to np.intp dtype if it is of a larger dtype.
Raise an error if the array contains a value that is too large for
intp.
"""
if arr.dtype.itemsize > np.dtype(np.intp).itemsize:
if arr.size == 0:
return arr.astype(np.intp)
maxval = arr.max()
minval = arr.min()
if maxval > np.iinfo(np.intp).max or minval < np.iinfo(np.intp).min:
raise ValueError("Cannot deal with arrays with indices larger "
"than the machine maximum address size "
"(e.g. 64-bit indices on 32-bit machine).")
return arr.astype(np.intp)
return arr
def to_native(A):
return np.asarray(A, dtype=A.dtype.newbyteorder('native'))
def getdtype(dtype, a=None, default=None):
"""Function used to simplify argument processing. If 'dtype' is not
specified (is None), returns a.dtype; otherwise returns a np.dtype
object created from the specified dtype argument. If 'dtype' and 'a'
are both None, construct a data type out of the 'default' parameter.
Furthermore, 'dtype' must be in 'allowed' set.
"""
# TODO is this really what we want?
if dtype is None:
try:
newdtype = a.dtype
except AttributeError:
if default is not None:
newdtype = np.dtype(default)
else:
raise TypeError("could not interpret data type")
else:
newdtype = np.dtype(dtype)
if newdtype == np.object_:
warnings.warn("object dtype is not supported by sparse matrices")
return newdtype
def get_index_dtype(arrays=(), maxval=None, check_contents=False):
"""
Based on input (integer) arrays `a`, determine a suitable index data
type that can hold the data in the arrays.
Parameters
----------
arrays : tuple of array_like
Input arrays whose types/contents to check
maxval : float, optional
Maximum value needed
check_contents : bool, optional
Whether to check the values in the arrays and not just their types.
Default: False (check only the types)
Returns
-------
dtype : dtype
Suitable index data type (int32 or int64)
"""
int32max = np.iinfo(np.int32).max
dtype = np.intc
if maxval is not None:
if maxval > int32max:
dtype = np.int64
if isinstance(arrays, np.ndarray):
arrays = (arrays,)
for arr in arrays:
arr = np.asarray(arr)
if arr.dtype > np.int32:
if check_contents:
if arr.size == 0:
# a bigger type not needed
continue
elif np.issubdtype(arr.dtype, np.integer):
maxval = arr.max()
minval = arr.min()
if (minval >= np.iinfo(np.int32).min and
maxval <= np.iinfo(np.int32).max):
# a bigger type not needed
continue
dtype = np.int64
break
return dtype
def get_sum_dtype(dtype):
"""Mimic numpy's casting for np.sum"""
if np.issubdtype(dtype, np.float_):
return np.float_
if dtype.kind == 'u' and np.can_cast(dtype, np.uint):
return np.uint
if np.can_cast(dtype, np.int_):
return np.int_
return dtype
def isscalarlike(x):
"""Is x either a scalar, an array scalar, or a 0-dim array?"""
return np.isscalar(x) or (isdense(x) and x.ndim == 0)
def isintlike(x):
"""Is x appropriate as an index into a sparse matrix? Returns True
if it can be cast safely to a machine int.
"""
if issequence(x):
return False
try:
return bool(int(x) == x)
except (TypeError, ValueError):
return False
def isshape(x):
"""Is x a valid 2-tuple of dimensions?
"""
try:
# Assume it's a tuple of matrix dimensions (M, N)
(M, N) = x
except:
return False
else:
if isintlike(M) and isintlike(N):
if np.ndim(M) == 0 and np.ndim(N) == 0:
return True
return False
def issequence(t):
return ((isinstance(t, (list, tuple)) and
(len(t) == 0 or np.isscalar(t[0]))) or
(isinstance(t, np.ndarray) and (t.ndim == 1)))
def ismatrix(t):
return ((isinstance(t, (list, tuple)) and
len(t) > 0 and issequence(t[0])) or
(isinstance(t, np.ndarray) and t.ndim == 2))
def isdense(x):
return isinstance(x, np.ndarray)
def validateaxis(axis):
if axis is not None:
axis_type = type(axis)
# In NumPy, you can pass in tuples for 'axis', but they are
# not very useful for sparse matrices given their limited
# dimensions, so let's make it explicit that they are not
# allowed to be passed in
if axis_type == tuple:
raise TypeError(("Tuples are not accepted for the 'axis' "
"parameter. Please pass in one of the "
"following: {-2, -1, 0, 1, None}."))
# If not a tuple, check that the provided axis is actually
# an integer and raise a TypeError similar to NumPy's
if not np.issubdtype(np.dtype(axis_type), np.integer):
raise TypeError("axis must be an integer, not {name}"
.format(name=axis_type.__name__))
if not (-2 <= axis <= 1):
raise ValueError("axis out of range")
class IndexMixin(object):
"""
This class simply exists to hold the methods necessary for fancy indexing.
"""
def _slicetoarange(self, j, shape):
""" Given a slice object, use numpy arange to change it to a 1D
array.
"""
start, stop, step = j.indices(shape)
return np.arange(start, stop, step)
def _unpack_index(self, index):
""" Parse index. Always return a tuple of the form (row, col).
Where row/col is a integer, slice, or array of integers.
"""
# First, check if indexing with single boolean matrix.
from .base import spmatrix # This feels dirty but...
if (isinstance(index, (spmatrix, np.ndarray)) and
(index.ndim == 2) and index.dtype.kind == 'b'):
return index.nonzero()
# Parse any ellipses.
index = self._check_ellipsis(index)
# Next, parse the tuple or object
if isinstance(index, tuple):
if len(index) == 2:
row, col = index
elif len(index) == 1:
row, col = index[0], slice(None)
else:
raise IndexError('invalid number of indices')
else:
row, col = index, slice(None)
# Next, check for validity, or transform the index as needed.
row, col = self._check_boolean(row, col)
return row, col
def _check_ellipsis(self, index):
"""Process indices with Ellipsis. Returns modified index."""
if index is Ellipsis:
return (slice(None), slice(None))
elif isinstance(index, tuple):
# Find first ellipsis
for j, v in enumerate(index):
if v is Ellipsis:
first_ellipsis = j
break
else:
first_ellipsis = None
# Expand the first one
if first_ellipsis is not None:
# Shortcuts
if len(index) == 1:
return (slice(None), slice(None))
elif len(index) == 2:
if first_ellipsis == 0:
if index[1] is Ellipsis:
return (slice(None), slice(None))
else:
return (slice(None), index[1])
else:
return (index[0], slice(None))
# General case
tail = ()
for v in index[first_ellipsis + 1:]:
if v is not Ellipsis:
tail = tail + (v,)
nd = first_ellipsis + len(tail)
nslice = max(0, 2 - nd)
return index[:first_ellipsis] + (slice(None),) * nslice + tail
return index
def _check_boolean(self, row, col):
from .base import isspmatrix # ew...
# Supporting sparse boolean indexing with both row and col does
# not work because spmatrix.ndim is always 2.
if isspmatrix(row) or isspmatrix(col):
raise IndexError(
"Indexing with sparse matrices is not supported "
"except boolean indexing where matrix and index "
"are equal shapes.")
if isinstance(row, np.ndarray) and row.dtype.kind == 'b':
row = self._boolean_index_to_array(row)
if isinstance(col, np.ndarray) and col.dtype.kind == 'b':
col = self._boolean_index_to_array(col)
return row, col
def _boolean_index_to_array(self, i):
if i.ndim > 1:
raise IndexError('invalid index shape')
return i.nonzero()[0]
def _index_to_arrays(self, i, j):
i, j = self._check_boolean(i, j)
i_slice = isinstance(i, slice)
if i_slice:
i = self._slicetoarange(i, self.shape[0])[:, None]
else:
i = np.atleast_1d(i)
if isinstance(j, slice):
j = self._slicetoarange(j, self.shape[1])[None, :]
if i.ndim == 1:
i = i[:, None]
elif not i_slice:
raise IndexError('index returns 3-dim structure')
elif isscalarlike(j):
# row vector special case
j = np.atleast_1d(j)
if i.ndim == 1:
i, j = np.broadcast_arrays(i, j)
i = i[:, None]
j = j[:, None]
return i, j
else:
j = np.atleast_1d(j)
if i_slice and j.ndim > 1:
raise IndexError('index returns 3-dim structure')
i, j = np.broadcast_arrays(i, j)
if i.ndim == 1:
# return column vectors for 1-D indexing
i = i[None, :]
j = j[None, :]
elif i.ndim > 2:
raise IndexError("Index dimension must be <= 2")
return i, j
| mit |
medja/notes | js/main.js | 12747 | window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
String.prototype.default = function(value) {
return this == "" ? value : this;
}
String.prototype.escape = function() {
return this.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
};
String.prototype.isNumeric = function() {
return !isNaN(parseFloat(this)) && isFinite(this);
};
String.prototype.list = function() {
if (delimiter == undefined) delimiter = ",";
return this.split(delimiter).map(function(item) {
return item.trim();
}).filter(function(item) { return item != ""; });
};
HTMLElement.prototype.insertAfter = function(element, target) {
this.insertBefore(element, target.nextSibling);
};
HTMLElement.prototype.closest = function(selector) {
var elements = Array.prototype.slice.call(document.querySelectorAll(selector));
var element = this;
while (element != null && elements.indexOf(element) < 0)
element = element.parentElement;
return element;
};
HTMLElement.prototype.index = function() {
return Array.prototype.slice.call(this.parentElement.children).indexOf(this);
};
if (!HTMLElement.prototype.remove) {
HTMLElement.prototype.remove = function() {
this.parentElement.removeChild(this);
};
}
String.prototype.repeat = function(count) {
return new Array(count + 1).join(this);
};
Number.prototype.format = function(length) {
var value = this.toString();
return ("0".repeat(Math.max(0, length - value.length)) + value).substr(-length);
};
Date.ISO = "YYYY-MM-DDTHH:mm:ssZ";
Date.prototype.format = function(format, utc) {
if (utc == null) utc = format[format.length - 1] == "Z";
var regex = /[YMDHhms]{1,4}/g;
var time = format;
while (match = regex.exec(format)) {
var match = match[0],
type = match[0];
time = time.replace(match, (
type == "Y" ? (utc ? this.getUTCFullYear() : this.getFullYear()) :
type == "M" ? (utc ? this.getUTCMonth() : this.getMonth()) + 1 :
type == "D" ? (utc ? this.getUTCDate() : this.getDate()) :
type == "H" ? (utc ? this.getUTCHours() : this.getHours()) :
type == "h" ? ((utc ? this.getUTCHours() : this.getHours()) - 1) % 12 + 1 :
type == "m" ? (utc ? this.getUTCMinutes() : this.getMinutes()) :
type == "s" ? (utc ? this.getUTCSeconds() : this.getSeconds()) :
"").format(match.length));
}
return time;
};
if (!Array.prototype.findIndex) {
Array.prototype.findIndex = function(callback, scope) {
for (var i = 0; i < this.length; i++) {
if (i in this && callback.call(scope, this[i], i, this)) {
return i;
}
}
return -1;
};
}
(function() {
var markdown = (function() {
var parse = function(markdown) {
var html = "";
var matches = (markdown.replace(/\t/g, " ") + "\n\n").match(/(.*\n)+?\n+/g);
for (var i = 0; i < matches.length; i++) {
var block = matches[i];
if (block[0] === ">") {
html += "<blockquote>" + parse(block.replace(
/^(?:>|\s)?\s?/gm, "")) + "</blockquote>";
} else if (match = /^(#{1,5})\s+(.*)\n/.exec(block)) {
var tag = "h" + (match[1].length + 1);
html += "<" + tag + ">" + inline(match[2]) + "</" + tag + ">";
} else if (block.match(/^\s{4}/)) {
html += "<code>" + block.trim()
.replace(/^\s{4}/gm, "").escape() + "</code>";
} else if (match = /^\s?(\*|\+|\-|\d+\.)\s/.exec(block)) {
var tag, item, regex = match[0][0] === " " ? "\\s" : "";
if (match[1][0].isNumeric()) {
tag = "ol";
regex += "\\d+\\.";
} else {
tag = "ul";
regex += "[\\*\\+\\-]";
};
if (match[0][match[0].length - 1] === " ")
regex += "\\s";
html += "<" + tag + ">";
var regexp = new RegExp(regex + "(.*\\n)+?(?=" + regex + "|$)", "g");
while (item = regexp.exec(block)) {
html += "<li>";
if (match = new RegExp("^" + regex + "\\s*(.*?)\\n?\\s*$").exec(item[0])) {
html += inline(match[1]);
} else {
var match = new RegExp("^"
+ regex, "g").exec(item);
html += parse(item[0].replace(
new RegExp("^(?:" + regex
+ "|\\s{0," + match[0].length + "})", "gm"), ""));
};
html += "</li>";
};
html += "</" + tag + ">";
} else {
html += "<p>" + inline(block) + "</p>";
};
};
return html;
},
inline = function(markdown) {
return markdown.trim().escape()
.replace(/\s{2,}$/gm, "<br>")
.replace(/(?:\*|\_){2}((?:.|\n)*?)(?:\*|\_){2}/g, "<strong>$1</strong>")
.replace(/(?:\*|\_)((?:.|\n)*?)(?:\*|\_)/g, "<em>$1</em>")
.replace(/`((?:.|\n)*?)`/g, "<code>$1</code>")
.replace(/\!\[(.*?)\]\((.+?)(?:\s+"(.*?)")?\)/g,
"<img src=\"$2\" alt=\"$1\" title=\"$3\">")
.replace(/\[(.*?)\]\((.+?)(?:\s+"(.*?)")?\)/g,
"<a href=\"$2\" title=\"$3\">$1</a>");
};
return parse;
})();
var app = function(db) {
var aside = document.querySelector("aside"),
note = document.querySelector("#note"),
source = document.querySelector("#source textarea"),
preview = document.querySelector("#preview"),
title = document.querySelector("header input"),
settings = document.querySelector("#settings"),
item, store = [], saving = false, created = false,
display = function(note) {
var index = Math.max(store.findIndex(function(time) {
return time < note.time;
}), 0);
store.splice(index, 0, note.time);
var element = document.createElement("article");
var title = document.createElement("h1");
title.innerHTML = note.title.escape();
element.appendChild(title);
var time = document.createElement("time");
var date = new Date(note.time);
time.setAttribute("datetime", date.format(Date.ISO));
time.innerHTML = date.format("HH:mm DD/MM/YYYY");
element.appendChild(time);
aside.insertAfter(element, aside.children[index]);
},
fetch = function() {
var update = {
title: title.value.trim().default(title.placeholder),
content: source.value,
tags: []
};
if (item != null) update.id = item.id;
return update;
},
scroll = (function() {
var ignore = false;
return function(from, to) {
ignore = !ignore;
if (ignore) {
var diff = from.scrollHeight - from.clientHeight;
if (diff > 0) {
to.scrollTop = from.scrollTop *
(to.scrollHeight - to.clientHeight) / diff;
} else if (from.nodeName == "TEXTAREA") {
to.scrollTop = from.selectionEnd *
(to.scrollHeight - to.clientHeight) / from.value.length;
}
}
};
})();
this.find = function(args, callback) {
if (callback == undefined) {
callback = args;
args = null; }
var list = [];
var keys = args == null ? [] : Object.keys(args);
db.transaction("notes").objectStore("notes").openCursor().onsuccess = function() {
var cursor = event.target.result;
if (cursor) {
var item = cursor.value;
keys.every(function(key) {
return args[key] == item[key];
}) && list.push(item);
cursor.continue();
} else callback.call(null, list);
};
};
this.get = function(item, callback) {
db.transaction("notes").objectStore("notes").get(item).onsuccess = function(event) {
callback.call(null, event.target.result);
};
};
this.add = function(item, callback) {
item.time = item.time || new Date().getTime();
item.id = item.id || item.time;
db.transaction("notes", "readwrite").objectStore("notes").add(item).onsuccess = function() {
display(item);
if (callback != undefined) callback.call(null, item);
};
};
this.remove = function(item, callback) {
aside.children[store.indexOf(item) + 1].remove();
store.splice(store.indexOf(item), 1);
db.transaction("notes", "readwrite").objectStore("notes").delete(item).onsuccess = function() {
if (callback != undefined) callback.call(null);
};
};
this.update = function(item, update, callback) {
this.remove(item, function() {
this.add(update, callback);
}.bind(this));
};
this.open = function(id) {
if (id == undefined) return note.innerHTML = "";
this.get(id, function(item) {
note.scrollTop = 0;
note.innerHTML = "<h1>" + item.title + "</h1>" + markdown(item.content);
});
if (elm = document.querySelector("aside article.open"))
elm.classList.remove("open");
document.querySelector("aside article:nth-child("
+ (store.indexOf(id) + 2) + ")").classList.add("open");
};
this.new = function() {
item = null;
title.value = "";
source.value = "";
preview.innerHTML = "";
document.body.classList.add("edit");
};
this.edit = function(id) {
this.get(id, function(note) {
item = note;
title.value = item.title;
source.value = item.content;
preview.innerHTML = markdown(item.content);
});
document.body.classList.add("edit");
};
this.save = function(callback) {
if (!saving) {
saving = true;
var complete = function(update) {
item = update;
saving = false;
if (callback != undefined) callback.call(null, update);
}.bind(this);
if (item == null) {
created = true;
this.add(fetch(), complete);
} else {
this.update(item.time, fetch(), complete);
}
}
};
this.close = function() {
if (created) this.open(store[0]);
document.body.classList.remove("edit");
};
this.import = function(notes) {
if (notes instanceof String || !notes instanceof Object)
notes = JSON.parse(notes);
if (!(notes instanceof Array)) notes = [notes];
notes.forEach(function(note) {
this.add(note);
}.bind(this));
};
this.export = function(id, callback) {
if (callback == undefined) {
callback = id;
id = null; }
if (id == null) {
this.find(function(notes) {
callback.call(null, JSON.stringify(notes));
});
} else {
this.get(id, function(note) {
callback.call(null, JSON.stringify(note));
});
}
};
aside.addEventListener("click", function(event) {
if (event.target.nodeName == "H2") {
this.new();
} else if (element = event.target.closest("aside article")) {
if (window.innerWidth <= 800) document.body.classList.add("open");
this.open(store[element.index() - 1]);
}
}.bind(this));
document.querySelector("#edit").addEventListener("click", function() {
var element = document.querySelector("aside article.open");
if (element !== null) this.edit(store[element.index() - 1]);
}.bind(this));
source.addEventListener("input", function(event) {
preview.innerHTML = markdown(source.value);
if (source.value.length - source.selectionEnd === 0)
source.scrollTop = source.scrollHeight - source.clientHeight;
scroll(source, preview);
this.save();
}.bind(this));
title.addEventListener("input", function(event) {
this.save();
}.bind(this));
source.addEventListener("scroll", function() {
scroll(source, preview);
});
preview.addEventListener("scroll", function() {
scroll(preview, source);
});
document.querySelector("#back").addEventListener("click", function() {
document.body.classList.remove("open");
this.close();
}.bind(this));
document.querySelector("#delete").addEventListener("click", function() {
var element = document.querySelector("aside article.open");
if (element !== null) {
this.remove(store[element.index() - 1]);
this.close();
this.open(store[0]);
aside.scrollTop = 0;
}
}.bind(this));
(function() {
var time, start, end;
window.addEventListener("touchstart", function(event) {
time = new Date().getTime();
start = [event.touches[0].clientX, event.touches[0].clientY];
end = null;
});
window.addEventListener("touchmove", function(event) {
event.preventDefault();
end = [event.touches[0].clientX, event.touches[0].clientY];
});
window.addEventListener("touchend", function(event) {
if (end != null) {
var move = end[0] - start[0];
if (Math.abs(move / (new Date().getTime() - time)) > 0.35
&& move > 160 && Math.abs(y = end[1] - start[1]) < 100) {
this.close();
}
}
}.bind(this));
}.bind(this))();
window.addEventListener("resize", function() {
if (window.innerWidth > 800) document.body.classList.remove("open");
});
this.find(function(notes) {
notes.forEach(display);
this.open(store[0]);
}.bind(this));
};
var request = window.indexedDB.open("notes", 1);
request.onupgradeneeded = function() {
request.result.createObjectStore("notes", { keyPath: "time" });
};
request.onsuccess = function() {
window.notes = new app(request.result);
};
})(); | mit |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_10_01/_network_management_client.py | 29817 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
from azure.mgmt.core import ARMPipelineClient
from msrest import Deserializer, Serializer
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Optional
from azure.core.credentials import TokenCredential
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from ._configuration import NetworkManagementClientConfiguration
from .operations import ApplicationGatewaysOperations
from .operations import ApplicationSecurityGroupsOperations
from .operations import AvailableDelegationsOperations
from .operations import AvailableResourceGroupDelegationsOperations
from .operations import AzureFirewallsOperations
from .operations import AzureFirewallFqdnTagsOperations
from .operations import NetworkManagementClientOperationsMixin
from .operations import DdosProtectionPlansOperations
from .operations import AvailableEndpointServicesOperations
from .operations import ExpressRouteCircuitAuthorizationsOperations
from .operations import ExpressRouteCircuitPeeringsOperations
from .operations import ExpressRouteCircuitConnectionsOperations
from .operations import ExpressRouteCircuitsOperations
from .operations import ExpressRouteServiceProvidersOperations
from .operations import ExpressRouteCrossConnectionsOperations
from .operations import ExpressRouteCrossConnectionPeeringsOperations
from .operations import ExpressRouteGatewaysOperations
from .operations import ExpressRouteConnectionsOperations
from .operations import ExpressRoutePortsLocationsOperations
from .operations import ExpressRoutePortsOperations
from .operations import ExpressRouteLinksOperations
from .operations import InterfaceEndpointsOperations
from .operations import LoadBalancersOperations
from .operations import LoadBalancerBackendAddressPoolsOperations
from .operations import LoadBalancerFrontendIPConfigurationsOperations
from .operations import InboundNatRulesOperations
from .operations import LoadBalancerLoadBalancingRulesOperations
from .operations import LoadBalancerOutboundRulesOperations
from .operations import LoadBalancerNetworkInterfacesOperations
from .operations import LoadBalancerProbesOperations
from .operations import NetworkInterfacesOperations
from .operations import NetworkInterfaceIPConfigurationsOperations
from .operations import NetworkInterfaceLoadBalancersOperations
from .operations import NetworkInterfaceTapConfigurationsOperations
from .operations import NetworkProfilesOperations
from .operations import NetworkSecurityGroupsOperations
from .operations import SecurityRulesOperations
from .operations import DefaultSecurityRulesOperations
from .operations import NetworkWatchersOperations
from .operations import PacketCapturesOperations
from .operations import ConnectionMonitorsOperations
from .operations import Operations
from .operations import PublicIPAddressesOperations
from .operations import PublicIPPrefixesOperations
from .operations import RouteFiltersOperations
from .operations import RouteFilterRulesOperations
from .operations import RouteTablesOperations
from .operations import RoutesOperations
from .operations import BgpServiceCommunitiesOperations
from .operations import ServiceEndpointPoliciesOperations
from .operations import ServiceEndpointPolicyDefinitionsOperations
from .operations import UsagesOperations
from .operations import VirtualNetworksOperations
from .operations import SubnetsOperations
from .operations import VirtualNetworkPeeringsOperations
from .operations import VirtualNetworkGatewaysOperations
from .operations import VirtualNetworkGatewayConnectionsOperations
from .operations import LocalNetworkGatewaysOperations
from .operations import VirtualNetworkTapsOperations
from .operations import VirtualWansOperations
from .operations import VpnSitesOperations
from .operations import VpnSitesConfigurationOperations
from .operations import VirtualHubsOperations
from .operations import HubVirtualNetworkConnectionsOperations
from .operations import VpnGatewaysOperations
from .operations import VpnConnectionsOperations
from .operations import P2SVpnServerConfigurationsOperations
from .operations import P2SVpnGatewaysOperations
from . import models
class NetworkManagementClient(NetworkManagementClientOperationsMixin):
"""Network Client.
:ivar application_gateways: ApplicationGatewaysOperations operations
:vartype application_gateways: azure.mgmt.network.v2018_10_01.operations.ApplicationGatewaysOperations
:ivar application_security_groups: ApplicationSecurityGroupsOperations operations
:vartype application_security_groups: azure.mgmt.network.v2018_10_01.operations.ApplicationSecurityGroupsOperations
:ivar available_delegations: AvailableDelegationsOperations operations
:vartype available_delegations: azure.mgmt.network.v2018_10_01.operations.AvailableDelegationsOperations
:ivar available_resource_group_delegations: AvailableResourceGroupDelegationsOperations operations
:vartype available_resource_group_delegations: azure.mgmt.network.v2018_10_01.operations.AvailableResourceGroupDelegationsOperations
:ivar azure_firewalls: AzureFirewallsOperations operations
:vartype azure_firewalls: azure.mgmt.network.v2018_10_01.operations.AzureFirewallsOperations
:ivar azure_firewall_fqdn_tags: AzureFirewallFqdnTagsOperations operations
:vartype azure_firewall_fqdn_tags: azure.mgmt.network.v2018_10_01.operations.AzureFirewallFqdnTagsOperations
:ivar ddos_protection_plans: DdosProtectionPlansOperations operations
:vartype ddos_protection_plans: azure.mgmt.network.v2018_10_01.operations.DdosProtectionPlansOperations
:ivar available_endpoint_services: AvailableEndpointServicesOperations operations
:vartype available_endpoint_services: azure.mgmt.network.v2018_10_01.operations.AvailableEndpointServicesOperations
:ivar express_route_circuit_authorizations: ExpressRouteCircuitAuthorizationsOperations operations
:vartype express_route_circuit_authorizations: azure.mgmt.network.v2018_10_01.operations.ExpressRouteCircuitAuthorizationsOperations
:ivar express_route_circuit_peerings: ExpressRouteCircuitPeeringsOperations operations
:vartype express_route_circuit_peerings: azure.mgmt.network.v2018_10_01.operations.ExpressRouteCircuitPeeringsOperations
:ivar express_route_circuit_connections: ExpressRouteCircuitConnectionsOperations operations
:vartype express_route_circuit_connections: azure.mgmt.network.v2018_10_01.operations.ExpressRouteCircuitConnectionsOperations
:ivar express_route_circuits: ExpressRouteCircuitsOperations operations
:vartype express_route_circuits: azure.mgmt.network.v2018_10_01.operations.ExpressRouteCircuitsOperations
:ivar express_route_service_providers: ExpressRouteServiceProvidersOperations operations
:vartype express_route_service_providers: azure.mgmt.network.v2018_10_01.operations.ExpressRouteServiceProvidersOperations
:ivar express_route_cross_connections: ExpressRouteCrossConnectionsOperations operations
:vartype express_route_cross_connections: azure.mgmt.network.v2018_10_01.operations.ExpressRouteCrossConnectionsOperations
:ivar express_route_cross_connection_peerings: ExpressRouteCrossConnectionPeeringsOperations operations
:vartype express_route_cross_connection_peerings: azure.mgmt.network.v2018_10_01.operations.ExpressRouteCrossConnectionPeeringsOperations
:ivar express_route_gateways: ExpressRouteGatewaysOperations operations
:vartype express_route_gateways: azure.mgmt.network.v2018_10_01.operations.ExpressRouteGatewaysOperations
:ivar express_route_connections: ExpressRouteConnectionsOperations operations
:vartype express_route_connections: azure.mgmt.network.v2018_10_01.operations.ExpressRouteConnectionsOperations
:ivar express_route_ports_locations: ExpressRoutePortsLocationsOperations operations
:vartype express_route_ports_locations: azure.mgmt.network.v2018_10_01.operations.ExpressRoutePortsLocationsOperations
:ivar express_route_ports: ExpressRoutePortsOperations operations
:vartype express_route_ports: azure.mgmt.network.v2018_10_01.operations.ExpressRoutePortsOperations
:ivar express_route_links: ExpressRouteLinksOperations operations
:vartype express_route_links: azure.mgmt.network.v2018_10_01.operations.ExpressRouteLinksOperations
:ivar interface_endpoints: InterfaceEndpointsOperations operations
:vartype interface_endpoints: azure.mgmt.network.v2018_10_01.operations.InterfaceEndpointsOperations
:ivar load_balancers: LoadBalancersOperations operations
:vartype load_balancers: azure.mgmt.network.v2018_10_01.operations.LoadBalancersOperations
:ivar load_balancer_backend_address_pools: LoadBalancerBackendAddressPoolsOperations operations
:vartype load_balancer_backend_address_pools: azure.mgmt.network.v2018_10_01.operations.LoadBalancerBackendAddressPoolsOperations
:ivar load_balancer_frontend_ip_configurations: LoadBalancerFrontendIPConfigurationsOperations operations
:vartype load_balancer_frontend_ip_configurations: azure.mgmt.network.v2018_10_01.operations.LoadBalancerFrontendIPConfigurationsOperations
:ivar inbound_nat_rules: InboundNatRulesOperations operations
:vartype inbound_nat_rules: azure.mgmt.network.v2018_10_01.operations.InboundNatRulesOperations
:ivar load_balancer_load_balancing_rules: LoadBalancerLoadBalancingRulesOperations operations
:vartype load_balancer_load_balancing_rules: azure.mgmt.network.v2018_10_01.operations.LoadBalancerLoadBalancingRulesOperations
:ivar load_balancer_outbound_rules: LoadBalancerOutboundRulesOperations operations
:vartype load_balancer_outbound_rules: azure.mgmt.network.v2018_10_01.operations.LoadBalancerOutboundRulesOperations
:ivar load_balancer_network_interfaces: LoadBalancerNetworkInterfacesOperations operations
:vartype load_balancer_network_interfaces: azure.mgmt.network.v2018_10_01.operations.LoadBalancerNetworkInterfacesOperations
:ivar load_balancer_probes: LoadBalancerProbesOperations operations
:vartype load_balancer_probes: azure.mgmt.network.v2018_10_01.operations.LoadBalancerProbesOperations
:ivar network_interfaces: NetworkInterfacesOperations operations
:vartype network_interfaces: azure.mgmt.network.v2018_10_01.operations.NetworkInterfacesOperations
:ivar network_interface_ip_configurations: NetworkInterfaceIPConfigurationsOperations operations
:vartype network_interface_ip_configurations: azure.mgmt.network.v2018_10_01.operations.NetworkInterfaceIPConfigurationsOperations
:ivar network_interface_load_balancers: NetworkInterfaceLoadBalancersOperations operations
:vartype network_interface_load_balancers: azure.mgmt.network.v2018_10_01.operations.NetworkInterfaceLoadBalancersOperations
:ivar network_interface_tap_configurations: NetworkInterfaceTapConfigurationsOperations operations
:vartype network_interface_tap_configurations: azure.mgmt.network.v2018_10_01.operations.NetworkInterfaceTapConfigurationsOperations
:ivar network_profiles: NetworkProfilesOperations operations
:vartype network_profiles: azure.mgmt.network.v2018_10_01.operations.NetworkProfilesOperations
:ivar network_security_groups: NetworkSecurityGroupsOperations operations
:vartype network_security_groups: azure.mgmt.network.v2018_10_01.operations.NetworkSecurityGroupsOperations
:ivar security_rules: SecurityRulesOperations operations
:vartype security_rules: azure.mgmt.network.v2018_10_01.operations.SecurityRulesOperations
:ivar default_security_rules: DefaultSecurityRulesOperations operations
:vartype default_security_rules: azure.mgmt.network.v2018_10_01.operations.DefaultSecurityRulesOperations
:ivar network_watchers: NetworkWatchersOperations operations
:vartype network_watchers: azure.mgmt.network.v2018_10_01.operations.NetworkWatchersOperations
:ivar packet_captures: PacketCapturesOperations operations
:vartype packet_captures: azure.mgmt.network.v2018_10_01.operations.PacketCapturesOperations
:ivar connection_monitors: ConnectionMonitorsOperations operations
:vartype connection_monitors: azure.mgmt.network.v2018_10_01.operations.ConnectionMonitorsOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.network.v2018_10_01.operations.Operations
:ivar public_ip_addresses: PublicIPAddressesOperations operations
:vartype public_ip_addresses: azure.mgmt.network.v2018_10_01.operations.PublicIPAddressesOperations
:ivar public_ip_prefixes: PublicIPPrefixesOperations operations
:vartype public_ip_prefixes: azure.mgmt.network.v2018_10_01.operations.PublicIPPrefixesOperations
:ivar route_filters: RouteFiltersOperations operations
:vartype route_filters: azure.mgmt.network.v2018_10_01.operations.RouteFiltersOperations
:ivar route_filter_rules: RouteFilterRulesOperations operations
:vartype route_filter_rules: azure.mgmt.network.v2018_10_01.operations.RouteFilterRulesOperations
:ivar route_tables: RouteTablesOperations operations
:vartype route_tables: azure.mgmt.network.v2018_10_01.operations.RouteTablesOperations
:ivar routes: RoutesOperations operations
:vartype routes: azure.mgmt.network.v2018_10_01.operations.RoutesOperations
:ivar bgp_service_communities: BgpServiceCommunitiesOperations operations
:vartype bgp_service_communities: azure.mgmt.network.v2018_10_01.operations.BgpServiceCommunitiesOperations
:ivar service_endpoint_policies: ServiceEndpointPoliciesOperations operations
:vartype service_endpoint_policies: azure.mgmt.network.v2018_10_01.operations.ServiceEndpointPoliciesOperations
:ivar service_endpoint_policy_definitions: ServiceEndpointPolicyDefinitionsOperations operations
:vartype service_endpoint_policy_definitions: azure.mgmt.network.v2018_10_01.operations.ServiceEndpointPolicyDefinitionsOperations
:ivar usages: UsagesOperations operations
:vartype usages: azure.mgmt.network.v2018_10_01.operations.UsagesOperations
:ivar virtual_networks: VirtualNetworksOperations operations
:vartype virtual_networks: azure.mgmt.network.v2018_10_01.operations.VirtualNetworksOperations
:ivar subnets: SubnetsOperations operations
:vartype subnets: azure.mgmt.network.v2018_10_01.operations.SubnetsOperations
:ivar virtual_network_peerings: VirtualNetworkPeeringsOperations operations
:vartype virtual_network_peerings: azure.mgmt.network.v2018_10_01.operations.VirtualNetworkPeeringsOperations
:ivar virtual_network_gateways: VirtualNetworkGatewaysOperations operations
:vartype virtual_network_gateways: azure.mgmt.network.v2018_10_01.operations.VirtualNetworkGatewaysOperations
:ivar virtual_network_gateway_connections: VirtualNetworkGatewayConnectionsOperations operations
:vartype virtual_network_gateway_connections: azure.mgmt.network.v2018_10_01.operations.VirtualNetworkGatewayConnectionsOperations
:ivar local_network_gateways: LocalNetworkGatewaysOperations operations
:vartype local_network_gateways: azure.mgmt.network.v2018_10_01.operations.LocalNetworkGatewaysOperations
:ivar virtual_network_taps: VirtualNetworkTapsOperations operations
:vartype virtual_network_taps: azure.mgmt.network.v2018_10_01.operations.VirtualNetworkTapsOperations
:ivar virtual_wans: VirtualWansOperations operations
:vartype virtual_wans: azure.mgmt.network.v2018_10_01.operations.VirtualWansOperations
:ivar vpn_sites: VpnSitesOperations operations
:vartype vpn_sites: azure.mgmt.network.v2018_10_01.operations.VpnSitesOperations
:ivar vpn_sites_configuration: VpnSitesConfigurationOperations operations
:vartype vpn_sites_configuration: azure.mgmt.network.v2018_10_01.operations.VpnSitesConfigurationOperations
:ivar virtual_hubs: VirtualHubsOperations operations
:vartype virtual_hubs: azure.mgmt.network.v2018_10_01.operations.VirtualHubsOperations
:ivar hub_virtual_network_connections: HubVirtualNetworkConnectionsOperations operations
:vartype hub_virtual_network_connections: azure.mgmt.network.v2018_10_01.operations.HubVirtualNetworkConnectionsOperations
:ivar vpn_gateways: VpnGatewaysOperations operations
:vartype vpn_gateways: azure.mgmt.network.v2018_10_01.operations.VpnGatewaysOperations
:ivar vpn_connections: VpnConnectionsOperations operations
:vartype vpn_connections: azure.mgmt.network.v2018_10_01.operations.VpnConnectionsOperations
:ivar p2_svpn_server_configurations: P2SVpnServerConfigurationsOperations operations
:vartype p2_svpn_server_configurations: azure.mgmt.network.v2018_10_01.operations.P2SVpnServerConfigurationsOperations
:ivar p2_svpn_gateways: P2SVpnGatewaysOperations operations
:vartype p2_svpn_gateways: azure.mgmt.network.v2018_10_01.operations.P2SVpnGatewaysOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.
:type subscription_id: str
:param str base_url: Service URL
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
"""
def __init__(
self,
credential, # type: "TokenCredential"
subscription_id, # type: str
base_url=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> None
if not base_url:
base_url = 'https://management.azure.com'
self._config = NetworkManagementClientConfiguration(credential, subscription_id, **kwargs)
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._serialize.client_side_validation = False
self._deserialize = Deserializer(client_models)
self.application_gateways = ApplicationGatewaysOperations(
self._client, self._config, self._serialize, self._deserialize)
self.application_security_groups = ApplicationSecurityGroupsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.available_delegations = AvailableDelegationsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.available_resource_group_delegations = AvailableResourceGroupDelegationsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.azure_firewalls = AzureFirewallsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.azure_firewall_fqdn_tags = AzureFirewallFqdnTagsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.ddos_protection_plans = DdosProtectionPlansOperations(
self._client, self._config, self._serialize, self._deserialize)
self.available_endpoint_services = AvailableEndpointServicesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_circuit_authorizations = ExpressRouteCircuitAuthorizationsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_circuit_peerings = ExpressRouteCircuitPeeringsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_circuit_connections = ExpressRouteCircuitConnectionsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_circuits = ExpressRouteCircuitsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_service_providers = ExpressRouteServiceProvidersOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_cross_connections = ExpressRouteCrossConnectionsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_cross_connection_peerings = ExpressRouteCrossConnectionPeeringsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_gateways = ExpressRouteGatewaysOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_connections = ExpressRouteConnectionsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_ports_locations = ExpressRoutePortsLocationsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_ports = ExpressRoutePortsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.express_route_links = ExpressRouteLinksOperations(
self._client, self._config, self._serialize, self._deserialize)
self.interface_endpoints = InterfaceEndpointsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.load_balancers = LoadBalancersOperations(
self._client, self._config, self._serialize, self._deserialize)
self.load_balancer_backend_address_pools = LoadBalancerBackendAddressPoolsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.load_balancer_frontend_ip_configurations = LoadBalancerFrontendIPConfigurationsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.inbound_nat_rules = InboundNatRulesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.load_balancer_load_balancing_rules = LoadBalancerLoadBalancingRulesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.load_balancer_outbound_rules = LoadBalancerOutboundRulesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.load_balancer_network_interfaces = LoadBalancerNetworkInterfacesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.load_balancer_probes = LoadBalancerProbesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.network_interfaces = NetworkInterfacesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.network_interface_ip_configurations = NetworkInterfaceIPConfigurationsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.network_interface_load_balancers = NetworkInterfaceLoadBalancersOperations(
self._client, self._config, self._serialize, self._deserialize)
self.network_interface_tap_configurations = NetworkInterfaceTapConfigurationsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.network_profiles = NetworkProfilesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.network_security_groups = NetworkSecurityGroupsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.security_rules = SecurityRulesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.default_security_rules = DefaultSecurityRulesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.network_watchers = NetworkWatchersOperations(
self._client, self._config, self._serialize, self._deserialize)
self.packet_captures = PacketCapturesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.connection_monitors = ConnectionMonitorsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(
self._client, self._config, self._serialize, self._deserialize)
self.public_ip_addresses = PublicIPAddressesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.public_ip_prefixes = PublicIPPrefixesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.route_filters = RouteFiltersOperations(
self._client, self._config, self._serialize, self._deserialize)
self.route_filter_rules = RouteFilterRulesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.route_tables = RouteTablesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.routes = RoutesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.bgp_service_communities = BgpServiceCommunitiesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.service_endpoint_policies = ServiceEndpointPoliciesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.service_endpoint_policy_definitions = ServiceEndpointPolicyDefinitionsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.usages = UsagesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.virtual_networks = VirtualNetworksOperations(
self._client, self._config, self._serialize, self._deserialize)
self.subnets = SubnetsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.virtual_network_peerings = VirtualNetworkPeeringsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.virtual_network_gateways = VirtualNetworkGatewaysOperations(
self._client, self._config, self._serialize, self._deserialize)
self.virtual_network_gateway_connections = VirtualNetworkGatewayConnectionsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.local_network_gateways = LocalNetworkGatewaysOperations(
self._client, self._config, self._serialize, self._deserialize)
self.virtual_network_taps = VirtualNetworkTapsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.virtual_wans = VirtualWansOperations(
self._client, self._config, self._serialize, self._deserialize)
self.vpn_sites = VpnSitesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.vpn_sites_configuration = VpnSitesConfigurationOperations(
self._client, self._config, self._serialize, self._deserialize)
self.virtual_hubs = VirtualHubsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.hub_virtual_network_connections = HubVirtualNetworkConnectionsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.vpn_gateways = VpnGatewaysOperations(
self._client, self._config, self._serialize, self._deserialize)
self.vpn_connections = VpnConnectionsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.p2_svpn_server_configurations = P2SVpnServerConfigurationsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.p2_svpn_gateways = P2SVpnGatewaysOperations(
self._client, self._config, self._serialize, self._deserialize)
def _send_request(self, http_request, **kwargs):
# type: (HttpRequest, Any) -> HttpResponse
"""Runs the network request through the client's chained policies.
:param http_request: The network request you want to make. Required.
:type http_request: ~azure.core.pipeline.transport.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to True.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.pipeline.transport.HttpResponse
"""
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
http_request.url = self._client.format_url(http_request.url, **path_format_arguments)
stream = kwargs.pop("stream", True)
pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs)
return pipeline_response.http_response
def close(self):
# type: () -> None
self._client.close()
def __enter__(self):
# type: () -> NetworkManagementClient
self._client.__enter__()
return self
def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
| mit |
adames/coledatchi | app/controllers/sessions_controller.rb | 485 | class SessionsController < ApplicationController
def new
@user
end
def create
#lets look up a user
@user = User.find_by(email: params[:email])
if @user && @user.authenticate(params[:password])
session[:user_id] = @user.id
redirect_to user_path(@user)
# let them in redirect_to some page
else
# couldnt log in
render :new
end
end
def destroy
session[:user_id] = nil
redirect_to login_path
end
end
| mit |
antigremlin/ember.js | packages/ember-htmlbars/tests/integration/binding_integration_test.js | 5035 | import run from 'ember-metal/run_loop';
import jQuery from 'ember-views/system/jquery';
import EmberView from 'ember-views/views/view';
import { Binding } from 'ember-metal/binding';
import EmberObject from 'ember-runtime/system/object';
import { computed } from 'ember-metal/computed';
import ContainerView from 'ember-views/views/container_view';
import compile from 'ember-template-compiler/system/compile';
import { runAppend, runDestroy } from 'ember-runtime/tests/utils';
import { registerHelper } from 'ember-htmlbars/helpers';
import { set } from 'ember-metal/property_set';
var view, MyApp, originalLookup, lookup;
var trim = jQuery.trim;
QUnit.module('ember-htmlbars: binding integration', {
setup() {
originalLookup = Ember.lookup;
Ember.lookup = lookup = {};
MyApp = lookup.MyApp = EmberObject.create({});
},
teardown() {
Ember.lookup = originalLookup;
runDestroy(view);
view = null;
MyApp = null;
}
});
QUnit.test('should call a registered helper for mustache without parameters', function() {
registerHelper('foobar', function() {
return 'foobar';
});
view = EmberView.create({
template: compile('{{foobar}}')
});
runAppend(view);
ok(view.$().text() === 'foobar', 'Regular helper was invoked correctly');
});
QUnit.test('should bind to the property if no registered helper found for a mustache without parameters', function() {
view = EmberView.createWithMixins({
template: compile('{{view.foobarProperty}}'),
foobarProperty: computed(function() {
return 'foobarProperty';
})
});
runAppend(view);
ok(view.$().text() === 'foobarProperty', 'Property was bound to correctly');
});
QUnit.test('should be able to update when bound property updates', function() {
MyApp.set('controller', EmberObject.create({ name: 'first' }));
var View = EmberView.extend({
template: compile('<i>{{view.value.name}}, {{view.computed}}</i>'),
valueBinding: 'MyApp.controller',
computed: computed(function() {
return this.get('value.name') + ' - computed';
}).property('value')
});
run(function() {
view = View.create();
});
runAppend(view);
run(function() {
MyApp.set('controller', EmberObject.create({
name: 'second'
}));
});
equal(view.get('computed'), 'second - computed', 'view computed properties correctly update');
equal(view.$('i').text(), 'second, second - computed', 'view rerenders when bound properties change');
});
QUnit.test('should allow rendering of undefined props', function() {
view = EmberView.create({
template: compile('{{name}}')
});
runAppend(view);
equal(view.$().text(), '', 'rendered undefined binding');
});
QUnit.test('should cleanup bound properties on rerender', function() {
view = EmberView.create({
controller: EmberObject.create({ name: 'wycats' }),
template: compile('{{name}}')
});
runAppend(view);
equal(view.$().text(), 'wycats', 'rendered binding');
run(view, 'rerender');
equal(view.$().text(), 'wycats', 'rendered binding');
});
QUnit.test('should update bound values after view\'s parent is removed and then re-appended', function() {
expectDeprecation('Setting `childViews` on a Container is deprecated.');
var controller = EmberObject.create();
var parentView = ContainerView.create({
childViews: ['testView'],
controller: controller,
testView: EmberView.create({
template: compile('{{#if showStuff}}{{boundValue}}{{else}}Not true.{{/if}}')
})
});
controller.setProperties({
showStuff: true,
boundValue: 'foo'
});
runAppend(parentView);
view = parentView.get('testView');
equal(trim(view.$().text()), 'foo');
run(function() {
set(controller, 'showStuff', false);
});
equal(trim(view.$().text()), 'Not true.');
run(function() {
set(controller, 'showStuff', true);
});
equal(trim(view.$().text()), 'foo');
run(function() {
parentView.remove();
set(controller, 'showStuff', false);
});
run(function() {
set(controller, 'showStuff', true);
});
runAppend(parentView);
run(function() {
set(controller, 'boundValue', 'bar');
});
equal(trim(view.$().text()), 'bar');
runDestroy(parentView);
});
QUnit.test('should accept bindings as a string or an Ember.Binding', function() {
var ViewWithBindings = EmberView.extend({
oneWayBindingTestBinding: Binding.oneWay('context.direction'),
twoWayBindingTestBinding: Binding.from('context.direction'),
stringBindingTestBinding: 'context.direction',
template: compile(
'one way: {{view.oneWayBindingTest}}, ' +
'two way: {{view.twoWayBindingTest}}, ' +
'string: {{view.stringBindingTest}}'
)
});
view = EmberView.create({
viewWithBindingsClass: ViewWithBindings,
context: EmberObject.create({
direction: 'down'
}),
template: compile('{{view view.viewWithBindingsClass}}')
});
runAppend(view);
equal(trim(view.$().text()), 'one way: down, two way: down, string: down');
});
| mit |
stoplightio/gitlabhq | db/migrate/20180502122856_create_project_mirror_data.rb | 1107 | class CreateProjectMirrorData < ActiveRecord::Migration[4.2]
include Gitlab::Database::MigrationHelpers
DOWNTIME = false
# rubocop:disable Migration/AddLimitToStringColumns
def up
if table_exists?(:project_mirror_data)
add_column :project_mirror_data, :status, :string unless column_exists?(:project_mirror_data, :status)
add_column :project_mirror_data, :jid, :string unless column_exists?(:project_mirror_data, :jid)
add_column :project_mirror_data, :last_error, :text unless column_exists?(:project_mirror_data, :last_error)
else
create_table :project_mirror_data do |t|
t.references :project, index: true, foreign_key: { on_delete: :cascade }
t.string :status
t.string :jid
t.text :last_error
end
end
end
# rubocop:enable Migration/AddLimitToStringColumns
def down
remove_column :project_mirror_data, :status
remove_column :project_mirror_data, :jid
remove_column :project_mirror_data, :last_error
# ee/db/migrate/20170509153720_create_project_mirror_data_ee.rb will remove the table.
end
end
| mit |
anisku11/Laravel-SIG | app/views/kategori/edit.blade.php | 954 | @extends('template.default')
@section('content')
<legend>Edit Kategori # {{$kategori->nm_kategori}}</legend>
{{Form::model($kategori,array('url'=>route('kategori.update',['kategori'=>$kategori->id_kategori]),'method'=>'PUT','class'=>'form-horizontal','files'=>'true'))}}
{{Bootstrap::horizontal('col-sm-4','col-sm-2')
->text('nama','Nama Kategori',$kategori->nm_kategori,$errors)}}
<div class="form-group">
{{Form::label('icon','Icon',array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-4">
{{HTML::image('uploads/icon/'.$kategori->icon,'',array('style'=>'width:100px'))}}
</div>
</div>
{{Bootstrap::horizontal('col-sm-4','col-sm-2')
->file('icon',' ',$errors)}}
<div class="well">
<button class="btn btn-primary">
<i class="glyphicon glyphicon-saved"></i>
Simpan
</button>
<a href="{{URL::to('kategori')}}" class="btn btn-default">
Kembali
</a>
</div>
{{Form::close()}}
@stop | mit |
DenkerAffe/IPOS | src/commands/swap/swap.spec.ts | 417 | import { ensure } from 'charly/testHelper'
import { CInteger, CString } from 'charly/types'
import { describe, it } from 'mocha'
// tslint:disable:no-unused-expression
describe('/ - swap', () => {
it('[itm,itm] => []', () => {
ensure`1 'a/`.returns`a1`.withStack(CString, CInteger)
ensure`1 'a//`.returns`1a`.withStack(CInteger, CString)
ensure`1 2/`.returns`21`.withStack(CInteger, CInteger)
})
})
| mit |
calewis/SmallProjectsAndDev | code_tests/hierarchical_clustering/atom_example.cpp | 327 | #include "atom.h"
#include <array>
#include <iostream>
int main() {
std::cout << "Please enter a charge for the atom." << std::endl;
double Z = 0.0;
std::cin >> Z;
std::array<double, 3> pos = {{0, 0, 0}};
Atom a(pos, Z);
std::cout << "The Atoms charge is " << charge(a) << std::endl;
return 0;
}
| mit |
aggumati/frame | src/main/java/io/github/aggumati/frame/formtype/FrameFieldFile.java | 300 | package io.github.aggumati.frame.formtype;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({java.lang.annotation.ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface FrameFieldFile {
}
| mit |
cezerin/cezerin | src/api/server/lib/mailer.js | 1960 | import winston from 'winston';
import nodemailer from 'nodemailer';
import smtpTransport from 'nodemailer-smtp-transport';
import settings from './settings';
import EmailSettingsService from '../services/settings/email';
const SMTP_FROM_CONFIG_FILE = {
host: settings.smtpServer.host,
port: settings.smtpServer.port,
secure: settings.smtpServer.secure,
auth: {
user: settings.smtpServer.user,
pass: settings.smtpServer.pass
}
};
const getSmtpFromEmailSettings = emailSettings => {
return {
host: emailSettings.host,
port: emailSettings.port,
secure: emailSettings.port === 465,
auth: {
user: emailSettings.user,
pass: emailSettings.pass
}
};
};
const getSmtp = emailSettings => {
const useSmtpServerFromConfigFile = emailSettings.host === '';
const smtp = useSmtpServerFromConfigFile
? SMTP_FROM_CONFIG_FILE
: getSmtpFromEmailSettings(emailSettings);
return smtp;
};
const sendMail = (smtp, message) => {
return new Promise((resolve, reject) => {
if (!message.to.includes('@')) {
reject('Invalid email address');
return;
}
const transporter = nodemailer.createTransport(smtpTransport(smtp));
transporter.sendMail(message, (err, info) => {
if (err) {
reject(err);
} else {
resolve(info);
}
});
});
};
const getFrom = emailSettings => {
const useSmtpServerFromConfigFile = emailSettings.host === '';
return useSmtpServerFromConfigFile
? `"${settings.smtpServer.fromName}" <${settings.smtpServer.fromAddress}>`
: `"${emailSettings.from_name}" <${emailSettings.from_address}>`;
};
const send = async message => {
const emailSettings = await EmailSettingsService.getEmailSettings();
const smtp = getSmtp(emailSettings);
message.from = getFrom(emailSettings);
try {
const result = await sendMail(smtp, message);
winston.info('Email sent', result);
return true;
} catch (e) {
winston.error('Email send failed', e);
return false;
}
};
export default {
send: send
};
| mit |
aspireq/new_realgujarat | application/controllers/Auth.php | 28450 | <?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Auth extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->database();
$this->load->library('session');
$this->load->helper('url');
$this->load->helper('form');
$this->auth = new stdClass;
$this->load->library('flexi_auth');
if ($this->flexi_auth->is_logged_in_via_password() && uri_string() != 'auth/logout') {
if ($this->session->flashdata('message')) {
$this->session->keep_flashdata('message');
}
}
$this->data = null;
if ($this->flexi_auth->is_logged_in()) {
$this->data['userinfo'] = $this->userinfo = $this->flexi_auth->get_user_by_identity_row_array();
$this->user_id = $this->data['userinfo']['uacc_id'];
}
}
function index() {
$this->home();
}
public function include_files() {
$this->data['header'] = $this->load->view('user/header', $this->data, TRUE);
$this->data['footer'] = $this->load->view('user/footer', $this->data, TRUE);
return $this->data;
}
public function home() {
$this->data['categories'] = $this->Common_model->select_where('categories', array('status' => 1));
$this->data['cities'] = $this->Common_model->select_where('cities', array('state_id' => 12));
$this->data['top_business'] = $this->Common_model->get_top_business(8);
$this->data['top_all_business'] = $this->Common_model->get_top_business('');
$this->data['business_cities'] = $this->Common_model->get_business_cities();
$this->data['siteinfo'] = $this->Common_model->siteinfo();
$this->data = $this->include_files();
$this->load->view('user/home', $this->data);
}
public function get_category() {
$category_id = $this->input->post('category');
die($category_id);
}
public function businesses() {
if ($this->input->post('category_id_row')) {
$this->session->unset_userdata('session_category');
$this->session->set_userdata('session_category', $this->input->post('category_id_row'));
}
$category_id = $this->session->userdata('session_category');
$search_key = ($this->input->post('search_key') != "") ? $this->input->post('search_key') : '';
$search_category_id = ($this->input->post('category') != "") ? $this->input->post('category') : '';
$search_city = ($this->input->post('city') != "") ? $this->input->post('city') : '';
if ($search_key != "" || $search_category_id != "" || $search_city != "") {
$this->session->unset_userdata('search_data');
$search_data = array(
'key' => $search_key,
'category' => $search_category_id,
'city' => $search_city
);
$this->session->set_userdata('search_data', $search_data);
$this->session->unset_userdata('session_category');
}
$this->load->library('pagination');
$config = array();
$config["base_url"] = base_url() . "auth/businesses/";
$config["per_page"] = 5;
$config['use_page_numbers'] = FALSE;
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['cur_tag_open'] = ' <li class="active"><a>';
$config['cur_tag_close'] = '</a></li>';
$config['first_link'] = 'First';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['next_link'] = 'Next';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['prev_link'] = 'Previous';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$from_date = "";
$to_date = "";
if ($this->input->post()) {
$this->data['from_date'] = $from_date = date('Y-m-d', strtotime($this->input->post('from_date')));
$this->data['to_date'] = $to_date = date('Y-m-d', strtotime($this->input->post('to_date')));
}
$total_row = $this->Common_model->business_data('', '', $category_id, $search_key, $search_category_id, $search_city);
$config["total_rows"] = $total_row['counts'];
$config['num_links'] = $total_row['counts'];
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$this->data["results"] = $this->Common_model->business_data($config["per_page"], $page, $category_id, $search_key, $search_category_id, $search_city);
$this->pagination->initialize($config);
$str_links = $this->pagination->create_links();
$this->data["links"] = explode(' ', $str_links);
$this->data['categories'] = $this->Common_model->select_where('categories', array('status' => 1));
$this->data['cities'] = $this->Common_model->select_where('cities', array('state_id' => 12));
$this->data = $this->include_files();
$this->load->view('user/businesses', $this->data);
}
public function businessinfo() {
if ($this->input->post('business_id_row')) {
$this->session->unset_userdata('session_business');
$this->session->set_userdata('session_business', $this->input->post('business_id_row'));
}
$business_id = $this->session->userdata('session_business');
$this->data['business'] = $this->Common_model->get_business($business_id);
$this->load->library('pagination');
$config = array();
$config["base_url"] = base_url() . "auth/businessinfo/" . $business_id;
$config["per_page"] = 5;
$config['use_page_numbers'] = FALSE;
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['cur_tag_open'] = ' <li class="active"><a>';
$config['cur_tag_close'] = '</a></li>';
$config['first_link'] = 'First';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['next_link'] = 'Next';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['prev_link'] = 'Previous';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$total_row = $this->Common_model->review_data('', '', $business_id);
$config["total_rows"] = $total_row['counts'];
$config['num_links'] = $total_row['counts'];
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$this->data["results"] = $this->Common_model->review_data($config["per_page"], $page, $business_id);
// $reviews = (array) $this->Common_model->select_where('reviews', array('business_id' => $business_id, 'status' => 1));
$reviews = $this->db->query('select rating from reviews where business_id = ' . $business_id . ' AND status = 1')->result_array();
$total_ratings = array_sum(array_column($reviews, 'rating'));
// echo $total_ratings;die();
foreach ($reviews as $review) {
if ($review['rating'] == 1.0) {
$star_1 += $review['rating'];
} else if ($review['rating'] == 2.0) {
$star_2 += $review['rating'];
} else if ($review['rating'] == 3.0) {
$star_3 += $review['rating'];
} else if ($review['rating'] == 4.0) {
$star_4 += $review['rating'];
} else if ($review['rating'] == 5.0) {
$star_5 += $review['rating'];
}
}
$string = ($star_1 + $star_2 * 2 + $star_3 * 3 + $star_4 * 4 + $star_5 * 5) / $total_ratings;
$this->data["total_ratings"] = round(mb_substr($string, 0, -1));
$this->pagination->initialize($config);
$str_links = $this->pagination->create_links();
$this->data["links"] = explode(' ', $str_links);
$this->data = $this->include_files();
$this->load->view('user/businessinfo', $this->data);
}
function add_review() {
$data = array(
'business_id' => $this->input->post('business_id'),
'name' => $this->input->post('name'),
'review' => $this->input->post('review'),
'rating' => $this->input->post('rating')
);
$review_added = $this->Common_model->inserted_id('reviews', $data);
die(json_encode($review_added));
}
public function free_listing() {
$confirmation_code = "";
if ($confirmation_code == "" && $this->input->post('verification') == "verification") {
$this->load->library('form_validation');
$this->form_validation->set_rules('company_name', 'Company Name', 'required');
$this->form_validation->set_rules('mobile_no', 'Mobile No.', 'required|min_length[10]|max_length[10]');
if ($this->form_validation->run()) {
$confirmation_code = substr(number_format(time() * rand(), 0, '', ''), 0, 6);
$visitorinfo = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'contact_no' => $this->input->post('mobile_no'),
'company_name' => $this->input->post('company_name'),
'confirmation_code' => $confirmation_code
);
$visitor_id = $this->Common_model->inserted_id('visitorinfo', $visitorinfo);
} else {
$this->data['visitorinfo'] = array(
'company_name' => $this->input->post('company_name'),
'mobile_no' => $this->input->post('mobile_no')
);
$this->data['message'] = validation_errors('<p class="error_msg">', '</p>');
}
} else if ($this->input->post('verified') == 'verified') {
$this->load->library('form_validation');
$this->form_validation->set_rules('code', 'Code', 'required');
$this->form_validation->set_rules('confirmation_code', 'Confirmation Code', 'required|matches[code]');
$this->form_validation->set_message('matches', 'Confimation code is invalid.');
if ($this->form_validation->run()) {
$get_visitor = $this->Common_model->select_where_row('visitorinfo', array('confirmation_code' => $this->input->post('code')));
$visitorinfo = array(
'is_verified' => 1
);
$visitor_id = $this->Common_model->select_update('visitorinfo', $visitorinfo, array('confirmation_code' => $this->input->post('code')));
$this->session->set_flashdata('message', "Your mobile no. is verified !");
$this->session->set_flashdata('is_allowed', 1);
$this->session->set_flashdata('visitor_id', $get_visitor->id);
redirect('business');
} else {
$this->data['message'] = validation_errors('<p class="error_msg">', '</p>');
$confirmation_code = $this->input->post('code');
}
$this->data['confirmation_code'] = $confirmation_code;
}
$this->data['confirmation_code'] = $confirmation_code;
$this->data['message'] = (!isset($this->data['message'])) ? $this->session->flashdata('message') : $this->data['message'];
$this->data = $this->include_files();
$this->load->view('user/free_listing', $this->data);
}
public function business() {
if ($this->input->post()) {
$from_timings_1 = implode(',', $this->input->post('from_timings'));
$to_timings_1 = implode(',', $this->input->post('to_timings'));
if ($this->input->post('dual_timings') == 1) {
$from_timings_2 = implode(',', $this->input->post('from_timings_1'));
$to_timings_2 = implode(',', $this->input->post('to_timings_1'));
}
$this->load->library('upload');
$error = "";
if (!empty($_FILES['avatar-1']['name'])) {
$config['upload_path'] = 'include_files/logo';
$config['allowed_types'] = 'gif|jpg|png';
$config['overwrite'] = FALSE;
$config['encrypt_name'] = TRUE;
$config['max_filename'] = 25;
$this->upload->initialize($config);
if (!$this->upload->do_upload('avatar-1')) {
$error = $this->upload->display_errors();
} else {
$file_info = $this->upload->data();
$company_logo = $file_info['file_name'];
}
}
if (!empty($_FILES['company_banner']['name'])) {
$config['upload_path'] = 'include_files/banners';
$config['allowed_types'] = 'gif|jpg|png';
$config['overwrite'] = FALSE;
$config['encrypt_name'] = TRUE;
$config['max_filename'] = 25;
$this->upload->initialize($config);
if (!$this->upload->do_upload('company_banner')) {
$error = $this->upload->display_errors();
} else {
$file_info = $this->upload->data();
$banner = $file_info['file_name'];
}
}
if ($error == "") {
$business_data = array(
'name' => $this->input->post('company_name'),
'category_id' => $this->input->post('category'),
'subcategory_id' => $this->input->post('subcategory'),
'address' => $this->input->post('company_address'),
'pincode' => $this->input->post('pincode'),
'state' => $this->input->post('state'),
'city' => $this->input->post('city'),
'email' => $this->input->post('email'),
'business_description' => $this->input->post('about_company'),
'services' => implode(',', $this->input->post('services')),
'payment_methods' => implode(',', $this->input->post('payment_mode')),
'min_price_range ' => $this->input->post('min_rate'),
'max_price_range' => $this->input->post('max_rate'),
'banner' => $banner,
'logo' => $company_logo,
'from_timings_1' => $from_timings_1,
'to_timings_1' => $to_timings_1,
'from_timings_2' => $from_timings_2,
'to_timings_2' => $to_timings_2,
'visitor_id' => $this->input->post('visitor_id')
);
if ($this->input->post('website')) {
$business_data['website'] = $this->input->post('website');
}
if ($this->input->post('contact_person_name')) {
$business_data['contact_person_name'] = $this->input->post('contact_person_name');
}
if ($this->input->post('landline_no') && $this->input->post('landline_code')) {
$business_data['landline_no'] = $this->input->post('landline_no');
$business_data['landline_code'] = $this->input->post('landline_code');
}
if ($this->input->post('mobile_no') && $this->input->post('mobile_code')) {
$business_data['mobile_no'] = $this->input->post('mobile_no');
$business_data['mobile_code'] = $this->input->post('mobile_code');
}
if ($this->input->post('other_no') && $this->input->post('other_code')) {
$business_data['other_no'] = $this->input->post('other_no');
$business_data['other_code'] = $this->input->post('other_code');
}
$business_id = $this->Common_model->inserted_id('businesses', $business_data);
if ($business_id) {
$more_mobile_no_codes = $this->input->post('more_mobile_code');
$more_mobile_nos = $this->input->post('more_mobile_no');
$more_landline_no_codes = $this->input->post('more_landline_code');
$more_landline_nos = $this->input->post('more_landline_no');
$this->Common_model->delete_where('business_contacts', array('business_id' => $business_id));
if (count($more_mobile_nos) > count($more_landline_nos)) {
$more_contacts = $more_mobile_nos;
} else {
$more_contacts = $more_landline_nos;
}
foreach ($more_contacts as $key => $more_contact) {
$business_contacts_data = array(
'business_id' => $business_id
);
$add_record = '';
if ($more_landline_no_codes[$key] != "" && $more_landline_nos[$key]) {
$add_record = 1;
$business_contacts_data['landline_code_number'] = $more_landline_no_codes[$key];
$business_contacts_data['landline_number'] = $more_landline_nos[$key];
}
if ($more_mobile_no_codes[$key] != "" && $more_mobile_nos[$key] != "") {
$add_record = 1;
$business_contacts_data['mobile_no_code'] = $more_mobile_no_codes[$key];
$business_contacts_data['mobile_number'] = $more_mobile_nos[$key];
}
if ($add_record == 1) {
$this->Common_model->insert('business_contacts', $business_contacts_data);
}
}
}
$this->Common_model->select_update('visitorinfo', array('ad_id' => $business_id, 'advertize_added' => 1), array('id' => $this->input->post('visitor_id')));
if (!empty($_FILES['userFiles']['name'])) {
$filesCount = count($_FILES['userFiles']['name']);
for ($i = 0; $i < $filesCount; $i++) {
$_FILES['userFile']['name'] = $_FILES['userFiles']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['userFiles']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['userFiles']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['userFiles']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['userFiles']['size'][$i];
$uploadPath = 'include_files/business_images';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('userFile')) {
$fileData = $this->upload->data();
$uploadData[$i]['business_id'] = $business_id;
$uploadData[$i]['image'] = $fileData['file_name'];
}
}
if (!empty($uploadData) && $business_id) {
if (!empty($uploadData)) {
$insert = $this->db->insert_batch('company_images', $uploadData);
}
$statusMsg = $business_id ? 'Your add has been submitted succesfully !' : 'Some problem occurred, please try again.';
$this->session->set_flashdata('message', $statusMsg);
} else {
$this->session->set_flashdata('message', "Something went wrong!.Please try again later");
$this->data['businessinfo'] = $business_data;
}
}
} else {
$this->session->set_flashdata('message', $error);
$this->data['businessinfo'] = $business_data;
}
}
if ($this->session->flashdata('is_allowed') == 1) {
$this->data['visitor_id'] = $this->session->flashdata('visitor_id');
$this->data['categories'] = $this->Common_model->select_where('categories', array('status' => 1));
$this->data['states'] = $this->Common_model->select_where('states', array('id' => 12));
$this->data['message'] = (!isset($this->data['message'])) ? $this->session->flashdata('message') : $this->data['message'];
$this->data = $this->include_files();
$this->load->view('user/business', $this->data);
} else {
$this->session->set_flashdata('message', "You can not post advertizement without verification");
redirect('free_listing');
}
}
function admin() {
if ($this->input->post()) {
$this->load->model('demo_auth_model');
$result = $this->demo_auth_model->login();
}
$this->data['message'] = (!isset($this->data['message'])) ? $this->session->flashdata('message') : $this->data['message'];
$this->data['common'] = $this->load->view('admin/common', $this->data, TRUE);
$this->load->view('admin/login', $this->data);
}
function activate_account($user_id, $token = FALSE) {
$this->flexi_auth->activate_user($user_id, $token, TRUE);
$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
redirect('auth');
}
function hours_of_operation() {
$business_id = $this->input->post('id');
$timings = $this->Common_model->select_where_row('businesses', array('id' => $business_id));
$days = array(
0 => 'Monday',
1 => 'Tuesday',
2 => 'Wednesday',
3 => 'Thursday',
4 => 'Friday',
5 => 'Saturday',
6 => 'Sunday');
$from_timings_1 = explode(',', $timings->from_timings_1);
$to_timings_1 = explode(',', $timings->to_timings_1);
$from_timings_2 = explode(',', $timings->from_timings_2);
$to_timings_2 = explode(',', $timings->to_timings_2);
$data = '';
foreach ($days as $key => $day) {
if ($this->input->post('type') == "Show Less") {
if (date('l', strtotime(date('Y-m-d'))) == $day) {
$data .= '<p>' . $day . ' ' . $from_timings_1[$key] . ' - ' . $to_timings_1[$key];
if (!empty($from_timings_2[0])) {
$data .= ' || ' . $from_timings_2[$key] . ' - ' . $to_timings_2[$key];
}
$data .= '</p>';
}
} else {
$data .= '<p>' . $day . ' ' . $from_timings_1[$key] . ' - ' . $to_timings_1[$key];
if (!empty($from_timings_2[0])) {
$data .= ' || ' . $from_timings_2[$key] . ' - ' . $to_timings_2[$key];
}
$data .= '</p>';
}
}
die(json_encode($data));
}
function get_record() {
$table_name = $this->input->post('table_name');
$id = $this->input->post('id');
$table_coloum = $this->input->post('table_coloum');
$data = $this->Common_model->select_where_row($table_name, array($table_coloum => $id));
die(json_encode($data));
}
function map($id = null) {
$businessinfo = $this->Common_model->select_where_row('businesses', array('id' => $id));
$addres = $businessinfo->address;
$address = str_replace(" ", "+", $addres);
$json_result = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region");
$json = json_decode($json_result);
$this->data['lat'] = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$this->data['long'] = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
$this->data['name'] = $businessinfo->name;
$this->data = $this->include_files();
$this->load->view('user/map', $this->data);
}
function send_information() {
$business_id = $this->input->post('business_id');
$name = $this->input->post('name');
$email = $this->input->post('email');
//$mobile = $this->input->post('mobile');
$businessinfo = $this->Common_model->select_where_row('businesses', array('id' => $business_id));
$mobile = ($businessinfo->mobile_code != "") ? $businessinfo->mobile_code . $businessinfo->mobile_no : $businessinfo->mobile_no;
$subject = 'realgujarat - ' . ucfirst($businessinfo->name);
$message = "Hello " . $name . "\n";
$message .= "Business Info \n";
$message .= "Name : " . $businessinfo->name . "\n";
$message .= "Address : " . $businessinfo->address . "\n";
$message .= "Contact : " . $mobile . "\n";
$message .= "\r";
$message .= "Services Provided : " . $businessinfo->services;
$headers = 'From: ' . From_Email . '' . "\r\n" .
'Reply-To: ' . Reply_Email . '' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if (mail($email, $subject, $message, $headers)) {
die(json_encode(true));
} else {
die(json_encode(false));
}
}
function add_more_contacts() {
$data = '<div class="col-md-12 col-sm-12 col-xs-12">';
$data .= '<div class="form-group col-md-4 col-sm-12 col-xs-12">';
$data .= '<div class="input-group">';
$data .= '<div class="input-group-addon">';
$data .= '<i class="fa fa-phone"></i>';
$data .= '</div>';
$data .= '<div class="input-group-addon codeinput">';
$data .= '<input type="text" placeholder="Code" class="form-control" name="more_landline_code[]" id="more_landline_code" >';
$data .= '</div>';
$data .= '<input type="text" class="form-control" placeholder="Landline No." name="more_landline_no[]" id="more_landline_no" maxlength="10"">';
$data .= '</div>';
$data .= '</div>';
$data .= '<div class="form-group col-md-4 col-sm-12 col-xs-12">';
$data .= '<div class="input-group">';
$data .= '<div class="input-group-addon"><i class="fa fa-mobile"></i></div>';
$data .= '<div class="input-group-addon codeinput">';
$data .= '<input type="text" placeholder="Code" class="form-control" name="more_mobile_code[]" id="more_mobile_code">';
$data .= '</div>';
$data .= '<input type="text" class="form-control" placeholder="Mobile No." name="more_mobile_no[]" id="more_mobile_no" maxlength="10">';
$data .= '</div>';
$data .= '</div>';
$data .= '</div>';
die(json_encode($data));
}
function get_businessinfo() {
$id = $this->input->post('id');
$data = $this->Common_model->select_where_row('business_earnings', array('business_id' => $id));
if (empty($data)) {
die(json_encode(array('status' => false)));
} else {
die(json_encode(array('status' => true, 'earninginfo' => $data)));
}
}
function unset_logins() {
$data = $this->Common_model->select_where('user_accounts', array('uacc_group_fk' => 2));
foreach ($data as $user) {
$this->Common_model->select_update('user_accounts', array('is_login' => 0), array('uacc_id' => $user->uacc_id));
}
}
}
| mit |
driftyco/ionic-native | src/@ionic-native/plugins/keychain-touch-id/index.ts | 3143 | import { Injectable } from '@angular/core';
import { Cordova, IonicNativePlugin, Plugin } from '@ionic-native/core';
/**
* @name Keychain Touch Id
* @description
* A cordova plugin adding the iOS TouchID / Android fingerprint to your
* app and allowing you to store a password securely in the device keychain.
*
* @usage
* ```typescript
* import { KeychainTouchId } from '@ionic-native/keychain-touch-id/ngx';
*
*
* constructor(private keychainTouchId: KeychainTouchId) { }
*
* ...
*
*
* this.keychainTouchId.isAvailable()
* .then((res: any) => console.log(res))
* .catch((error: any) => console.error(error));
*
* ```
*/
@Plugin({
pluginName: 'KeychainTouchId',
plugin: 'cordova-plugin-keychain-touch-id',
pluginRef: 'plugins.touchid',
repo: 'https://github.com/sjhoeksma/cordova-plugin-keychain-touch-id',
platforms: ['Android', 'iOS']
})
@Injectable({
providedIn: 'root'
})
export class KeychainTouchId extends IonicNativePlugin {
/**
* Check if Touch ID / Fingerprint is supported by the device
* @return {Promise<any>} Returns a promise that resolves when there is hardware support
*/
@Cordova()
isAvailable(): Promise<any> {
return;
}
/**
* Encrypts and Saves a password under the key in the device keychain, which can be retrieved after
* successful authentication using fingerprint
* @param key {string} the key you want to store
* @param password {string} the password you want to encrypt and store
* @return {Promise<any>} Returns a promise that resolves when there is a result
*/
@Cordova()
save(key: string, password: string): Promise<any> {
return;
}
/**
* Opens the fingerprint dialog, for the given key, showing an additional message. Promise will resolve
* with the password stored in keychain or will resolve an error code, where -1 indicated not available.
* @param key {string} the key you want to retrieve from keychain
* @param message {string} a message to the user
* @return {Promise<any>} Returns a promise that resolves when the key value is successfully retrieved or an error
*/
@Cordova()
verify(key: string, message: string): Promise<any> {
return;
}
/**
* Checks if there is a password stored within the keychain for the given key.
* @param key {string} the key you want to check from keychain
* @return {Promise<any>} Returns a promise that resolves with success if the key is available or failure if key is not.
*/
@Cordova()
has(key: string): Promise<any> {
return;
}
/**
* Deletes the password stored under given key from the keychain.
* @param key {string} the key you want to delete from keychain
* @return {Promise<any>} Returns a promise that resolves with success if the key is deleted or failure if key is not
*/
@Cordova()
delete(key: string): Promise<any> {
return;
}
/**
* Sets the language of the fingerprint dialog
* @param locale {string} locale subtag from [this list](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry).
*/
@Cordova()
setLocale(locale: string): void {
}
}
| mit |
pellu/roadtothesuccess | vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php | 4012 | <?php
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Logger;
use Monolog\Formatter\JsonFormatter;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Channel\AMQPChannel;
use AMQPExchange;
class AmqpHandler extends AbstractProcessingHandler
{
/**
* @var AMQPExchange|AMQPChannel $exchange
*/
protected $exchange;
/**
* @var string
*/
protected $exchangeName;
/**
* @param AMQPExchange|AMQPChannel $exchange AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use
* @param string $exchangeName
* @param int $level
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct($exchange, $exchangeName = 'log', $level = Logger::DEBUG, $bubble = true)
{
if ($exchange instanceof AMQPExchange) {
$exchange->setName($exchangeName);
} elseif ($exchange instanceof AMQPChannel) {
$this->exchangeName = $exchangeName;
} else {
throw new \InvalidArgumentException('PhpAmqpLib\Channel\AMQPChannel or AMQPExchange instance required');
}
$this->exchange = $exchange;
parent::__construct($level, $bubble);
}
/**
* {@inheritDoc}
*/
protected function write(array $record)
{
$data = $record["formatted"];
$routingKey = $this->getRoutingKey($record);
if ($this->exchange instanceof AMQPExchange) {
$this->exchange->publish(
$data,
$routingKey,
0,
array(
'delivery_mode' => 2,
'Content-type' => 'application/json',
)
);
} else {
$this->exchange->basic_publish(
$this->createAmqpMessage($data),
$this->exchangeName,
$routingKey
);
}
}
/**
* {@inheritDoc}
*/
public function handleBatch(array $records)
{
if ($this->exchange instanceof AMQPExchange) {
parent::handleBatch($records);
return;
}
foreach ($records as $record) {
if (!$this->isHandling($record)) {
continue;
}
$record = $this->processRecord($record);
$data = $this->getFormatter()->format($record);
$this->exchange->batch_basic_publish(
$this->createAmqpMessage($data),
$this->exchangeName,
$this->getRoutingKey($record)
);
}
$this->exchange->publish_batch();
}
/**
* Gets the routing key for the AMQP exchange
*
* @param array $record
* @return string
*/
private function getRoutingKey(array $record)
{
$routingKey = sprintf(
'%s.%s',
// TODO 2.0 remove substr call
substr($record['level_name'], 0, 4),
$record['channel']
);
return strtolower($routingKey);
}
/**
* @param string $data
* @return AMQPMessage
*/
private function createAmqpMessage($data)
{
return new AMQPMessage(
(string) $data,
array(
'delivery_mode' => 2,
'content_type' => 'application/json',
)
);
}
/**
* {@inheritDoc}
*/
protected function getDefaultFormatter()
{
return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
}
}
| mit |
sergiorykov/Platron.Client | Source/Platron.Client/Http/IHttpResponse.cs | 860 | using System;
using System.Collections.Generic;
using System.Net;
namespace Platron.Client.Http
{
/// <summary>
/// Represents a generic HTTP response
/// </summary>
public interface IHttpResponse
{
/// <summary>
/// Raw response body.
/// </summary>
string Body { get; }
/// <summary>
/// Information about the API.
/// </summary>
IReadOnlyDictionary<string, string> Headers { get; }
/// <summary>
/// The response status code.
/// </summary>
HttpStatusCode StatusCode { get; }
/// <summary>
/// The content type of the response.
/// </summary>
string ContentType { get; }
/// <summary>
/// Request url.
/// </summary>
Uri RequestUri { get; }
}
} | mit |
petr/gqlclans | frontend/app/components/ClansList/__tests__/index.js | 1478 | import React from 'react'
import ClansList from '../'
import { shallow } from 'enzyme'
const setUp = (props) => {
const defaultProps = {
ids: ['123'],
data: {
loading: false,
clans: [
{
clanId: '123',
name: 'Gold LordS',
tag: 'GLS',
color: '#1010E6',
members: [
{
name: 'Zibiro',
accountId: '30915272',
role: 'executive_officer',
__typename: 'Member'
},
],
messages: [],
__typename: 'Clan',
},
],
}
}
return shallow(<ClansList {...defaultProps} {...props} />)
}
describe('ClansList specification', () => {
it('render CircularProgress if data is loading', () => {
const wrapper = setUp({ data: { loading: true } })
expect(wrapper.find('CircularProgress').length).toEqual(1)
})
it('render CircularProgress if clans are empty', () => {
const wrapper = setUp({ data: { clans: null } })
expect(wrapper.find('CircularProgress').length).toEqual(1)
})
it('render Table if there is clans data', () => {
const wrapper = setUp()
expect(wrapper.find('Table').length).toEqual(1)
})
}) | mit |