repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
richtermark/SMEAGOnline
src/Biz/CloudData/Dao/CloudDataDao.php
145
<?php namespace Biz\CloudData\Dao; use Codeages\Biz\Framework\Dao\GeneralDaoInterface; interface CloudDataDao extends GeneralDaoInterface { }
mit
davidchristie/react-vision
src/components/VideoStream/VideoStream.test.js
1312
import { shallow, mount } from 'enzyme' import React from 'react' import VideoStream from './VideoStream' it('mounts without stream', () => { expect(mount(<VideoStream />)).toMatchSnapshot() }) it('mounts with stream', () => { const props = { stream: {} } expect(mount(<VideoStream {...props} />)).toMatchSnapshot() }) describe('when the stream is changed', () => { it('updates the video srcObject if mounted', () => { const stream = {} const wrapper = mount(<VideoStream />) wrapper.setProps({ stream }) expect(wrapper.find('video').at(0).instance().srcObject).toEqual(stream) }) it('runs without crashing if unmounted', () => { const stream = {} const wrapper = shallow(<VideoStream />) wrapper.setProps({ stream }) }) }) describe('getImage method', () => { beforeEach(() => { window.HTMLCanvasElement.prototype.getContext = () => ({ drawImage: () => {} }) }) it('takes snapshot image', () => { const props = { stream: {} } const wrapper = mount(<VideoStream {...props} />) expect(wrapper.instance().getImage()).toBeDefined() }) it('returns null if component is unmounted', () => { const wrapper = shallow(<VideoStream />) expect(wrapper.instance().getImage()).toBeNull() }) })
mit
ybzhou/JointAE
AE.py
5239
import theano import theano.tensor as T import numpy as np from AELayer import AELayer, Gaussian_AELayer, Bernoulli_AELayer, \ SaltPepper_AELayer, Contractive_AELayer class BasicAE(object): def __init__(self, en_input, de_input, n_in, n_hid, init, act_func, tie_weights=False, We=None, be=None, Wd=None, bd=None, **kargs): self.encoder = AELayer(n_in, n_hid, init, act_func[0], W=We, b=be, **kargs) self.tie_weights = tie_weights self.params = [] self.params.extend(self.encoder.params) if tie_weights: self.decoder = AELayer(n_hid, n_in, init, act_func[1], W=self.encoder.W.T, b=bd, **kargs) self.params.append(self.decoder.b) else: self.decoder = AELayer(n_hid, n_in, init, act_func[1], W=Wd, b=bd, **kargs) self.params.extend(self.decoder.params) def cost(self): ''' L2 cost for ae layer''' if self.tie_weights: return self.encoder.layer_cost() else: return self.encoder.layer_cost() + self.decoder.layer_cost() #------------------------------------------------------------------------------- class GaussianDAE(object): def __init__(self, n_in, n_hid, init, act_func, tie_weights=False, We=None, be=None, Wd=None, bd=None, **kargs): self.encoder = Gaussian_AELayer(n_in, n_hid, init, act_func[0], W=We, b=be, **kargs) self.params = [] self.params.extend(self.encoder.params) self.tie_weights = tie_weights if tie_weights: self.decoder = AELayer(n_hid, n_in, init, act_func[1], W=self.encoder.W.T, b=bd, **kargs) self.params.append(self.decoder.b) else: self.decoder = AELayer(n_hid, n_in, init, act_func[1], W=Wd, b=bd, **kargs) self.params.extend(self.decoder.params) def cost(self): ''' L2 cost for ae layer''' if self.tie_weights: return self.encoder.layer_cost() else: return self.encoder.layer_cost() + self.decoder.layer_cost() #------------------------------------------------------------------------------- class BernoulliDAE(object): def __init__(self, n_in, n_hid, init, act_func, tie_weights=False, We=None, be=None, Wd=None, bd=None, **kargs): self.encoder = Bernoulli_AELayer(n_in, n_hid, init, act_func[0], W=We, b=be, **kargs) self.tie_weights = tie_weights self.params = [] self.params.extend(self.encoder.params) if tie_weights: self.decoder = AELayer(n_hid, n_in, init, act_func[1], W=self.encoder.W.T, b=bd, **kargs) self.params.append(self.decoder.b) else: self.decoder = AELayer(n_hid, n_in, init, act_func[1], W=Wd, b=bd, **kargs) self.params.extend(self.decoder.params) def cost(self): ''' L2 cost for ae layer''' if self.tie_weights: return self.encoder.layer_cost() else: return self.encoder.layer_cost() + self.decoder.layer_cost() #------------------------------------------------------------------------------- class SaltPepperDAE(object): def __init__(self, n_in, n_hid, init, act_func, tie_weights=False, We=None, be=None, Wd=None, bd=None, **kargs): self.encoder = SaltPepper_AELayer(n_in, n_hid, init, act_func[0], W=We, b=be, **kargs) self.tie_weights = tie_weights self.params = [] self.params.extend(self.encoder.params) if tie_weights: self.decoder = AELayer(n_hid, n_in, init, act_func[1], W=self.encoder.W.T, b=bd, **kargs) self.params.append(self.decoder.b) else: self.decoder = AELayer(n_hid, n_in, init, act_func[1], W=Wd, b=bd, **kargs) self.params.extend(self.decoder.params) def cost(self): ''' L2 cost for ae layer''' if self.tie_weights: return self.encoder.layer_cost() else: return self.encoder.layer_cost() + self.decoder.layer_cost() #------------------------------------------------------------------------------- class ContractiveAE(object): def __init__(self, n_in, n_hid, init, act_func, tie_weights=False, We=None, be=None, Wd=None, bd=None, **kargs): self.encoder = Contractive_AELayer(n_in, n_hid, init, act_func[0], W=We, b=be, **kargs) self.tie_weights = tie_weights self.params = [] self.params.extend(self.encoder.params) if tie_weights: self.decoder = AELayer(n_hid, n_in, init, act_func[1], W=self.encoder.W.T, b=bd, **kargs) self.params.append(self.decoder.b) else: self.decoder = AELayer(n_hid, n_in, init, act_func[1], W=Wd, b=bd, **kargs) self.params.extend(self.decoder.params) def cost(self): ''' L2 cost for ae layer''' if self.tie_weights: return self.encoder.layer_cost() else: return self.encoder.layer_cost() + self.decoder.layer_cost()
mit
danliris/bateeq-module
src/managers/master/unit-manager.js
9504
'use strict' var ObjectId = require("mongodb").ObjectId; require("mongodb-toolkit"); var BateeqModels = require('bateeq-models'); var map = BateeqModels.map; var Unit = BateeqModels.master.Unit; var BaseManager = require('module-toolkit').BaseManager; var DivisionManager = require('./division-manager'); module.exports = class UnitManager extends BaseManager { constructor(db, user) { super(db, user); this.collection = this.db.use(map.master.collection.Unit); this.divisionManager = new DivisionManager(db, user); } _getQuery(paging) { var _default = { _deleted: false }, pagingFilter = paging.filter || {}, keywordFilter = {}, query = {}; if (paging.keyword) { var regex = new RegExp(paging.keyword, "i"); var codeFilter = { 'code': { '$regex': regex } }; var nameFilter = { 'name': { '$regex': regex } }; var divisionNameFilter = { 'division.name': { '$regex': regex } }; keywordFilter['$or'] = [codeFilter, nameFilter, divisionNameFilter]; } query["$and"] = [_default, keywordFilter, pagingFilter]; return query; } _validate(unit) { var errors = {}; return new Promise((resolve, reject) => { var valid = unit; // 1. begin: Declare promises. var getUnitPromise = this.collection.singleOrDefault({ _id: { '$ne': new ObjectId(valid._id) }, code: valid.code }); var getDivision = ObjectId.isValid(valid.divisionId) ? this.divisionManager.getSingleByIdOrDefault(new ObjectId(valid.divisionId)) : Promise.resolve(null); // 2. begin: Validation. Promise.all([getUnitPromise, getDivision]) .then(results => { var _unit = results[0]; var _division = results[1]; if (!valid.code || valid.code == '') errors["code"] = "code is required"; else if (_unit) { errors["code"] ="code is already exists"; } if (!_division) errors["division"] = "division is required"; if (!valid.name || valid.name == '') errors["name"] = "name is required"; if (Object.getOwnPropertyNames(errors).length > 0) { var ValidationError = require('module-toolkit').ValidationError; reject(new ValidationError('data does not pass validation', errors)); } valid = new Unit(unit); valid.divisionId = _division._id; valid.division = _division; valid.stamp(this.user.username, 'manager'); resolve(valid); }) .catch(e => { reject(e); }) }); } getUnit() { return new Promise((resolve, reject) => { var query = { _deleted: false }; this.collection .where(query) .execute() .then(vats => { resolve(vats); }) .catch(e => { reject(e); }); }); } insert(dataFile) { return new Promise((resolve, reject) => { var unit; var div; this.getUnit() .then(results => { this.divisionManager.getDivision() .then(divisions => { unit = results.data; div = divisions.data; var data = []; if (dataFile != "") { for (var i = 1; i < dataFile.length; i++) { data.push({ "code": dataFile[i][0].trim(), "division": dataFile[i][1].trim(), "name": dataFile[i][2].trim(), "description": dataFile[i][3].trim() }); } } var dataError = [], errorMessage; var flag = false; for (var i = 0; i < data.length; i++) { errorMessage = ""; if (data[i]["code"] === "" || data[i]["code"] === undefined) { errorMessage = errorMessage + "Kode tidak boleh kosong, "; } else { for (var j = 0; j < div.length; j++) { if ((div[j]["name"]).toLowerCase() === (data[i]["division"]).toLowerCase()) { flag = true; break; } } if (flag === false) { errorMessage = errorMessage + "Divisi tidak terdaftar di Master Divisi"; } } if (data[i]["division"] === "" || data[i]["division"] === undefined) { errorMessage = errorMessage + "Divisi tidak boleh kosong, "; } if (data[i]["name"] === "" || data[i]["name"] === undefined) { errorMessage = errorMessage + "Nama tidak boleh kosong, "; } for (var j = 0; j < unit.length; j++) { if (unit[j]["code"] === data[i]["code"]) { errorMessage = errorMessage + "Kode tidak boleh duplikat, "; } if (unit[j]["name"] === data[i]["name"]) { errorMessage = errorMessage + "Nama tidak boleh duplikat, "; } } if (errorMessage !== "") { dataError.push({ "code": data[i]["code"], "division": data[i]["division"], "name": data[i]["name"], "description": data[i]["description"], "Error": errorMessage }); } } if (dataError.length === 0) { var newUnit = []; for (var i = 0; i < data.length; i++) { var valid = new Unit(data[i]); for (var j = 0; j < div.length; j++) { if (data[i]["division"] == div[j]["name"]) { valid.divisionId = new ObjectId(div[j]["_id"]); valid.division = div[j]; valid.stamp(this.user.username, 'manager'); this.collection.insert(valid) .then(id => { this.getSingleById(id) .then(resultItem => { newUnit.push(resultItem) resolve(newUnit); }) .catch(e => { reject(e); }); }) .catch(e => { reject(e); }); break; } } } } else { resolve(dataError); } }) }) }) } _createIndexes() { var dateIndex = { name: `ix_${map.master.collection.Unit}__updatedDate`, key: { _updatedDate: -1 } } var codeIndex = { name: `ix_${map.master.collection.Unit}_code`, key: { code: 1 }, unique: true } return this.collection.createIndexes([dateIndex, codeIndex]); } }
mit
ratellohq/ratello-landing
cache/compiled/files/ef6bcfcd7ab29bb2429e3b002e2feb7d.yaml.php
60281
<?php return [ '@class' => 'Grav\\Common\\File\\CompiledYamlFile', 'filename' => '/Users/emil/Documents/code/ratello-landing/user/plugins/admin/languages/ru.yaml', 'modified' => 1492456033, 'data' => [ 'PLUGIN_ADMIN' => [ 'ADMIN_BETA_MSG' => 'Это бета-релиз! Вы используете это расширение на свой страх и риск...', 'ADMIN_REPORT_ISSUE' => 'Нашли ошибку? Пожалуйста, сообщите об этом на GitHub.', 'EMAIL_FOOTER' => '<a href="http://getgrav.org">Работает на Grav</a> - The Modern Flat File CMS', 'LOGIN_BTN' => 'Логин', 'LOGIN_BTN_FORGOT' => 'Забыл', 'LOGIN_BTN_RESET' => 'Сбросить пароль', 'LOGIN_BTN_SEND_INSTRUCTIONS' => 'Отправить инструкции по сбросу', 'LOGIN_BTN_CLEAR' => 'Очистить форму', 'LOGIN_BTN_CREATE_USER' => 'Создать пользователя', 'LOGIN_LOGGED_IN' => 'Вы успешно вошли в систему', 'LOGIN_FAILED' => 'Не удалось войти', 'LOGGED_OUT' => 'Вы вышли из системы', 'RESET_NEW_PASSWORD' => 'Пожалуйста, введите новый пароль &hellip;', 'RESET_LINK_EXPIRED' => 'Истекло время сброса, пожалуйста, попробуйте ещё раз', 'RESET_PASSWORD_RESET' => 'Пароль был сброшен', 'RESET_INVALID_LINK' => 'Неверная ссылка восстановления пароля, пожалуйста, попробуйте ещё раз', 'FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL' => 'Инструкции для сброса пароля были высланы на ваш адрес электронной почты %s', 'FORGOT_FAILED_TO_EMAIL' => 'Не удалось отправить инструкции по электронной почте, пожалуйста, повторите попытку позже', 'FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL' => 'Невозможно сбросить пароль для %s, не задан адрес электронной почты', 'FORGOT_USERNAME_DOES_NOT_EXIST' => 'Пользователь с логином <b>%s</b> не существует', 'FORGOT_EMAIL_NOT_CONFIGURED' => 'Не удаётся сбросить пароль. Этот сайт не настроен для отправки электронной почты', 'FORGOT_EMAIL_SUBJECT' => '%s Запрос на восстановление пароля', 'FORGOT_EMAIL_BODY' => '<h1>Сброс пароля</h1><p>Уважемый %1$s,</p><p>Был отправлен запрос на <b>%4$s</b> для сброса пароля.</p><p><br /><a href="%2$s" class="btn-primary">Нажмите эту кнопку, чтобы сбросить свой пароль</a><br /><br /></p><p>Или скопируйте следующий URL в адресную строку вашего браузера:</p> <p>%2$s</p><p><br />С уважением,<br /><br />%3$s</p>', 'MANAGE_PAGES' => 'Менеджер страниц', 'CONFIGURATION' => 'Настройка', 'PAGES' => 'Страницы', 'PLUGINS' => 'Плагины', 'PLUGIN' => 'Плагин', 'THEMES' => 'Темы', 'LOGOUT' => 'Выход', 'BACK' => 'Назад', 'ADD_PAGE' => 'Добавить cтраницу', 'ADD_MODULAR' => 'Добавить модульный блок', 'MOVE' => 'Перенести', 'DELETE' => 'Удалить', 'SAVE' => 'Сохранить', 'NORMAL' => 'Стандартный', 'EXPERT' => 'Экспертный', 'EXPAND_ALL' => 'Развернуть все', 'COLLAPSE_ALL' => 'Свернуть все', 'ERROR' => 'Ошибка', 'CLOSE' => 'Закрыть', 'CANCEL' => 'Отменить', 'CONTINUE' => 'Продолжить', 'MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_TITLE' => 'Требуется подтверждение', 'MODAL_CHANGED_DETECTED_TITLE' => 'Обнаружены изменения', 'MODAL_CHANGED_DETECTED_DESC' => 'У вас есть несохраненные изменения. Вы уверены, что хотите выйти без сохранения?', 'MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_TITLE' => 'Требуется подтверждение', 'MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_DESC' => 'Вы уверены, что хотите удалить этот файл? Это действие не может быть отменено.', 'ADD_FILTERS' => 'Добавить фильтры', 'SEARCH_PAGES' => 'Поиск страниц', 'VERSION' => 'Версия', 'WAS_MADE_WITH' => 'сделано с', 'BY' => 'От', 'UPDATE_THEME' => 'Обновить тему', 'UPDATE_PLUGIN' => 'Обновить плагин', 'OF_THIS_THEME_IS_NOW_AVAILABLE' => 'этой темы теперь доступно', 'OF_THIS_PLUGIN_IS_NOW_AVAILABLE' => 'этого плагина теперь доступно', 'AUTHOR' => 'Автор', 'HOMEPAGE' => 'Домашняя страница', 'DEMO' => 'Демо', 'BUG_TRACKER' => 'Баг-трекер', 'KEYWORDS' => 'Ключевые слова', 'LICENSE' => 'Лицензия', 'DESCRIPTION' => 'Описание', 'README' => 'Инструкция', 'REMOVE_THEME' => 'Удалить тему', 'INSTALL_THEME' => 'Установить тему', 'THEME' => 'Тема', 'BACK_TO_THEMES' => 'Назад к темам', 'BACK_TO_PLUGINS' => 'Назад к плагинам', 'CHECK_FOR_UPDATES' => 'Проверить обновления', 'ADD' => 'Добавить', 'CLEAR_CACHE' => 'Очистить кэш', 'CLEAR_CACHE_ALL_CACHE' => 'Весь кэш', 'CLEAR_CACHE_ASSETS_ONLY' => 'Только ресурсы', 'CLEAR_CACHE_IMAGES_ONLY' => 'Только изображения', 'CLEAR_CACHE_CACHE_ONLY' => 'Только кэш', 'DASHBOARD' => 'Панель управления', 'UPDATES_AVAILABLE' => 'Доступны обновления', 'DAYS' => 'Дни', 'UPDATE' => 'Обновление', 'BACKUP' => 'Резервная копия', 'STATISTICS' => 'Статистика', 'TODAY' => 'Сегодня', 'WEEK' => 'Неделя', 'MONTH' => 'Месяц', 'LATEST_PAGE_UPDATES' => 'Последние обновлённые страницы', 'MAINTENANCE' => 'Техническое обслуживание', 'UPDATED' => 'Обновлено', 'MON' => 'Пн', 'TUE' => 'Вт', 'WED' => 'Ср', 'THU' => 'Чт', 'FRI' => 'Пт', 'SAT' => 'Сб', 'SUN' => 'Вс', 'COPY' => 'Копировать', 'EDIT' => 'Редактировать', 'CREATE' => 'Создать', 'GRAV_ADMIN' => 'Админка Grav', 'GRAV_OFFICIAL_PLUGIN' => 'Официальный плагин Grav', 'GRAV_OFFICIAL_THEME' => 'Официальная тема Grav', 'PLUGIN_SYMBOLICALLY_LINKED' => 'Этот плагин символически связан. Обновления не будут найдены.', 'THEME_SYMBOLICALLY_LINKED' => 'Эта тема символически связана. Обновления не будут найдены.', 'REMOVE_PLUGIN' => 'Удалить плагин', 'INSTALL_PLUGIN' => 'Установить плагин', 'AVAILABLE' => 'Доступен', 'INSTALLED' => 'Установлен', 'INSTALL' => 'Установить', 'ACTIVE_THEME' => 'Активная тема', 'SWITCHING_TO' => 'Переключить', 'SWITCHING_TO_DESCRIPTION' => 'При переключении на другую тему нет никакой гарантии того, что поддерживаются все страницы макетов. Возможно, это приведет к ошибкам при попытке загрузки указанных страниц.', 'SWITCHING_TO_CONFIRMATION' => 'Вы действительно хотите продолжить и перейти к теме', 'CREATE_NEW_USER' => 'Создать нового пользователя', 'REMOVE_USER' => 'Удалить пользователя', 'ACCESS_DENIED' => 'Доступ запрещен', 'ACCOUNT_NOT_ADMIN' => 'ваша учетная запись не имеет прав администратора', 'PHP_INFO' => 'Информация о PHP', 'INSTALLER' => 'Установщик', 'AVAILABLE_THEMES' => 'Доступные темы', 'AVAILABLE_PLUGINS' => 'Доступные плагины', 'INSTALLED_THEMES' => 'Установленные темы', 'INSTALLED_PLUGINS' => 'Установленные плагины', 'BROWSE_ERROR_LOGS' => 'Просмотр журналов ошибок', 'SITE' => 'Сайт', 'INFO' => 'Информация', 'SYSTEM' => 'Система', 'USER' => 'Пользователь', 'ADD_ACCOUNT' => 'Добавить учетную запись', 'SWITCH_LANGUAGE' => 'Переключить язык', 'SUCCESSFULLY_ENABLED_PLUGIN' => 'Плагин успешно включён', 'SUCCESSFULLY_DISABLED_PLUGIN' => 'Плагин успешно отключён', 'SUCCESSFULLY_CHANGED_THEME' => 'Успешно изменена тема по умолчанию', 'INSTALLATION_FAILED' => 'Ошибка при установке', 'INSTALLATION_SUCCESSFUL' => 'Установка завершена успешно', 'UNINSTALL_FAILED' => 'Удаление не удалось', 'UNINSTALL_SUCCESSFUL' => 'Удаление успешно', 'SUCCESSFULLY_SAVED' => 'Сохранение успешно', 'SUCCESSFULLY_COPIED' => 'Копирование успешно', 'REORDERING_WAS_SUCCESSFUL' => 'Изменение порядка прошло успешно', 'SUCCESSFULLY_DELETED' => 'Успешно удалено', 'SUCCESSFULLY_SWITCHED_LANGUAGE' => 'Язык подключён успешно', 'INSUFFICIENT_PERMISSIONS_FOR_TASK' => 'У вас недостаточно прав доступа для задачи', 'CACHE_CLEARED' => 'Кэш очищен', 'METHOD' => 'Метод', 'ERROR_CLEARING_CACHE' => 'Ошибка отчистки кэша', 'AN_ERROR_OCCURRED' => 'Произошла ошибка', 'YOUR_BACKUP_IS_READY_FOR_DOWNLOAD' => 'Резервная копия готова', 'DOWNLOAD_BACKUP' => 'Скачать', 'PAGES_FILTERED' => 'Фильтр страниц', 'NO_PAGE_FOUND' => 'Страница не найдена', 'INVALID_PARAMETERS' => 'Неверные параметры', 'NO_FILES_SENT' => 'Файлы не отправляются', 'EXCEEDED_FILESIZE_LIMIT' => 'Превышен предельный размер файла конфигурации PHP', 'UNKNOWN_ERRORS' => 'Неизвестная ошибка', 'EXCEEDED_GRAV_FILESIZE_LIMIT' => 'Превышен предельный размер файла конфигурации Grav', 'UNSUPPORTED_FILE_TYPE' => 'Неподдерживаемый тип файла', 'FAILED_TO_MOVE_UPLOADED_FILE' => 'Не удалось переместить загруженный файл.', 'FILE_UPLOADED_SUCCESSFULLY' => 'Файл загружен успешно', 'FILE_DELETED' => 'Файл удалён', 'FILE_COULD_NOT_BE_DELETED' => 'Файл не может быть удалён', 'FILE_NOT_FOUND' => 'Файл не найден', 'NO_FILE_FOUND' => 'Файлы не найдены', 'GRAV_WAS_SUCCESSFULLY_UPDATED_TO' => 'Grav успешно обновлён', 'GRAV_UPDATE_FAILED' => 'Ошибка обновления Grav', 'EVERYTHING_UPDATED' => 'Обновляются', 'UPDATES_FAILED' => 'Обновление не удалось', 'AVATAR_BY' => 'Аватар', 'LAST_BACKUP' => 'Последняя резервная копия', 'FULL_NAME' => 'Полное имя', 'USERNAME' => 'Имя пользователя', 'EMAIL' => 'Email', 'USERNAME_EMAIL' => 'Имя пользователя или адрес электронной почты', 'PASSWORD' => 'Пароль', 'PASSWORD_CONFIRM' => 'Подтвердите пароль', 'TITLE' => 'Заголовок', 'LANGUAGE' => 'Язык', 'ACCOUNT' => 'Аккаунт', 'EMAIL_VALIDATION_MESSAGE' => 'Должен быть действительный адрес электронной почты', 'PASSWORD_VALIDATION_MESSAGE' => 'Пароль должен содержать хотя бы одну цифру и одну заглавную и строчную букву, и по крайней мере 8 или более символов', 'LANGUAGE_HELP' => 'Выберите предпочитаемый язык', 'MEDIA' => 'Медиа', 'DEFAULTS' => 'По умолчанию', 'SITE_TITLE' => 'Заголовок сайта', 'SITE_TITLE_PLACEHOLDER' => 'Название сайта', 'SITE_TITLE_HELP' => 'Название для вашего сайта по умолчанию, часто используется в темах оформления', 'SITE_DEFAULT_LANG' => 'Язык по умолчанию', 'DEFAULT_AUTHOR' => 'Автор по умолчанию', 'DEFAULT_AUTHOR_HELP' => 'Имя автора по умолчанию, часто используется в темах оформления или содержимом страниц', 'DEFAULT_EMAIL' => 'Email по умолчанию', 'DEFAULT_EMAIL_HELP' => 'Адрес электронной почты по умолчанию, используется для создания ссылки на почту в темах или страницах', 'TAXONOMY_TYPES' => 'Типы таксономии', 'TAXONOMY_TYPES_HELP' => 'Таксономия типов должна быть определена здесь, если вы хотите использовать их на страницах вашего сайта', 'PAGE_SUMMARY' => 'Анонс', 'ENABLED' => 'Включено', 'ENABLED_HELP' => 'Показывать анонс (содержание страницы до разделителя)', 'YES' => 'Да', 'NO' => 'Нет', 'SUMMARY_SIZE' => 'Размер анонса', 'SUMMARY_SIZE_HELP' => 'Количество символов страницы, выводимых в кратком содержании', 'FORMAT' => 'Формат', 'FORMAT_HELP' => 'Короткий = использовать первое вхождение разделителя или размер; Длинный = разделитель игнорируется', 'SHORT' => 'Короткий', 'LONG' => 'Длинный', 'DELIMITER' => 'Разделитель', 'DELIMITER_HELP' => 'Разделитель для функции «Читать далее...» (по умолчанию \'===\')', 'METADATA' => 'Метаданные', 'METADATA_HELP' => 'По умолчанию значения метаданных, которые будут отображаться на каждой странице, если это не определено у страницы', 'NAME' => 'Имя', 'CONTENT' => 'Содержание', 'REDIRECTS_AND_ROUTES' => 'Редиректы и маршрутизация', 'CUSTOM_REDIRECTS' => 'Пользовательские редиректы', 'CUSTOM_REDIRECTS_HELP' => 'Маршрутизация для перенаправления на другие страницы. Действует замена стандартных регулярных выражений', 'CUSTOM_REDIRECTS_PLACEHOLDER_KEY' => '/your/alias', 'CUSTOM_REDIRECTS_PLACEHOLDER_VALUE' => '/your/redirect', 'CUSTOM_ROUTES' => 'Нестандартная маршрутизация', 'CUSTOM_ROUTES_HELP' => 'Маршрутизация алиасов других страниц. Действует замена стандартных регулярных выражений', 'CUSTOM_ROUTES_PLACEHOLDER_KEY' => '/your/alias', 'CUSTOM_ROUTES_PLACEHOLDER_VALUE' => '/your/route', 'FILE_STREAMS' => 'Файловые потоки', 'DEFAULT' => 'По умолчанию', 'PAGE_MEDIA' => 'Вложения', 'OPTIONS' => 'Опции', 'PUBLISHED' => 'Опубликованная', 'PUBLISHED_HELP' => 'По умолчанию, страница опубликована, если вы явно не указали, что материал не опубликован, или через дату публикации, находясь в будущем, или дату снятия с публиации, находясь в в прошлом', 'DATE' => 'Дата', 'DATE_HELP' => 'Переменная даты позволяет специально установить дату, связанную с этой страницей.', 'PUBLISHED_DATE' => 'Дата публикации', 'PUBLISHED_DATE_HELP' => 'Можете указать дату автоматической публикации.', 'UNPUBLISHED_DATE' => 'Дата снятия с публикации', 'UNPUBLISHED_DATE_HELP' => 'Можете указать дату автоматического снятия с публикации.', 'ROBOTS' => 'Роботы', 'TAXONOMIES' => 'Таксономии', 'TAXONOMY' => 'Таксономия', 'ADVANCED' => 'Дополнительно', 'SETTINGS' => 'Настройки', 'FOLDER_NUMERIC_PREFIX' => 'Числовой префикс папки', 'FOLDER_NUMERIC_PREFIX_HELP' => 'Числовой префикс, который обеспечивает ручное упорядочение и подразумевает отображение числа', 'FOLDER_NAME' => 'Имя папки', 'FOLDER_NAME_HELP' => 'Имя папки, которое будут храниться в файловой системе для этой страницы', 'PARENT' => 'Родитель', 'DEFAULT_OPTION_ROOT' => '- Корень -', 'DEFAULT_OPTION_SELECT' => '- Выбрать -', 'DISPLAY_TEMPLATE' => 'Шаблон отображения', 'DISPLAY_TEMPLATE_HELP' => 'Тип страницы, который определяет, какая ветка шаблона отображает страницу', 'BODY_CLASSES' => 'Класс страницы', 'ORDERING' => 'Порядок', 'PAGE_ORDER' => 'Порядок страниц', 'OVERRIDES' => 'Переопределения', 'MENU' => 'Меню', 'MENU_HELP' => 'Строка, которая будет использоваться в меню. Если не задана, будет использоваться заголовок.', 'SLUG' => 'Алиас', 'SLUG_HELP' => 'Эта переменная позволяет установить алиас страницы (часть URL-адреса)', 'SLUG_VALIDATE_MESSAGE' => 'Алиас должен состоять только из строчных алфавитно-цифровых символов и дефисов', 'PROCESS' => 'Процессор', 'PROCESS_HELP' => 'Контроль над тем, как обрабатываются страницы. Может быть установлен индивидуально для каждой страницы', 'DEFAULT_CHILD_TYPE' => 'Тип вложенного элемента', 'USE_GLOBAL' => 'Использовать глобальный', 'ROUTABLE' => 'Маршрутизируемая', 'ROUTABLE_HELP' => 'Использовать маршрутизацию для данной страницы', 'CACHING' => 'Кэширование', 'VISIBLE' => 'Видимая', 'VISIBLE_HELP' => 'Отображать материал в меню сайта или нет', 'DISABLED' => 'Отключено', 'ITEMS' => 'Элементы', 'ORDER_BY' => 'Сортировать по', 'ORDER' => 'Порядок', 'FOLDER' => 'Папка', 'ASCENDING' => 'По возрастанию', 'DESCENDING' => 'По убыванию', 'ADD_MODULAR_CONTENT' => 'Добавить модульное содержимое', 'PAGE_TITLE' => 'Заголовок страницы', 'PAGE_TITLE_HELP' => 'Заголовок текущей страницы', 'PAGE' => 'Страница', 'MODULAR_TEMPLATE' => 'Модульный шаблон', 'FRONTMATTER' => 'Вступление', 'FILENAME' => 'Имя файла', 'PARENT_PAGE' => 'Родительская страница', 'HOME_PAGE' => 'Главная страница', 'HOME_PAGE_HELP' => 'Страница, которую Grav будет использовать по умолчанию в качестве главной', 'DEFAULT_THEME' => 'Тема по умолчанию', 'DEFAULT_THEME_HELP' => 'Шаблон оформления, используемый по умолчанию', 'TIMEZONE' => 'Часовой пояс', 'TIMEZONE_HELP' => 'Изменить значение часового пояса, используемого сервером по умолчанию', 'SHORT_DATE_FORMAT' => 'Краткий формат даты', 'SHORT_DATE_FORMAT_HELP' => 'Задать короткий формат даты, который может использоваться в темах оформления', 'LONG_DATE_FORMAT' => 'Длинный формат даты', 'LONG_DATE_FORMAT_HELP' => 'Задать длинный формат даты, который может использоваться в темах оформления', 'DEFAULT_ORDERING' => 'Порядок по умолчанию', 'DEFAULT_ORDERING_HELP' => 'Страницы в списке будут выводиться с учетом этого порядка, если он не переопределен.', 'DEFAULT_ORDERING_DEFAULT' => 'По умолчанию - в зависимости от имени папки', 'DEFAULT_ORDERING_FOLDER' => 'Папка - в зависимости от приставки имени папки', 'DEFAULT_ORDERING_TITLE' => 'Заголовок - в зависимости от названия поля заголовка', 'DEFAULT_ORDERING_DATE' => 'Дата - в зависимости от поля даты', 'DEFAULT_ORDER_DIRECTION' => 'Порядок сортировки по умолчанию', 'DEFAULT_ORDER_DIRECTION_HELP' => 'Направление сортировки страниц в списке материалов', 'DEFAULT_PAGE_COUNT' => 'Количество страниц по умолчанию', 'DEFAULT_PAGE_COUNT_HELP' => 'Максимальное количество страниц в списке по умолчанию ', 'DATE_BASED_PUBLISHING' => 'Публикация на основе даты', 'DATE_BASED_PUBLISHING_HELP' => 'Автоматически (не)публикует посты на основе их даты', 'EVENTS' => 'События', 'EVENTS_HELP' => 'Включить или отключить специфические события. Отключение этих событий можно привести к ошибкам в работе плагинов', 'REDIRECT_DEFAULT_ROUTE' => 'Перенаправление маршрутизатора по умолчанию', 'REDIRECT_DEFAULT_ROUTE_HELP' => 'Автоматическое перенаправление страниц согласно маршрутизатору', 'LANGUAGES' => 'Язык', 'SUPPORTED' => 'Мультиязычность', 'SUPPORTED_HELP' => 'Укажите необходимые вам языки через запятую (пример \'en,fr,de\')', 'TRANSLATIONS_ENABLED' => 'Поддержка перевода', 'TRANSLATIONS_ENABLED_HELP' => 'Поддержка в Grav перевода плагинов и расширений', 'TRANSLATIONS_FALLBACK' => 'Резервный перевод', 'TRANSLATIONS_FALLBACK_HELP' => 'Использовать запасной вариант перевода, если активный язык не существует', 'ACTIVE_LANGUAGE_IN_SESSION' => 'Активный язык в сессии', 'ACTIVE_LANGUAGE_IN_SESSION_HELP' => 'Хранить активный язык в сессии пользователя', 'HTTP_HEADERS' => 'Заголовки HTTP', 'EXPIRES' => 'Срок действия', 'EXPIRES_HELP' => 'Устанавливает заголовок Expires. Значение в секундах.', 'LAST_MODIFIED' => 'Дата последнего изменения', 'LAST_MODIFIED_HELP' => 'Устанавливает заголовок последнего изменения, который может помочь оптимизировать кэширование и браузере', 'ETAG' => 'ETag', 'ETAG_HELP' => 'Устанавливает заголовок ETag, чтобы помочь определить, когда страница была изменена', 'VARY_ACCEPT_ENCODING' => 'Vary: Accept Encoding', 'VARY_ACCEPT_ENCODING_HELP' => 'Установите заголовок `Vary: Accept Encoding` для помощи прокси-кэширования и cdn', 'MARKDOWN_EXTRA_HELP' => 'Включение по умолчанию для поддержки Markdown Extra - https://michelf.ca/projects/php-markdown/extra/', 'AUTO_LINE_BREAKS' => 'Авторазрывы строк', 'AUTO_LINE_BREAKS_HELP' => 'Включить поддержку автоматических разрывов строк в markdown', 'AUTO_URL_LINKS' => 'Автопреобразование URL', 'AUTO_URL_LINKS_HELP' => 'Включить автоматическое преобразование URL в HTML-код гиперссылки', 'ESCAPE_MARKUP' => 'Экранирование разметки', 'ESCAPE_MARKUP_HELP' => 'Избегать тегов разметки в HTML объектах', 'CACHING_HELP' => 'Глобальный выключатель для включения/отключения кэширования Grav', 'CACHE_CHECK_METHOD' => 'Метод проверки кэша', 'CACHE_CHECK_METHOD_HELP' => 'Выберите метод, который Grav использует для проверки, если файлы страниц были изменены.', 'CACHE_DRIVER' => 'Драйвер кэширования', 'CACHE_DRIVER_HELP' => 'Выберите метод кеширования, который должен использовать Grav. \'Auto Detect\' - CMS попытается определить лучшый метод для вашего сайта', 'CACHE_PREFIX' => 'Префикс кэша', 'CACHE_PREFIX_HELP' => 'Идентификатор для части ключа Grav. Не изменяйте, если Вы не знаете к чему это приведет.', 'CACHE_PREFIX_PLACEHOLDER' => 'Производный от базового URL (переопределите, введя произвольную строку)', 'LIFETIME' => 'Время жизни', 'LIFETIME_HELP' => 'Задает время жизни кэша в секундах. 0 = бесконечно', 'GZIP_COMPRESSION' => 'Gzip сжатие', 'GZIP_COMPRESSION_HELP' => 'Включить сжатие GZip в Grav для увеличения скорости загрузки страниц.', 'TWIG_TEMPLATING' => 'Шаблоны Twig', 'TWIG_CACHING' => 'Кэширование Twig', 'TWIG_CACHING_HELP' => 'Управление механизмом кэширования Twig. Оставьте его включённым для обеспечения лучшей производительности.', 'TWIG_DEBUG' => 'Отладка Twig', 'TWIG_DEBUG_HELP' => 'Позволяет не загружается расширение отладчика Twig', 'DETECT_CHANGES' => 'Обнаружение изменений', 'DETECT_CHANGES_HELP' => 'Twig автоматически перекомпилирует кэш Twig, если обнаружит какие-либо изменения в шаблонах Twig', 'AUTOESCAPE_VARIABLES' => 'Авто исключение переменных', 'AUTOESCAPE_VARIABLES_HELP' => 'Авто исключение всех переменные. Это скорей всего нарушит работу вашего сайта.', 'ASSETS' => 'Дополнительные библиотеки', 'CSS_PIPELINE' => 'Объединение CSS', 'CSS_PIPELINE_HELP' => 'Позволит объединить несколько файлов CSS в один.', 'CSS_PIPELINE_INCLUDE_EXTERNALS' => 'Включать внешние ресурсы в CSS пайплайн', 'CSS_PIPELINE_INCLUDE_EXTERNALS_HELP' => 'Внешние URL-адреса иногда имеют связанные ссылки на файлы и не могут быть в пайплайне', 'CSS_PIPELINE_BEFORE_EXCLUDES' => 'Рендер CSS пайплайна сначала', 'CSS_PIPELINE_BEFORE_EXCLUDES_HELP' => 'Рендер CSS пайплайна до остальных CSS связей, которые не включены', 'CSS_MINIFY' => 'Минимизировать CSS', 'CSS_MINIFY_HELP' => 'Минимизировать в CSS во время объединения', 'CSS_MINIFY_WINDOWS_OVERRIDE' => 'Минимизировать CSS переопределение для Windows.', 'CSS_MINIFY_WINDOWS_OVERRIDE_HELP' => 'Минимизировать переопределение для платформ Windows. Отключено по умолчанию из-за ThreadStackSize', 'CSS_REWRITE' => 'Переписать CSS', 'CSS_REWRITE_HELP' => 'Переписать любые CSS относительные URL-адреса во время объединения', 'JAVASCRIPT_PIPELINE' => 'Объединение JavaScript', 'JAVASCRIPT_PIPELINE_HELP' => 'Объединение нескольких JS файлов в один', 'JAVASCRIPT_PIPELINE_INCLUDE_EXTERNALS' => 'Включать внешние ресурсы в JS пайплайн', 'JAVASCRIPT_PIPELINE_INCLUDE_EXTERNALS_HELP' => 'Внешние URL-адреса иногда имеют относительные ссылки на файлы и не могут быть в пайплайне', 'JAVASCRIPT_PIPELINE_BEFORE_EXCLUDES' => 'Рендер JS пайплайна сначала', 'JAVASCRIPT_PIPELINE_BEFORE_EXCLUDES_HELP' => 'Рендер JS пайплайна до остальных JS связей, которые не включены', 'JAVASCRIPT_MINIFY' => 'Минимизировать JavaScript', 'JAVASCRIPT_MINIFY_HELP' => 'Минимизировать в JS во время объединения', 'ENABLED_TIMESTAMPS_ON_ASSETS' => 'Включить временные метки по активам', 'ENABLED_TIMESTAMPS_ON_ASSETS_HELP' => 'Включить временные метки активов', 'COLLECTIONS' => 'Коллекции', 'ERROR_HANDLER' => 'Обработчик ошибок', 'DISPLAY_ERRORS' => 'Выводить ошибки', 'DISPLAY_ERRORS_HELP' => 'Отобразить полную цепочку стилей при ошибке на странице', 'LOG_ERRORS' => 'Логи ошибок', 'LOG_ERRORS_HELP' => 'Логи ошибок находятся в папке /logs', 'DEBUGGER' => 'Отладчик', 'DEBUGGER_HELP' => 'Включите отладчик Grav и после параметров настройки', 'DEBUG_TWIG' => 'Отладчик Twig', 'DEBUG_TWIG_HELP' => 'Включите отладчик шаблонов Twig', 'SHUTDOWN_CLOSE_CONNECTION' => 'Завершение открытых соединений', 'SHUTDOWN_CLOSE_CONNECTION_HELP' => 'Закройте соединение до вызова onShutdown(). ложно для отладки', 'DEFAULT_IMAGE_QUALITY' => 'Качество изображений по умолчанию', 'DEFAULT_IMAGE_QUALITY_HELP' => 'Качество изображения по умолчанию для использования при повторной выборки или кэширования изображений (85%)', 'CACHE_ALL' => 'Кэшировать все картинки', 'CACHE_ALL_HELP' => 'Выполните все изображения через систему кэша Grav, даже если у них нет взаимодействия диском', 'IMAGES_DEBUG' => 'Отладка водяного знака изображения', 'IMAGES_DEBUG_HELP' => 'Показать накладку над изображениями с указанием глубины пикселя изображения при работе с сеткой', 'UPLOAD_LIMIT' => 'Лимит загрузки файла', 'UPLOAD_LIMIT_HELP' => 'Установите максимальный размер в байтах для загрузки (0 безлимита)', 'ENABLE_MEDIA_TIMESTAMP' => 'Включить временные метки на медиа', 'ENABLE_MEDIA_TIMESTAMP_HELP' => 'Добавляет метку на основе даты последнего изменения каждого элемента в медиа', 'SESSION' => 'Сессия', 'SESSION_ENABLED_HELP' => 'Включить поддержку сессий в рамках Grav', 'TIMEOUT' => 'Время ожидания', 'TIMEOUT_HELP' => 'Устанавливает тайм-аут сеанса в секундах', 'SESSION_NAME_HELP' => 'Идентификатор используется для формирования имени сессионной куки', 'ABSOLUTE_URLS' => 'Абсолютный путь', 'ABSOLUTE_URLS_HELP' => 'Абсолютных или относительных URL-адресов для `base_url`', 'PARAMETER_SEPARATOR' => 'Параметр разделителя', 'PARAMETER_SEPARATOR_HELP' => 'Разделитель для передаваемых параметров, которые могут быть изменены для Apache на Windows', 'TASK_COMPLETED' => 'Задача завершена', 'EVERYTHING_UP_TO_DATE' => 'Всё актуально', 'UPDATES_ARE_AVAILABLE' => 'обновления доступны', 'IS_AVAILABLE_FOR_UPDATE' => 'доступно для обновления', 'IS_NOW_AVAILABLE' => 'теперь доступно', 'CURRENT' => 'Текущий', 'UPDATE_GRAV_NOW' => 'Обновить Grav сейчас', 'GRAV_SYMBOLICALLY_LINKED' => 'Grav символично связаны. Обновление не будет доступно', 'UPDATING_PLEASE_WAIT' => 'Обновление... Пожалуйста, подождите, загрузка', 'OF_THIS' => 'этого', 'OF_YOUR' => 'из ваших', 'HAVE_AN_UPDATE_AVAILABLE' => 'есть доступное обновление', 'SAVE_AS' => 'Сохранить как', 'MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_DESC' => 'Вы уверены, что хотите удалить эту страницу и все вложенные? Если страница переведена на другие языки, эти переводы будут сохранены и должны быть удалены отдельно. В противном случае папка страницы будет удалена вместе со своими подстраницами. Это действие не может быть отменено.', 'AND' => 'и', 'UPDATE_AVAILABLE' => 'Доступно обновление', 'METADATA_KEY' => 'Ключ (например \'Ключевые слова\')', 'METADATA_VALUE' => 'Значение (например \'Blog, Grav\')', 'USERNAME_HELP' => 'Имя пользователя должно быть от 3 до 16 символов, в том числе строчных букв, цифр, подчеркивания и дефиса. Прописные буквы, пробелы и специальные символы не допускаются', 'FULLY_UPDATED' => 'Полностью обновлено', 'SAVE_LOCATION' => 'Расположение', 'PAGE_FILE' => 'Шаблон страницы', 'PAGE_FILE_HELP' => 'Название файла шаблона страницы, используемого для отображения содержимого', 'NO_USER_ACCOUNTS' => 'Учетные записи не найдены, пожалуйста, создайте первую запись...', 'REDIRECT_TRAILING_SLASH' => 'Перенаправление замыкающей слэш', 'REDIRECT_TRAILING_SLASH_HELP' => 'Выполните 301 редирект на замыкающий слэш.', 'DEFAULT_DATE_FORMAT' => 'Формат даты', 'DEFAULT_DATE_FORMAT_HELP' => 'Формат даты страницы, используемый в Grav. По умолчанию Grav пытается определить правильный формат даты, однако вы можете задать формат с помощью РНР синтаксиса для работы с датами (например: Y-m-d H:i)', 'DEFAULT_DATE_FORMAT_PLACEHOLDER' => 'Определить автоматически', 'IGNORE_FILES' => 'Игнорировать файлы', 'IGNORE_FILES_HELP' => 'Файлы, которые будут проигнорированы при обработке страниц', 'IGNORE_FOLDERS' => 'Игнорировать папки', 'IGNORE_FOLDERS_HELP' => 'Папки, которые будут проигнорированы при обработке страниц', 'HTTP_ACCEPT_LANGUAGE' => 'Определять язык браузера', 'HTTP_ACCEPT_LANGUAGE_HELP' => 'Вы можете разрешить попытаться установить язык на основе \'http_accept_language\' тега заголовка в браузере пользователя', 'OVERRIDE_LOCALE' => 'Переопределение локали', 'OVERRIDE_LOCALE_HELP' => 'Переопределение языковой локали в PHP на основе текущего языка', 'REDIRECT' => 'Страница редиректа', 'REDIRECT_HELP' => 'Введите адрес страницы или внешний URL для страницы сайта, чтобы перенаправить например, \'/some/route\' или \'http://somesite.com\'', 'PLUGIN_STATUS' => 'Статус плагина', 'INCLUDE_DEFAULT_LANG' => 'Включить язык по умолчанию', 'INCLUDE_DEFAULT_LANG_HELP' => 'Все URL-адреса будут предваряться приставкой языка. Например, `/en/blog/my-post`', 'ALLOW_URL_TAXONOMY_FILTERS' => 'URL для фильтров таксономии', 'ALLOW_URL_TAXONOMY_FILTERS_HELP' => 'Базовая страница для фильтров`/taxonomy:value`.', 'REDIRECT_DEFAULT_CODE' => 'Перенаправление по умолчанию', 'REDIRECT_DEFAULT_CODE_HELP' => 'Статус заголовка HTTP при перенаправлении URL', 'IGNORE_HIDDEN' => 'Игнорировать скрытые', 'IGNORE_HIDDEN_HELP' => 'Игнорировать все скрытые файлы и папки', 'WRAPPED_SITE' => 'Завернутый сайт', 'WRAPPED_SITE_HELP' => 'Сообщает плагину или теме оформления, что Grav обернут в другую платформу', 'FALLBACK_TYPES' => 'Разрешенные резервные типы', 'FALLBACK_TYPES_HELP' => 'Разрешенные типы файлов, которые могут быть найдены, если обратиться через маршрутизатор страниц', 'INLINE_TYPES' => 'Встроенные типы запасных вариантов', 'INLINE_TYPES_HELP' => 'Список типов файлов, которые должны отображаться, как строенные, а не загружаться', 'APPEND_URL_EXT' => 'Добавьте URL расширения', 'APPEND_URL_EXT_HELP' => 'Будет добавлено пользовательское расширение URL страницы. Обратите внимание, что Grav будет искать шаблон в формате `<template>.<extension>.twig`', 'PAGE_MODES' => 'Режимы страницы', 'PAGE_TYPES' => 'Типы страницы', 'ACCESS_LEVELS' => 'Уровни доступа', 'GROUPS' => 'Группы', 'GROUPS_HELP' => 'Список групп пользователей входящих в', 'ADMIN_ACCESS' => 'Доступ администратора', 'SITE_ACCESS' => 'Доступ сайта', 'INVALID_SECURITY_TOKEN' => 'Неверный маркер безопасности', 'ACTIVATE' => 'Активировать', 'TWIG_UMASK_FIX' => 'Umask Fix', 'TWIG_UMASK_FIX_HELP' => 'По умолчанию Twig создает кэшированные файлы с правами 0755, исправить переключатели на 0775', 'CACHE_PERMS' => 'Права кэша', 'CACHE_PERMS_HELP' => 'По умолчанию права папки кэша. Обычно 0755 или 0775 в зависимости от настроек сервера', 'REMOVE_SUCCESSFUL' => 'Успешно удалено', 'REMOVE_FAILED' => 'Не удалось удалить', 'HIDE_HOME_IN_URLS' => 'Убрать путь к главной странице из адресов дочерних', 'HIDE_HOME_IN_URLS_HELP' => 'Все дочерние страницы внутри главной не будут содержать в адресах маршрутизатор главной (например, вместо /blog/mypage будет отображаться просто /mypage)', 'TWIG_FIRST' => 'Процесс Twig первый', 'TWIG_FIRST_HELP' => 'Если включали обработку страницы Twig, то можно сконфигурировать Twig, чтобы обработать прежде или после markdown', 'SESSION_SECURE' => 'Безопасный', 'SESSION_SECURE_HELP' => 'Если включено, указывает, что соединение для этого cookie должна быть по зашифрованной передаче. ПРЕДУПРЕЖДЕНИЕ: Включите это только на сайтах, которые работают исключительно на HTTPS', 'SESSION_HTTPONLY' => 'Только HTTP', 'SESSION_HTTPONLY_HELP' => 'Если Да, то, куки должны быть использованы только по протоколу HTTP, и модификация JavaScript не допускается', 'REVERSE_PROXY' => 'Обратный прокси-сервер', 'REVERSE_PROXY_HELP' => 'Включить, если вы находитесь за обратным прокси, и вы испытываете проблемы с URL-адресов, содержащих некорректные порты', 'INVALID_FRONTMATTER_COULD_NOT_SAVE' => 'Неверный вводная, не может быть сохранено', 'ADD_FOLDER' => 'Добавить папку', 'PROXY_URL' => 'Адрес прокси', 'PROXY_URL_HELP' => 'Введите адрес прокси или IP-адрес и номер порта', 'NOTHING_TO_SAVE' => 'Нечего сохранять', 'FILE_ERROR_ADD' => 'Произошла ошибка при попытке добавить файл', 'FILE_ERROR_UPLOAD' => 'Произошла ошибка при попытке загрузить файл', 'FILE_UNSUPPORTED' => 'Неподдерживаемый тип файла', 'ADD_ITEM' => 'Добавить элемент', 'FILE_TOO_LARGE' => 'Файл слишком большой, чтобы быть загруженным, максимально допустимый размер %s согласно <br>настройке PHP. Увеличте значение параметра настройки PHP `post_max_size`', 'INSTALLING' => 'Установка', 'LOADING' => 'Загрузка..', 'DEPENDENCIES_NOT_MET_MESSAGE' => 'Для начала должны быть удовлетворены следующие зависимости:', 'ERROR_INSTALLING_PACKAGES' => 'Ошибка при установке пакетов', 'INSTALLING_DEPENDENCIES' => 'Установка зависимостей...', 'INSTALLING_PACKAGES' => 'Установка пакетов..', 'PACKAGES_SUCCESSFULLY_INSTALLED' => 'Пакеты успешно установлены.', 'READY_TO_INSTALL_PACKAGES' => 'Всё готово для установки пакетов', 'PACKAGES_NOT_INSTALLED' => 'Пакеты не установлены', 'PACKAGES_NEED_UPDATE' => 'Пакеты уже установлены, но их версии слишком старые', 'PACKAGES_SUGGESTED_UPDATE' => 'Пакеты уже установлены и их версии в порядке, но они будут обновлены, чтобы использовать последние версии', 'REMOVE_THE' => 'Удалить %s', 'CONFIRM_REMOVAL' => 'Вы уверены, что хотите удалить %s?', 'REMOVED_SUCCESSFULLY' => '%s успешно удалён', 'ERROR_REMOVING_THE' => 'Ошибка удаления %s', 'ADDITIONAL_DEPENDENCIES_CAN_BE_REMOVED' => '%s требует следующие зависимости, которые не требуются в других установленных пакетах. Если вы не используете их, можно удалить их прямо отсюда.', 'READY_TO_UPDATE_PACKAGES' => 'Всё готово для обновления пакетов', 'ERROR_UPDATING_PACKAGES' => 'Ошибка при обновлении пакетов', 'UPDATING_PACKAGES' => 'Обновление пакетов..', 'PACKAGES_SUCCESSFULLY_UPDATED' => 'Пакеты успешно обновлены.', 'UPDATING' => 'Обновление', 'GPM_RELEASES' => 'Релизы GPM', 'GPM_RELEASES_HELP' => 'Выберите вариант «Testing» для установки бета-релизов или тестовых версий', 'AUTO' => 'Автоматически', 'FOPEN' => 'fopen', 'CURL' => 'cURL', 'STABLE' => 'Стабильная версия', 'TESTING' => 'Тестирование', 'FRONTMATTER_PROCESS_TWIG' => 'Обрабатывать Twig в обобщенных страницах', 'FRONTMATTER_PROCESS_TWIG_HELP' => 'При включении вы можете использовать конфигурационные переменные Twig в обобщенных страницах', 'FRONTMATTER_IGNORE_FIELDS' => 'Игнорировать обобщенные поля', 'FRONTMATTER_IGNORE_FIELDS_HELP' => 'Некоторые обобщенные поля могут содержать Twig, но не должны быть обработаны как «формы»', 'PACKAGE_X_INSTALLED_SUCCESSFULLY' => 'Пакет %s успешно установлен', 'NEEDS_GRAV_1_1' => '<i class="fa fa-exclamation-triangle"></i> <strong>Вы используете Grav v%s</strong>. Необходимо обновить её до последней версии <strong>Grav v1.1.x</strong> для обеспечения совместимости. Это может потребовать переключения в <strong>Тестовый GPM режим</strong> в Конфигурации системы.', 'ORDERING_DISABLED_BECAUSE_PARENT_SETTING_ORDER' => 'Установка сортировки родителя, изменение порядка отключено', 'ORDERING_DISABLED_BECAUSE_PAGE_NOT_VISIBLE' => 'Страница не отображаема, изменение порядка отключено', 'ORDERING_DISABLED_BECAUSE_TOO_MANY_SIBLINGS' => 'Сортировка через админ-панель не поддерживается, поскольку используется более 200 потомков', 'CANNOT_ADD_MEDIA_FILES_PAGE_NOT_SAVED' => 'Примечание: добавление файлов невозможно, пока вы не сохраните страницу. Кликните «Сохранить» в верхней части админки.', 'CANNOT_ADD_FILES_PAGE_NOT_SAVED' => 'Примечание: страница должна быть сохранена перед загрузкой файлов.', 'DROP_FILES_HERE_TO_UPLOAD' => 'Переместите файлы сюда или <strong>нажмите на эту область</strong>', 'INSERT' => 'Вставить', 'UNDO' => 'Отменить', 'REDO' => 'Повторить', 'HEADERS' => 'Заголовки', 'BOLD' => 'Жирный', 'ITALIC' => 'Курсив', 'STRIKETHROUGH' => 'Перечеркнутый', 'SUMMARY_DELIMITER' => 'Разделитель', 'LINK' => 'Ссылка', 'IMAGE' => 'Изображение', 'BLOCKQUOTE' => 'Цитата', 'UNORDERED_LIST' => 'Маркированный список', 'ORDERED_LIST' => 'Нумерованный список', 'EDITOR' => 'Редактор', 'PREVIEW' => 'Просмотреть', 'FULLSCREEN' => 'Полноэкранный режим', 'MODULAR' => 'Модульная', 'NON_ROUTABLE' => 'Немаршрутизируемая', 'NON_MODULAR' => 'Немодульная', 'NON_VISIBLE' => 'Невидимая', 'NON_PUBLISHED' => 'Неопубликованная', 'CHARACTERS' => 'символов', 'PUBLISHING' => 'Публикация', 'NOTIFICATIONS' => 'Уведомления', 'MEDIA_TYPES' => 'Типы вложений', 'IMAGE_OPTIONS' => 'Параметры изображения', 'MIME_TYPE' => 'Mime-тип', 'THUMB' => 'Миниатюра', 'TYPE' => 'Тип', 'FILE_EXTENSION' => 'Расширение файла', 'LEGEND' => 'Обозначения', 'MEMCACHE_SERVER' => 'Memcache сервер', 'MEMCACHE_SERVER_HELP' => 'Адрес сервера Memcache', 'MEMCACHE_PORT' => 'Memcache порт', 'MEMCACHE_PORT_HELP' => 'Порт сервера Memcache', 'MEMCACHED_SERVER' => 'Memcached сервер', 'MEMCACHED_SERVER_HELP' => 'Адрес сервера Memcached', 'MEMCACHED_PORT' => 'Memcached порт', 'MEMCACHED_PORT_HELP' => 'Порт сервера Memcached', 'REDIS_SERVER' => 'Redis сервер', 'REDIS_SERVER_HELP' => 'Адрес сервера Redis', 'REDIS_PORT' => 'Redis порт', 'REDIS_PORT_HELP' => 'Порт сервера Redis', 'ALL' => 'все', 'FROM' => 'от', 'TO' => 'к', 'RELEASE_DATE' => 'Дата выпуска', 'SORT_BY' => 'Сортировать по', 'RESOURCE_FILTER' => 'Фильтр...', 'FORCE_SSL' => 'Принудительный SSL', 'FORCE_SSL_HELP' => 'Принудительно включить SSL по всему сайту. Если включено, при открытии сайта по HTTP Grav перенаправит на HTTPS', 'NEWS_FEED' => 'Лента новостей', 'EXTERNAL_URL' => 'Внешний URL', 'SESSION_PATH_HELP' => 'Используйте, только если выбран пользовательский базовый URL (вы изменяли домен сайта / подпапку)', 'CUSTOM_BASE_URL' => 'Пользовательский базовый URL', 'CUSTOM_BASE_URL_HELP' => 'Используйте, если вы хотите переписать домен сайта или использовать подпапку, отличную от той, что использует Grav. Пример: http://localhost', 'FILEUPLOAD_PREVENT_SELF' => 'Нельзя использовать "%s" за пределами страницы.', 'FILEUPLOAD_UNABLE_TO_UPLOAD' => 'Не удается загрузить файл %s: %s', 'FILEUPLOAD_UNABLE_TO_MOVE' => 'Не удается переместить файл %s в "%s"', 'DROPZONE_CANCEL_UPLOAD' => 'Отменить загрузку', 'DROPZONE_CANCEL_UPLOAD_CONFIRMATION' => 'Вы уверены, что хотите отменить эту загрузку?', 'DROPZONE_DEFAULT_MESSAGE' => 'Перетащите файлы сюда или <strong>нажмите на эту область</strong>', 'DROPZONE_FALLBACK_MESSAGE' => 'Ваш браузер не поддерживает жест перетаскивания для загрузки файлов.', 'DROPZONE_FALLBACK_TEXT' => 'Пожалуйста, используйте резервную форму ниже, чтобы загрузить файлы как раньше.', 'DROPZONE_FILE_TOO_BIG' => 'Файл слишком велик ({{filesize}}MiB). Максимальный допустимый размер: {{maxFilesize}}MiB.', 'DROPZONE_INVALID_FILE_TYPE' => 'Вы не можете загружать файлы этого типа.', 'DROPZONE_MAX_FILES_EXCEEDED' => 'Вы не можете загрузить больше файлов.', 'DROPZONE_REMOVE_FILE' => 'Удалить файл', 'DROPZONE_RESPONSE_ERROR' => 'Сервер ответил с кодом {{statusCode}}.', 'ADMIN_CACHING' => 'Включить кэширование админки', 'ADMIN_CACHING_HELP' => 'Кэшированием в админке можно управлять независимо от основного сайта', 'UPLOAD_ERR_NO_TMP_DIR' => 'Отсутствует временная директория', 'ERROR_SIMPLE' => 'Простая ошибка', 'ERROR_SYSTEM' => 'Системная ошибка', 'OFFLINE_WARNING' => 'Невозможно установить подключение к GPM' ] ] ];
mit
meziantou/Meziantou.Framework
tests/Meziantou.Framework.Tests/TaskExtensionsTests.cs
1096
using System; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Xunit; namespace Meziantou.Framework.Tests { public sealed class TaskExtensionsTests { [Fact] public void ForgetTest_SuccessfullyCompleted() { var task = Task.FromResult(0); task.Forget(); // Should not throw exception } [Fact] public void ForgetTest_Faulted() { var task = Task.FromException(new InvalidOperationException("")); task.Forget(); // Should not throw exception } [Fact] public void ForgetTest_Canceled() { using var cts = new CancellationTokenSource(); cts.Cancel(); var task = Task.FromCanceled(cts.Token); task.Forget(); // Should not throw exception } [Fact] public async Task WhenAll() { var (a, b) = await (Task.FromResult(0), Task.FromResult("test")); a.Should().Be(0); b.Should().Be("test"); } } }
mit
jonpearse/jonpearse.net
app/controllers/admin/work/techs_controller.rb
122
class Admin::Work::TechsController < Admin::CmsController def initialize super @model_class = Tech end end
mit
Bodaclick/EVTAE
src/EVT/DIYBundle/Model/Mapper/ShowroomMapper.php
726
<?php namespace EVT\DIYBundle\Model\Mapper; use EVT\DIYBundle\Entity\Showroom; /** * Class ShowroomMapper * * @author Marco Ferrari <[email protected]> * @copyright 2014 Bodaclick */ class ShowroomMapper { /** * @param $wsModel * * @return Showroom */ public function mapWStoModel($wsModel) { return new Showroom( $wsModel['id'], $wsModel['name'], $wsModel['description'] ); } public function mapModeltoWS(Showroom $showroom) { return [ 'id' => $showroom->getEvtId(), 'name' => $showroom->getName(), 'description' => $showroom->getDescription() ]; } }
mit
WielderOfMjoelnir/pypeira
pypeira/io/common.py
5526
import os from pypeira.io.reader import _read_file from pypeira.core.hdu import HDU def read(path, ftype='fits', dtype=None, walk=True, headers_only=False, image_only=False, *args, **kwargs): """ Proper description will be written when implementation is more complete. Reads files from path. Parameters ---------- path: str The path you want to read files from. Can be directory or file name. If path corresponds to a directory and 'walk' is true, it will walk the directory and its children, reading files as it goes along, otherwise it will simply read the files in the directory given. If file name then it will simply read the data form the given file. ftype: str, optional The file type/extension of the files you want to read data from. Default is 'fits'. dtype: str, optional The type of FITS file you want to read. If not None, will filter out all path names not ending in "dtype.FITS", i.e. if dtype = 'bcd' just_a_test_bcd.FITS is a valid, but just_a_test.FITS is not valid, in this case. walk: bool, optional Specifies whether or not to walk the directory. If 'path' is not a directory, 'walk' affects nothing. Default is True. headers_only: bool, optional Set to True if you only want to read the headers of the files. If True, the data return will only be the headers of the files read. Default is False. image_only: bool, optional Set to True if you only want to read the image data of the files. NOT IMPLEMENTED. *args: optional Contains all arguments that will be passed onto the actual reader function, where the reader function used for each file type/extension is as specified above. **kwargs: optional Same as for 'args'. Contains all keyword arguments that will be passed onto the actual reader function, where the reader used for each file type/extension is as specified above. (The specification will come later on. For now there's nothing more than fitsio.read()) Returns ------- HDU object If 'path' pointed to is a single file - returned 'data' will be a single HDU object, directory - returned 'data' will be a list of HDU objects, no valid files - returned 'data' will be None. "valid" is as specified by the ftype argument, which defaults to 'fits'. Note for a single file the returned 'data' will be only one HDU object, NOT a list as if the path is a directory. See pypeira.core.hdu for implementation of HDU. FITSHDR object If 'headers_only' is not False it will return in the same manner as for the FITS object, but now the type of the files will be FITSHDR objects. Can be access like a regular dictionary using indices. See fitsio.fitslib.FITSHDR for implementation of FITSHDR. numpy.array If 'image_only' is not False it will return in the same manner as for the FITS object, but now the type of the tiles will be numpy.arrays. Raises ------ OSError Raises OSError if the given path does not exist. """ # Reads from whatever path the user inputs # Initialize variables data = list() # First check if path is valid, raise OSError() if invalid if not os.path.exists(path): raise RuntimeError("{0} does not exists.".format(path)) # Check if file if os.path.isfile(path): # Read file if headers_only or image_only: data = _read_file(path, ftype, dtype, headers_only, image_only, *args, **kwargs) else: data = HDU(path, ftype=ftype, dtype=dtype) # Check if dir elif os.path.isdir(path): # If dir to be walked if walk: # Walk directory nodes = os.walk(path) # Iterate through the nodes: # node[0] is the current node # node[1] contains folders in current node # node[2] contains the file names in current node for node in nodes: for fname in node[2]: # Create path for 'fname' file_path = os.path.join(node[0], fname) if headers_only or image_only: file_data = _read_file(file_path, ftype, dtype, headers_only, image_only, *args, **kwargs) # If read was successful, append to data if file_data is not None: data.append(file_data) else: # Create HDU instance which will call _read_file() itself hdu = HDU(file_path, ftype=ftype, dtype=dtype, *args, **kwargs) # If read was successful, append to data if hdu.has_data: data.append(hdu) else: # Read files from top dir only for fname in os.listdir(path): # os.listdir() returns a list of paths as strings for each file in path file_data = _read_file(fname, ftype, dtype, headers_only, image_only, *args, **kwargs) # if _read_file() was successful, append returned value to 'data' list if file_data is not None: data.append(file_data) return data
mit
yunomichawan/AloneWar
Assets/Scripts/Stage/Event/TriggerSender/Base/UnitTriggerSender.cs
1023
using AloneWar.Common; using AloneWar.DataObject.Sqlite.SqliteObject.Master; using AloneWar.Stage.Event.EventObject; using System.Collections.Generic; namespace AloneWar.Stage.Event.TriggerSender { /// <summary> /// ユニットに対するイベントトリガーの基本クラス /// </summary> /// public class UnitTriggerSender { /// <summary> /// /// </summary> public List<int> UnitStageStatusIdList { get; set; } /// <summary> /// /// </summary> public AiCategory ChangeAiCategory { get; set; } /// <summary> /// /// </summary> public UnitSideCategory ChangeUnitSideCategory { get; set; } /// <summary> /// /// </summary> public int StatusGrantedParamId { get; set; } /// <summary> /// /// </summary> public StatusGrantedParamData StatusGrantedParamData { get; set; } } }
mit
benlakey/letter_histogram
LetterHistogram/LetterHistogram.cs
1723
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LetterHistogram { class LetterHistogram { private string input; private int largestCount; private Dictionary<char, int> counts; public LetterHistogram(string input) { this.input = input; this.counts = new Dictionary<char, int>(); } public void Process() { foreach (char c in input) { if (counts.ContainsKey(c)) { counts[c]++; if (counts[c] > largestCount) largestCount = counts[c]; } else { counts.Add(c, 1); } } } public override string ToString() { var stringBuilder = new StringBuilder(); for (int i = largestCount; i > 0; i--) { for (char c = 'a'; c <= 'z'; c++) { if (counts.ContainsKey(c) && counts[c] >= i) { stringBuilder.Append("*"); } else { stringBuilder.Append(" "); } } stringBuilder.AppendLine(); } for (char c = 'a'; c <= 'z'; c++) { stringBuilder.Append(c); } stringBuilder.AppendLine(); return stringBuilder.ToString(); } } }
mit
CooloiStudio/SH_HotelSystem
src/java/Action/LoginAction.java
3703
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Action; import com.opensymphony.xwork2.ActionSupport; import com.orm.Staff; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.interceptor.ServletRequestAware; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * * @author vip */ public class LoginAction extends ActionSupport implements ServletRequestAware{ private int staff_id; private String password; private HttpServletRequest request; public LoginAction(int staff_id, String password, HttpServletRequest request) { this.staff_id = staff_id; this.password = password; this.request = request; } public LoginAction() { } public void validate(){ List<Staff> list_s = null;//验证用户名是否正确 List<Staff> list_p = null;//验证用户密码是否正确 try{ //加载hibernate配置文件 Configuration configuration = new Configuration(); Configuration config = configuration.configure("hibernate.cfg.xml"); //建立session SessionFactory sessionfactory = config.buildSessionFactory(); Session session = sessionfactory.openSession(); //查询账号和密码 String hql_s = "from Staff where staff_id=?"; String hql_p = "from Staff where staff_id=? and password=?"; //不开启事物,查询用户名和密码 Query query_s = session.createQuery(hql_s); Query query_p = session.createQuery(hql_p); query_s.setParameter(0, staff_id); query_p.setParameter(0, staff_id); query_p.setParameter(1, password); //查询,将结果返回到list中 list_s = query_s.list(); list_p = query_p.list(); }catch(Exception e){ e.printStackTrace(); } if(this.staff_id==0){//判断是否输入用户账号 this.addFieldError("staff_id", "请输入用户名"); }else if(this.password.length()==0||this.password==null){//判断是否输入用户密码 this.addFieldError("password", "请输入密码"); }else if(list_s.size()==0||list_s==null){//判断用户存在 this.addFieldError("staff_id", "用户名不存在"); }else if(list_p.size()==0||list_p==null){//判断输入密码是否正确 this.addFieldError("password", "密码输入错误"); }else{//通过验证,将用户信息通过session传回前台 HttpSession httpsession = request.getSession(); httpsession.setAttribute("staff", list_s); } } public String execute() throws Exception { // throw new UnsupportedOperationException("Not supported yet."); return "login_success"; } @Override public void setServletRequest(HttpServletRequest request) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. this.request = request; } public int getStaff_id() { return staff_id; } public void setStaff_id(int staff_id) { this.staff_id = staff_id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
mit
anqqa/Anqh
modules/anqh/helpers/MY_html.php
8803
<?php defined('SYSPATH') OR die('No direct access allowed.'); /** * Anqh extended HTML5 helper class. * * @package Anqh * @author Antti Qvickström * @copyright (c) 2009-2010 Antti Qvickström * @license http://www.opensource.org/licenses/mit-license.php MIT license */ class html extends html_Core { /** * Print user avatar * * @param string $avatar * @param string $title * @param bool $mini * @return string */ public static function avatar($avatar, $title = '', $mini = false) { if (empty($avatar) || /*strpos($avatar, ':') ||*/ strpos($avatar, '/') === false) $avatar = 'avatar/unknown.png'; if (empty($title)) { return '<div class="avatar">' . html::image(array('src' => $avatar), 'Avatar') . '</div>'; } else { return '<div class="avatar">' . html::anchor(url::user($title), html::image(array('src' => $avatar, 'title' => $title), $title)) . '</div>'; } } /** * Prints date box * * @param string|integer $date * @param boolean $show_year * @param string $class * @return string */ public static function box_day($date, $show_year = false, $class = '') { // Get date elements $date = !is_numeric($date) ? strtotime($date) : (int)$date; list($weekday, $day, $month, $year) = explode(' ', date('D d M y', $date)); if ($show_year) { $month .= " '" . $year; } // Today? if (date('Y-m-d', $date) == date('Y-m-d')) { $class .= ' date today'; $weekday = __('Today'); } else { $class .= ' date'; } $template = '<span class="weekday">%s</span><span class="day">%s</span><span class="month">%s</span>'; return self::time(sprintf($template, $weekday, $day, $month), array('class' => trim($class), 'datetime' => $date), true); } /** * Prints step / rank box * * @param mixed $content */ public static function box_step($content) { return '<div class="grid-1 step">' . $content . '</div>'; } /** * UI button * * @param string $uri * @param string $title * @param array $attributes * @return string */ public static function button($uri, $title, $attributes = null) { if (empty($attributes)) { $attributes = array('class' => 'button'); } else { $attributes['class'] = trim($attributes['class'] . ' button'); } $attributes['class'] .= ' medium'; return html::anchor($uri, $title, $attributes); } /** * Returns errors * * @param string|array $error or $errors array * @param string $filter, $filter, ... * @return string */ public static function error($errors = false) { // no errors given if (empty($errors)) return ''; // more than one argument = filters if (func_num_args() > 1) { $argv = func_get_args(); $filters = is_array(next($argv)) ? current($argv) : array_slice($argv, 1); } $error = array(); // single error if (!is_array($errors)) { $error[] = $errors; } else { // show error only if found in filters or no filters at all if (!empty($filters)) { foreach ($filters as $error_id) { if (isset($errors[$error_id])) $error[] = $errors[$error_id]; } } else { $error = $errors; } } return empty($error) ? '' : '<span class="info">' . implode('<br />', $error). '</span>'; } /** * Print user Gravatar * * @param string $email * @param string $title * @param boolean $mini * @return string */ public static function gravatar($email, $title = '', $mini = false) { $gravatar = new Gravatar($email, ($mini ? 25 : 50), url::site('/avatar/unknown.png')); if (empty($title)) { return '<div class="avatar">' . html::image(array('src' => $gravatar->get_url()), 'Gravatar') . '</div>'; } else { return '<div class="avatar">' . html::anchor(url::user($title), html::image(array('src' => $gravatar->get_url(), 'title' => $title), $title)) . '</div>'; } } /** * Print icon with value * * @param integer|array $value :var => value * @param string $singular title for singular value * @param string $plural title for plural value * @param string $class icon class */ public static function icon_value($value, $singular = '', $plural = '', $class = '') { $class = $class ? 'icon ' . $class : 'icon'; if (is_array($value)) { $var = key($value); $value = $value[$var]; } $formatted = num::format($value); $plural = $plural ? $plural : $singular; $title = ($singular && $plural) ? ' title="' . __2($singular, $plural, $value, array($var => $formatted)) . '"' : ''; return '<var class="' . $class . '"' . $title . '>' . $formatted . '</var>'; } /** * Creates image link * * @param Image_Model|int $image or image_id * @param string $size thumb|normal * @param string|array $alt alt attribute or array of attributes * @return string */ public static function img($image = null, $size = 'normal', $alt = null) { if (!($image instanceof Image_Model)) { $image = new Image_Model((int)$image); } switch ($size) { case 'original': $size_prefix = 'original_'; break; case 'normal': $size_prefix = ''; break; case 'thumb': $size_prefix = 'thumb_'; break; } $attributes = is_array($alt) ? $alt : array( 'width' => $image->{$size_prefix . 'width'}, 'height' => $image->{$size_prefix . 'height'}, 'alt' => is_string($alt) ? $alt : (($size == 'thumb' ? __('Thumb') : __('Image')) . ' ' . sprintf('[%dx%d]', $image->{$size_prefix . 'width'}, $image->{$size_prefix . 'height'})), ); return html::image($image->url($size), $attributes); } /** * Returns nick link * * @param User_Model $user or uid * @param string $nick * @return string * * @deprecated User html::user instead */ public static function nick($user, $nick = null) { return self::user($user, $nick); } /** * Creates a script link. * * @param string|array filename * @param boolean include the index_page in the link * @return string */ public static function script($script, $index = FALSE) { return str_replace(' type="text/javascript"', '', parent::script($script, $index)); } /** * JavaScript source code block * * @param string $source * @return string */ public static function script_source($source) { $complied = ''; if (is_array($source)) { foreach ($source as $script) $compiled .= html::script_source($script); } else { $compiled = implode("\n", array('<script>', /*'// <![CDATA[',*/ trim($source), /*'// ]]>',*/ '</script>')); } return $compiled; } /** * Convert special characters to HTML entities * * @param string string to convert * @param boolean encode existing entities * @return string */ public static function specialchars($str) { return self::chars($str); } /** * Return formatted <time> tag * * @param string $str * @param array|string $attributes handled as time if not an array * @param boolean $short use only date */ public static function time($str, $attributes = null, $short = false) { // Extract datetime $datetime = (is_array($attributes)) ? arr::remove('datetime', $attributes) : $attributes; if ($datetime) { $time = is_int($datetime) ? $datetime : strtotime($datetime); $datetime = date::format($short ? date::DATE_8601 : date::TIME_8601, $time); if (is_array($attributes)) { $attributes['datetime'] = $datetime; } else { $attributes = array('datetime' => $datetime); } // Set title if not the same as content if (!isset($attributes['title'])) { $title = date::format($short ? 'DMYYYY' : 'DMYYYY_HM', $time); if ($title != $str) { $attributes['title'] = date::format($short ? 'DMYYYY' : 'DMYYYY_HM', $time); } } } return '<time' . html::attributes($attributes) . '>' . $str . '</time>'; } /** * Returns user link * * @param mixed $user User_Model, uid or username * @param string $nick * @param string $class * @return string */ public static function user($user, $nick = null, $class = null) { static $viewer; // Load current user for friend styling if (is_null($viewer)) { $viewer = Visitor::instance()->get_user(); if (!$viewer) $viewer = false; } $class = $class ? array($class, 'user') : array('user'); if ($user instanceof User_Model || $user && $user = ORM::factory('user')->find_user($user)) { $nick = $user->username; if ($viewer && $viewer->is_friend($user)) { $class[] = 'friend'; } if ($user->gender) { $class[] = $user->gender == 'f' ? 'female' : 'male'; } } return empty($nick) ? __('Unknown') : html::anchor(url::user($nick), $nick, array('class' => implode(' ', $class))); } }
mit
pact-foundation/pact_broker
spec/lib/pact_broker/config/runtime_configuration_documentation_spec.rb
1085
require "pact_broker/config/runtime_configuration" module PactBroker module Config describe RuntimeConfiguration do ATTRIBUTES = RuntimeConfiguration.config_attributes DOCUMENTATION = File.read("docs/configuration.yml") DOCUMENTED_ATTRIBUTES = YAML.load(DOCUMENTATION)["groups"].flat_map{ | group | group["vars"].keys.collect(&:to_sym) } DELIBERATELY_UNDOCUMENTED_ATTRIBUTES = [ :warning_error_class_names, :log_configuration_on_startup, :use_rack_protection, :use_case_sensitive_resource_names, :order_versions_by_date, :base_equality_only_on_content_that_affects_verification_results, :semver_formats, :seed_example_data, :use_first_tag_as_branch_time_limit, :validate_database_connection_config ] (ATTRIBUTES - DELIBERATELY_UNDOCUMENTED_ATTRIBUTES).each do | attribute_name | it "has documentation for #{attribute_name}" do expect(DOCUMENTED_ATTRIBUTES & [attribute_name]).to include(attribute_name) end end end end end
mit
S7uXN37/NineMensMorrisBoard
board/praesi.py
399
import motors import magnet import time print() print() print("move to 0,0! place white piece on 6,6!") input("press ENTER for x-axis...") motors.goTo(6,0) input("press ENTER for y-axis...") motors.goTo(6,6) input("press ENTER for magnet action...") magnet.turnOn(-1) time.sleep(0.5) motors.goTo(3,6) time.sleep(0.5) magnet.turnOff() time.sleep(0.5) motors.goTo(0,0) time.sleep(0.5) motors.reset()
mit
urho3d/Urho3D
Source/Urho3D/UI/FontFaceFreeType.cpp
17494
// // Copyright (c) 2008-2022 the Urho3D project. // // 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. // #include "../Precompiled.h" #include "../Core/Context.h" #include "../Graphics/Graphics.h" #include "../Graphics/Texture2D.h" #include "../IO/FileSystem.h" #include "../IO/Log.h" #include "../IO/MemoryBuffer.h" #include "../UI/Font.h" #include "../UI/FontFaceFreeType.h" #include "../UI/UI.h" #include <cassert> #include <ft2build.h> #include FT_FREETYPE_H #include FT_TRUETYPE_TABLES_H #include "../DebugNew.h" namespace Urho3D { inline float FixedToFloat(FT_Pos value) { return value / 64.0f; } /// FreeType library subsystem. class FreeTypeLibrary : public Object { URHO3D_OBJECT(FreeTypeLibrary, Object); public: /// Construct. explicit FreeTypeLibrary(Context* context) : Object(context) { FT_Error error = FT_Init_FreeType(&library_); if (error) URHO3D_LOGERROR("Could not initialize FreeType library"); } /// Destruct. ~FreeTypeLibrary() override { FT_Done_FreeType(library_); } FT_Library GetLibrary() const { return library_; } private: /// FreeType library. FT_Library library_{}; }; FontFaceFreeType::FontFaceFreeType(Font* font) : FontFace(font), loadMode_(FT_LOAD_DEFAULT) { } FontFaceFreeType::~FontFaceFreeType() { if (face_) { FT_Done_Face((FT_Face)face_); face_ = nullptr; } } bool FontFaceFreeType::Load(const unsigned char* fontData, unsigned fontDataSize, float pointSize) { Context* context = font_->GetContext(); // Create & initialize FreeType library if it does not exist yet auto* freeType = font_->GetSubsystem<FreeTypeLibrary>(); if (!freeType) context->RegisterSubsystem(freeType = new FreeTypeLibrary(context)); // Ensure the FreeType library is kept alive as long as TTF font resources exist freeType_ = freeType; auto* ui = font_->GetSubsystem<UI>(); const int maxTextureSize = ui->GetMaxFontTextureSize(); const FontHintLevel hintLevel = ui->GetFontHintLevel(); const float subpixelThreshold = ui->GetFontSubpixelThreshold(); subpixel_ = (hintLevel <= FONT_HINT_LEVEL_LIGHT) && (pointSize <= subpixelThreshold); oversampling_ = subpixel_ ? ui->GetFontOversampling() : 1; if (pointSize <= 0) { URHO3D_LOGERROR("Zero or negative point size"); return false; } if (!fontDataSize) { URHO3D_LOGERROR("Could not create font face from zero size data"); return false; } FT_Library library = freeType->GetLibrary(); FT_Face face; FT_Error error = FT_New_Memory_Face(library, fontData, fontDataSize, 0, &face); if (error) { URHO3D_LOGERROR("Could not create font face"); return false; } error = FT_Set_Char_Size(face, 0, pointSize * 64, oversampling_ * FONT_DPI, FONT_DPI); if (error) { FT_Done_Face(face); URHO3D_LOGERROR("Could not set font point size " + String(pointSize)); return false; } face_ = face; unsigned numGlyphs = (unsigned)face->num_glyphs; URHO3D_LOGDEBUGF("Font face %s (%fpt) has %d glyphs", GetFileName(font_->GetName()).CString(), pointSize, numGlyphs); // Load each of the glyphs to see the sizes & store other information loadMode_ = FT_LOAD_DEFAULT; if (ui->GetForceAutoHint()) { loadMode_ |= FT_LOAD_FORCE_AUTOHINT; } if (ui->GetFontHintLevel() == FONT_HINT_LEVEL_NONE) { loadMode_ |= FT_LOAD_NO_HINTING; } if (ui->GetFontHintLevel() == FONT_HINT_LEVEL_LIGHT) { loadMode_ |= FT_LOAD_TARGET_LIGHT; } ascender_ = FixedToFloat(face->size->metrics.ascender); rowHeight_ = FixedToFloat(face->size->metrics.height); pointSize_ = pointSize; // Check if the font's OS/2 info gives different (larger) values for ascender & descender auto* os2Info = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2); if (os2Info) { float descender = FixedToFloat(face->size->metrics.descender); float unitsPerEm = face->units_per_EM; ascender_ = Max(ascender_, os2Info->usWinAscent * face->size->metrics.y_ppem / unitsPerEm); ascender_ = Max(ascender_, os2Info->sTypoAscender * face->size->metrics.y_ppem / unitsPerEm); descender = Max(descender, os2Info->usWinDescent * face->size->metrics.y_ppem / unitsPerEm); descender = Max(descender, os2Info->sTypoDescender * face->size->metrics.y_ppem / unitsPerEm); rowHeight_ = Max(rowHeight_, ascender_ + descender); } int textureWidth = maxTextureSize; int textureHeight = maxTextureSize; hasMutableGlyph_ = false; SharedPtr<Image> image(new Image(font_->GetContext())); image->SetSize(textureWidth, textureHeight, 1); unsigned char* imageData = image->GetData(); memset(imageData, 0, (size_t)image->GetWidth() * image->GetHeight()); allocator_.Reset(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, textureWidth, textureHeight); HashMap<FT_UInt, FT_ULong> charCodes; FT_UInt glyphIndex; FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex); while (glyphIndex != 0) { if (!LoadCharGlyph(charCode, image)) { hasMutableGlyph_ = true; break; } // TODO: FT_Get_Next_Char can return same glyphIndex for different charCode charCodes[glyphIndex] = charCode; charCode = FT_Get_Next_Char(face, charCode, &glyphIndex); } SharedPtr<Texture2D> texture = LoadFaceTexture(image); if (!texture) return false; textures_.Push(texture); font_->SetMemoryUse(font_->GetMemoryUse() + textureWidth * textureHeight); // Store kerning if face has kerning information if (FT_HAS_KERNING(face)) { // Read kerning manually to be more efficient and avoid out of memory crash when use large font file, for example there // are 29354 glyphs in msyh.ttf FT_ULong tagKern = FT_MAKE_TAG('k', 'e', 'r', 'n'); FT_ULong kerningTableSize = 0; FT_Error error = FT_Load_Sfnt_Table(face, tagKern, 0, nullptr, &kerningTableSize); if (error) { URHO3D_LOGERROR("Could not get kerning table length"); return false; } SharedArrayPtr<unsigned char> kerningTable(new unsigned char[kerningTableSize]); error = FT_Load_Sfnt_Table(face, tagKern, 0, kerningTable, &kerningTableSize); if (error) { URHO3D_LOGERROR("Could not load kerning table"); return false; } // Convert big endian to little endian for (unsigned i = 0; i < kerningTableSize; i += 2) Swap(kerningTable[i], kerningTable[i + 1]); MemoryBuffer deserializer(kerningTable, (unsigned)kerningTableSize); unsigned short version = deserializer.ReadUShort(); if (version == 0) { unsigned numKerningTables = deserializer.ReadUShort(); for (unsigned i = 0; i < numKerningTables; ++i) { unsigned short version = deserializer.ReadUShort(); unsigned short length = deserializer.ReadUShort(); unsigned short coverage = deserializer.ReadUShort(); if (version == 0 && coverage == 1) { unsigned numKerningPairs = deserializer.ReadUShort(); // Skip searchRange, entrySelector and rangeShift deserializer.Seek((unsigned)(deserializer.GetPosition() + 3 * sizeof(unsigned short))); // x_scale is a 16.16 fixed-point value that converts font units -> 26.6 pixels (oversampled!) auto xScale = (float)face->size->metrics.x_scale / (1u << 22u) / oversampling_; for (unsigned j = 0; j < numKerningPairs; ++j) { unsigned leftIndex = deserializer.ReadUShort(); unsigned rightIndex = deserializer.ReadUShort(); float amount = deserializer.ReadShort() * xScale; unsigned leftCharCode = charCodes[leftIndex]; unsigned rightCharCode = charCodes[rightIndex]; unsigned value = (leftCharCode << 16u) + rightCharCode; // TODO: need to store kerning for glyphs but not for charCodes kerningMapping_[value] = amount; } } else { // Kerning table contains information we do not support; skip and move to the next (length includes header) deserializer.Seek((unsigned)(deserializer.GetPosition() + length - 3 * sizeof(unsigned short))); } } } else URHO3D_LOGWARNING("Can not read kerning information: not version 0"); } if (!hasMutableGlyph_) { FT_Done_Face(face); face_ = nullptr; } return true; } const FontGlyph* FontFaceFreeType::GetGlyph(unsigned c) { HashMap<unsigned, FontGlyph>::Iterator i = glyphMapping_.Find(c); if (i != glyphMapping_.End()) { FontGlyph& glyph = i->second_; glyph.used_ = true; return &glyph; } if (LoadCharGlyph(c)) { HashMap<unsigned, FontGlyph>::Iterator i = glyphMapping_.Find(c); if (i != glyphMapping_.End()) { FontGlyph& glyph = i->second_; glyph.used_ = true; return &glyph; } } return nullptr; } bool FontFaceFreeType::SetupNextTexture(int textureWidth, int textureHeight) { SharedPtr<Image> image(new Image(font_->GetContext())); image->SetSize(textureWidth, textureHeight, 1); unsigned char* imageData = image->GetData(); memset(imageData, 0, (size_t)image->GetWidth() * image->GetHeight()); SharedPtr<Texture2D> texture = LoadFaceTexture(image); if (!texture) return false; textures_.Push(texture); allocator_.Reset(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, textureWidth, textureHeight); font_->SetMemoryUse(font_->GetMemoryUse() + textureWidth * textureHeight); return true; } void FontFaceFreeType::BoxFilter(unsigned char* dest, size_t destSize, const unsigned char* src, size_t srcSize) { const int filterSize = oversampling_; assert(filterSize > 0); assert(destSize == srcSize + filterSize - 1); if (filterSize == 1) { memcpy(dest, src, srcSize); return; } // "accumulator" holds the total value of filterSize samples. We add one sample // and remove one sample per step (with special cases for left and right edges). int accumulator = 0; // The divide might make these inner loops slow. If so, some possible optimizations: // a) Turn it into a fixed-point multiply-and-shift rather than an integer divide; // b) Make this function a template, with the filter size a compile-time constant. int i = 0; if (srcSize < filterSize) { for (; i < srcSize; ++i) { accumulator += src[i]; dest[i] = accumulator / filterSize; } for (; i < filterSize; ++i) { dest[i] = accumulator / filterSize; } } else { for ( ; i < filterSize; ++i) { accumulator += src[i]; dest[i] = accumulator / filterSize; } for (; i < srcSize; ++i) { accumulator += src[i]; accumulator -= src[i - filterSize]; dest[i] = accumulator / filterSize; } } for (; i < srcSize + filterSize - 1; ++i) { accumulator -= src[i - filterSize]; dest[i] = accumulator / filterSize; } } bool FontFaceFreeType::LoadCharGlyph(unsigned charCode, Image* image) { if (!face_) return false; auto face = (FT_Face)face_; FT_GlyphSlot slot = face->glyph; FontGlyph fontGlyph; FT_Error error = FT_Load_Char(face, charCode, loadMode_ | FT_LOAD_RENDER); if (error) { const char* family = face->family_name ? face->family_name : "NULL"; URHO3D_LOGERRORF("FT_Load_Char failed (family: %s, char code: %u)", family, charCode); fontGlyph.texWidth_ = 0; fontGlyph.texHeight_ = 0; fontGlyph.width_ = 0; fontGlyph.height_ = 0; fontGlyph.offsetX_ = 0; fontGlyph.offsetY_ = 0; fontGlyph.advanceX_ = 0; fontGlyph.page_ = 0; } else { // Note: position within texture will be filled later fontGlyph.texWidth_ = slot->bitmap.width + oversampling_ - 1; fontGlyph.texHeight_ = slot->bitmap.rows; fontGlyph.width_ = slot->bitmap.width + oversampling_ - 1; fontGlyph.height_ = slot->bitmap.rows; fontGlyph.offsetX_ = slot->bitmap_left - (oversampling_ - 1) / 2.0f; fontGlyph.offsetY_ = floorf(ascender_ + 0.5f) - slot->bitmap_top; if (subpixel_ && slot->linearHoriAdvance) { // linearHoriAdvance is stored in 16.16 fixed point, not the usual 26.6 fontGlyph.advanceX_ = slot->linearHoriAdvance / 65536.0; } else { // Round to nearest pixel (only necessary when hinting is disabled) fontGlyph.advanceX_ = floorf(FixedToFloat(slot->metrics.horiAdvance) + 0.5f); } fontGlyph.width_ /= oversampling_; fontGlyph.offsetX_ /= oversampling_; fontGlyph.advanceX_ /= oversampling_; } int x = 0, y = 0; if (fontGlyph.texWidth_ > 0 && fontGlyph.texHeight_ > 0) { if (!allocator_.Allocate(fontGlyph.texWidth_ + 1, fontGlyph.texHeight_ + 1, x, y)) { if (image) { // We're rendering into a fixed image and we ran out of room. return false; } int w = allocator_.GetWidth(); int h = allocator_.GetHeight(); if (!SetupNextTexture(w, h)) { URHO3D_LOGWARNINGF("FontFaceFreeType::LoadCharGlyph: failed to allocate new %dx%d texture", w, h); return false; } if (!allocator_.Allocate(fontGlyph.texWidth_ + 1, fontGlyph.texHeight_ + 1, x, y)) { URHO3D_LOGWARNINGF("FontFaceFreeType::LoadCharGlyph: failed to position char code %u in blank page", charCode); return false; } } fontGlyph.x_ = (short)x; fontGlyph.y_ = (short)y; unsigned char* dest = nullptr; unsigned pitch = 0; if (image) { fontGlyph.page_ = 0; dest = image->GetData() + fontGlyph.y_ * image->GetWidth() + fontGlyph.x_; pitch = (unsigned)image->GetWidth(); } else { fontGlyph.page_ = textures_.Size() - 1; dest = new unsigned char[fontGlyph.texWidth_ * fontGlyph.texHeight_]; pitch = (unsigned)fontGlyph.texWidth_; } if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) { for (unsigned y = 0; y < (unsigned)slot->bitmap.rows; ++y) { unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y; unsigned char* rowDest = dest + (oversampling_ - 1)/2 + y * pitch; // Don't do any oversampling, just unpack the bits directly. for (unsigned x = 0; x < (unsigned)slot->bitmap.width; ++x) rowDest[x] = (unsigned char)((src[x >> 3u] & (0x80u >> (x & 7u))) ? 255 : 0); } } else { for (unsigned y = 0; y < (unsigned)slot->bitmap.rows; ++y) { unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y; unsigned char* rowDest = dest + y * pitch; BoxFilter(rowDest, fontGlyph.texWidth_, src, slot->bitmap.width); } } if (!image) { textures_.Back()->SetData(0, fontGlyph.x_, fontGlyph.y_, fontGlyph.texWidth_, fontGlyph.texHeight_, dest); delete[] dest; } } else { fontGlyph.x_ = 0; fontGlyph.y_ = 0; fontGlyph.page_ = 0; } glyphMapping_[charCode] = fontGlyph; return true; } }
mit
mattbierner/khepri-compile
dist/ecma_peep.js
2177
/* * THIS FILE IS AUTO GENERATED FROM 'lib/ecma_peep.kep' * DO NOT EDIT */ define(["require", "exports", "ecma-ast/node", "./ast", "./fun", "./rewriter"], (function(require, exports, __o, __o0, __o1, __o2) { "use strict"; var optimize, modify = __o["modify"], type = __o0["type"], concat = __o1["concat"], flatten = __o1["flatten"], map = __o1["map"], foldr = __o1["foldr"], UP = __o2["UP"], DOWN = __o2["DOWN"], Rewriter = __o2["Rewriter"], rewrite = __o2["rewrite"], x, flattenBlockBody = ((x = map.bind(null, (function(x0) { return (((!x0) || (type(x0) === "EmptyStatement")) ? [] : ((type(x0) === "BlockStatement") ? x0.body : x0)); }))), (function(z) { return flatten(x(z)); })), mergeBlockDeclarations = foldr.bind(null, (function(p, c) { return (((type(c) === "VariableDeclaration") && (type(p[0]) === "VariableDeclaration")) ? concat(modify(c, ({ declarations: concat(c.declarations, p[0].declarations) })), p.slice(1)) : concat(c, p)); }), []), peepholes = new(Rewriter)(), always = (function(_) { return true; }); peepholes.add("VariableDeclaration", DOWN, always, (function(node) { var declarations = node.declarations.filter((function(x0) { return (!(!x0)); })); return modify(node, ({ declarations: declarations })); })); peepholes.add("VariableDeclaration", UP, (function(node) { return (!node.declarations.length); }), (function(_) { return null; })); peepholes.add(["Program", "BlockStatement"], UP, always, (function(node) { return modify(node, ({ body: flattenBlockBody(node.body) })); })); peepholes.add(["Program", "BlockStatement"], UP, always, (function(node) { return modify(node, ({ body: mergeBlockDeclarations(node.body) })); })); (optimize = rewrite.bind(null, peepholes)); (exports["optimize"] = optimize); }));
mit
ericpoe/haystack
src/Container/HArrayRemove.php
948
<?php declare(strict_types=1); namespace Haystack\Container; use Haystack\HArray; use Haystack\HaystackInterface; class HArrayRemove { /** @var HArray */ private $arr; public function __construct(HArray $arr) { $this->arr = $arr; } /** * @param int|string|HaystackInterface $value * @return array * @throws ElementNotFoundException */ public function remove($value): array { if (false === $this->arr->contains($value)) { return $this->arr->toArray(); } $newArr = $this->arr->toArray(); $key = $this->arr->locate($value); unset($newArr[$key]); if ($this->allKeysNumeric(array_keys($newArr))) { return array_values($newArr); } return $newArr; } private function allKeysNumeric(array $keys): bool { return count($keys) === count(array_filter($keys, 'is_numeric')); } }
mit
osmantuna/Dosyalama
Main.cpp
14335
#include <stdlib.h> #include <stdio.h> #include <conio.h> #include <string.h> #include <windows.h> void kayitMenu(); void kayitEkle(); void kayitListele(); void kayitAra(); void kayitGuncelle(); void kayitSil(); void menu(); void kirala(); bool kayitAra(char *); bool filmAra(char *,char *,char *); void filmEkle(); void filmMenu(); void filmListele(); void teslimEt(); int main() { system("color 0e"); menu(); system("pause"); return 0; } void menu() { do{ system("cls"); printf("---------------------------------------------------\n"); printf("| F1 : Kirala |\n"); printf("| |\n"); printf("| F2 : Teslim Et |\n"); printf("| |\n"); printf("| F3 : Film Menu |\n"); printf("| |\n"); printf("| F4 : Kayit Menu |\n"); printf("| |\n"); printf("| ESC : Cikis |\n"); printf("---------------------------------------------------\n"); char sec=getche(); printf("\n"); if(sec == 0){ switch(sec=getche()){ case 59: kirala(); break; case 60: teslimEt(); break; case 61: filmMenu(); break; case 62: kayitMenu(); break; } } else if(sec == 27) exit(0); else{ printf("Hatali giris yaptiniz. Lutfen gecerli bir tusa basiniz."); Sleep(800); } }while(1); } void kirala() { char kayitt[30]; system("cls"); printf("Aranacak TC numarasini giriniz : "); scanf("%s", kayitt); if(!kayitAra(kayitt)) { printf("TC No bulunamadi. Kayit olmak icin 'e|E'ye basiniz..Cikmak icin herhangi bir tusa basiniz.."); char secim = getch(); if(secim == 'e' || secim == 'E') kayitEkle(); else return; } char idFilm[30]; char adFilm[30]; char sahipFilm[30]; char bos[30] = "bos"; printf("\nKiralanacak film id'sini giriniz giriniz giriniz : "); scanf("%s", idFilm); if(!filmAra(idFilm,adFilm,sahipFilm)) { printf("\nFilm bulunamadi.Eklemek icin 'e|E'ye basiniz.. Cikmak icin herhangi bir tusa basiniz.."); char secim = getch(); if(secim == 'e' || secim == 'E') filmEkle(); else return; } if(strcmp(sahipFilm,bos)) { printf("\nBu film zaten baskasina kiralanmis...\n\nDevam etmek icin bir tusa basiniz.."); getch(); return; } FILE *filmDefteri; FILE *geciciFilmDefteri; char geciciId[30]; char geciciAd[30]; char geciciSahip[30]; if((filmDefteri=fopen("C:\\filmDefteri.txt","r")) == NULL) printf("Dosya Acilamadi \n"); if ((geciciFilmDefteri=fopen("C:\\geciciFilmDefteri.txt","w+"))==NULL) printf("Dosya Acilamadi \n"); while(!feof(filmDefteri)) { fscanf(filmDefteri, "%s\t%s\t%s\n",geciciId,geciciAd,geciciSahip); if(!strcmp(idFilm,geciciId)) fprintf(geciciFilmDefteri, "%s\t%s\t%s\n",idFilm,adFilm,kayitt); else fprintf(geciciFilmDefteri, "%s\t%s\t%s\n",geciciId,geciciAd,geciciSahip); } printf("\n\nDevam etmek icin bir tusa basiniz..."); getch(); fclose(filmDefteri); fclose(geciciFilmDefteri); remove ("C:\\filmDefteri.txt"); rename ("C:\\geciciFilmDefteri.txt" , "C:\\filmDefteri.txt"); } bool filmAra(char *id, char *film, char *sahip) { char filmId[30]; char filmAdi[30]; char kiralayaci[30]; FILE *filmDefteri; if ((filmDefteri=fopen("C:\\filmDefteri.txt","r"))==NULL) printf("Dosya Acilamadi \n"); while(!feof(filmDefteri)) { fscanf(filmDefteri, "%s\t%s\t%s\n",filmId,filmAdi,kiralayaci); if(!strcmp(id,filmId)) { strcpy(sahip,kiralayaci); strcpy(film,filmAdi); fclose(filmDefteri); return true; } } fclose(filmDefteri); return false; } void kayitMenu() { do{ system("cls"); printf("---------------------------------------------------\n"); printf("| F1 : Kayit Ekle |\n"); printf("| |\n"); printf("| F2 : Kayit Listele |\n"); printf("| |\n"); printf("| F3 : Kayit Ara |\n"); printf("| |\n"); printf("| F4 : Kayit Guncelle |\n"); printf("| |\n"); printf("| F5 : Kayit Sil |\n"); printf("| |\n"); printf("| F6 : Ana Menuye Don |\n"); printf("| |\n"); printf("| ESC : Cikis |\n"); printf("---------------------------------------------------\n"); char sec=getche(); printf("\n"); if(sec == 0){ switch(sec=getche()){ case 59: kayitEkle(); break; case 60: kayitListele(); break; case 61: kayitAra(); break; case 62: kayitGuncelle(); break; case 63: kayitSil(); break; case 64: menu(); break; } } else if(sec == 27) exit(0); else{ printf("Hatali giris yaptiniz. Lutfen gecerli bir tusa basiniz."); Sleep(800); } }while(1); } void kayitEkle() { system("cls"); char ad[30]; char soyad[30]; char tel[30]; FILE *kayitDefteri; if((kayitDefteri=fopen("C:\\kayitDefteri.txt","a")) == NULL) printf("Dosya Acilamadi \n"); printf("Ad giriniz : "); scanf("%s",ad); printf("Soyad giriniz : "); scanf("%s",soyad); printf("Tel Numarasi giriniz : "); scanf("%s",tel); fprintf(kayitDefteri, "%s\t%s\t%s\n",ad,soyad,tel); printf("\n\nDevam etmek icin bir tusa basiniz..."); getch(); fclose(kayitDefteri); } void filmEkle() { system("cls"); char film[30]; char id[30]; char bos[30] = "bos"; FILE *filmDefteri; if((filmDefteri=fopen("C:\\filmDefteri.txt","a")) == NULL) printf("Dosya Acilamadi \n"); printf("Film id'sini giriniz : "); scanf("%s",id); printf("Film adini giriniz : "); scanf("%s",film); fprintf(filmDefteri, "%s\t%s\t%s\n",id,film,bos); printf("\n\nDevam etmek icin bir tusa basiniz..."); getch(); fclose(filmDefteri); } void kayitListele() { system("cls"); printf("Dosyadaki Kayitlar\n\n"); FILE *kayitDefteri; char ad[30]; char soyad[30]; char tc[30]; if ((kayitDefteri=fopen("C:\\kayitDefteri.txt","r"))==NULL) printf("Dosya Acilamadi \n"); while(!feof(kayitDefteri)) { fscanf(kayitDefteri, "%s\t%s\t%s\n",ad,soyad,tc); printf("%s\t", ad); printf("%s\t", soyad); printf("%s\n", tc); } printf("\n\nDevam etmek icin bir tusa basiniz..."); getch(); fclose(kayitDefteri); } void filmListele() { system("cls"); printf("Dosyadaki Filmler\n\n"); FILE *filmDefteri; char id[30]; char film[30]; char sahip[30]; if ((filmDefteri=fopen("C:\\filmDefteri.txt","r"))==NULL) printf("Dosya Acilamadi \n"); while(!feof(filmDefteri)) { fscanf(filmDefteri, "%s\t%s\t%s\n",id,film,sahip); printf("%s\t", id); printf("%s\t", film); printf("%s\n", sahip); } printf("\n\nDevam etmek icin bir tusa basiniz..."); getch(); fclose(filmDefteri); } void kayitAra() { char aranacakTC[30]; system("cls"); printf("Aranacak tel numarasini giriniz : "); scanf("%s", aranacakTC); FILE *kayitDefteri; char ad[30]; char soyad[30]; char tc[30]; if ((kayitDefteri=fopen("C:\\kayitDefteri.txt","r"))==NULL) printf("Dosya Acilamadi \n"); while(!feof(kayitDefteri)) { fscanf(kayitDefteri, "%s\t%s\t%s\n",ad,soyad,tc); if(!strcmp(aranacakTC,tc)) { printf("\n%s\t", ad); printf("%s\t", soyad); printf("%s\n", tc); printf("\nKiraladigi filmler\n"); char filmId[30]; char filmAdi[30]; char kiralayaci[30]; FILE *filmDefteri; if ((filmDefteri=fopen("C:\\filmDefteri.txt","r"))==NULL) printf("Dosya Acilamadi \n"); while(!feof(filmDefteri)) { fscanf(filmDefteri, "%s\t%s\t%s\n",filmId,filmAdi,kiralayaci); if(!strcmp(kiralayaci,tc)) { printf("\n%s\t", filmId); printf("%s\n", filmAdi); } } fclose(filmDefteri); } } printf("\n\nDevam etmek icin bir tusa basiniz..."); getch(); fclose(kayitDefteri); } bool kayitAra(char *kayit) { char aranacakTel[30]; strcpy(aranacakTel,kayit); FILE *kayitDefteri; char ad[30]; char soyad[30]; char tel[30]; if ((kayitDefteri=fopen("C:\\kayitDefteri.txt","r"))==NULL) printf("Dosya Acilamadi \n"); while(!feof(kayitDefteri)) { fscanf(kayitDefteri, "%s\t%s\t%s\n",ad,soyad,tel); if(!strcmp(aranacakTel,tel)) { printf("\n%s\t", ad); printf("%s\t", soyad); printf("%s\n", tel); fclose(kayitDefteri); return true; } } fclose(kayitDefteri); return false; } void kayitGuncelle() { char aranacakTel[30]; system("cls"); printf("Degistirmek istediginiz kayidin tel numarasini giriniz : "); scanf("%s", aranacakTel); FILE *kayitDefteri; FILE *geciciKayitDefteri; char ad[30]; char soyad[30]; char tel[30]; char geciciAd[30]; char geciciSoyad[30]; if ((kayitDefteri=fopen("C:\\kayitDefteri.txt","r"))==NULL) printf("Dosya Acilamadi \n"); if ((geciciKayitDefteri=fopen("C:\\geciciKayitDefteri.txt","w+"))==NULL) printf("Dosya Acilamadi \n"); while(!feof(kayitDefteri)) { fscanf(kayitDefteri, "%s\t%s\t%s\n",ad,soyad,tel); if(!strcmp(aranacakTel,tel)) { printf("\n%s\t", ad); printf("%s\t", soyad); printf("%s\n", tel); printf("\nYeni isim giriniz : "); scanf("%s",&geciciAd); printf("Yeni soyisim giriniz : "); scanf("%s",&geciciSoyad); fprintf(geciciKayitDefteri, "%s\t%s\t%s\n",geciciAd,geciciSoyad,tel); } else fprintf(geciciKayitDefteri, "%s\t%s\t%s\n",ad,soyad,tel); } printf("\n\nDevam etmek icin bir tusa basiniz..."); getch(); fclose(kayitDefteri); fclose(geciciKayitDefteri); remove ("C:\\kayitDefteri.txt"); rename ("C:\\geciciKayitDefteri.txt" , "C:\\kayitDefteri.txt"); } void kayitSil() { char aranacakTC[30]; system("cls"); printf("Silmek istediginiz kayidin TC numarasini giriniz : "); scanf("%s", aranacakTC); FILE *kayitDefteri; FILE *geciciKayitDefteri; char ad[30]; char soyad[30]; char tc[30]; if ((kayitDefteri=fopen("C:\\kayitDefteri.txt","r"))==NULL) printf("Dosya Acilamadi \n"); if ((geciciKayitDefteri=fopen("C:\\geciciKayitDefteri.txt","w+"))==NULL) printf("Dosya Acilamadi \n"); while(!feof(kayitDefteri)) { fscanf(kayitDefteri, "%s\t%s\t%s\n",ad,soyad,tc); if(!strcmp(aranacakTC,tc)) { printf("\n%s\t", ad); printf("%s\t", soyad); printf("%s\n", tc); } else fprintf(geciciKayitDefteri, "%s\t%s\t%s\n",ad,soyad,tc); } printf("\nSilmek istediginize emin misiniz ? ( Evet: e|E )"); char secim = getch(); if(secim == 'e' || secim == 'E') { fclose(kayitDefteri); fclose(geciciKayitDefteri); remove ("C:\\kayitDefteri.txt"); rename ("C:\\geciciKayitDefteri.txt" , "C:\\kayitDefteri.txt"); } else { fclose(kayitDefteri); fclose(geciciKayitDefteri); remove ("C:\\geciciKayitDefteri.txt"); } printf("\n\nDevam etmek icin bir tusa basiniz..."); getch(); } void filmMenu() { do{ system("cls"); printf("---------------------------------------------------\n"); printf("| F1 : Film Ekle |\n"); printf("| |\n"); printf("| F2 : Film Listele |\n"); printf("| |\n"); printf("| F3 : Ana Menuye Don |\n"); printf("| |\n"); printf("| ESC : Cikis |\n"); printf("---------------------------------------------------\n"); char sec=getche(); printf("\n"); if(sec == 0){ switch(sec=getche()){ case 59: filmEkle(); break; case 60: filmListele(); break; case 61: menu(); break; } } else if(sec == 27) exit(0); else{ printf("Hatali giris yaptiniz. Lutfen gecerli bir tusa basiniz."); Sleep(800); } }while(1); } void teslimEt() { char idFilm[30]; char adFilm[30]; char sahipFilm[30]; char bos[30] = "bos"; system("cls"); printf("Teslim etmek istediginiz kitabin id'sini giriniz : "); scanf("%s", idFilm); if(!filmAra(idFilm,adFilm,sahipFilm)) { printf("\nFilm bulunamadi.Eklemek icin 'e|E'ye basiniz.. Cikmak icin herhangi bir tusa basiniz.."); char secim = getch(); if(secim == 'e' || secim == 'E') filmEkle(); else return; } if(!strcmp(sahipFilm,bos)) { printf("\nBu film zaten rafta...\n\nDevam etmek icin bir tusa basiniz.."); getch(); return; } FILE *filmDefteri; FILE *geciciFilmDefteri; char geciciId[30]; char geciciAd[30]; char geciciSahip[30]; if((filmDefteri=fopen("C:\\filmDefteri.txt","r")) == NULL) printf("Dosya Acilamadi \n"); if ((geciciFilmDefteri=fopen("C:\\geciciFilmDefteri.txt","w+"))==NULL) printf("Dosya Acilamadi \n"); while(!feof(filmDefteri)) { fscanf(filmDefteri, "%s\t%s\t%s\n",geciciId,geciciAd,geciciSahip); if(!strcmp(idFilm,geciciId)) fprintf(geciciFilmDefteri, "%s\t%s\t%s\n",idFilm,adFilm,bos); else fprintf(geciciFilmDefteri, "%s\t%s\t%s\n",geciciId,geciciAd,geciciSahip); } printf("\n\nDevam etmek icin bir tusa basiniz..."); getch(); fclose(filmDefteri); fclose(geciciFilmDefteri); remove ("C:\\filmDefteri.txt"); rename ("C:\\geciciFilmDefteri.txt" , "C:\\filmDefteri.txt"); }
mit
oldmantaiter/telegraf
plugins/inputs/rabbitmq/rabbitmq.go
27412
package rabbitmq import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strconv" "sync" "time" "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/filter" "github.com/influxdata/telegraf/plugins/common/tls" "github.com/influxdata/telegraf/plugins/inputs" ) // DefaultUsername will set a default value that corresponds to the default // value used by Rabbitmq const DefaultUsername = "guest" // DefaultPassword will set a default value that corresponds to the default // value used by Rabbitmq const DefaultPassword = "guest" // DefaultURL will set a default value that corresponds to the default value // used by Rabbitmq const DefaultURL = "http://localhost:15672" // Default http timeouts const DefaultResponseHeaderTimeout = 3 const DefaultClientTimeout = 4 // RabbitMQ defines the configuration necessary for gathering metrics, // see the sample config for further details type RabbitMQ struct { URL string `toml:"url"` Name string `toml:"name"` Username string `toml:"username"` Password string `toml:"password"` tls.ClientConfig ResponseHeaderTimeout config.Duration `toml:"header_timeout"` ClientTimeout config.Duration `toml:"client_timeout"` Nodes []string `toml:"nodes"` Queues []string `toml:"queues"` Exchanges []string `toml:"exchanges"` MetricInclude []string `toml:"metric_include"` MetricExclude []string `toml:"metric_exclude"` QueueInclude []string `toml:"queue_name_include"` QueueExclude []string `toml:"queue_name_exclude"` FederationUpstreamInclude []string `toml:"federation_upstream_include"` FederationUpstreamExclude []string `toml:"federation_upstream_exclude"` Log telegraf.Logger `toml:"-"` client *http.Client excludeEveryQueue bool metricFilter filter.Filter queueFilter filter.Filter upstreamFilter filter.Filter } // OverviewResponse ... type OverviewResponse struct { MessageStats *MessageStats `json:"message_stats"` ObjectTotals *ObjectTotals `json:"object_totals"` QueueTotals *QueueTotals `json:"queue_totals"` Listeners []Listeners `json:"listeners"` } // Listeners ... type Listeners struct { Protocol string `json:"protocol"` } // Details ... type Details struct { Rate float64 `json:"rate"` } // MessageStats ... type MessageStats struct { Ack int64 AckDetails Details `json:"ack_details"` Deliver int64 DeliverDetails Details `json:"deliver_details"` DeliverGet int64 `json:"deliver_get"` DeliverGetDetails Details `json:"deliver_get_details"` Publish int64 PublishDetails Details `json:"publish_details"` Redeliver int64 RedeliverDetails Details `json:"redeliver_details"` PublishIn int64 `json:"publish_in"` PublishInDetails Details `json:"publish_in_details"` PublishOut int64 `json:"publish_out"` PublishOutDetails Details `json:"publish_out_details"` ReturnUnroutable int64 `json:"return_unroutable"` ReturnUnroutableDetails Details `json:"return_unroutable_details"` } // ObjectTotals ... type ObjectTotals struct { Channels int64 Connections int64 Consumers int64 Exchanges int64 Queues int64 } // QueueTotals ... type QueueTotals struct { Messages int64 MessagesReady int64 `json:"messages_ready"` MessagesUnacknowledged int64 `json:"messages_unacknowledged"` MessageBytes int64 `json:"message_bytes"` MessageBytesReady int64 `json:"message_bytes_ready"` MessageBytesUnacknowledged int64 `json:"message_bytes_unacknowledged"` MessageRAM int64 `json:"message_bytes_ram"` MessagePersistent int64 `json:"message_bytes_persistent"` } // Queue ... type Queue struct { QueueTotals // just to not repeat the same code MessageStats `json:"message_stats"` Memory int64 Consumers int64 ConsumerUtilisation float64 `json:"consumer_utilisation"` Name string Node string Vhost string Durable bool AutoDelete bool `json:"auto_delete"` IdleSince string `json:"idle_since"` SlaveNodes []string `json:"slave_nodes"` SynchronisedSlaveNodes []string `json:"synchronised_slave_nodes"` } // Node ... type Node struct { Name string DiskFree int64 `json:"disk_free"` DiskFreeLimit int64 `json:"disk_free_limit"` DiskFreeAlarm bool `json:"disk_free_alarm"` FdTotal int64 `json:"fd_total"` FdUsed int64 `json:"fd_used"` MemLimit int64 `json:"mem_limit"` MemUsed int64 `json:"mem_used"` MemAlarm bool `json:"mem_alarm"` ProcTotal int64 `json:"proc_total"` ProcUsed int64 `json:"proc_used"` RunQueue int64 `json:"run_queue"` SocketsTotal int64 `json:"sockets_total"` SocketsUsed int64 `json:"sockets_used"` Running bool `json:"running"` Uptime int64 `json:"uptime"` MnesiaDiskTxCount int64 `json:"mnesia_disk_tx_count"` MnesiaDiskTxCountDetails Details `json:"mnesia_disk_tx_count_details"` MnesiaRAMTxCount int64 `json:"mnesia_ram_tx_count"` MnesiaRAMTxCountDetails Details `json:"mnesia_ram_tx_count_details"` GcNum int64 `json:"gc_num"` GcNumDetails Details `json:"gc_num_details"` GcBytesReclaimed int64 `json:"gc_bytes_reclaimed"` GcBytesReclaimedDetails Details `json:"gc_bytes_reclaimed_details"` IoReadAvgTime float64 `json:"io_read_avg_time"` IoReadAvgTimeDetails Details `json:"io_read_avg_time_details"` IoReadBytes int64 `json:"io_read_bytes"` IoReadBytesDetails Details `json:"io_read_bytes_details"` IoWriteAvgTime float64 `json:"io_write_avg_time"` IoWriteAvgTimeDetails Details `json:"io_write_avg_time_details"` IoWriteBytes int64 `json:"io_write_bytes"` IoWriteBytesDetails Details `json:"io_write_bytes_details"` } type Exchange struct { Name string MessageStats `json:"message_stats"` Type string Internal bool Vhost string Durable bool AutoDelete bool `json:"auto_delete"` } // FederationLinkChannelMessageStats ... type FederationLinkChannelMessageStats struct { Confirm int64 `json:"confirm"` ConfirmDetails Details `json:"confirm_details"` Publish int64 `json:"publish"` PublishDetails Details `json:"publish_details"` ReturnUnroutable int64 `json:"return_unroutable"` ReturnUnroutableDetails Details `json:"return_unroutable_details"` } // FederationLinkChannel ... type FederationLinkChannel struct { AcksUncommitted int64 `json:"acks_uncommitted"` ConsumerCount int64 `json:"consumer_count"` MessagesUnacknowledged int64 `json:"messages_unacknowledged"` MessagesUncommitted int64 `json:"messages_uncommitted"` MessagesUnconfirmed int64 `json:"messages_unconfirmed"` MessageStats FederationLinkChannelMessageStats `json:"message_stats"` } // FederationLink ... type FederationLink struct { Type string `json:"type"` Queue string `json:"queue"` UpstreamQueue string `json:"upstream_queue"` Exchange string `json:"exchange"` UpstreamExchange string `json:"upstream_exchange"` Vhost string `json:"vhost"` Upstream string `json:"upstream"` LocalChannel FederationLinkChannel `json:"local_channel"` } type HealthCheck struct { Status string `json:"status"` } // MemoryResponse ... type MemoryResponse struct { Memory *Memory `json:"memory"` } // Memory details type Memory struct { ConnectionReaders int64 `json:"connection_readers"` ConnectionWriters int64 `json:"connection_writers"` ConnectionChannels int64 `json:"connection_channels"` ConnectionOther int64 `json:"connection_other"` QueueProcs int64 `json:"queue_procs"` QueueSlaveProcs int64 `json:"queue_slave_procs"` Plugins int64 `json:"plugins"` OtherProc int64 `json:"other_proc"` Metrics int64 `json:"metrics"` MgmtDb int64 `json:"mgmt_db"` Mnesia int64 `json:"mnesia"` OtherEts int64 `json:"other_ets"` Binary int64 `json:"binary"` MsgIndex int64 `json:"msg_index"` Code int64 `json:"code"` Atom int64 `json:"atom"` OtherSystem int64 `json:"other_system"` AllocatedUnused int64 `json:"allocated_unused"` ReservedUnallocated int64 `json:"reserved_unallocated"` Total interface{} `json:"total"` } // Error response type ErrorResponse struct { Error string `json:"error"` Reason string `json:"reason"` } // gatherFunc ... type gatherFunc func(r *RabbitMQ, acc telegraf.Accumulator) var gatherFunctions = map[string]gatherFunc{ "exchange": gatherExchanges, "federation": gatherFederationLinks, "node": gatherNodes, "overview": gatherOverview, "queue": gatherQueues, } var sampleConfig = ` ## Management Plugin url. (default: http://localhost:15672) # url = "http://localhost:15672" ## Tag added to rabbitmq_overview series; deprecated: use tags # name = "rmq-server-1" ## Credentials # username = "guest" # password = "guest" ## Optional TLS Config # tls_ca = "/etc/telegraf/ca.pem" # tls_cert = "/etc/telegraf/cert.pem" # tls_key = "/etc/telegraf/key.pem" ## Use TLS but skip chain & host verification # insecure_skip_verify = false ## Optional request timeouts ## ## ResponseHeaderTimeout, if non-zero, specifies the amount of time to wait ## for a server's response headers after fully writing the request. # header_timeout = "3s" ## ## client_timeout specifies a time limit for requests made by this client. ## Includes connection time, any redirects, and reading the response body. # client_timeout = "4s" ## A list of nodes to gather as the rabbitmq_node measurement. If not ## specified, metrics for all nodes are gathered. # nodes = ["rabbit@node1", "rabbit@node2"] ## A list of queues to gather as the rabbitmq_queue measurement. If not ## specified, metrics for all queues are gathered. # queues = ["telegraf"] ## A list of exchanges to gather as the rabbitmq_exchange measurement. If not ## specified, metrics for all exchanges are gathered. # exchanges = ["telegraf"] ## Metrics to include and exclude. Globs accepted. ## Note that an empty array for both will include all metrics ## Currently the following metrics are supported: "exchange", "federation", "node", "overview", "queue" # metric_include = [] # metric_exclude = [] ## Queues to include and exclude. Globs accepted. ## Note that an empty array for both will include all queues queue_name_include = [] queue_name_exclude = [] ## Federation upstreams include and exclude when gathering the rabbitmq_federation measurement. ## If neither are specified, metrics for all federation upstreams are gathered. ## Federation link metrics will only be gathered for queues and exchanges ## whose non-federation metrics will be collected (e.g a queue excluded ## by the 'queue_name_exclude' option will also be excluded from federation). ## Globs accepted. # federation_upstream_include = ["dataCentre-*"] # federation_upstream_exclude = [] ` func boolToInt(b bool) int64 { if b { return 1 } return 0 } // SampleConfig ... func (r *RabbitMQ) SampleConfig() string { return sampleConfig } // Description ... func (r *RabbitMQ) Description() string { return "Reads metrics from RabbitMQ servers via the Management Plugin" } func (r *RabbitMQ) Init() error { var err error // Create gather filters if err := r.createQueueFilter(); err != nil { return err } if err := r.createUpstreamFilter(); err != nil { return err } // Create a filter for the metrics if r.metricFilter, err = filter.NewIncludeExcludeFilter(r.MetricInclude, r.MetricExclude); err != nil { return err } tlsCfg, err := r.ClientConfig.TLSConfig() if err != nil { return err } tr := &http.Transport{ ResponseHeaderTimeout: time.Duration(r.ResponseHeaderTimeout), TLSClientConfig: tlsCfg, } r.client = &http.Client{ Transport: tr, Timeout: time.Duration(r.ClientTimeout), } return nil } // Gather ... func (r *RabbitMQ) Gather(acc telegraf.Accumulator) error { var wg sync.WaitGroup for name, f := range gatherFunctions { // Query only metrics that are supported if !r.metricFilter.Match(name) { continue } wg.Add(1) go func(gf gatherFunc) { defer wg.Done() gf(r, acc) }(f) } wg.Wait() return nil } func (r *RabbitMQ) requestEndpoint(u string) ([]byte, error) { if r.URL == "" { r.URL = DefaultURL } endpoint := r.URL + u r.Log.Debugf("Requesting %q...", endpoint) req, err := http.NewRequest("GET", endpoint, nil) if err != nil { return nil, err } username := r.Username if username == "" { username = DefaultUsername } password := r.Password if password == "" { password = DefaultPassword } req.SetBasicAuth(username, password) resp, err := r.client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() r.Log.Debugf("HTTP status code: %v %v", resp.StatusCode, http.StatusText(resp.StatusCode)) if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, fmt.Errorf("getting %q failed: %v %v", u, resp.StatusCode, http.StatusText(resp.StatusCode)) } return ioutil.ReadAll(resp.Body) } func (r *RabbitMQ) requestJSON(u string, target interface{}) error { buf, err := r.requestEndpoint(u) if err != nil { return err } if err := json.Unmarshal(buf, target); err != nil { if _, ok := err.(*json.UnmarshalTypeError); ok { // Try to get the error reason from the response var errResponse ErrorResponse if json.Unmarshal(buf, &errResponse) == nil && errResponse.Error != "" { // Return the error reason in the response return fmt.Errorf("error response trying to get %q: %q (reason: %q)", u, errResponse.Error, errResponse.Reason) } } return fmt.Errorf("decoding answer from %q failed: %v", u, err) } return nil } func gatherOverview(r *RabbitMQ, acc telegraf.Accumulator) { overview := &OverviewResponse{} err := r.requestJSON("/api/overview", &overview) if err != nil { acc.AddError(err) return } if overview.QueueTotals == nil || overview.ObjectTotals == nil || overview.MessageStats == nil || overview.Listeners == nil { acc.AddError(fmt.Errorf("Wrong answer from rabbitmq. Probably auth issue")) return } var clusteringListeners, amqpListeners int64 = 0, 0 for _, listener := range overview.Listeners { if listener.Protocol == "clustering" { clusteringListeners++ } else if listener.Protocol == "amqp" { amqpListeners++ } } tags := map[string]string{"url": r.URL} if r.Name != "" { tags["name"] = r.Name } fields := map[string]interface{}{ "messages": overview.QueueTotals.Messages, "messages_ready": overview.QueueTotals.MessagesReady, "messages_unacked": overview.QueueTotals.MessagesUnacknowledged, "channels": overview.ObjectTotals.Channels, "connections": overview.ObjectTotals.Connections, "consumers": overview.ObjectTotals.Consumers, "exchanges": overview.ObjectTotals.Exchanges, "queues": overview.ObjectTotals.Queues, "messages_acked": overview.MessageStats.Ack, "messages_delivered": overview.MessageStats.Deliver, "messages_delivered_get": overview.MessageStats.DeliverGet, "messages_published": overview.MessageStats.Publish, "clustering_listeners": clusteringListeners, "amqp_listeners": amqpListeners, "return_unroutable": overview.MessageStats.ReturnUnroutable, "return_unroutable_rate": overview.MessageStats.ReturnUnroutableDetails.Rate, } acc.AddFields("rabbitmq_overview", fields, tags) } func gatherNodes(r *RabbitMQ, acc telegraf.Accumulator) { allNodes := make([]*Node, 0) err := r.requestJSON("/api/nodes", &allNodes) if err != nil { acc.AddError(err) return } nodes := allNodes[:0] for _, node := range allNodes { if r.shouldGatherNode(node) { nodes = append(nodes, node) } } var wg sync.WaitGroup for _, node := range nodes { wg.Add(1) go func(node *Node) { defer wg.Done() tags := map[string]string{"url": r.URL} tags["node"] = node.Name fields := map[string]interface{}{ "disk_free": node.DiskFree, "disk_free_limit": node.DiskFreeLimit, "disk_free_alarm": boolToInt(node.DiskFreeAlarm), "fd_total": node.FdTotal, "fd_used": node.FdUsed, "mem_limit": node.MemLimit, "mem_used": node.MemUsed, "mem_alarm": boolToInt(node.MemAlarm), "proc_total": node.ProcTotal, "proc_used": node.ProcUsed, "run_queue": node.RunQueue, "sockets_total": node.SocketsTotal, "sockets_used": node.SocketsUsed, "uptime": node.Uptime, "mnesia_disk_tx_count": node.MnesiaDiskTxCount, "mnesia_disk_tx_count_rate": node.MnesiaDiskTxCountDetails.Rate, "mnesia_ram_tx_count": node.MnesiaRAMTxCount, "mnesia_ram_tx_count_rate": node.MnesiaRAMTxCountDetails.Rate, "gc_num": node.GcNum, "gc_num_rate": node.GcNumDetails.Rate, "gc_bytes_reclaimed": node.GcBytesReclaimed, "gc_bytes_reclaimed_rate": node.GcBytesReclaimedDetails.Rate, "io_read_avg_time": node.IoReadAvgTime, "io_read_avg_time_rate": node.IoReadAvgTimeDetails.Rate, "io_read_bytes": node.IoReadBytes, "io_read_bytes_rate": node.IoReadBytesDetails.Rate, "io_write_avg_time": node.IoWriteAvgTime, "io_write_avg_time_rate": node.IoWriteAvgTimeDetails.Rate, "io_write_bytes": node.IoWriteBytes, "io_write_bytes_rate": node.IoWriteBytesDetails.Rate, "running": boolToInt(node.Running), } var memory MemoryResponse err = r.requestJSON("/api/nodes/"+node.Name+"/memory", &memory) if err != nil { acc.AddError(err) return } if memory.Memory != nil { fields["mem_connection_readers"] = memory.Memory.ConnectionReaders fields["mem_connection_writers"] = memory.Memory.ConnectionWriters fields["mem_connection_channels"] = memory.Memory.ConnectionChannels fields["mem_connection_other"] = memory.Memory.ConnectionOther fields["mem_queue_procs"] = memory.Memory.QueueProcs fields["mem_queue_slave_procs"] = memory.Memory.QueueSlaveProcs fields["mem_plugins"] = memory.Memory.Plugins fields["mem_other_proc"] = memory.Memory.OtherProc fields["mem_metrics"] = memory.Memory.Metrics fields["mem_mgmt_db"] = memory.Memory.MgmtDb fields["mem_mnesia"] = memory.Memory.Mnesia fields["mem_other_ets"] = memory.Memory.OtherEts fields["mem_binary"] = memory.Memory.Binary fields["mem_msg_index"] = memory.Memory.MsgIndex fields["mem_code"] = memory.Memory.Code fields["mem_atom"] = memory.Memory.Atom fields["mem_other_system"] = memory.Memory.OtherSystem fields["mem_allocated_unused"] = memory.Memory.AllocatedUnused fields["mem_reserved_unallocated"] = memory.Memory.ReservedUnallocated switch v := memory.Memory.Total.(type) { case float64: fields["mem_total"] = int64(v) case map[string]interface{}: var foundEstimator bool for _, estimator := range []string{"rss", "allocated", "erlang"} { if x, found := v[estimator]; found { if total, ok := x.(float64); ok { fields["mem_total"] = int64(total) foundEstimator = true break } acc.AddError(fmt.Errorf("unknown type %T for %q total memory", x, estimator)) } } if !foundEstimator { acc.AddError(fmt.Errorf("no known memory estimation in %v", v)) } default: acc.AddError(fmt.Errorf("unknown type %T for total memory", memory.Memory.Total)) } } acc.AddFields("rabbitmq_node", fields, tags) }(node) } wg.Wait() } func gatherQueues(r *RabbitMQ, acc telegraf.Accumulator) { if r.excludeEveryQueue { return } // Gather information about queues queues := make([]Queue, 0) err := r.requestJSON("/api/queues", &queues) if err != nil { acc.AddError(err) return } for _, queue := range queues { if !r.queueFilter.Match(queue.Name) { continue } tags := map[string]string{ "url": r.URL, "queue": queue.Name, "vhost": queue.Vhost, "node": queue.Node, "durable": strconv.FormatBool(queue.Durable), "auto_delete": strconv.FormatBool(queue.AutoDelete), } acc.AddFields( "rabbitmq_queue", map[string]interface{}{ // common information "consumers": queue.Consumers, "consumer_utilisation": queue.ConsumerUtilisation, "idle_since": queue.IdleSince, "slave_nodes": len(queue.SlaveNodes), "synchronised_slave_nodes": len(queue.SynchronisedSlaveNodes), "memory": queue.Memory, // messages information "message_bytes": queue.MessageBytes, "message_bytes_ready": queue.MessageBytesReady, "message_bytes_unacked": queue.MessageBytesUnacknowledged, "message_bytes_ram": queue.MessageRAM, "message_bytes_persist": queue.MessagePersistent, "messages": queue.Messages, "messages_ready": queue.MessagesReady, "messages_unack": queue.MessagesUnacknowledged, "messages_ack": queue.MessageStats.Ack, "messages_ack_rate": queue.MessageStats.AckDetails.Rate, "messages_deliver": queue.MessageStats.Deliver, "messages_deliver_rate": queue.MessageStats.DeliverDetails.Rate, "messages_deliver_get": queue.MessageStats.DeliverGet, "messages_deliver_get_rate": queue.MessageStats.DeliverGetDetails.Rate, "messages_publish": queue.MessageStats.Publish, "messages_publish_rate": queue.MessageStats.PublishDetails.Rate, "messages_redeliver": queue.MessageStats.Redeliver, "messages_redeliver_rate": queue.MessageStats.RedeliverDetails.Rate, }, tags, ) } } func gatherExchanges(r *RabbitMQ, acc telegraf.Accumulator) { // Gather information about exchanges exchanges := make([]Exchange, 0) err := r.requestJSON("/api/exchanges", &exchanges) if err != nil { acc.AddError(err) return } for _, exchange := range exchanges { if !r.shouldGatherExchange(exchange.Name) { continue } tags := map[string]string{ "url": r.URL, "exchange": exchange.Name, "type": exchange.Type, "vhost": exchange.Vhost, "internal": strconv.FormatBool(exchange.Internal), "durable": strconv.FormatBool(exchange.Durable), "auto_delete": strconv.FormatBool(exchange.AutoDelete), } acc.AddFields( "rabbitmq_exchange", map[string]interface{}{ "messages_publish_in": exchange.MessageStats.PublishIn, "messages_publish_in_rate": exchange.MessageStats.PublishInDetails.Rate, "messages_publish_out": exchange.MessageStats.PublishOut, "messages_publish_out_rate": exchange.MessageStats.PublishOutDetails.Rate, }, tags, ) } } func gatherFederationLinks(r *RabbitMQ, acc telegraf.Accumulator) { // Gather information about federation links federationLinks := make([]FederationLink, 0) err := r.requestJSON("/api/federation-links", &federationLinks) if err != nil { acc.AddError(err) return } for _, link := range federationLinks { if !r.shouldGatherFederationLink(link) { continue } tags := map[string]string{ "url": r.URL, "type": link.Type, "vhost": link.Vhost, "upstream": link.Upstream, } if link.Type == "exchange" { tags["exchange"] = link.Exchange tags["upstream_exchange"] = link.UpstreamExchange } else { tags["queue"] = link.Queue tags["upstream_queue"] = link.UpstreamQueue } acc.AddFields( "rabbitmq_federation", map[string]interface{}{ "acks_uncommitted": link.LocalChannel.AcksUncommitted, "consumers": link.LocalChannel.ConsumerCount, "messages_unacknowledged": link.LocalChannel.MessagesUnacknowledged, "messages_uncommitted": link.LocalChannel.MessagesUncommitted, "messages_unconfirmed": link.LocalChannel.MessagesUnconfirmed, "messages_confirm": link.LocalChannel.MessageStats.Confirm, "messages_publish": link.LocalChannel.MessageStats.Publish, "messages_return_unroutable": link.LocalChannel.MessageStats.ReturnUnroutable, }, tags, ) } } func (r *RabbitMQ) shouldGatherNode(node *Node) bool { if len(r.Nodes) == 0 { return true } for _, name := range r.Nodes { if name == node.Name { return true } } return false } func (r *RabbitMQ) createQueueFilter() error { // Backwards compatibility for deprecated `queues` parameter. if len(r.Queues) > 0 { r.QueueInclude = append(r.QueueInclude, r.Queues...) } queueFilter, err := filter.NewIncludeExcludeFilter(r.QueueInclude, r.QueueExclude) if err != nil { return err } r.queueFilter = queueFilter for _, q := range r.QueueExclude { if q == "*" { r.excludeEveryQueue = true } } return nil } func (r *RabbitMQ) createUpstreamFilter() error { upstreamFilter, err := filter.NewIncludeExcludeFilter(r.FederationUpstreamInclude, r.FederationUpstreamExclude) if err != nil { return err } r.upstreamFilter = upstreamFilter return nil } func (r *RabbitMQ) shouldGatherExchange(exchangeName string) bool { if len(r.Exchanges) == 0 { return true } for _, name := range r.Exchanges { if name == exchangeName { return true } } return false } func (r *RabbitMQ) shouldGatherFederationLink(link FederationLink) bool { if !r.upstreamFilter.Match(link.Upstream) { return false } switch link.Type { case "exchange": return r.shouldGatherExchange(link.Exchange) case "queue": return r.queueFilter.Match(link.Queue) default: return false } } func init() { inputs.Add("rabbitmq", func() telegraf.Input { return &RabbitMQ{ ResponseHeaderTimeout: config.Duration(DefaultResponseHeaderTimeout * time.Second), ClientTimeout: config.Duration(DefaultClientTimeout * time.Second), } }) }
mit
Whoaa512/javascript-koans
koans/AboutExpects.js
1174
describe("About Expects", function() { //We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(true).toBeTruthy(); //This should be true }); //To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = 2; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); //Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = 2; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); //Sometimes you need to be really exact about what you "type". it("should assert equality with ===", function () { var expectedValue = "2"; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); //Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(1+1); }); });
mit
VMatrixTeam/open-matrix
src/judgesystem/src/utils/mysqller/__init__.py
16
import mysqller
mit
diegofigueroa/world_cup
db/migrate/20140219014723_create_players.rb
316
class CreatePlayers < ActiveRecord::Migration def change create_table :players do |t| t.string :name t.date :birthday t.integer :height t.integer :weight t.integer :squad_number t.string :photo_url t.references :team, index: true t.timestamps end end end
mit
fmdjs/fmd.js
test/specs/use/o.js
63
define('specs/use/o',function(){ window.specsUseO = 1; });
mit
yonglehou/sharpsnmplib
SharpSnmpLib/Messaging/MessageFactoryException.cs
3376
// Message factory exception. // Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors. // // 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. /* * Created by SharpDevelop. * User: lextm * Date: 9/6/2009 * Time: 4:53 PM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Globalization; using System.Runtime.Serialization; #if !NETFX_CORE using System.Security.Permissions; #endif namespace Lextm.SharpSnmpLib.Messaging { /// <summary> /// Message factory exception. /// </summary> [DataContract] public sealed class MessageFactoryException : SnmpException { private byte[] _bytes; /// <summary> /// Creates a <see cref="MessageFactoryException"/>. /// </summary> public MessageFactoryException() { } /// <summary> /// Creates a <see cref="MessageFactoryException"/> instance with a specific <see cref="String"/>. /// </summary> /// <param name="message">Message</param> public MessageFactoryException(string message) : base(message) { } /// <summary> /// Creates a <see cref="MessageFactoryException"/> instance with a specific <see cref="String"/> and an <see cref="Exception"/>. /// </summary> /// <param name="message">Message</param> /// <param name="inner">Inner exception</param> public MessageFactoryException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Gets the bytes. /// </summary> public byte[] GetBytes() { return _bytes; } /// <summary> /// Sets the bytes. /// </summary> /// <param name="value">Bytes.</param> public void SetBytes(byte[] value) { _bytes = value; } /// <summary> /// Returns a <see cref="String"/> that represents this <see cref="MessageFactoryException"/>. /// </summary> /// <returns></returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "SharpMessageFactoryInnerException: {0}", Message); } } }
mit
dennisdegreef/Dns
src/Entry/Type/Txt.php
426
<?php namespace Link0\Dns\Entry\Type; use Link0\Dns\Entry; use Link0\Dns\Entry\Type; /** * Txt type * * @package Link0\Dns\Entry\Type */ final class Txt extends Type { /** * @return string */ public function name() { return 'TXT'; } /** * @param string $content * * @return bool */ public function isSatisfiedBy($content) { return true; } }
mit
DALEKZ/staff-management
static/javascripts/examples/dashboard.js
3240
$(function () { "use strict"; //TOASTR NOTIFICATION // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= toastr.options = { "progressBar": true, "positionClass": "toast-bottom-right", "timeOut": 3500, "showEasing": "swing", "hideEasing": "linear", "showMethod": "slideDown", "hideMethod": "fadeOut" }; toastr.info('66666666', '<h5 style="margin-top: 0px; margin-bottom: 5px;"><b>This is Helsinki Template!</b></h5>'); //AREA CHART EXAMPLE // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= var area = document.getElementById("area-chart"); var options ={ scales: { yAxes: [{ ticks: { beginAtZero:true } }] } }; var dataArea = { labels: ["一月","二月","三月","四月","五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], datasets: [ { label: "入职人数", fill: true, backgroundColor: "rgba(55, 209, 119, 0.45)", borderColor: "rgba(55, 209, 119, 0.45)", pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "#fff", pointHoverBackgroundColor: "343d3e", pointHoverBorderColor: "rgba(220,220,220,1)", data: [12p, 13, 11, 6, 9, 12,2,4,5,21] } ], options: { scales: { yAxes: [{ stacked: true }] } } }; var areaChart = new Chart(area, { type: 'line', data: dataArea, options: options }); //PIE & POLAR CHART EXAMPLE // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= var pie = document.getElementById("pie-chart"); var dataPie = { labels: [ "Data 1", "Data 2", "Data 3" ], datasets: [ { data: [300, 50, 100], backgroundColor: [ "rgba(55, 209, 119, 0.45)", "#FFCE56", "rgba(175, 175, 175, 0.26)" ], hoverBackgroundColor: [ "rgba(55, 209, 119, 0.6)", "#FFCE56", "rgba(175, 175, 175, 0.4)" ] }] }; var pieChar = new Chart(pie, { type: 'pie', data: dataPie }); //MAGNIFIC POPUP GALLERY // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= $('.gallery-wrap').magnificPopup({ delegate: 'a', type: 'image', gallery: { enabled: true, navigateByImgClick: true, preload: [0, 1] }, tLoading: 'Loading image #%curr%...', mainClass: 'mfp-no-margins mfp-with-zoom', zoom: { enabled: true, duration: 300 } }); });
mit
chi-cicadas-2015/galleriamia
db/migrate/20151012210833_create_profiles.rb
234
class CreateProfiles < ActiveRecord::Migration def change create_table :profiles do |t| t.string :top_collection t.string :website_url t.string :primary_medium t.timestamps null: false end end end
mit
waynemunro/orleans
test/ServiceBus.Tests/Streaming/EHStreamPerPartitionTests.cs
6297
 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.WindowsAzure.Storage.Table; using Orleans; using Orleans.AzureUtils; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.ServiceBus.Providers; using Orleans.Streams; using Orleans.TestingHost; using Orleans.TestingHost.Utils; using Tester; using ServiceBus.Tests.TestStreamProviders.EventHub; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace ServiceBus.Tests.StreamingTests { [TestCategory("EventHub"), TestCategory("Streaming")] public class EHStreamPerPartitionTests : OrleansTestingBase, IClassFixture<EHStreamPerPartitionTests.Fixture> { private readonly Fixture fixture; private const string StreamProviderName = "EHStreamPerPartition"; private const string EHPath = "ehorleanstest"; private const string EHConsumerGroup = "orleansnightly"; private const string EHCheckpointTable = "ehcheckpoint"; private static readonly string CheckpointNamespace = Guid.NewGuid().ToString(); private static readonly Lazy<EventHubSettings> EventHubConfig = new Lazy<EventHubSettings>(() => new EventHubSettings( TestDefaultConfiguration.EventHubConnectionString, EHConsumerGroup, EHPath)); private static readonly EventHubCheckpointerSettings CheckpointerSettings = new EventHubCheckpointerSettings(TestDefaultConfiguration.DataConnectionString, EHCheckpointTable, CheckpointNamespace, TimeSpan.FromSeconds(1)); private static readonly EventHubStreamProviderSettings ProviderSettings = new EventHubStreamProviderSettings(StreamProviderName); public class Fixture : BaseTestClusterFixture { protected override TestCluster CreateTestCluster() { var options = new TestClusterOptions(2); // register stream provider options.ClusterConfiguration.AddMemoryStorageProvider("PubSubStore"); options.ClusterConfiguration.Globals.RegisterStreamProvider<StreamPerPartitionEventHubStreamProvider>(StreamProviderName, BuildProviderSettings()); options.ClientConfiguration.RegisterStreamProvider<EventHubStreamProvider>(StreamProviderName, BuildProviderSettings()); return new TestCluster(options); } public override void Dispose() { base.Dispose(); var dataManager = new AzureTableDataManager<TableEntity>(CheckpointerSettings.TableName, CheckpointerSettings.DataConnectionString, NullLoggerFactory.Instance); dataManager.InitTableAsync().Wait(); dataManager.ClearTableAsync().Wait(); } private static Dictionary<string, string> BuildProviderSettings() { var settings = new Dictionary<string, string>(); // get initial settings from configs ProviderSettings.WriteProperties(settings); EventHubConfig.Value.WriteProperties(settings); CheckpointerSettings.WriteProperties(settings); // add queue balancer setting settings.Add(PersistentStreamProviderConfig.QUEUE_BALANCER_TYPE, StreamQueueBalancerType.StaticClusterConfigDeploymentBalancer.AssemblyQualifiedName); return settings; } } public EHStreamPerPartitionTests(Fixture fixture) { this.fixture = fixture; } [Fact] public async Task EH100StreamsTo4PartitionStreamsTest() { this.fixture.Logger.Info("************************ EH100StreamsTo4PartitionStreamsTest *********************************"); int streamCount = 100; int eventsInStream = 10; int partitionCount = 4; List<ISampleStreaming_ConsumerGrain> consumers = new List<ISampleStreaming_ConsumerGrain>(partitionCount); for (int i = 0; i < partitionCount; i++) { consumers.Add(this.fixture.GrainFactory.GetGrain<ISampleStreaming_ConsumerGrain>(Guid.NewGuid())); } // subscribe to each partition List<Task> becomeConsumersTasks = consumers .Select( (consumer, i) => consumer.BecomeConsumer( StreamPerPartitionEventHubStreamProvider.GetPartitionGuid(i.ToString()), null, StreamProviderName)) .ToList(); await Task.WhenAll(becomeConsumersTasks); await GenerateEvents(streamCount, eventsInStream); await TestingUtils.WaitUntilAsync(assertIsTrue => CheckCounters(consumers, streamCount * eventsInStream, assertIsTrue), TimeSpan.FromSeconds(30)); } private async Task GenerateEvents(int streamCount, int eventsInStream) { IStreamProvider streamProvider = this.fixture.Client.GetStreamProvider(StreamProviderName); IAsyncStream<int>[] producers = Enumerable.Range(0, streamCount) .Select(i => streamProvider.GetStream<int>(Guid.NewGuid(), null)) .ToArray(); for (int i = 0; i < eventsInStream; i++) { // send event on each stream for (int j = 0; j < streamCount; j++) { await producers[j].OnNextAsync(i); } } } private async Task<bool> CheckCounters(List<ISampleStreaming_ConsumerGrain> consumers, int totalEventCount, bool assertIsTrue) { List<Task<int>> becomeConsumersTasks = consumers .Select((consumer, i) => consumer.GetNumberConsumed()) .ToList(); int[] counts = await Task.WhenAll(becomeConsumersTasks); if (assertIsTrue) { // one stream per queue Assert.Equal(totalEventCount, counts.Sum()); } else if (totalEventCount != counts.Sum()) { return false; } return true; } } }
mit
projectweekend/Node-API-Utils
lib/handlers/create.js
1495
var util = require( "util" ); var ClassyHandler = require( "./classy" ); module.exports = CreateHandler; function CreateHandler ( req, res, next ) { ClassyHandler.call( this, req, res, next ); this.on( "preCreate", this.preCreate ); this.on( "create", this.create ); this.on( "postCreate", this.postCreate ); } util.inherits( CreateHandler, ClassyHandler ); CreateHandler.prototype.validate = function() { "Emit 'invalid' and pass errors to send validation error response"; "Emit 'create' and pass data to invoke 'create' method"; "Emit 'preCreate' and pass data to invoke 'preCreate' method"; throw new Error( "Not implemented" ); }; CreateHandler.prototype.preCreate = function( data ) { "Emit 'create' and pass data to invoke 'create' method"; "Emit 'error' and pass error to send error response"; throw new Error( "Not implemented" ); }; CreateHandler.prototype.create = function( data ) { "Emit 'error' and pass error to send error response"; "Emit 'respond' and pass data and status code to send response"; "Emit 'postCreate' and pass data to invoke 'postCreate' method"; throw new Error( "Not implemented" ); }; CreateHandler.prototype.postCreate = function( data ) { "Emit 'error' and pass error to send error response"; "Emit 'respond' and pass data and status code to send response"; throw new Error( "Not implemented" ); }; CreateHandler.prototype.handle = function() { this.validate(); };
mit
JeffGillispie/LoadFileAdapter
LoadFileAdapterTests/Exporters/TU_XrefExporter.cs
17117
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using LoadFileAdapter; using LoadFileAdapter.Builders; using LoadFileAdapter.Exporters; using LoadFileAdapter.Instructions; using LoadFileAdapter.Parsers; namespace LoadFileAdapterTests.Exporters { [TestClass] public class TU_XrefExporter { public class TestExporter : XrefExporter { public new string getCustomValue(string imageKey, Document doc, string customValueField) { return base.getCustomValue(imageKey, doc, customValueField); } public new bool getCodeEndFlag(int docIndex, int imageIndex, Switch trigger) { return base.getCodeEndFlag(docIndex, imageIndex, trigger); } public new bool getGroupEndFlag(int docIndex, int imageIndex, Switch trigger) { return base.getGroupEndFlag(docIndex, imageIndex, trigger); } public bool isFlagNeeded(Document doc, Switch trigger, Document previousDoc) { bool result = false; if (trigger != null) { result = trigger.IsTriggered(doc, previousDoc); } return result; } public static bool hasFieldValueChanged(Document doc, Document previousDoc, Switch trigger) { bool result = false; if (trigger != null) { result = trigger.IsTriggered(doc, previousDoc); } return result; } public new Document getNextDoc(int index) { return base.getNextDoc(index); } public new Document getPreviousDoc(int index) { return base.getPreviousDoc(index); } public new static string boolToString(bool b) { return XrefExporter.boolToString(b); } public new string getNextImageKey(int imgIndex, int docIndex) { return base.getNextImageKey(imgIndex, docIndex); } public new string[] getRecordComponents( int docIndex, int imageIndex) { return base.getRecordComponents(docIndex, imageIndex); } public new string getGhostBoxLine(string imageKey, string pageRecord, int docIndex, bool hasSlipsheet) { return base.getGhostBoxLine(imageKey, pageRecord, docIndex, hasSlipsheet); } public new List<string> getPageRecords(int docIndex, SlipSheets slipsheets) { return base.getPageRecords(docIndex, slipsheets); } public void SetBoxNo(int n) { base.boxNumber = n; } public void SetWaitingForFlag(bool flag) { base.waitingForCodeEnd = flag; base.waitingForGroupEnd = flag; } public void SetDocs(DocumentCollection docs) { base.docs = docs; } public void SetBoxTrigger(Switch trigger) { base.boxTrigger = trigger; } public void SetSlipsheets(SlipSheets ss) { base.slipsheets = ss; } } public DocumentCollection GetDocs() { var datLines = new List<string>(new string[] { "þDOCIDþþBEGATTþþVOLUMEþþDOCTYPEþþNATIVEþ", "þDOC000001þþDOC000001þþVOL001þþEMAILþþX:\\VOL001\\NATIVE\\0001\\DOC000001.XLSXþ", "þDOC000002þþDOC000001þþVOL001þþPDFþþþ", null,null }); var optLines = new List<string[]> { new string[] { "DOC000001", "VOL001","X:\\VOL001\\IMAGES\\0001\\DOC000001.jpg","Y","","","1" }, new string[] { "DOC000002", "VOL001","X:\\VOL001\\IMAGES\\0001\\DOC000002.tif","Y","","","2" }, new string[] { "DOC000003", "VOL001","X:\\VOL001\\IMAGES\\0001\\DOC000003.tif","","","","" } }; var mockReader = new Mock<TextReader>(); int calls = 0; mockReader .Setup(r => r.ReadLine()) .Returns(() => datLines[calls]) .Callback(() => calls++); FileInfo infile = new FileInfo(@"X:\VOL001\infile.dat"); bool hasHeader = true; string keyColName = "DOCID"; string parentColName = "BEGATT"; string childColName = String.Empty; string childColDelim = ";"; RepresentativeBuilder repSetting = new RepresentativeBuilder("NATIVE", Representative.FileType.Native); List<RepresentativeBuilder> reps = new List<RepresentativeBuilder>(); reps.Add(repSetting); var builder = new DatBuilder(); IParser parser = new DatParser(Delimiters.CONCORDANCE); List<string[]> records = parser.Parse(mockReader.Object); builder.HasHeader = hasHeader; builder.KeyColumnName = keyColName; builder.ParentColumnName = parentColName; builder.ChildColumnName = childColName; builder.ChildSeparator = childColDelim; builder.RepresentativeBuilders = reps; builder.ParentColumnName = infile.Directory.FullName; List<Document> documents = builder.Build(records); var docs = new DocumentCollection(documents); var optBuilder = new OptBuilder(); optBuilder.PathPrefix = String.Empty; optBuilder.TextBuilder = null; List<Document> optDocs = optBuilder.Build(optLines); docs.AddRange(optDocs); docs[1].SetParent(docs[0]); return docs; } [TestMethod] public void Exporters_XrefExporter_getCustomValue() { string key1 = "DOC000123"; string key2 = "DOC000124"; string field = "DocType"; string value = "Email"; Document doc = new Document(key1, null, null, new Dictionary<string, string>() { { field, value } }, null); TestExporter exporter = new TestExporter(); Assert.AreEqual(value, exporter.getCustomValue(key1, doc, field)); Assert.AreEqual(String.Empty, exporter.getCustomValue(key2, doc, field)); Assert.AreEqual(String.Empty, exporter.getCustomValue(key1, doc, null)); Assert.AreEqual(String.Empty, exporter.getCustomValue(key1, doc, String.Empty)); Assert.AreEqual(String.Empty, exporter.getCustomValue(key1, doc, "bananas")); } [TestMethod] public void Exporters_XrefExporter_getEndFlag() { var docs = GetDocs(); int docIndex = 1; int imgIndex = 0; Trigger trigger = new Trigger(); trigger.Type = Switch.SwitchType.FieldValueChange; trigger.FieldName = "DOCTYPE"; trigger.FieldChangeOption = Switch.ValueChangeOption.None; TestExporter exporter = new TestExporter(); exporter.SetDocs(docs); exporter.SetWaitingForFlag(true); Assert.IsTrue(exporter.getCodeEndFlag(docIndex, imgIndex, trigger.ToSwitch())); Assert.IsTrue(exporter.getGroupEndFlag(docIndex, imgIndex, trigger.ToSwitch())); exporter.SetWaitingForFlag(false); Assert.IsFalse(exporter.getCodeEndFlag(docIndex, imgIndex, trigger.ToSwitch())); Assert.IsFalse(exporter.getGroupEndFlag(docIndex, imgIndex, trigger.ToSwitch())); } [TestMethod] public void Exporters_XrefExporter_isFlagNeeded() { Document parent = new Document("DOC122", null, null, new Dictionary<string, string>() { { "TEST", "abc123" } }, null); Document doc = new Document("DOC123", parent, null, new Dictionary<string, string>() { { "TEST", "XYZ321" } }, null); Trigger trigger = new Trigger(); trigger.Type = Switch.SwitchType.None; TestExporter exporter = new TestExporter(); Assert.IsFalse(exporter.isFlagNeeded(doc, trigger.ToSwitch(), parent)); trigger.Type = Switch.SwitchType.Family; Assert.IsTrue(exporter.isFlagNeeded(parent, trigger.ToSwitch(), null)); Assert.IsFalse(exporter.isFlagNeeded(doc, trigger.ToSwitch(), parent)); trigger.Type = Switch.SwitchType.Regex; trigger.FieldName = "TEST"; trigger.RegexPattern = "[a-zA-Z]+\\d+"; Assert.IsTrue(exporter.isFlagNeeded(parent, trigger.ToSwitch(), null)); Assert.IsTrue(exporter.isFlagNeeded(doc, trigger.ToSwitch(), parent)); doc.Metadata["TEST"] = "123nope"; Assert.IsFalse(exporter.isFlagNeeded(doc, trigger.ToSwitch(), parent)); } [TestMethod] public void Exporters_XrefExporter_hasFieldValueChanged() { Document parent = new Document("DOC122", null, null, new Dictionary<string, string>() { { "FILE", @"X:\ROOT\VOL\DIR1\FILE1.TXT" }, { "EXT", "TXT" } }, null); Document doc = new Document("DOC123", parent, null, new Dictionary<string, string>() { { "FILE", @"X:\ROOT\VOL\DIR2\FILE2.TXT" }, { "EXT", "TXT" } }, null); Document child = new Document("DOC124", doc, null, new Dictionary<string, string>() { { "FILE", @"X:\ROOT\VOL\DIR2\FILE3.PDF" }, { "EXT", "PDF" } }, null); Trigger trigger = new Trigger(); trigger.Type = Switch.SwitchType.FieldValueChange; trigger.FieldName = "EXT"; trigger.FieldChangeOption = Switch.ValueChangeOption.None; Assert.IsFalse(TestExporter.hasFieldValueChanged(doc, parent, trigger.ToSwitch())); Assert.IsTrue(TestExporter.hasFieldValueChanged(child, doc, trigger.ToSwitch())); trigger.FieldName = "FILE"; trigger.FieldChangeOption = Switch.ValueChangeOption.StripFileName; Assert.IsTrue(TestExporter.hasFieldValueChanged(doc, parent, trigger.ToSwitch())); Assert.IsFalse(TestExporter.hasFieldValueChanged(child, doc, trigger.ToSwitch())); trigger.FieldChangeOption = Switch.ValueChangeOption.UseStartingSegments; trigger.SegmentDelimiter = "\\"; trigger.SegmentCount = 4; Assert.IsTrue(TestExporter.hasFieldValueChanged(doc, parent, trigger.ToSwitch())); Assert.IsFalse(TestExporter.hasFieldValueChanged(child, doc, trigger.ToSwitch())); trigger.FieldChangeOption = Switch.ValueChangeOption.UseEndingSegments; trigger.SegmentDelimiter = "."; trigger.SegmentCount = 1; Assert.IsFalse(TestExporter.hasFieldValueChanged(doc, parent, trigger.ToSwitch())); Assert.IsTrue(TestExporter.hasFieldValueChanged(child, doc, trigger.ToSwitch())); } [TestMethod] public void Exporters_XrefExporter_moveDocPos() { var docs = GetDocs(); Document first = docs[0]; Document last = docs[1]; TestExporter exporter = new TestExporter(); exporter.SetDocs(docs); Assert.AreEqual(last, exporter.getNextDoc(0)); Assert.AreEqual(first, exporter.getPreviousDoc(1)); Assert.AreEqual(null, exporter.getNextDoc(1)); Assert.AreEqual(null, exporter.getPreviousDoc(0)); } [TestMethod] public void Exporters_XrefExporter_boolToString() { Assert.AreEqual("1", TestExporter.boolToString(true)); Assert.AreEqual("0", TestExporter.boolToString(false)); } [TestMethod] public void Exporters_XrefExporter_getNextImageKey() { var docs = GetDocs(); TestExporter exporter = new TestExporter(); exporter.SetDocs(docs); Assert.AreEqual("DOC000002", exporter.getNextImageKey(0, 0)); Assert.AreEqual("DOC000003", exporter.getNextImageKey(0, 1)); Assert.AreEqual(null, exporter.getNextImageKey(1, 1)); Assert.AreEqual(null, exporter.getNextImageKey(2, 1)); } [TestMethod] public void Exporters_XrefExporter_getRecordComponents() { var docs = GetDocs(); TestExporter exporter = new TestExporter(); exporter.SetDocs(docs); var settings = new XrefExport(); string record = String.Join(", ", exporter.getRecordComponents(0, 0)); string expected = "X:\\VOL001\\IMAGES\\0001\\DOC000001.jpg, DOC, 000001, , 0, 0, 1, 0, 0, 0, 0, , , "; Assert.AreEqual(expected, record); } [TestMethod] public void Exporters_XrefExporter_getGhostBoxLine() { var docs = GetDocs(); TestExporter exporter = new TestExporter(); exporter.SetDocs(docs); exporter.SetBoxNo(0); Trigger trigger = new Trigger() { Type = Switch.SwitchType.Family }; exporter.SetBoxTrigger(trigger.ToSwitch()); string result = exporter.getGhostBoxLine("DOC000001", String.Empty, 0, false); Assert.AreEqual(@"\Box001\..", result); result = exporter.getGhostBoxLine("DOC000002", String.Empty, 1, false); Assert.AreEqual(@"\Box001\..", result); result = exporter.getGhostBoxLine("DOC000003", String.Empty, 1, false); Assert.AreEqual(@"\Box001\..", result); trigger.Type = Switch.SwitchType.FieldValueChange; trigger.FieldName = "DOCID"; exporter.SetBoxTrigger(trigger.ToSwitch()); exporter.SetBoxNo(0); result = exporter.getGhostBoxLine("DOC000001", String.Empty, 0, false); Assert.AreEqual(@"\Box001\..", result); result = exporter.getGhostBoxLine("DOC000002", String.Empty, 1, false); Assert.AreEqual(@"\Box002\..", result); result = exporter.getGhostBoxLine("DOC000003", String.Empty, 1, false); Assert.AreEqual(@"\Box002\..", result); exporter.SetBoxNo(1); result = exporter.getGhostBoxLine("DOC000002", String.Empty, 1, true); Assert.AreEqual(@"\Box001\..", result); result = exporter.getGhostBoxLine("DOC000002", String.Empty, 1, false); Assert.AreEqual(@"\Box002\..", result); } [TestMethod] public void Exporters_XrefExporter_getPageRecords() { var docs = GetDocs(); TestExporter exporter = new TestExporter(); exporter.SetDocs(docs); var field = new SlipsheetField(); field.FieldName = "DOCID"; field.Alias = "begno"; var fields = new SlipsheetField[] { field }; Trigger trigger = new Trigger(); trigger.Type = Switch.SwitchType.FieldValueChange; trigger.FieldName = "DOCID"; trigger.FieldChangeOption = Switch.ValueChangeOption.None; var ss = SlipSheets.Builder .Start(trigger.ToSwitch()) .SetAliasMap(fields.ToDictionary(f => f.FieldName, f => f.Alias)) .SetFolderName("SlipSheets") .Build(); ss.GenerateSlipSheets(docs); exporter.SetSlipsheets(ss); var actual = exporter.getPageRecords(1, ss); List<string> expected = new List<string>(); expected.Add("\\SlipSheets\\DOC000001.001.TIF, DOC, 000001, .001, 0, 0, 1, 0, 0, 0, 1, , , "); expected.Add("X:\\VOL001\\IMAGES\\0001\\DOC000002.tif, DOC, 000002, , 0, 0, 1, 0, 0, 0, 0, , , "); expected.Add("X:\\VOL001\\IMAGES\\0001\\DOC000003.tif, DOC, 000003, , 0, 0, 0, 0, 0, 0, 0, , , "); for (int i = 0; i < expected.Count; i++) { Assert.AreEqual(expected[i], actual[i]); } } } }
mit
aressler38/Excerpts
excerpts/database.py
807
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('mysql://admin:f1$hSt1ck$@localhost:3306/excerpts', convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property() def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import excerpts.model.Pages import excerpts.model.Password Base.metadata.create_all(bind=engine)
mit
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2020-08-01/generated/azure_mgmt_network/models/azure_firewall_rcaction_type.rb
381
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2020_08_01 module Models # # Defines values for AzureFirewallRCActionType # module AzureFirewallRCActionType Allow = "Allow" Deny = "Deny" end end end
mit
UselessToucan/osu
osu.Game/Screens/Edit/Compose/Components/Timeline/TimelineSelectionHandler.cs
2246
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Allocation; using osu.Framework.Input.Bindings; using osu.Game.Input.Bindings; using osu.Game.Rulesets.Objects; using osuTK; namespace osu.Game.Screens.Edit.Compose.Components.Timeline { internal class TimelineSelectionHandler : EditorSelectionHandler, IKeyBindingHandler<GlobalAction> { [Resolved] private Timeline timeline { get; set; } public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => timeline.ScreenSpaceDrawQuad.Contains(screenSpacePos); // for now we always allow movement. snapping is provided by the Timeline's "distance" snap implementation public override bool HandleMovement(MoveSelectionEvent<HitObject> moveEvent) => true; public bool OnPressed(GlobalAction action) { switch (action) { case GlobalAction.EditorNudgeLeft: nudgeSelection(-1); return true; case GlobalAction.EditorNudgeRight: nudgeSelection(1); return true; } return false; } public void OnReleased(GlobalAction action) { } /// <summary> /// Nudge the current selection by the specified multiple of beat divisor lengths, /// based on the timing at the first object in the selection. /// </summary> /// <param name="amount">The direction and count of beat divisor lengths to adjust.</param> private void nudgeSelection(int amount) { var selected = EditorBeatmap.SelectedHitObjects; if (selected.Count == 0) return; var timingPoint = EditorBeatmap.ControlPointInfo.TimingPointAt(selected.First().StartTime); double adjustment = timingPoint.BeatLength / EditorBeatmap.BeatDivisor * amount; EditorBeatmap.PerformOnSelection(h => { h.StartTime += adjustment; EditorBeatmap.Update(h); }); } } }
mit
troyGH/Cudos
application/views/login_view.php
3125
<?php $this->load->view('template/header.php'); ?> <!-- LOGIN FORM --> <div class="login-body"> <?php echo $this->session->flashdata('reg_msg');?> <?php echo $this->session->flashdata('lg_err'); ?> <div id="back"> <div class="backRight"></div> <div class="backLeft"></div> </div> <div id="slideBox"> <div class="topLayer"> <div class="leftpart"> <div class="content"> <h2 style="margin-bottom:0;margin-top: 0">Sign Up</h2> <?php $attributes = array("id" => "register-form", "class" => "text-left"); echo form_open("user/signup", $attributes); ?> <div class="form-group"> <label for="reg_fname" class="form-label"><span class="glyphicon glyphicon-user"></span> First Name</label> <input type="text" class="form-control" id="reg_fname" name="reg_fname" required /> </div> <div class="form-group"> <label for="reg_lname" class="form-label"><span class="glyphicon glyphicon-user"></span> Last Name</label> <input type="text" class="form-control" id="reg_lname" name="reg_lname" required /> </div> <div class="form-group"> <label for="reg_zip" class="form-label"><span class="glyphicon glyphicon-map-marker"></span> Zip Code</label> <input type="text" class="form-control" id="reg_zip" name="reg_zip" required /> </div> <div class="form-group"> <label for="reg_email" class="form-label"><span class="glyphicon glyphicon-envelope"></span> Email</label> <input type="email" class="form-control" id="reg_email" name="reg_email" required /> </div> <div class="form-group"> <label for="reg_password" class="form-label"><span class="glyphicon glyphicon-lock"></span> Password</label> <input type="password" class="form-control" id="reg_password" name="reg_password" required /> </div> <button id="goLeft" class="off" ng-disabled="form.$invalid">Login</button> <button id="signup" type="submit">Sign up</button> <?php echo form_close();?> </div> </div> <div class="rightpart"> <div class="content"> <h2>Login</h2> <?php $attributes = array("id" => "login-form", "class" => "text-left"); echo form_open("user/login", $attributes); ?> <!-- Error Message --> <div class="form-group"> <label for="lg_email" class="form-label"><span class="glyphicon glyphicon-envelope"></span> Email Address</label> <input type="email" class="form-control" id="lg_email" name="lg_email" required /> </div> <div class="form-group"> <label for="lg_password" class="form-label"><span class="glyphicon glyphicon-lock"></span> Password</label> <input type="password" class="form-control" id="lg_password" name="lg_password" required /> </div> <button id="goRight" class="off" ng-disabled="form.$invalid">Sign Up</button> <button id="login" type="submit">Login</button> <?php echo form_close();?> </div> </div> </div> </div> </div> <?php $this->load->view('template/footer.php'); ?>
mit
colkito/freshbooksjs
lib/services/Project.js
4116
/* * Full Documentation: * http://developers.freshbooks.com/docs/projects/ * */ var utils = require('./utils'); function ProjectService(config) { if (!(this instanceof ProjectService)) { return new ProjectService(config); } this.config = config; } /* http://developers.freshbooks.com/docs/projects/#project.list */ ProjectService.prototype.list = function(callback) { //cb(err, project, metaData) var options = { method: 'project.list', url: this.config.url, token: this.config.token }; var filters, cb; if (typeof arguments[1] === 'function') { cb = arguments[1]; filters = arguments[0]; } utils.callAPI(filters, options, function(err, result) { if (err) { cb(err, null); } else if (!result || !result.projects) { cb(null, null); } else { var meta; if (result.projects.$) { meta = { page: result.projects.$.page, per_page: result.projects.$.per_page, pages: result.projects.$.pages, total: result.projects.$.total }; } else { meta = {}; } var projects; if (result.projects.project) { if (Array.isArray(result.projects.project)) { projects = result.projects.project; } else { projects = [result.projects.project]; } } else { projects = []; } cb(null, projects, meta); } }); }; /* http://developers.freshbooks.com/docs/projects/#project.create */ ProjectService.prototype.create = function(project, cb) { //cb(err, project) var self = this, data = { project: project }, options = { method: 'project.create', url: this.config.url, token: this.config.token }; utils.callAPI(data, options, function(err, result) { if (err) { cb(err, null); } else if (!result || !result.project_id) { cb(new Error('Server returned no ID for project create'), null); } else { self.get(result.project_id, cb); } }); }; /* http://developers.freshbooks.com/docs/projects/#project.update */ ProjectService.prototype.update = function(project, cb) { //cb(err, project) var self = this, data = { project: project }, options = { method: 'project.update', url: this.config.url, token: this.config.token }; utils.callAPI(data, options, function(err, result) { if (err) { cb(err, null); } else { self.get(project.project_id, cb); } }); }; /* http://developers.freshbooks.com/docs/projects/#project.get */ ProjectService.prototype.get = function(id, cb) { //cb(err, project) var data = { project_id: id }, options = { method: 'project.get', url: this.config.url, token: this.config.token }; utils.callAPI(data, options, function(err, result) { if (err) { cb(err, null); } else if (!result) { cb(null, null); } else { cb(null, result.project || null); } }); }; /* http://developers.freshbooks.com/docs/projects/#project.delete */ ProjectService.prototype.delete = function(id, cb) { //cb(err) var data = { project_id: id }, options = { method: 'project.delete', url: this.config.url, token: this.config.token }; utils.callAPI(data, options, function(err, result) { if (err) { cb(err); } else { cb(null); } }); }; module.exports = ProjectService;
mit
MarkEWaite/git-client-plugin
src/test/java/org/jenkinsci/plugins/gitclient/trilead/StandardUsernamePasswordCredentialsImpl.java
1339
package org.jenkinsci.plugins.gitclient.trilead; import com.cloudbees.plugins.credentials.CredentialsDescriptor; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.util.Secret; class StandardUsernamePasswordCredentialsImpl implements StandardUsernamePasswordCredentials { private final String userName; private final Secret password; public StandardUsernamePasswordCredentialsImpl(String userName, Secret password) { this.userName = userName; this.password = password; } @NonNull public String getDescription() { throw new UnsupportedOperationException("Should not be called"); } @NonNull public String getId() { throw new UnsupportedOperationException("Should not be called"); } public CredentialsScope getScope() { throw new UnsupportedOperationException("Should not be called"); } @NonNull public CredentialsDescriptor getDescriptor() { throw new UnsupportedOperationException("Should not be called"); } @NonNull public String getUsername() { return userName; } @NonNull public Secret getPassword() { return password; } }
mit
joshswan/react-native-globalize
test/setup.test.js
356
/*! * React Native Globalize * * Copyright 2015-2020 Josh Swan * Released under the MIT license * https://github.com/joshswan/react-native-globalize/blob/master/LICENSE */ import { loadCldr } from '../src'; beforeAll(() => { loadCldr( require('../locale-data/de'), require('../locale-data/en'), require('../locale-data/es'), ); });
mit
vikkio88/dsManager-php
app/controllers/matches/newMatchController.js
868
(function () { "use strict"; angular.module("DsManager") .controller( "NewMatchController", [ "Common", "$scope", "$stateParams", NewMatchController ]); function NewMatchController(Common, $scope, $stateParams) { var vm = this; vm.teams = {}; vm.isValidSelection = function (homeTeam, awayTeam) { return (homeTeam !== undefined && awayTeam !== undefined && homeTeam.id != awayTeam.id); }; Common.Get ( "teams" ).then( function (data) { if (Common.isDebug()) console.log(data.data); vm.teams = data.data; }, function (data) { console.log(data); } ); } })();
mit
jonas054/rubocop
spec/rubocop/cop/style/if_unless_modifier_of_if_unless_spec.rb
1491
# frozen_string_literal: true describe RuboCop::Cop::Style::IfUnlessModifierOfIfUnless do include StatementModifierHelper subject(:cop) { described_class.new } it 'provides a good error message' do source = 'condition ? then_part : else_part unless external_condition' inspect_source(cop, source) expect(cop.messages) .to eq(['Avoid modifier `unless` after another conditional.']) end context 'ternary with modifier' do let(:source) do 'condition ? then_part : else_part unless external_condition' end it 'registers an offense' do inspect_source(cop, source) expect(cop.offenses.size).to eq(1) end end context 'conditional with modifier' do let(:source) do ['unless condition', ' then_part', 'end if external_condition'] end it 'registers an offense' do inspect_source(cop, source) expect(cop.offenses.size).to eq(1) end end context 'conditional with modifier in body' do let(:source) do ['if condition', ' then_part if maybe?', 'end'] end it 'accepts' do inspect_source(cop, source) expect(cop.offenses).to be_empty end end context 'nested conditionals' do let(:source) do ['if external_condition', ' if condition', ' then_part', ' end', 'end'] end it 'accepts' do inspect_source(cop, source) expect(cop.offenses).to be_empty end end end
mit
jn2840/bitcoin
src/qt/locale/bitcoin_th_TH.ts
14224
<TS language="th_TH" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Create a new address</source> <translation>สร้างที่อยู่ใหม่</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>คัดลอกที่อยู่ที่ถูกเลือกไปยัง คลิปบอร์ดของระบบ</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;ลบ</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>คั่นไฟล์ด้วยเครื่องหมายจุลภาค (*.csv)</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>ชื่อ</translation> </message> <message> <source>Address</source> <translation>ที่อยู่</translation> </message> <message> <source>(no label)</source> <translation>(ไม่มีชื่อ)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Enter passphrase</source> <translation>ใส่รหัสผ่าน</translation> </message> <message> <source>New passphrase</source> <translation>รหัสผา่นใหม่</translation> </message> <message> <source>Repeat new passphrase</source> <translation>กรุณากรอกรหัสผ่านใหม่อีกครั้งหนึ่ง</translation> </message> <message> <source>Encrypt wallet</source> <translation>กระเป๋าสตางค์ที่เข้ารหัส</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>การดำเนินการนี้ต้องมีรหัสผ่านกระเป๋าเงินของคุณเพื่อปลดล็อคกระเป๋าเงิน</translation> </message> <message> <source>Unlock wallet</source> <translation>เปิดกระเป๋าสตางค์</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>การดำเนินการนี้ต้องมีรหัสผ่านกระเป๋าเงินของคุณในการถอดรหัสกระเป๋าเงิน</translation> </message> <message> <source>Decrypt wallet</source> <translation>ถอดรหัสกระเป๋าสตางค์</translation> </message> <message> <source>Change passphrase</source> <translation>เปลี่ยนรหัสผ่าน</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>ยืนยันการเข้ารหัสกระเป๋าสตางค์</translation> </message> <message> <source>Wallet encrypted</source> <translation>กระเป๋าสตางค์ถูกเข้ารหัสเรียบร้อยแล้ว</translation> </message> <message> <source>Wallet encryption failed</source> <translation>การเข้ารหัสกระเป๋าสตางค์ผิดพลาด</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>กระเป๋าเงินเข้ารหัสล้มเหลวเนื่องจากข้อผิดพลาดภายใน กระเป๋าเงินของคุณไม่ได้เข้ารหัส</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>รหัสผ่านที่คุณกรอกไม่ตรงกัน</translation> </message> <message> <source>Wallet unlock failed</source> <translation>ปลดล็อคกระเป๋าเงินล้มเหลว</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>ป้อนรหัสผ่านสำหรับการถอดรหัสกระเป๋าเงินไม่ถูกต้อง</translation> </message> <message> <source>Wallet decryption failed</source> <translation>ถอดรหัสกระเป๋าเงินล้มเหลว</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Synchronizing with network...</source> <translation>กำลังทำข้อมูลให้ตรงกันกับเครือข่าย ...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;ภาพรวม</translation> </message> <message> <source>Show general overview of wallet</source> <translation>แสดงภาพรวมทั่วไปของกระเป๋าเงิน</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;การทำรายการ</translation> </message> <message> <source>Browse transaction history</source> <translation>เรียกดูประวัติการทำธุรกรรม</translation> </message> <message> <source>Quit application</source> <translation>ออกจากโปรแกรม</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;ตัวเลือก...</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>เปลี่ยนรหัสผ่านที่ใช้สำหรับการเข้ารหัสกระเป๋าเงิน</translation> </message> <message> <source>&amp;File</source> <translation>&amp;ไฟล์</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;การตั้งค่า</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;ช่วยเหลือ</translation> </message> <message> <source>Tabs toolbar</source> <translation>แถบเครื่องมือ</translation> </message> <message numerus="yes"> <source>%n active connection(s) to Beardcoin network</source> <translation><numerusform>%n ที่ใช้งานการเชื่อมต่อกับเครือข่าย Beardcoin</numerusform></translation> </message> <message> <source>Up to date</source> <translation>ทันสมัย</translation> </message> <message> <source>Catching up...</source> <translation>จับได้...</translation> </message> <message> <source>Sent transaction</source> <translation>รายการที่ส่ง</translation> </message> <message> <source>Incoming transaction</source> <translation>การทำรายการขาเข้า</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>ระเป๋าเงินถูก &lt;b&gt;เข้ารหัส&lt;/b&gt; และในขณะนี้ &lt;b&gt;ปลดล็อคแล้ว&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>กระเป๋าเงินถูก &lt;b&gt;เข้ารหัส&lt;/b&gt; และในปัจจุบัน &lt;b&gt;ล็อค &lt;/b&gt;</translation> </message> </context> <context> <name>ClientModel</name> </context> <context> <name>CoinControlDialog</name> <message> <source>(no label)</source> <translation>(ไม่มีชื่อ)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>แก้ไขที่อยู่</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;ชื่อ</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;ที่อยู่</translation> </message> <message> <source>New receiving address</source> <translation>ที่อยู่ผู้รับใหม่</translation> </message> <message> <source>New sending address</source> <translation>ที่อยู่ผู้ส่งใหม่</translation> </message> <message> <source>Edit receiving address</source> <translation>แก้ไขที่อยู่ผู้รับ</translation> </message> <message> <source>Edit sending address</source> <translation>แก้ไขที่อยู่ผู้ส่ง</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>ป้อนที่อยู่ "%1" ที่มีอยู่แล้วในสมุดที่อยู่</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>ไม่สามารถปลดล็อคกระเป๋าเงิน</translation> </message> <message> <source>New key generation failed.</source> <translation>สร้างกุญแจใหม่ล้มเหลว</translation> </message> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> </context> <context> <name>Intro</name> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>ตัวเลือก</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>รูป</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> </context> <context> <name>ReceiveCoinsDialog</name> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>Address</source> <translation>ที่อยู่</translation> </message> <message> <source>Label</source> <translation>ชื่อ</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Label</source> <translation>ชื่อ</translation> </message> <message> <source>(no label)</source> <translation>(ไม่มีชื่อ)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>ส่งเหรียญ</translation> </message> <message> <source>(no label)</source> <translation>(ไม่มีชื่อ)</translation> </message> </context> <context> <name>SendCoinsEntry</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> </context> <context> <name>TransactionDescDialog</name> </context> <context> <name>TransactionTableModel</name> <message> <source>Label</source> <translation>ชื่อ</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>Today</source> <translation>วันนี้</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>คั่นไฟล์ด้วยเครื่องหมายจุลภาค (*.csv)</translation> </message> <message> <source>Label</source> <translation>ชื่อ</translation> </message> <message> <source>Address</source> <translation>ที่อยู่</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>ส่งเหรียญ</translation> </message> </context> <context> <name>WalletView</name> </context> <context> <name>beardcoin-core</name> </context> </TS>
mit
zreed/StarQuestCode
Standalone/SubcontractGenerator/src/com/dibujaron/subcontractor/Certification.java
3456
package com.dibujaron.subcontractor; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; public class Certification { public HashMap<String, String> values = new HashMap<String, String>(); public ArrayList<String> onAdd = new ArrayList<String>(); public ArrayList<String> onRemove = new ArrayList<String>(); public Certification(HashMap<String, String> values, ArrayList<String> onAdd, ArrayList<String> onRemove){ this.values = values; this.onAdd = onAdd; this.onRemove = onRemove; } public Certification(String path) { try { List<String> lines = Files.readAllLines(Paths.get(path), Charset.defaultCharset()); for (String s : lines) { if (s.startsWith("#")) continue; if (s.length() == 0) continue; String[] split = s.split(": "); if(split.length < 2) continue; String key = split[0].toLowerCase(); if (key.equals("onadd")) { onAdd.add(split[1]); } else if (key.equals("onremove")) { onRemove.add(split[1]); } else { values.put(key, split[1]); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void writeToFile(File f){ try{ PrintWriter w = new PrintWriter(new FileWriter(f)); for(String s : values.keySet()){ String value = values.get(s); String fnl = s + ": " + value; w.println(fnl); } for(String s : onAdd){ String fnl = "onAdd: " + s; w.println(fnl); } for(String s : onRemove){ String fnl = "onRemove: " + s; w.println(fnl); } w.close(); } catch (Exception e){ e.printStackTrace(); } } public String getIdentifier() { return values.get("identifier"); } public String getDescription() { return values.get("description"); } public String[] getPreRequisites() { String pre = values.get("prerequisites"); if (pre.equals("none")) return new String[0]; else return pre.split(", "); } public int getRequirementInContractCurrency(String currency) { String val = values.get(currency + "min"); if (val == null) return 0; return Integer.parseInt(val); } public int getCostInCurrency(String currency) { try { return Integer.parseInt(values.get("cost" + currency)); } catch (Exception e) { return 0; } } public int getCost() { return getCostInCurrency("Credits"); } public boolean satisfiesPreReqs(List<String> existing) { for (String s : getPreRequisites()) { if (!existing.contains(s)) return false; } return true; } public String getTag() { return values.get("tag"); } public String getTagColor() { return "§" + values.get("tagcolor"); } public int getMaxSubCerts() { String val = values.get("maxsubcerts"); if (val == null) return 0; return Integer.parseInt(val); } public String[] getConflicts() { String mut = values.get("conflicts"); if (mut.equals("none")) return new String[0]; else return mut.split(", "); } private String formatStringArray(String[] str) { if (str.length == 1) return str[0]; if (str.length == 2) return str[0] + " and " + str[1]; String retval = ""; for (int i = 0; i < str.length - 1; i++) { retval = retval + str[i] + ", "; } retval = retval + " and " + str[str.length - 1]; return retval; } }
mit
rsbauer/RoundelRemoteAndroid
RoundelRemote/mobile/src/main/java/com/rsbauer/roundelremote/webservices/models/response/VehicleStatus.java
1034
package com.rsbauer.roundelremote.webservices.models.response; /** * Created by astro on 2/22/15. */ public class VehicleStatus { private String vin; private String updateTime; private Position position; /** * * @return * The vin */ public String getVin() { return vin; } /** * * @param vin * The vin */ public void setVin(String vin) { this.vin = vin; } /** * * @return * The updateTime */ public String getUpdateTime() { return updateTime; } /** * * @param updateTime * The updateTime */ public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } /** * * @return * The position */ public Position getPosition() { return position; } /** * * @param position * The position */ public void setPosition(Position position) { this.position = position; } }
mit
KenticoAcademy/PV247-2017
DemoReactApp/src/reducers/shared/token.js
457
import { SHARED_RECEIVE_TOKEN, SHARED_INVALIDATE_TOKEN, SHARED_AUTHENTICATION_FAILED, } from '../../constants/actionTypes'; export const token = (prevState = null, action) => { switch (action.type) { case SHARED_RECEIVE_TOKEN: return action.payload.token; case SHARED_AUTHENTICATION_FAILED: case SHARED_INVALIDATE_TOKEN: return null; default: return prevState; } };
mit
jrhenderson1988/blixt
tests/Persistence/Repositories/AbstractRepositoryTest.php
9452
<?php namespace BlixtTests\Persistence\Repositories; use Blixt\Persistence\Drivers\Storage; use Blixt\Persistence\Entities\Entity; use Blixt\Persistence\Record; use Blixt\Persistence\Repositories\AbstractRepository; use BlixtTests\TestCase; use Illuminate\Support\Collection; use Mockery as m; class AbstractRepositoryTest extends TestCase { /** * @var \Mockery\MockInterface|\Blixt\Persistence\Drivers\Storage */ protected $storage; /** * @var \Blixt\Persistence\Repositories\AbstractRepository */ protected $repository; public function setUp() { $this->storage = m::mock(Storage::class); $this->repository = new TestRepository($this->storage); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::toAttributes() */ public function testToAttributes() { $this->assertEquals( [TestRepository::NAME => 'test'], TestRepository::toAttributes(TestEntity::make(1, 'test')) ); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::toEntity() */ public function testToEntity() { $this->assertEquals( TestEntity::make(1, 'test'), TestRepository::toEntity(1, [TestRepository::NAME => 'test']) ); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::create() * @throws \Blixt\Exceptions\StorageException */ public function testCreate() { $this->storage->shouldReceive('create') ->once() ->withArgs([TestRepository::TABLE, [TestRepository::NAME => 'test']]) ->andReturn(new Record(1, [TestRepository::NAME => 'test'])); $this->assertEquals(TestEntity::make(1, 'test'), $this->repository->create(TestEntity::create('test'))); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::update() * @throws \Blixt\Exceptions\StorageException */ public function testUpdate() { $this->storage->shouldReceive('update') ->once() ->withArgs([TestRepository::TABLE, 1, [TestRepository::NAME => 'test']]) ->andReturn(new Record(1, [TestRepository::NAME => 'test'])); $this->assertEquals(TestEntity::make(1, 'test'), $this->repository->update(TestEntity::make(1, 'test'))); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::save() * @throws \Blixt\Exceptions\StorageException */ public function testSaveOnExistingRecord() { $this->storage->shouldReceive('update') ->once() ->withArgs([TestRepository::TABLE, 1, [TestRepository::NAME => 'test']]) ->andReturn(new Record(1, [TestRepository::NAME => 'test'])); $this->storage->shouldNotReceive('create'); $this->assertEquals(TestEntity::make(1, 'test'), $this->repository->save(TestEntity::make(1, 'test'))); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::save() * @throws \Blixt\Exceptions\StorageException */ public function testSaveOnNewRecord() { $this->storage->shouldReceive('create') ->once() ->withArgs([TestRepository::TABLE, [TestRepository::NAME => 'test']]) ->andReturn(new Record(1, [TestRepository::NAME => 'test'])); $this->storage->shouldNotReceive('update'); $this->assertEquals(TestEntity::make(1, 'test'), $this->repository->save(TestEntity::create('test'))); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::findBy() */ public function testFindBy() { $this->storage->shouldReceive('getWhere') ->once() ->withArgs([TestRepository::TABLE, [TestRepository::NAME => 1], 0, 1]) ->andReturn([new Record(1, [TestRepository::NAME => 'test'])]); $this->assertEquals(TestEntity::make(1, 'test'), $this->repository->findBy([TestRepository::NAME => 1])); $this->storage->shouldReceive('getWhere') ->once() ->withArgs([TestRepository::TABLE, [TestRepository::NAME => 1234], 0, 1]) ->andReturn([]); $this->assertNull($this->repository->findBy([TestRepository::NAME => 1234])); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::get() */ public function testGet() { $this->storage->shouldReceive('get') ->once() ->withArgs([TestRepository::TABLE, [1, 2, 3]]) ->andReturn([ new Record(1, [TestRepository::NAME => 'one']), new Record(2, [TestRepository::NAME => 'two']), new Record(3, [TestRepository::NAME => 'three']), ]); $this->assertEquals( Collection::make([ 1 => TestEntity::make(1, 'one'), 2 => TestEntity::make(2, 'two'), 3 => TestEntity::make(3, 'three') ]), $this->repository->get([1, 2, 3]) ); $this->storage->shouldReceive('get') ->once() ->withArgs([TestRepository::TABLE, [4]]) ->andReturn([]); $this->assertEquals(Collection::make([]), $this->repository->get([4])); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::find() */ public function testFind() { $this->storage->shouldReceive('get') ->once() ->withArgs([TestRepository::TABLE, [1]]) ->andReturn([new Record(1, [TestRepository::NAME => 'test'])]); $this->assertEquals(TestEntity::make(1, 'test'), $this->repository->find(1)); $this->storage->shouldReceive('get') ->once() ->withArgs([TestRepository::TABLE, [1234]]) ->andReturn([]); $this->assertNull($this->repository->find(1234)); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::getWhere() */ public function testGetWhere() { $this->storage->shouldReceive('getWhere') ->once() ->withArgs([TestRepository::TABLE, [TestRepository::NAME => 1], 0, 1]) ->andReturn([new Record(1, [TestRepository::NAME => 'test'])]); $this->assertEquals( Collection::make([1 => TestEntity::make(1, 'test')]), $this->repository->getWhere([TestRepository::NAME => 1], 0, 1) ); $this->storage->shouldReceive('getWhere') ->once() ->withArgs([TestRepository::TABLE, [TestRepository::NAME => 1234], 0, 1]) ->andReturn([]); $this->assertEquals( Collection::make([]), $this->repository->getWhere([TestRepository::NAME => 1234], 0, 1) ); } /** * @test * @covers \Blixt\Persistence\Repositories\AbstractRepository::all() */ public function testAll() { $this->storage->shouldReceive('getWhere') ->once() ->withArgs([TestRepository::TABLE, [], 0, null]) ->andReturn([new Record(1, [TestRepository::NAME => 'test'])]); $this->assertEquals(Collection::make([1 => TestEntity::make(1, 'test')]), $this->repository->all()); $this->storage->shouldReceive('getWhere') ->once() ->withArgs([TestRepository::TABLE, [], 10, 10]) ->andReturn([]); $this->assertEquals(Collection::make([]), $this->repository->all(10, 10)); } } class TestRepository extends AbstractRepository { public const TABLE = 'tests'; public const NAME = 'name'; /** * @param \BlixtTests\Persistence\Repositories\TestEntity|\Blixt\Persistence\Entities\Entity $entity * * @return array */ public static function toAttributes(Entity $entity): array { return [ static::NAME => $entity->getName() ]; } /** * @param int $id * @param array $attributes * * @return \BlixtTests\Persistence\Repositories\TestEntity|\Blixt\Persistence\Entities\Entity */ public static function toEntity(int $id, array $attributes): Entity { return TestEntity::make($id, $attributes[static::NAME]); } } class TestEntity extends Entity { /** * @var string */ protected $name; /** * TestEntity constructor. * * @param int|null $id * @param string $name */ public function __construct(?int $id, string $name) { parent::__construct($id); $this->setName($name); } /** * @param string $name */ public function setName(string $name) { $this->name = $name; } /** * @return string */ public function getName() { return $this->name; } /** * @param int $id * @param string $name * * @return \BlixtTests\Persistence\Repositories\TestEntity */ public static function make(int $id, string $name) { return new static($id, $name); } /** * @param string $name * * @return \BlixtTests\Persistence\Repositories\TestEntity */ public static function create(string $name) { return new static(null, $name); } }
mit
nh13/picard
src/main/java/picard/illumina/IlluminaPhasingMetrics.java
3728
/* * The MIT License * * Copyright (c) 2014 The Broad Institute * * 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 picard.illumina; import htsjdk.samtools.metrics.MetricBase; import picard.illumina.parser.Tile; import picard.illumina.parser.TileTemplateRead; import java.util.ArrayList; import java.util.Collection; /** * Metrics for Illumina Basecalling that stores median phasing and prephasing percentages on a per-template-read, per-lane basis. * Phasing refers to the fraction of molecules that fall behind or jump ahead (prephasing) during a read cycle. * For each lane/template read # (i.e. FIRST, SECOND) combination we will store the median values of both the phasing and prephasing * values for every tile in that lane/template read pair. * * @author jgentry */ public class IlluminaPhasingMetrics extends MetricBase { /** Illumina flowcell lane number */ public long LANE; /** Defines an Illumina template read number (first or second) */ public String TYPE_NAME; /** Median phasing value across all tiles in a lane, applied to the first and second template reads */ public double PHASING_APPLIED; /** Median pre-phasing value across all tiles in a lane, applied to the first and second template reads */ public double PREPHASING_APPLIED; /** Calculate the median phasing & prephasing values for a lane's tiles and create the appropriate IlluminaPhasingMetrics for them */ public static Collection<IlluminaPhasingMetrics> getPhasingMetricsForTiles(final long lane, final Collection<Tile> tilesForLane, boolean usePercentage) { final LanePhasingMetricsCollector lanePhasingMetricsCollector = new LanePhasingMetricsCollector(tilesForLane, usePercentage); final Collection<IlluminaPhasingMetrics> phasingMetrics = new ArrayList<IlluminaPhasingMetrics>(); for (final TileTemplateRead tileTemplateRead : lanePhasingMetricsCollector.getMedianPhasingMap().keySet()) { final IlluminaPhasingMetrics phasingMetric = new IlluminaPhasingMetrics(); phasingMetric.LANE = lane; phasingMetric.TYPE_NAME = tileTemplateRead.toString(); phasingMetric.PHASING_APPLIED = lanePhasingMetricsCollector.getMedianPhasingMap().get(tileTemplateRead); phasingMetric.PREPHASING_APPLIED = lanePhasingMetricsCollector.getMedianPrePhasingMap().get(tileTemplateRead); phasingMetrics.add(phasingMetric); } return phasingMetrics; } /** This property is not exposed in a field to avoid complications with MetricBase's dependency on reflection. */ public static String getExtension() { return "illumina_phasing_metrics"; } }
mit
bassmastry101/NutBot
node_modules/barse/example/next.js
449
var parse = require('..'); var parser = parse() .next('a', 1, function (chunk, offset) { return chunk.readUInt8(offset); }) .next('b', 4, function (chunk, offset) { return chunk.readUInt32LE(offset); }) parser.on('data', console.log); var leet = new Buffer(5); leet.writeUInt8(13, 0); leet.writeUInt32LE(37, 1); parser.write(leet); var teel = new Buffer(5); teel.writeUInt8(73, 0); teel.writeUInt32LE(31, 1); parser.write(teel);
mit
uhoh-itsmaciek/heroku
lib/heroku/command/config.rb
3008
require "heroku/command/base" # manage app config vars # class Heroku::Command::Config < Heroku::Command::Base # config # # display the config vars for an app # # -s, --shell # output config vars in shell format # #Examples: # # $ heroku config # A: one # B: two # # $ heroku config --shell # A=one # B=two # def index validate_arguments! vars = api.get_config_vars(app).body if vars.empty? display("#{app} has no config vars.") else vars.each {|key, value| vars[key] = value.to_s} if options[:shell] vars.keys.sort.each do |key| display(%{#{key}=#{vars[key]}}) end else styled_header("#{app} Config Vars") styled_hash(vars) end end end # config:set KEY1=VALUE1 [KEY2=VALUE2 ...] # # set one or more config vars # #Example: # # $ heroku config:set A=one # Setting config vars and restarting myapp... done, v123 # A: one # # $ heroku config:set A=one B=two # Setting config vars and restarting myapp... done, v123 # A: one # B: two # def set unless args.size > 0 and args.all? { |a| a.include?('=') } error("Usage: heroku config:set KEY1=VALUE1 [KEY2=VALUE2 ...]\nMust specify KEY and VALUE to set.") end vars = args.inject({}) do |vars, arg| key, value = arg.split('=', 2) vars[key] = value vars end action("Setting config vars and restarting #{app}") do api.put_config_vars(app, vars) @status = begin if release = api.get_release(app, 'current').body release['name'] end rescue Heroku::API::Errors::RequestFailed => e end end vars.each {|key, value| vars[key] = value.to_s} styled_hash(vars) end alias_command "config:add", "config:set" # config:get KEY # # display a config value for an app # #Examples: # # $ heroku config:get A # one # def get unless key = shift_argument error("Usage: heroku config:get KEY\nMust specify KEY.") end validate_arguments! vars = api.get_config_vars(app).body key, value = vars.detect {|k,v| k == key} display(value.to_s) end # config:unset KEY1 [KEY2 ...] # # unset one or more config vars # # $ heroku config:unset A # Unsetting A and restarting myapp... done, v123 # # $ heroku config:unset A B # Unsetting A and restarting myapp... done, v123 # Unsetting B and restarting myapp... done, v124 # def unset if args.empty? error("Usage: heroku config:unset KEY1 [KEY2 ...]\nMust specify KEY to unset.") end args.each do |key| action("Unsetting #{key} and restarting #{app}") do api.delete_config_var(app, key) @status = begin if release = api.get_release(app, 'current').body release['name'] end rescue Heroku::API::Errors::RequestFailed => e end end end end alias_command "config:remove", "config:unset" end
mit
harryggg/coursemology2
lib/autoload/course/assessment/programming_package.rb
4745
# frozen_string_literal: true # Represents a programming package, containing the tests and submitted code for a given question. # # A package has these files at the very minimum: # # - +Makefile+: the makefile for building and executing the package. There are at least three # targets: # - +prepare+: for initialising the environment. This can be used to set up libraries or other # modifications to the package. # - +compile+: for building the package. For scripting languages, this is a no-op, but <b>must # still be defined</b> # - +test+: for testing the package. After completing the task, +tests.junit.xml+ must be found # in the root directory of the package (beside the +tests/+ directory) # - +submission/+: where the template code/students' code will be placed. When this package is # uploaded by the instructor as part of a question, this directory will contain the templates # that will be used when a student first attempts the question. When this package is generated # as part of auto grading, then this contains all the student's submitted code. # - +tests/+: where the tests will be placed. How this set of tests should be run is immaterial, # so long it is run when +make test+ is executed by the evaluator. # # Call {Course::Assessment::ProgrammingPackage#close} when changes have been made to persist the # changes to disk. Duplicate the file before modifying if you do not want to modify the original # file -- changes are made in-place. class Course::Assessment::ProgrammingPackage # The path to the Makefile. MAKEFILE_PATH = Pathname.new('Makefile').freeze # The path to the submission. SUBMISSION_PATH = Pathname.new('submission').freeze # The path to the tests. TESTS_PATH = Pathname.new('tests').freeze # Creates a new programming package instance. # # @overload initialize(path) # @param [String|Pathname] path The path to the package on disk. # @overload initialize(stream) # @param [IO] stream The stream to the file. def initialize(path_or_stream) case path_or_stream when String, Pathname @path = path_or_stream when IO @stream = path_or_stream else raise ArgumentError, 'Invalid path or stream object' end end # Gets the file path to the provided package. # # @return [String] The path to the file. # @return [nil] If the package is associated with a stream. def path if @file @file.name elsif @path @path.to_s elsif @stream.is_a?(File) @stream.path end end # Closes the package. def close ensure_file_open! @file.close @file = nil end # Checks if the given programming package is valid. # # @return [Boolean] def valid? ensure_file_open! ['Makefile', 'submission/', 'tests/'].all? { |entry| @file.find_entry(entry).present? } end # Gets the contents of all submission files. # # @return [Hash<Pathname, String>] A hash mapping the file path to the file contents of each # file. def submission_files ensure_file_open! @file.glob("#{SUBMISSION_PATH}/**/*").map do |entry| entry_file_name = Pathname.new(entry.name) submission_file_name = entry_file_name.relative_path_from(SUBMISSION_PATH) [submission_file_name, entry.get_input_stream(&:read)] end.to_h end # Replaces the contents of all submission files. # # @param [Hash<Pathname|String, String>] files A hash mapping the file path to the file # contents of each file. def submission_files=(files) ensure_file_open! remove_submission_files files.each do |path, file| path = Pathname.new(path) unless path.is_a?(Pathname) raise ArgumentError, 'Paths must be relative' unless path.relative? @file.get_output_stream(SUBMISSION_PATH.join(path)) do |stream| stream.write(file) end end end private # Ensures that the zip file is open. # # When a stream is open, some atypical code is required because Rubyzip doesn't support streams # in its API too well -- the entries in memory and loaded from stream are different. # # @raise [IllegalStateError] when the zip file is not open and it cannot be opened. def ensure_file_open! return if @file if @path @file = Zip::File.open(@path.to_s) elsif @stream @file = Zip::File.new(@stream.try(:path), true, true) @file.read_from_stream(@stream) @file.instance_variable_set(:@stored_entries, @file.instance_variable_get(:@entry_set).dup) end raise IllegalStateError unless @file end # Removes all submission files from the archive. def remove_submission_files @file.glob("#{SUBMISSION_PATH}/**/*").each do |entry| @file.remove(entry) end end end
mit
ikneb/lg
src/AppBundle/Controller/DefaultController.php
1075
<?php namespace AppBundle\Controller; use AppBundle\Entity\User; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class DefaultController extends Controller { /** * @Route("/", name="home") */ public function homepageAction(){ return $this->render('default/home.html.twig' ); } /** * @Route("/admin", name="index") */ public function indexAction(Request $request) { $user = $this->getDoctrine() ->getRepository('AppBundle:User') ->find(1); $contact = $this->getDoctrine() ->getRepository('AppBundle:Contact') ->find($user->getContact()); if (!$user) { throw $this->createNotFoundException('No product found'); } // replace this example code with whatever you need return $this->render('default/admin.html.twig',array('user' => $user,'contact' => $contact) ); } }
mit
angular/angular-cli-stress-test
src/app/components/comp-4236/comp-4236.component.spec.ts
847
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Comp4236Component } from './comp-4236.component'; describe('Comp4236Component', () => { let component: Comp4236Component; let fixture: ComponentFixture<Comp4236Component>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ Comp4236Component ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(Comp4236Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
mit
xaviergonz/js-angusj-clipper
src/PolyNode.ts
4682
import { NativeClipperLibInstance } from "./native/NativeClipperLibInstance"; import { NativePolyNode } from "./native/NativePolyNode"; import { nativePathToPath } from "./native/PathToNativePath"; import { ReadonlyPath } from "./Path"; /** * PolyNodes are encapsulated within a PolyTree container, and together provide a data structure representing the parent-child relationships of polygon * contours returned by clipping/ofsetting methods. * * A PolyNode object represents a single polygon. It's isHole property indicates whether it's an outer or a hole. PolyNodes may own any number of PolyNode * children (childs), where children of outer polygons are holes, and children of holes are (nested) outer polygons. */ export class PolyNode { protected _parent?: PolyNode; /** * Returns the parent PolyNode. * * The PolyTree object (which is also a PolyNode) does not have a parent and will return undefined. */ get parent(): PolyNode | undefined { return this._parent; } protected _childs: PolyNode[] = []; /** * A read-only list of PolyNode. * Outer PolyNode childs contain hole PolyNodes, and hole PolyNode childs contain nested outer PolyNodes. */ get childs(): PolyNode[] { return this._childs; } protected _contour: ReadonlyPath = []; /** * Returns a path list which contains any number of vertices. */ get contour(): ReadonlyPath { return this._contour; } protected _isOpen: boolean = false; /** * Returns true when the PolyNode's Contour results from a clipping operation on an open contour (path). Only top-level PolyNodes can contain open contours. */ get isOpen(): boolean { return this._isOpen; } protected _index: number = 0; /** * Index in the parent's child list, or 0 if no parent. */ get index(): number { return this._index; } protected _isHole?: boolean; /** * Returns true when the PolyNode's polygon (Contour) is a hole. * * Children of outer polygons are always holes, and children of holes are always (nested) outer polygons. * The isHole property of a PolyTree object is undefined but its children are always top-level outer polygons. * * @return {boolean} */ get isHole(): boolean { if (this._isHole === undefined) { let result = true; let node: PolyNode | undefined = this._parent; while (node !== undefined) { result = !result; node = node._parent; } this._isHole = result; } return this._isHole; } /** * The returned PolyNode will be the first child if any, otherwise the next sibling, otherwise the next sibling of the Parent etc. * * A PolyTree can be traversed very easily by calling GetFirst() followed by GetNext() in a loop until the returned object is undefined. * * @return {PolyNode | undefined} */ getNext(): PolyNode | undefined { if (this._childs.length > 0) { return this._childs[0]; } else { return this.getNextSiblingUp(); } } protected getNextSiblingUp(): PolyNode | undefined { if (this._parent === undefined) { return undefined; } else if (this._index === this._parent._childs.length - 1) { //noinspection TailRecursionJS return this._parent.getNextSiblingUp(); } else { return this._parent._childs[this._index + 1]; } } protected constructor() {} protected static fillFromNativePolyNode( pn: PolyNode, nativeLib: NativeClipperLibInstance, nativePolyNode: NativePolyNode, parent: PolyNode | undefined, childIndex: number, freeNativePolyNode: boolean ): void { pn._parent = parent; const childs = nativePolyNode.childs; for (let i = 0, max = childs.size(); i < max; i++) { const newChild = PolyNode.fromNativePolyNode( nativeLib, childs.get(i), pn, i, freeNativePolyNode ); pn._childs.push(newChild); } // do we need to clear the object ourselves? for now let's assume so (seems to work) pn._contour = nativePathToPath(nativeLib, nativePolyNode.contour, true); pn._isOpen = nativePolyNode.isOpen(); pn._index = childIndex; if (freeNativePolyNode) { nativePolyNode.delete(); } } protected static fromNativePolyNode( nativeLib: NativeClipperLibInstance, nativePolyNode: NativePolyNode, parent: PolyNode | undefined, childIndex: number, freeNativePolyNode: boolean ): PolyNode { const pn = new PolyNode(); PolyNode.fillFromNativePolyNode( pn, nativeLib, nativePolyNode, parent, childIndex, freeNativePolyNode ); return pn; } }
mit
tom5454/Toms-Mod
src/main/java/com/tom/defense/block/BlockForceField.java
4959
package com.tom.defense.block; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyInteger; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import com.tom.api.block.BlockContainerTomsMod; import com.tom.core.DamageSourceTomsMod; import com.tom.defense.tileentity.TileEntityForceField; public class BlockForceField extends BlockContainerTomsMod { public static final PropertyInteger TYPE = PropertyInteger.create("type", 0, 2); public BlockForceField() { super(Material.BARRIER); } @Override public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityForceField(); } /** * Called When an Entity Collided with the Block */ /*@Override public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) { entityIn.attackEntityFrom(DamageSourceTomsMod.fieldDamage, 6.0F * (state.getValue(TYPE) == 2 ? 2 : 1)); }*/ @Override public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos) { TileEntityForceField te = (TileEntityForceField) worldIn.getTileEntity(pos); te.update(worldIn); } @Override public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance) { entityIn.fall(fallDistance, 2.0F); IBlockState state = worldIn.getBlockState(pos); if (fallDistance > 5) entityIn.attackEntityFrom(DamageSourceTomsMod.fieldDamage, 4.0F * ((fallDistance - 4.5F) / 2) * (state.getValue(TYPE) == 2 ? 2 : 1)); } @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, TYPE); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(TYPE); } @Override public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(TYPE, meta % 3); } @Override public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) { super.onEntityCollidedWithBlock(worldIn, pos, state, entityIn); entityIn.attackEntityFrom(DamageSourceTomsMod.fieldDamage, 6.0F * (state.getValue(TYPE) == 2 ? 2 : 1)); } @Override public void onEntityWalk(World worldIn, BlockPos pos, Entity entityIn) { super.onEntityWalk(worldIn, pos, entityIn); IBlockState state = worldIn.getBlockState(pos); if (state.getValue(TYPE) == 2) entityIn.attackEntityFrom(DamageSourceTomsMod.fieldDamage, 6.0F * (state.getValue(TYPE) == 2 ? 3 : 1)); } @Override public void onBlockClicked(World worldIn, BlockPos pos, EntityPlayer playerIn) { IBlockState state = worldIn.getBlockState(pos); playerIn.attackEntityFrom(DamageSourceTomsMod.fieldDamage, 6.0F * (state.getValue(TYPE) == 2 ? 3 : 1)); } @Override public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return blockState.getValue(TYPE) == 2 ? new AxisAlignedBB(0.1, 0.1, 0.1, 0.9, 0.9, 0.9) : FULL_BLOCK_AABB; } /* @Override public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.CUTOUT; }*/ @Override public boolean isOpaqueCube(IBlockState s) { return false; } @Override public boolean isFullBlock(IBlockState s) { return false; } @Override public boolean isFullCube(IBlockState s) { return false; } @SuppressWarnings("deprecation") @Override @SideOnly(Side.CLIENT) public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { IBlockState iblockstate = blockAccess.getBlockState(pos.offset(side)); Block block = iblockstate.getBlock(); if (blockState != iblockstate) { return true; } if (block == this) { return false; } return block == this ? false : super.shouldSideBeRendered(blockState, blockAccess, pos, side); } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { return ItemStack.EMPTY; } @Override public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT; } @Override public int quantityDropped(Random random) { return 0; } @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) { return Items.AIR; } }
mit
NordikLab/TorqueLab
tlab/ipsEditor/scripts/system.cs
895
//============================================================================== // TorqueLab -> // Copyright (c) 2015 All Right Reserved, http://nordiklab.com/ //------------------------------------------------------------------------------ //============================================================================== $IPSP_Editor_DEFAULT_FILENAME = "art/gfx/particles/managedParticleData.cs"; //============================================================================================= // IPSP_Editor. //============================================================================================= //--------------------------------------------------------------------------------------------- function IPSP_Editor::doSystemSave( %this ) { %this.doEmitterSave(); %this.doParticleSave(); } function IPSP_Editor::refreshParticleList( %this ) { IPSP_Editor.guiSync(true); }
mit
jdsika/TUM_HOly
openrave/plugins/rplanners/ParabolicPathSmooth/DynamicPath.cpp
33660
/***************************************************************************** * * Copyright (c) 2010-2011, the Trustees of Indiana University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Indiana University nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE TRUSTEES OF INDIANA UNIVERSITY ''AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES OF INDIANA UNIVERSITY BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * ***************************************************************************/ #include "DynamicPath.h" #include "Timer.h" #include <stdlib.h> #include <stdio.h> #include <list> #include <algorithm> using namespace std; namespace ParabolicRampInternal { inline Real LInfDistance(const Vector& a,const Vector& b) { PARABOLIC_RAMP_ASSERT(a.size()==b.size()); Real d=0; for(size_t i=0; i<a.size(); i++) { d = Max(d,Abs(a[i]-b[i])); } return d; } inline bool InBounds(const Vector& x,const Vector& bmin,const Vector& bmax) { PARABOLIC_RAMP_ASSERT(x.size()==bmin.size()); PARABOLIC_RAMP_ASSERT(x.size()==bmax.size()); for(size_t i=0; i<x.size(); i++) { if(x[i] < bmin[i] || x[i] > bmax[i]) { return false; } } return true; } inline Real MaxBBLInfDistance(const Vector& x,const Vector& bmin,const Vector& bmax) { PARABOLIC_RAMP_ASSERT(x.size()==bmin.size()); PARABOLIC_RAMP_ASSERT(x.size()==bmax.size()); Real d=0; for(size_t i=0; i<x.size(); i++) { d = Max(d,Max(Abs(x[i]-bmin[i]),Abs(x[i]-bmax[i]))); } return d; } bool SolveMinTime(const Vector& x0,const Vector& dx0,const Vector& x1,const Vector& dx1, const Vector& accMax,const Vector& velMax,const Vector& xMin,const Vector& xMax,DynamicPath& out, int multidofinterp) { if(xMin.empty()) { out.ramps.resize(1); ParabolicRampND& temp=out.ramps[0]; temp.x0=x0; temp.x1=x1; temp.dx0=dx0; temp.dx1=dx1; bool res=temp.SolveMinTime(accMax,velMax); if(!res) { return false; } } else { vector<std::vector<ParabolicRamp1D> > ramps; Real res=SolveMinTimeBounded(x0,dx0,x1,dx1, accMax,velMax,xMin,xMax, ramps,multidofinterp); if(res < 0) { return false; } out.ramps.resize(0); CombineRamps(ramps,out.ramps); } out.accMax = accMax; out.velMax = velMax; PARABOLIC_RAMP_ASSERT(out.IsValid()); return true; } DynamicPath::DynamicPath() { _multidofinterp = 0; } void DynamicPath::Init(const Vector& _velMax,const Vector& _accMax) { velMax = _velMax; accMax = _accMax; PARABOLIC_RAMP_ASSERT(velMax.size() == accMax.size()); if(!velMax.empty() && !xMin.empty()) { PARABOLIC_RAMP_ASSERT(xMin.size() == velMax.size()); } } void DynamicPath::SetJointLimits(const Vector& _xMin,const Vector& _xMax) { xMin = _xMin; xMax = _xMax; PARABOLIC_RAMP_ASSERT(xMin.size() == xMax.size()); if(!velMax.empty() && !xMin.empty()) { PARABOLIC_RAMP_ASSERT(xMin.size() == velMax.size()); } } Real DynamicPath::GetTotalTime() const { Real t=0; for(size_t i=0; i<ramps.size(); i++) { t+=ramps[i].endTime; } return t; } int DynamicPath::GetSegment(Real t,Real& u) const { if(t < 0) return -1; for(size_t i=0; i<ramps.size(); i++) { if(t <= ramps[i].endTime) { u = t; return (int)i; } t -= ramps[i].endTime; } u = t; return (int)ramps.size(); } void DynamicPath::Evaluate(Real t,Vector& x) const { PARABOLIC_RAMP_ASSERT(!ramps.empty()); if(t < 0) { x = ramps.front().x0; } else { for(size_t i=0; i<ramps.size(); i++) { if(t <= ramps[i].endTime) { ramps[i].Evaluate(t,x); return; } t -= ramps[i].endTime; } x = ramps.back().x1; } } void DynamicPath::Derivative(Real t,Vector& dx) const { PARABOLIC_RAMP_ASSERT(!ramps.empty()); if(t < 0) { dx = ramps.front().dx0; } else { for(size_t i=0; i<ramps.size(); i++) { if(t <= ramps[i].endTime) { ramps[i].Derivative(t,dx); return; } t -= ramps[i].endTime; } dx = ramps.back().dx1; } } void DynamicPath::SetMilestones(const vector<Vector>& x) { if(x.empty()) { ramps.resize(0); } else if(x.size()==1) { ramps.resize(1); ramps[0].SetConstant(x[0]); } else { Vector zero(x[0].size(),0.0); ramps.resize(x.size()-1); for(size_t i=0; i<ramps.size(); i++) { ramps[i].x0 = x[i]; ramps[i].x1 = x[i+1]; ramps[i].dx0 = zero; ramps[i].dx1 = zero; bool res=ramps[i].SolveMinTimeLinear(accMax,velMax); PARABOLIC_RAMP_ASSERT(res && ramps[i].IsValid()); } } } void DynamicPath::SetMilestones(const vector<Vector>& x,const vector<Vector>& dx) { if(x.empty()) { ramps.resize(0); } else if(x.size()==1) { ramps.resize(1); ramps[0].SetConstant(x[0]); } else { if(xMin.empty()) { ramps.resize(x.size()-1); for(size_t i=0; i<ramps.size(); i++) { ramps[i].x0 = x[i]; ramps[i].x1 = x[i+1]; ramps[i].dx0 = dx[i]; ramps[i].dx1 = dx[i+1]; bool res=ramps[i].SolveMinTime(accMax,velMax); PARABOLIC_RAMP_ASSERT(res); PARABOLIC_RAMP_ASSERT(ramps[i].IsValid()); } } else { //bounded solving ramps.resize(0); ramps.reserve(x.size()-1); std::vector<std::vector<ParabolicRamp1D> > tempRamps; std::vector<ParabolicRampND> tempRamps2; PARABOLIC_RAMP_ASSERT(InBounds(x[0],xMin,xMax)); for(size_t i=0; i+1<x.size(); i++) { PARABOLIC_RAMP_ASSERT(InBounds(x[i+1],xMin,xMax)); Real res=SolveMinTimeBounded(x[i],dx[i],x[i+1],dx[i+1], accMax,velMax,xMin,xMax, tempRamps,_multidofinterp); PARABOLIC_RAMP_ASSERT(res >= 0); tempRamps2.resize(0); CombineRamps(tempRamps,tempRamps2); for(size_t j = 0; j < tempRamps2.size(); ++j) { PARABOLIC_RAMP_ASSERT(tempRamps2[j].IsValid()); } ramps.insert(ramps.end(),tempRamps2.begin(),tempRamps2.end()); } } } } void DynamicPath::GetMilestones(vector<Vector>& x,vector<Vector>& dx) const { if(ramps.empty()) { x.resize(0); dx.resize(0); return; } x.resize(ramps.size()+1); dx.resize(ramps.size()+1); x[0] = ramps[0].x0; dx[0] = ramps[0].dx0; for(size_t i=0; i<ramps.size(); i++) { x[i+1] = ramps[i].x1; dx[i+1] = ramps[i].dx1; } } void DynamicPath::Append(const Vector& x) { size_t n=ramps.size(); size_t p=n-1; if(ramps.size()==0) { ramps.resize(1); ramps[0].SetConstant(x); } else { if(xMin.empty()) { ramps.resize(ramps.size()+1); ramps[n].x0 = ramps[p].x1; ramps[n].dx0 = ramps[p].dx1; ramps[n].x1 = x; ramps[n].dx1.resize(x.size()); fill(ramps[n].dx1.begin(),ramps[n].dx1.end(),0); bool res=ramps[n].SolveMinTime(accMax,velMax); PARABOLIC_RAMP_ASSERT(res); } else { PARABOLIC_RAMP_ASSERT(InBounds(x,xMin,xMax)); std::vector<std::vector<ParabolicRamp1D> > tempRamps; std::vector<ParabolicRampND> tempRamps2; Vector zero(x.size(),0.0); Real res=SolveMinTimeBounded(ramps[p].x1,ramps[p].dx1,x,zero, accMax,velMax,xMin,xMax,tempRamps,_multidofinterp); PARABOLIC_RAMP_ASSERT(res>=0); tempRamps2.resize(0); CombineRamps(tempRamps,tempRamps2); ramps.insert(ramps.end(),tempRamps2.begin(),tempRamps2.end()); } } } void DynamicPath::Append(const Vector& x,const Vector& dx) { size_t n=ramps.size(); size_t p=n-1; PARABOLIC_RAMP_ASSERT(ramps.size()!=0); if(xMin.empty()) { ramps.resize(ramps.size()+1); ramps[n].x0 = ramps[p].x1; ramps[n].dx0 = ramps[p].dx1; ramps[n].x1 = x; ramps[n].dx1 = dx; bool res=ramps[n].SolveMinTime(accMax,velMax); PARABOLIC_RAMP_ASSERT(res); } else { PARABOLIC_RAMP_ASSERT(InBounds(x,xMin,xMax)); std::vector<std::vector<ParabolicRamp1D> > tempRamps; std::vector<ParabolicRampND> tempRamps2; Real res=SolveMinTimeBounded(ramps[p].x1,ramps[p].dx1,x,dx, accMax,velMax,xMin,xMax,tempRamps,_multidofinterp); PARABOLIC_RAMP_ASSERT(res>=0); tempRamps2.resize(0); CombineRamps(tempRamps,tempRamps2); ramps.insert(ramps.end(),tempRamps2.begin(),tempRamps2.end()); } } void DynamicPath::Concat(const DynamicPath& suffix) { PARABOLIC_RAMP_ASSERT(&suffix != this); if(suffix.ramps.empty()) { return; } if(ramps.empty()) { *this=suffix; return; } //double check continuity if(ramps.back().x1 != suffix.ramps.front().x0 || ramps.back().dx1 != suffix.ramps.front().dx0) { Real xmax=0,dxmax=0; for(size_t i=0; i<ramps.back().x1.size(); i++) { xmax=Max(xmax,Abs(ramps.back().x1[i]-suffix.ramps.front().x0[i])); dxmax=Max(dxmax,Abs(ramps.back().dx1[i]-suffix.ramps.front().dx0[i])); } if(Abs(xmax) > EpsilonX || Abs(dxmax) > EpsilonV) { PARABOLIC_RAMP_PLOG("Concat endpoint error\n"); PARABOLIC_RAMP_PLOG("x:\n"); for(size_t i=0; i<ramps.back().x1.size(); i++) { PARABOLIC_RAMP_PLOG("%g - %g = %g\n",ramps.back().x1[i],suffix.ramps.front().x0[i],ramps.back().x1[i]-suffix.ramps.front().x0[i]); } PARABOLIC_RAMP_PLOG("dx:\n"); for(size_t i=0; i<ramps.back().x1.size(); i++) { PARABOLIC_RAMP_PLOG("%g - %g = %g\n",ramps.back().dx1[i],suffix.ramps.front().dx0[i],ramps.back().dx1[i]-suffix.ramps.front().dx0[i]); } } ramps.back().x1 = ramps.front().x0; ramps.back().dx1 = ramps.front().dx0; for(size_t i=0; i<ramps.back().x1.size(); i++) { ramps.back().ramps[i].x1 = suffix.ramps.front().x0[i]; ramps.back().ramps[i].dx1 = suffix.ramps.front().dx0[i]; } } PARABOLIC_RAMP_ASSERT(ramps.back().x1 == suffix.ramps.front().x0); PARABOLIC_RAMP_ASSERT(ramps.back().dx1 == suffix.ramps.front().dx0); ramps.insert(ramps.end(),suffix.ramps.begin(),suffix.ramps.end()); } void DynamicPath::Split(Real t,DynamicPath& before,DynamicPath& after) const { PARABOLIC_RAMP_ASSERT(IsValid()); PARABOLIC_RAMP_ASSERT(&before != this); PARABOLIC_RAMP_ASSERT(&after != this); if(ramps.empty()) { before=*this; after=*this; return; } after.velMax = before.velMax = velMax; after.accMax = before.accMax = accMax; after.xMin = before.xMin = xMin; after.xMax = before.xMax = xMax; after.ramps.resize(0); before.ramps.resize(0); if(t < 0) { //we're before the path starts before.ramps.resize(1); before.ramps[0].SetConstant(ramps[0].x0); //place a constant for time -t on the after path after.ramps.resize(1); after.ramps[0].SetConstant(ramps[0].x0,-t); } for(size_t i=0; i<ramps.size(); i++) { if(t < 0) { after.ramps.push_back(ramps[i]); } else { if(t < ramps[i].endTime) { //cut current path ParabolicRampND temp=ramps[i]; temp.TrimBack(temp.endTime-t); before.ramps.push_back(temp); temp=ramps[i]; temp.TrimFront(t); if(!after.ramps.empty()) { PARABOLIC_RAMP_PLOG("DynamicPath::Split: Uh... weird, after is not empty?\n"); PARABOLIC_RAMP_PLOG("t = %g, i = %d, endtime = %g\n",t,i,ramps[i].endTime); } PARABOLIC_RAMP_ASSERT(after.ramps.size() == 0); after.ramps.push_back(temp); } else { before.ramps.push_back(ramps[i]); } t -= ramps[i].endTime; } } if(t > 0) { //dt is longer than path ParabolicRampND temp; temp.SetConstant(ramps.back().x1,t); before.ramps.push_back(temp); } if(t >= 0) { ParabolicRampND temp; temp.SetConstant(ramps.back().x1); after.ramps.push_back(temp); } PARABOLIC_RAMP_ASSERT(before.IsValid()); PARABOLIC_RAMP_ASSERT(after.IsValid()); } struct RampSection { Real ta,tb; Vector xa,xb; Real da,db; }; int CheckRamp(const ParabolicRampND& ramp,FeasibilityCheckerBase* feas,DistanceCheckerBase* distance,int maxiters) { ramp.constraintchecked = 1; int ret0 = feas->ConfigFeasible(ramp.x0, ramp.dx0); if( ret0 != 0) { return ret0; } int ret1 = feas->ConfigFeasible(ramp.x1, ramp.dx1); if( ret1 != 0 ) { return ret1; } PARABOLIC_RAMP_ASSERT(distance->ObstacleDistanceNorm()==Inf); RampSection section; section.ta = 0; section.tb = ramp.endTime; section.xa = ramp.x0; section.xb = ramp.x1; section.da = distance->ObstacleDistance(ramp.x0); section.db = distance->ObstacleDistance(ramp.x1); if(section.da <= 0.0) { return 0xffff; // no code } if(section.db <= 0.0) { return 0xffff; // no code } list<RampSection> queue; queue.push_back(section); int iters=0; while(!queue.empty()) { section = queue.front(); queue.erase(queue.begin()); //check the bounds around this section if(LInfDistance(section.xa,section.xb) <= section.da+section.db) { Vector bmin,bmax; ramp.Bounds(section.ta,section.tb,bmin,bmax); if(MaxBBLInfDistance(section.xa,bmin,bmax) < section.da && MaxBBLInfDistance(section.xb,bmin,bmax) < section.db) { //can cull out the section continue; } } Real tc = (section.ta+section.tb)*0.5; Vector xc, dxc; ramp.Evaluate(tc,xc); if( feas->NeedDerivativeForFeasibility() ) { ramp.Derivative(tc,dxc); } //infeasible config int retseg = feas->ConfigFeasible(xc, dxc); if( retseg != 0 ) { return retseg; } //subdivide Real dc = distance->ObstacleDistance(xc); RampSection sa,sb; sa.ta = section.ta; sa.xa = section.xa; sa.da = section.da; sa.tb = sb.ta = tc; sa.xb = sb.xa = xc; sa.db = sb.da = dc; sb.tb = section.tb; sb.xb = section.xb; sb.db = section.db; //recurse on segments queue.push_back(sa); queue.push_back(sb); if(iters++ >= maxiters) { return 0xffff; // no code } } return 0; } int CheckRamp(const ParabolicRampND& ramp,FeasibilityCheckerBase* space,const Vector& tol,int options) { PARABOLIC_RAMP_ASSERT(tol.size() == ramp.ramps.size()); for(size_t i = 0; i < tol.size(); ++i) { PARABOLIC_RAMP_ASSERT(tol[i] > 0); } int ret0 = space->ConfigFeasible(ramp.x0, ramp.dx0, options); if( ret0 != 0 ) { return ret0; } int ret1 = space->ConfigFeasible(ramp.x1, ramp.dx1, options); if( ret1 != 0 ) { return ret1; } //PARABOLIC_RAMP_ASSERT(space->ConfigFeasible(ramp.x0)); //PARABOLIC_RAMP_ASSERT(space->ConfigFeasible(ramp.x1)); //for a parabola of form f(x) = a x^2 + b x, and the straight line //of form g(X,u) = u*f(X) //d^2(g(X,u),p) = |p - <f(X),p>/<f(X),f(X)> f(X)|^2 < tol^2 //<p,p> - <f(X),p>^2/<f(X),f(X)> = p^T (I-f(X)f(X)^T/f(X)^T f(X)) p //max_x d^2(f(x)) => f(x)^T (I-f(X)f(X)^T/f(X)^T f(X)) f'(x) = 0 //(x^2 a^T + x b^T) A (2a x + b) = 0 //(x a^T + b^T) A (2a x + b) = 0 //2 x^2 a^T A a + 3 x b^T A a + b^T A b = 0 //the max X for which f(x) deviates from g(X,x) by at most tol is... //max_x |g(X,x)-f(x)| = max_x x/X f(X)-f(x) //=> f(X)/X - f'(x) = 0 //=> X/2 = x //=> max_x |g(X,x)-f(x)| = |(X/2)/X f(X)-f(X/2)| //= |1/2 (aX^2+bX) - a(X/2)^2 - b(X/2) + c | //= |a| X^2 / 4 //so... max X st max_x |g(X,x)-f(x)| < tol => X = 2*sqrt(tol/|a|) vector<Real> divs; Real t=0; divs.push_back(t); while(t < ramp.endTime) { Real tnext=t; Real amax = 0; Real switchNext=ramp.endTime; Real dtmin = 1e30; for(size_t i=0; i<ramp.ramps.size(); i++) { if(t < ramp.ramps[i].tswitch1) { //ramp up switchNext = Min(switchNext, ramp.ramps[i].tswitch1); amax = Max(amax,Max(Abs(ramp.ramps[i].a1),Abs(ramp.ramps[i].a2))); dtmin = Min(dtmin,2.0*Sqrt(tol[i]/amax)); } else if(t < ramp.ramps[i].tswitch2) { //constant vel switchNext = Min(switchNext, ramp.ramps[i].tswitch2); } else if(t < ramp.ramps[i].ttotal) { //ramp down amax = Max(amax,Max(Abs(ramp.ramps[i].a1),Abs(ramp.ramps[i].a2))); dtmin = Min(dtmin,2.0*Sqrt(tol[i]/amax)); } } if(t+dtmin > switchNext) { tnext = switchNext; } else { tnext = t+dtmin; } t = tnext; divs.push_back(tnext); } divs.push_back(ramp.endTime); //do a bisection thingie list<pair<int,int> > segs; segs.push_back(pair<int,int>(0,divs.size()-1)); Vector q1,q2, dq1, dq2; while(!segs.empty()) { int i=segs.front().first; int j=segs.front().second; segs.erase(segs.begin()); if(j == i+1) { //check path from t to tnext ramp.Evaluate(divs[i],q1); if( space->NeedDerivativeForFeasibility() ) { ramp.Derivative(divs[i],dq1); } ramp.Evaluate(divs[j],q2); if( space->NeedDerivativeForFeasibility() ) { ramp.Derivative(divs[j],dq2); } int retseg = space->SegmentFeasible(q1,q2, dq1, dq2, divs[j]-divs[i],options); if( retseg != 0 ) { return retseg; } } else { int k=(i+j)/2; ramp.Evaluate(divs[k],q1); if( space->NeedDerivativeForFeasibility() ) { ramp.Derivative(divs[k],dq1); } int retconf = space->ConfigFeasible(q1, dq1,options); if( retconf != 0 ) { return retconf; } segs.push_back(pair<int,int>(i,k)); segs.push_back(pair<int,int>(k,j)); } } return 0; } RampFeasibilityChecker::RampFeasibilityChecker(FeasibilityCheckerBase* _feas,const Vector& _tol) : feas(_feas),tol(_tol),distance(NULL),maxiters(0), constraintsmask(0) { } RampFeasibilityChecker::RampFeasibilityChecker(FeasibilityCheckerBase* _feas,DistanceCheckerBase* _distance,int _maxiters) : feas(_feas),tol(0),distance(_distance),maxiters(_maxiters), constraintsmask(0) { } int RampFeasibilityChecker::Check(const ParabolicRampND& x,int options) { // only set constraintchecked if all necessary constraints are checked if( (options & constraintsmask) == constraintsmask ) { x.constraintchecked = 1; } if(distance) { return CheckRamp(x,feas,distance,maxiters,options); } else { return CheckRamp(x,feas,tol,options); } } bool DynamicPath::TryShortcut(Real t1,Real t2,RampFeasibilityChecker& check) { if(t1 > t2) { Swap(t1,t2); } Real u1,u2; int i1 = GetSegment(t1,u1); int i2 = GetSegment(t2,u2); if(i1 == i2) { return false; } PARABOLIC_RAMP_ASSERT(u1 >= 0); PARABOLIC_RAMP_ASSERT(u1 <= ramps[i1].endTime+EpsilonT); PARABOLIC_RAMP_ASSERT(u2 >= 0); PARABOLIC_RAMP_ASSERT(u2 <= ramps[i2].endTime+EpsilonT); u1 = Min(u1,ramps[i1].endTime); u2 = Min(u2,ramps[i2].endTime); DynamicPath intermediate; if(xMin.empty()) { intermediate.ramps.resize(1); ParabolicRampND& test=intermediate.ramps[0]; ramps[i1].Evaluate(u1,test.x0); ramps[i2].Evaluate(u2,test.x1); ramps[i1].Derivative(u1,test.dx0); ramps[i2].Derivative(u2,test.dx1); bool res=test.SolveMinTime(accMax,velMax); if(!res) { return false; } PARABOLIC_RAMP_ASSERT(test.endTime >= 0); PARABOLIC_RAMP_ASSERT(test.IsValid()); } else { Vector x0,x1,dx0,dx1; ramps[i1].Evaluate(u1,x0); ramps[i2].Evaluate(u2,x1); ramps[i1].Derivative(u1,dx0); ramps[i2].Derivative(u2,dx1); vector<std::vector<ParabolicRamp1D> > intramps; Real res=SolveMinTimeBounded(x0,dx0,x1,dx1, accMax,velMax,xMin,xMax, intramps,_multidofinterp); if(res < 0) { return false; } intermediate.ramps.resize(0); CombineRamps(intramps,intermediate.ramps); intermediate.accMax = accMax; intermediate.velMax = velMax; PARABOLIC_RAMP_ASSERT(intermediate.IsValid()); } for(size_t i=0; i<intermediate.ramps.size(); i++) { if(check.Check(intermediate.ramps[i]) != 0) { return false; } } //perform shortcut //crop i1 and i2 ramps[i1].TrimBack(ramps[i1].endTime-u1); ramps[i1].x1 = intermediate.ramps.front().x0; ramps[i1].dx1 = intermediate.ramps.front().dx0; ramps[i2].TrimFront(u2); ramps[i2].x0 = intermediate.ramps.back().x1; ramps[i2].dx0 = intermediate.ramps.back().dx1; //replace intermediate ramps with test for(int i=0; i<i2-i1-1; i++) { ramps.erase(ramps.begin()+i1+1); } ramps.insert(ramps.begin()+i1+1,intermediate.ramps.begin(),intermediate.ramps.end()); //check for consistency for(size_t i=0; i+1<ramps.size(); i++) { PARABOLIC_RAMP_ASSERT(ramps[i].x1 == ramps[i+1].x0); PARABOLIC_RAMP_ASSERT(ramps[i].dx1 == ramps[i+1].dx0); } return true; } int DynamicPath::Shortcut(int numIters,RampFeasibilityChecker& check, Real mintimestep) { RandomNumberGeneratorBase rng; return Shortcut(numIters,check,&rng,mintimestep); } int DynamicPath::Shortcut(int numIters,RampFeasibilityChecker& check,RandomNumberGeneratorBase* rng, Real mintimestep) { int shortcuts = 0; vector<Real> rampStartTime(ramps.size()); Real endTime=0; for(size_t i=0; i<ramps.size(); i++) { rampStartTime[i] = endTime; endTime += ramps[i].endTime; } Vector x0,x1,dx0,dx1; DynamicPath intermediate; for(int iters=0; iters<numIters; iters++) { Real t1=rng->Rand()*endTime,t2=rng->Rand()*endTime; if( iters == 0 ) { t1 = 0; t2 = endTime; } if(t1 > t2) { Swap(t1,t2); } int i1 = std::upper_bound(rampStartTime.begin(),rampStartTime.end(),t1)-rampStartTime.begin()-1; int i2 = std::upper_bound(rampStartTime.begin(),rampStartTime.end(),t2)-rampStartTime.begin()-1; if(i1 == i2) { continue; } //same ramp Real u1 = t1-rampStartTime[i1]; Real u2 = t2-rampStartTime[i2]; PARABOLIC_RAMP_ASSERT(u1 >= 0); PARABOLIC_RAMP_ASSERT(u1 <= ramps[i1].endTime+EpsilonT); PARABOLIC_RAMP_ASSERT(u2 >= 0); PARABOLIC_RAMP_ASSERT(u2 <= ramps[i2].endTime+EpsilonT); u1 = Min(u1,ramps[i1].endTime); u2 = Min(u2,ramps[i2].endTime); ramps[i1].Evaluate(u1,x0); ramps[i2].Evaluate(u2,x1); ramps[i1].Derivative(u1,dx0); ramps[i2].Derivative(u2,dx1); bool res=SolveMinTime(x0,dx0,x1,dx1,accMax,velMax,xMin,xMax,intermediate,_multidofinterp); if(!res) { continue; } // check the new ramp time makes significant steps Real newramptime = intermediate.GetTotalTime(); if( newramptime+mintimestep > t2-t1 ) { // reject since it didn't make significant improvement PARABOLIC_RAMP_PLOG("shortcut iter=%d rejected time=%fs\n", iters, endTime-(t2-t1)+newramptime); continue; } bool feas=true; for(size_t i=0; i<intermediate.ramps.size(); i++) if(check.Check(intermediate.ramps[i]) != 0) { feas=false; break; } if(!feas) { continue; } //perform shortcut shortcuts++; ramps[i1].TrimBack(ramps[i1].endTime-u1); ramps[i1].x1 = intermediate.ramps.front().x0; ramps[i1].dx1 = intermediate.ramps.front().dx0; ramps[i2].TrimFront(u2); ramps[i2].x0 = intermediate.ramps.back().x1; ramps[i2].dx0 = intermediate.ramps.back().dx1; //replace intermediate ramps for(int i=0; i<i2-i1-1; i++) { ramps.erase(ramps.begin()+i1+1); } ramps.insert(ramps.begin()+i1+1,intermediate.ramps.begin(),intermediate.ramps.end()); //check for consistency for(size_t i=0; i+1<ramps.size(); i++) { PARABOLIC_RAMP_ASSERT(ramps[i].x1 == ramps[i+1].x0); PARABOLIC_RAMP_ASSERT(ramps[i].dx1 == ramps[i+1].dx0); } //revise the timing rampStartTime.resize(ramps.size()); endTime=0; for(size_t i=0; i<ramps.size(); i++) { rampStartTime[i] = endTime; endTime += ramps[i].endTime; } PARABOLIC_RAMP_PLOG("shortcut iter=%d endTime=%f\n",iters,endTime); } return shortcuts; } int DynamicPath::ShortCircuit(RampFeasibilityChecker& check) { int shortcuts=0; DynamicPath intermediate; for(int i=0; i+1<(int)ramps.size(); i++) { bool res=SolveMinTime(ramps[i].x0,ramps[i].dx0,ramps[i].x1,ramps[i].dx1,accMax,velMax,xMin,xMax,intermediate,_multidofinterp); if(!res) { continue; } bool feas=true; for(size_t j=0; j<intermediate.ramps.size(); j++) { if(check.Check(intermediate.ramps[j]) != 0) { feas=false; break; } } if(!feas) { continue; } ramps.erase(ramps.begin()+i+1); ramps.insert(ramps.begin()+i+1,intermediate.ramps.begin(),intermediate.ramps.end()); i += (int)intermediate.ramps.size()-2; shortcuts++; } return shortcuts; } int DynamicPath::OnlineShortcut(Real leadTime,Real padTime,RampFeasibilityChecker& check) { RandomNumberGeneratorBase rng; return OnlineShortcut(leadTime,padTime,check,&rng); } int DynamicPath::OnlineShortcut(Real leadTime,Real padTime,RampFeasibilityChecker& check,RandomNumberGeneratorBase* rng) { Timer timer; int shortcuts = 0; vector<Real> rampStartTime(ramps.size()); Real endTime=0; for(size_t i=0; i<ramps.size(); i++) { rampStartTime[i] = endTime; endTime += ramps[i].endTime; } Vector x0,x1,dx0,dx1; DynamicPath intermediate; while(1) { //can only start from here Real starttime = timer.ElapsedTime()-leadTime; if(starttime+padTime >= endTime) { break; } starttime = Max(0.0,starttime+padTime); Real t1=starttime+Sqr(rng->Rand())*(endTime-starttime),t2=starttime+rng->Rand()*(endTime-starttime); if(t1 > t2) { Swap(t1,t2); } int i1 = std::upper_bound(rampStartTime.begin(),rampStartTime.end(),t1)-rampStartTime.begin()-1; int i2 = std::upper_bound(rampStartTime.begin(),rampStartTime.end(),t2)-rampStartTime.begin()-1; if(i1 == i2) { //same ramp continue; } Real u1 = t1-rampStartTime[i1]; Real u2 = t2-rampStartTime[i2]; PARABOLIC_RAMP_ASSERT(u1 >= 0); PARABOLIC_RAMP_ASSERT(u1 <= ramps[i1].endTime+EpsilonT); PARABOLIC_RAMP_ASSERT(u2 >= 0); PARABOLIC_RAMP_ASSERT(u2 <= ramps[i2].endTime+EpsilonT); u1 = Min(u1,ramps[i1].endTime); u2 = Min(u2,ramps[i2].endTime); ramps[i1].Evaluate(u1,x0); ramps[i2].Evaluate(u2,x1); ramps[i1].Derivative(u1,dx0); ramps[i2].Derivative(u2,dx1); bool res=SolveMinTime(x0,dx0,x1,dx1,accMax,velMax,xMin,xMax,intermediate,_multidofinterp); if(!res) { continue; } bool feas=true; for(size_t i=0; i<intermediate.ramps.size(); i++) { if(check.Check(intermediate.ramps[i]) != 0) { feas=false; break; } } if(!feas) { continue; } //check for time elapse, otherwise can't perform this shortcut if(timer.ElapsedTime()-leadTime > t1) { continue; } shortcuts++; //crop i1 and i2 ramps[i1].TrimBack(ramps[i1].endTime-u1); ramps[i1].x1 = intermediate.ramps.front().x0; ramps[i1].dx1 = intermediate.ramps.front().dx0; ramps[i2].TrimFront(u2); ramps[i2].x0 = intermediate.ramps.back().x1; ramps[i2].dx0 = intermediate.ramps.back().dx1; PARABOLIC_RAMP_ASSERT(ramps[i1].IsValid()); PARABOLIC_RAMP_ASSERT(ramps[i2].IsValid()); //replace intermediate ramps for(int i=0; i<i2-i1-1; i++) { ramps.erase(ramps.begin()+i1+1); } ramps.insert(ramps.begin()+i1+1,intermediate.ramps.begin(),intermediate.ramps.end()); //check for consistency for(size_t i=0; i+1<ramps.size(); i++) { PARABOLIC_RAMP_ASSERT(ramps[i].x1 == ramps[i+1].x0); PARABOLIC_RAMP_ASSERT(ramps[i].dx1 == ramps[i+1].dx0); } //revise the timing rampStartTime.resize(ramps.size()); endTime=0; for(size_t i=0; i<ramps.size(); i++) { rampStartTime[i] = endTime; endTime += ramps[i].endTime; } } return shortcuts; } bool DynamicPath::IsValid() const { if(ramps.empty()) { PARABOLICWARN("DynamicPath::IsValid: empty path\n"); return false; } for(size_t i=0; i<ramps.size(); i++) { if(!ramps[i].IsValid()) { PARABOLICWARN("DynamicPath::IsValid: ramp %d is invalid\n",i); return false; } for(size_t j=0; j<ramps[i].ramps.size(); j++) { if(Abs(ramps[i].ramps[j].a1) > accMax.at(j)+EpsilonA || Abs(ramps[i].ramps[j].v) > velMax.at(j)+EpsilonV || Abs(ramps[i].ramps[j].a2) > accMax.at(j)+EpsilonA) { PARABOLICWARN("DynamicPath::IsValid: invalid acceleration or velocity on ramp %d\n",i); PARABOLICWARN("\ta1 %g, v %g, a2 %g. amax %g, vmax %g\n",ramps[i].ramps[j].a1,ramps[i].ramps[j].v,ramps[i].ramps[j].a2,accMax[j],velMax[j]); return false; } } } for(size_t i=1; i<ramps.size(); i++) { if(ramps[i].x0 != ramps[i-1].x1) { PARABOLICWARN("DynamicPath::IsValid: discontinuity at ramp %d\n",i); for(size_t j=0; j<ramps[i].x0.size(); j++) { PARABOLICWARN("%g ",ramps[i].x0[j]); } PARABOLICWARN("\n"); for(size_t j=0; j<ramps[i-1].x1.size(); j++) { PARABOLICWARN("%g ",ramps[i-1].x1[j]); } PARABOLICWARN("\n"); return false; } if(ramps[i].dx0 != ramps[i-1].dx1) { PARABOLICWARN("DynamicPath::IsValid: derivative discontinuity at ramp %d\n",i); for(size_t j=0; j<ramps[i].dx0.size(); j++) { PARABOLICWARN("%g ",ramps[i].dx0[j]); } PARABOLICWARN("\n"); for(size_t j=0; j<ramps[i-1].dx1.size(); j++) { PARABOLICWARN("%g ",ramps[i-1].dx1[j]); } PARABOLICWARN("\n"); return false; } } return true; } } //namespace ParabolicRamp
mit
kiwi-suite/servicemanager
tests/misc/DelegatorFactory.php
505
<?php /** * @link https://github.com/ixocreate * @copyright IXOLIT GmbH * @license MIT License */ declare(strict_types=1); namespace Ixocreate\Misc\ServiceManager; use Ixocreate\ServiceManager\DelegatorFactoryInterface; use Ixocreate\ServiceManager\ServiceManagerInterface; class DelegatorFactory implements DelegatorFactoryInterface { public function __invoke(ServiceManagerInterface $container, $name, callable $callback, array $options = null) { return new \DateTime(); } }
mit
aleste/proyectodev
plugins/sfBreadNav2Plugin/lib/model/map/sfBreadNavApplicationMapBuilder.php
2065
<?php /** * This class adds structure of 'sf_BreadNav_Application' table to 'propel' DatabaseMap object. * * * This class was autogenerated by Propel 1.3.0-dev on: * * 05/19/09 22:02:53 * * * These statically-built map classes are used by Propel to do runtime db structure discovery. * For example, the createSelectSql() method checks the type of a given column used in an * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive * (i.e. if it's a text column type). * * @package plugins.sfBreadNav2Plugin.lib.model.map */ class sfBreadNavApplicationMapBuilder implements MapBuilder { /** * The (dot-path) name of this class */ const CLASS_NAME = 'plugins.sfBreadNav2Plugin.lib.model.map.sfBreadNavApplicationMapBuilder'; /** * The database map. */ private $dbMap; /** * Tells us if this DatabaseMapBuilder is built so that we * don't have to re-build it every time. * * @return boolean true if this DatabaseMapBuilder is built, false otherwise. */ public function isBuilt() { return ($this->dbMap !== null); } /** * Gets the databasemap this map builder built. * * @return the databasemap */ public function getDatabaseMap() { return $this->dbMap; } /** * The doBuild() method builds the DatabaseMap * * @return void * @throws PropelException */ public function doBuild() { $this->dbMap = Propel::getDatabaseMap(sfBreadNavApplicationPeer::DATABASE_NAME); $tMap = $this->dbMap->addTable(sfBreadNavApplicationPeer::TABLE_NAME); $tMap->setPhpName('sfBreadNavApplication'); $tMap->setClassname('sfBreadNavApplication'); $tMap->setUseIdGenerator(true); $tMap->addPrimaryKey('ID', 'Id', 'INTEGER', true, null); $tMap->addColumn('USER_ID', 'UserId', 'INTEGER', false, null); $tMap->addColumn('NAME', 'Name', 'VARCHAR', true, 255); $tMap->addColumn('APPLICATION', 'Application', 'VARCHAR', true, 255); $tMap->addColumn('CSS', 'Css', 'VARCHAR', true, 2000); } // doBuild() } // sfBreadNavApplicationMapBuilder
mit
sirius2013/BuildCore
vendor/angular-pdf/dist/angular-pdf.js
2944
(function () { 'use strict'; angular.module('pdf', []).directive('ngPdf', function($window) { return { restrict: 'E', templateUrl: function(element, attr) { return attr.templateUrl ? attr.templateUrl : 'partials/viewer.html' }, link: function (scope, element, attrs) { var url = scope.pdfUrl, pdfDoc = null, pageNum = 1, scale = (attrs.scale ? attrs.scale : 1), canvas = (attrs.canvasid ? document.getElementById(attrs.canvasid) : document.getElementById('pdf-canvas')), ctx = canvas.getContext('2d'), windowEl = angular.element($window); windowEl.on('scroll', function() { scope.$apply(function() { scope.scroll = windowEl[0].scrollY; }); }); PDFJS.disableWorker = true; scope.pageNum = pageNum; scope.renderPage = function(num) { pdfDoc.getPage(num).then(function(page) { var viewport = page.getViewport(scale); canvas.height = viewport.height; canvas.width = viewport.height; var renderContext = { canvasContext: ctx, viewport: viewport }; page.render(renderContext); }); }; scope.goPrevious = function() { if (scope.pageNum <= 1) return; scope.pageNum = parseInt(scope.pageNum, 10) - 1; }; scope.goNext = function() { if (scope.pageNum >= pdfDoc.numPages) return; scope.pageNum = parseInt(scope.pageNum, 10) + 1; }; scope.zoomIn = function() { scale = parseFloat(scale) + 0.2; scope.renderPage(scope.pageNum); return scale; }; scope.zoomOut = function() { scale = parseFloat(scale) - 0.2; scope.renderPage(scope.pageNum); return scale; }; scope.changePage = function() { scope.renderPage(scope.pageNum); }; scope.rotate = function() { if (canvas.getAttribute('class') === 'rotate0') { canvas.setAttribute('class', 'rotate90'); } else if (canvas.getAttribute('class') === 'rotate90') { canvas.setAttribute('class', 'rotate180'); } else if (canvas.getAttribute('class') === 'rotate180') { canvas.setAttribute('class', 'rotate270'); } else { canvas.setAttribute('class', 'rotate0'); } }; PDFJS.getDocument(url).then(function (_pdfDoc) { pdfDoc = _pdfDoc; scope.renderPage(scope.pageNum); scope.$apply(function() { scope.pageCount = _pdfDoc.numPages; }); }); scope.$watch('pageNum', function (newVal) { if (pdfDoc !== null) scope.renderPage(newVal); }); } }; }); })();
mit
czim/laravel-cms-models
tests/ModelInformation/Data/Form/Layout/ModelFormFieldLabelDataTest.php
783
<?php namespace Czim\CmsModels\Test\ModelInformation\Data\Form\Layout; use Czim\CmsModels\ModelInformation\Data\Form\Layout\AbstractModelFormLayoutNodeData; use Czim\CmsModels\ModelInformation\Data\Form\Layout\ModelFormFieldLabelData; /** * Class ModelFormFieldLabelDataTest * * @group modelinformation-data */ class ModelFormFieldLabelDataTest extends AbstractModelFormLayoutNodeDataTestCase { /** * @test */ function it_returns_label_for() { $data = $this->makeDataObject(); $data->label_for = 'for_key'; static::assertEquals('for_key', $data->labelFor()); } /** * @return AbstractModelFormLayoutNodeData */ protected function makeDataObject() { return new ModelFormFieldLabelData; } }
mit
ArthurSecretProject/hera
config/webpack.dev.js
8173
/** * @author: @AngularClass */ const helpers = require('./helpers'); const webpackMerge = require('webpack-merge'); // used to merge webpack configs // const webpackMergeDll = webpackMerge.strategy({plugins: 'replace'}); const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev /** * Webpack Plugins */ const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin'); const DefinePlugin = require('webpack/lib/DefinePlugin'); const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin'); const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin'); const HotModuleReplacementPlugin = require('webpack/lib/HotModuleReplacementPlugin'); /** * Webpack Constants */ const ENV = process.env.ENV = process.env.NODE_ENV = 'development'; const HOST = process.env.HOST || 'localhost'; const API_URL = process.env.API_URL || 'localhost'; const API_PORT = process.env.API_PORT || '8080'; const PORT = process.env.PORT || 3000; const PUBLIC = process.env.PUBLIC_DEV || HOST + ':' + PORT; const AOT = process.env.BUILD_AOT || helpers.hasNpmFlag('aot'); const HMR = helpers.hasProcessFlag('hot'); const METADATA = { host: HOST, port: PORT, public: PUBLIC, ENV: ENV, HMR: HMR, API_URL: API_URL, API_PORT: API_PORT, AOT: AOT }; // const DllBundlesPlugin = require('webpack-dll-bundles-plugin').DllBundlesPlugin; /** * Webpack configuration * * See: http://webpack.github.io/docs/configuration.html#cli */ module.exports = function (options) { return webpackMerge(commonConfig({env: ENV}), { /** * Developer tool to enhance debugging * * See: http://webpack.github.io/docs/configuration.html#devtool * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps */ devtool: 'cheap-module-source-map', /** * Options affecting the output of the compilation. * * See: http://webpack.github.io/docs/configuration.html#output */ output: { /** * The output directory as absolute path (required). * * See: http://webpack.github.io/docs/configuration.html#output-path */ path: helpers.root('dist'), /** * Specifies the name of each output file on disk. * IMPORTANT: You must not specify an absolute path here! * * See: http://webpack.github.io/docs/configuration.html#output-filename */ filename: '[name].bundle.js', /** * The filename of the SourceMaps for the JavaScript files. * They are inside the output.path directory. * * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename */ sourceMapFilename: '[file].map', /** The filename of non-entry chunks as relative path * inside the output.path directory. * * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename */ chunkFilename: '[id].chunk.js', library: 'ac_[name]', libraryTarget: 'var', }, module: { rules: [ /** * Css loader support for *.css files (styles directory only) * Loads external css styles into the DOM, supports HMR * */ { test: /\.css$/, use: ['style-loader', 'css-loader'], include: [helpers.root('src', 'styles')] }, /** * Sass loader support for *.scss files (styles directory only) * Loads external sass styles into the DOM, supports HMR * */ { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'], include: [helpers.root('src', 'styles')] }, ] }, plugins: [ /** * Plugin: DefinePlugin * Description: Define free variables. * Useful for having development builds with debug logging or adding global constants. * * Environment helpers * * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin * * NOTE: when adding more properties, make sure you include them in custom-typings.d.ts */ new DefinePlugin({ 'ENV': JSON.stringify(METADATA.ENV), 'HMR': METADATA.HMR, 'process.env.ENV': JSON.stringify(METADATA.ENV), 'process.env.NODE_ENV': JSON.stringify(METADATA.ENV), 'process.env.HMR': METADATA.HMR, 'API_URL': JSON.stringify(METADATA.API_URL), 'API_PORT': JSON.stringify(METADATA.API_PORT), 'process.env.API_URL': JSON.stringify(METADATA.API_URL), 'process.env.API_PORT': JSON.stringify(METADATA.API_PORT) }), // new DllBundlesPlugin({ // bundles: { // polyfills: [ // 'core-js', // { // name: 'zone.js', // path: 'zone.js/dist/zone.js' // }, // { // name: 'zone.js', // path: 'zone.js/dist/long-stack-trace-zone.js' // }, // ], // vendor: [ // '@angular/platform-browser', // '@angular/platform-browser-dynamic', // '@angular/core', // '@angular/common', // '@angular/forms', // '@angular/http', // '@angular/router', // '@angularclass/hmr', // 'rxjs', // ] // }, // dllDir: helpers.root('dll'), // webpackConfig: webpackMergeDll(commonConfig({env: ENV}), { // devtool: 'cheap-module-source-map', // plugins: [] // }) // }), /** * Plugin: AddAssetHtmlPlugin * Description: Adds the given JS or CSS file to the files * Webpack knows about, and put it into the list of assets * html-webpack-plugin injects into the generated html. * * See: https://github.com/SimenB/add-asset-html-webpack-plugin */ // new AddAssetHtmlPlugin([ // { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('polyfills')}`) }, // { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('vendor')}`) } // ]), /** * Plugin: NamedModulesPlugin (experimental) * Description: Uses file names as module name. * * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb */ // new NamedModulesPlugin(), /** * Plugin LoaderOptionsPlugin (experimental) * * See: https://gist.github.com/sokra/27b24881210b56bbaff7 */ new LoaderOptionsPlugin({ debug: true, options: { } }), new HotModuleReplacementPlugin() ], /** * Webpack Development Server configuration * Description: The webpack-dev-server is a little node.js Express server. * The server emits information about the compilation state to the client, * which reacts to those events. * * See: https://webpack.github.io/docs/webpack-dev-server.html */ devServer: { port: METADATA.port, host: METADATA.host, hot: METADATA.HMR, public: METADATA.public, historyApiFallback: true, watchOptions: { // if you're using Docker you may need this // aggregateTimeout: 300, // poll: 1000, ignored: /node_modules/ }, /** * Here you can access the Express app object and add your own custom middleware to it. * * See: https://webpack.github.io/docs/webpack-dev-server.html */ setup: function(app) { // For example, to define custom handlers for some paths: // app.get('/some/path', function(req, res) { // res.json({ custom: 'response' }); // }); } }, /** * Include polyfills or mocks for various node stuff * Description: Node configuration * * See: https://webpack.github.io/docs/configuration.html#node */ node: { global: true, crypto: 'empty', process: true, module: false, clearImmediate: false, setImmediate: false } }); }
mit
evangelischeomroep/npo-api-interceptor
config/rollup.config.cjs.js
139
import config from './rollup.config' export default config({ format: 'cjs', dest: 'lib/npoapiinterceptor.cjs.js', browser: false })
mit
coyotebush/fullcalendar
src/EventManager.js
9209
fc.sourceNormalizers = []; fc.sourceFetchers = []; var ajaxDefaults = { dataType: 'json', cache: false }; var eventGUID = 1; function EventManager(options, _sources) { var t = this; // exports t.isFetchNeeded = isFetchNeeded; t.fetchEvents = fetchEvents; t.addEventSource = addEventSource; t.removeEventSource = removeEventSource; t.updateEvent = updateEvent; t.renderEvent = renderEvent; t.removeEvents = removeEvents; t.clientEvents = clientEvents; t.normalizeEvent = normalizeEvent; // imports var trigger = t.trigger; var getView = t.getView; var reportEvents = t.reportEvents; // locals var stickySource = { events: [] }; var sources = [ stickySource ]; var rangeStart, rangeEnd; var currentFetchID = 0; var pendingSourceCnt = 0; var cache = []; for (var i=0; i<_sources.length; i++) { _addEventSource(_sources[i]); } /* Fetching -----------------------------------------------------------------------------*/ function isFetchNeeded(start, end) { return !rangeStart || start < rangeStart || end > rangeEnd; } function fetchEvents(start, end, src) { rangeStart = start; rangeEnd = end; // partially clear cache if refreshing one source only (issue #1061) cache = typeof src != 'undefined' ? $.grep(cache, function(e) { return !isSourcesEqual(e.source, src); }) : []; var fetchID = ++currentFetchID; var len = sources.length; pendingSourceCnt = typeof src == 'undefined' ? len : 1; for (var i=0; i<len; i++) { if (typeof src == 'undefined' || isSourcesEqual(sources[i], src)) fetchEventSource(sources[i], fetchID); } } function fetchEventSource(source, fetchID) { _fetchEventSource(source, function(events) { if (fetchID == currentFetchID) { if (events) { for (var i=0; i<events.length; i++) { events[i].source = source; normalizeEvent(events[i]); } cache = cache.concat(events); } pendingSourceCnt--; if (!pendingSourceCnt) { reportEvents(cache); } } }); } function _fetchEventSource(source, callback) { var i; var fetchers = fc.sourceFetchers; var res; for (i=0; i<fetchers.length; i++) { res = fetchers[i](source, rangeStart, rangeEnd, callback); if (res === true) { // the fetcher is in charge. made its own async request return; } else if (typeof res == 'object') { // the fetcher returned a new source. process it _fetchEventSource(res, callback); return; } } var events = source.events; if (events) { if ($.isFunction(events)) { loading(); events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) { callback(events); loading(); }); } else if ($.isArray(events)) { callback(events); } else { callback(); } }else{ var url = source.url; if (url) { var success = source.success; var error = source.error; var complete = source.complete; var data = $.extend({}, source.data || {}); var startParam = firstDefined(source.startParam, options.startParam); var endParam = firstDefined(source.endParam, options.endParam); if (startParam) { data[startParam] = Math.round(+rangeStart / 1000); } if (endParam) { data[endParam] = Math.round(+rangeEnd / 1000); } loading(); $.ajax($.extend({}, ajaxDefaults, source, { data: data, success: function(events) { events = events || []; var res = applyAll(success, this, arguments); if ($.isArray(res)) { events = res; } callback(events); }, error: function() { applyAll(error, this, arguments); callback(); }, complete: function() { applyAll(complete, this, arguments); loading(); } })); }else{ callback(); } } } /* Sources -----------------------------------------------------------------------------*/ function addEventSource(source) { source = _addEventSource(source); if (source) { pendingSourceCnt++; fetchEventSource(source, currentFetchID); // will eventually call reportEvents } } function _addEventSource(source) { if ($.isFunction(source) || $.isArray(source)) { source = { events: source }; } else if (typeof source == 'string') { source = { url: source }; } if (typeof source == 'object') { normalizeSource(source); sources.push(source); return source; } } function removeEventSource(source) { sources = $.grep(sources, function(src) { return !isSourcesEqual(src, source); }); // remove all client events from that source cache = $.grep(cache, function(e) { return !isSourcesEqual(e.source, source); }); reportEvents(cache); } /* Manipulation -----------------------------------------------------------------------------*/ function updateEvent(event) { // update an existing event var i, len = cache.length, e, defaultEventEnd = getView().defaultEventEnd, // getView??? startDelta = event.start - event._start, endDelta = event.end ? (event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end : 0; // was null and event was just resized for (i=0; i<len; i++) { e = cache[i]; if (e._id == event._id && e != event) { e.start = new Date(+e.start + startDelta); if (event.end) { if (e.end) { e.end = new Date(+e.end + endDelta); }else{ e.end = new Date(+defaultEventEnd(e) + endDelta); } }else{ e.end = null; } e.title = event.title; e.url = event.url; e.allDay = event.allDay; e.className = event.className; e.editable = event.editable; e.color = event.color; e.backgroudColor = event.backgroudColor; e.borderColor = event.borderColor; e.textColor = event.textColor; normalizeEvent(e); } } normalizeEvent(event); reportEvents(cache); } function renderEvent(event, stick) { normalizeEvent(event); if (!event.source) { if (stick) { stickySource.events.push(event); event.source = stickySource; } } // always push event to cache (issue #1112:) cache.push(event); reportEvents(cache); } function removeEvents(filter) { if (!filter) { // remove all cache = []; // clear all array sources for (var i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = []; } } }else{ if (!$.isFunction(filter)) { // an event ID var id = filter + ''; filter = function(e) { return e._id == id; }; } cache = $.grep(cache, filter, true); // remove events from array sources for (var i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = $.grep(sources[i].events, filter, true); } } } reportEvents(cache); } function clientEvents(filter) { if ($.isFunction(filter)) { return $.grep(cache, filter); } else if (filter) { // an event ID filter += ''; return $.grep(cache, function(e) { return e._id == filter; }); } return cache; // else, return all } /* Loading State -----------------------------------------------------------------------------*/ function loading() { trigger('loading', null, pendingSourceCnt || false, sources.length); } /* Event Normalization -----------------------------------------------------------------------------*/ function normalizeEvent(event) { var source = event.source || {}; var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone); event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + ''); if (event.date) { if (!event.start) { event.start = event.date; } delete event.date; } event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone)); event.end = parseDate(event.end, ignoreTimezone); if (event.end && event.end <= event.start) { event.end = null; } event._end = event.end ? cloneDate(event.end) : null; if (event.allDay === undefined) { event.allDay = firstDefined(source.allDayDefault, options.allDayDefault); } if (event.className) { if (typeof event.className == 'string') { event.className = event.className.split(/\s+/); } }else{ event.className = []; } // TODO: if there is no start date, return false to indicate an invalid event } /* Utils ------------------------------------------------------------------------------*/ function normalizeSource(source) { if (source.className) { // TODO: repeat code, same code for event classNames if (typeof source.className == 'string') { source.className = source.className.split(/\s+/); } }else{ source.className = []; } var normalizers = fc.sourceNormalizers; for (var i=0; i<normalizers.length; i++) { normalizers[i](source); } } function isSourcesEqual(source1, source2) { return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2); } function getSourcePrimitive(source) { return ((typeof source == 'object') ? (source.events || source.url) : '') || source; } }
mit
VegasGoat/WoodworkingTFC
src/VegasGoatTFC/CarvingResultSlot.java
923
package VegasGoatTFC; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.inventory.Slot; import net.minecraft.inventory.IInventory; public class CarvingResultSlot extends Slot { ContainerCarvingBase container; int[] validItems; public CarvingResultSlot(ContainerCarvingBase container, IInventory parentInv, int index, int x, int y, int[] validItems) { super(parentInv, index, x, y); this.container = container; this.validItems = validItems; } @Override public boolean isItemValid(ItemStack is) { for(int testID : this.validItems) { if(is.itemID == testID) { return true; } } return false; } @Override public int getSlotStackLimit() { return 1; } @Override public void onPickupFromSlot(EntityPlayer player, ItemStack is) { this.container.onResultPickedUp(player); } }
mit
Akagi201/web-player
videojs/static/node_modules/mux.js/lib/mp4/transmuxer.js
35617
/** * mux.js * * Copyright (c) 2015 Brightcove * All rights reserved. * * A stream-based mp2t to mp4 converter. This utility can be used to * deliver mp4s to a SourceBuffer on platforms that support native * Media Source Extensions. */ 'use strict'; var Stream = require('../utils/stream.js'); var mp4 = require('./mp4-generator.js'); var m2ts = require('../m2ts/m2ts.js'); var AdtsStream = require('../codecs/adts.js'); var H264Stream = require('../codecs/h264').H264Stream; var AacStream = require('../aac'); // constants var AUDIO_PROPERTIES = [ 'audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize' ]; var VIDEO_PROPERTIES = [ 'width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', ]; // object types var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream; // Helper functions var createDefaultSample, isLikelyAacData, collectDtsInfo, clearDtsInfo, calculateTrackBaseMediaDecodeTime, arrayEquals, sumFrameByteLengths; /** * Default sample object * see ISO/IEC 14496-12:2012, section 8.6.4.3 */ createDefaultSample = function () { return { size: 0, flags: { isLeading: 0, dependsOn: 1, isDependedOn: 0, hasRedundancy: 0, degradationPriority: 0 } }; }; isLikelyAacData = function (data) { if ((data[0] === 'I'.charCodeAt(0)) && (data[1] === 'D'.charCodeAt(0)) && (data[2] === '3'.charCodeAt(0))) { return true; } return false; }; /** * Compare two arrays (even typed) for same-ness */ arrayEquals = function(a, b) { var i; if (a.length !== b.length) { return false; } // compare the value of each element in the array for (i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; }; /** * Sum the `byteLength` properties of the data in each AAC frame */ sumFrameByteLengths = function(array) { var i, currentObj, sum = 0; // sum the byteLength's all each nal unit in the frame for (i = 0; i < array.length; i++) { currentObj = array[i]; sum += currentObj.data.byteLength; } return sum; }; /** * Constructs a single-track, ISO BMFF media segment from AAC data * events. The output of this stream can be fed to a SourceBuffer * configured with a suitable initialization segment. */ AudioSegmentStream = function(track) { var adtsFrames = [], sequenceNumber = 0, earliestAllowedDts = 0; AudioSegmentStream.prototype.init.call(this); this.push = function(data) { collectDtsInfo(track, data); if (track) { AUDIO_PROPERTIES.forEach(function(prop) { track[prop] = data[prop]; }); } // buffer audio data until end() is called adtsFrames.push(data); }; this.setEarliestDts = function(earliestDts) { earliestAllowedDts = earliestDts - track.timelineStartInfo.baseMediaDecodeTime; }; this.flush = function() { var frames, moof, mdat, boxes; // return early if no audio data has been observed if (adtsFrames.length === 0) { this.trigger('done', 'AudioSegmentStream'); return; } frames = this.trimAdtsFramesByEarliestDts_(adtsFrames); // we have to build the index from byte locations to // samples (that is, adts frames) in the audio data track.samples = this.generateSampleTable_(frames); // concatenate the audio data to constuct the mdat mdat = mp4.mdat(this.concatenateFrameData_(frames)); adtsFrames = []; calculateTrackBaseMediaDecodeTime(track); moof = mp4.moof(sequenceNumber, [track]); boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time sequenceNumber++; boxes.set(moof); boxes.set(mdat, moof.byteLength); clearDtsInfo(track); this.trigger('data', {track: track, boxes: boxes}); this.trigger('done', 'AudioSegmentStream'); }; // If the audio segment extends before the earliest allowed dts // value, remove AAC frames until starts at or after the earliest // allowed DTS so that we don't end up with a negative baseMedia- // DecodeTime for the audio track this.trimAdtsFramesByEarliestDts_ = function(adtsFrames) { if (track.minSegmentDts >= earliestAllowedDts) { return adtsFrames; } // We will need to recalculate the earliest segment Dts track.minSegmentDts = Infinity; return adtsFrames.filter(function(currentFrame) { // If this is an allowed frame, keep it and record it's Dts if (currentFrame.dts >= earliestAllowedDts) { track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts); track.minSegmentPts = track.minSegmentDts; return true; } // Otherwise, discard it return false; }); }; // generate the track's raw mdat data from an array of frames this.generateSampleTable_ = function(frames) { var i, currentFrame, samples = []; for (i = 0; i < frames.length; i++) { currentFrame = frames[i]; samples.push({ size: currentFrame.data.byteLength, duration: 1024 // For AAC audio, all samples contain 1024 samples }); } return samples; }; // generate the track's sample table from an array of frames this.concatenateFrameData_ = function(frames) { var i, currentFrame, dataOffset = 0, data = new Uint8Array(sumFrameByteLengths(frames)); for (i = 0; i < frames.length; i++) { currentFrame = frames[i]; data.set(currentFrame.data, dataOffset); dataOffset += currentFrame.data.byteLength; } return data; }; }; AudioSegmentStream.prototype = new Stream(); /** * Constructs a single-track, ISO BMFF media segment from H264 data * events. The output of this stream can be fed to a SourceBuffer * configured with a suitable initialization segment. * @param track {object} track metadata configuration */ VideoSegmentStream = function(track) { var sequenceNumber = 0, nalUnits = [], config, pps; VideoSegmentStream.prototype.init.call(this); delete track.minPTS; this.gopCache_ = []; this.push = function(nalUnit) { collectDtsInfo(track, nalUnit); // record the track config if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) { config = nalUnit.config; track.sps = [nalUnit.data]; VIDEO_PROPERTIES.forEach(function(prop) { track[prop] = config[prop]; }, this); } if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) { pps = nalUnit.data; track.pps = [nalUnit.data]; } // buffer video until flush() is called nalUnits.push(nalUnit); }; this.flush = function() { var frames, gopForFusion, gops, moof, mdat, boxes; // Throw away nalUnits at the start of the byte stream until // we find the first AUD while (nalUnits.length) { if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') { break; } nalUnits.shift(); } // Return early if no video data has been observed if (nalUnits.length === 0) { this.resetStream_(); this.trigger('done', 'VideoSegmentStream'); return; } // Organize the raw nal-units into arrays that represent // higher-level constructs such as frames and gops // (group-of-pictures) frames = this.groupNalsIntoFrames_(nalUnits); gops = this.groupFramesIntoGops_(frames); // If the first frame of this fragment is not a keyframe we have // a problem since MSE (on Chrome) requires a leading keyframe. // // We have two approaches to repairing this situation: // 1) GOP-FUSION: // This is where we keep track of the GOPS (group-of-pictures) // from previous fragments and attempt to find one that we can // prepend to the current fragment in order to create a valid // fragment. // 2) KEYFRAME-PULLING: // Here we search for the first keyframe in the fragment and // throw away all the frames between the start of the fragment // and that keyframe. We then extend the duration and pull the // PTS of the keyframe forward so that it covers the time range // of the frames that were disposed of. // // #1 is far prefereable over #2 which can cause "stuttering" but // requires more things to be just right. if (!gops[0][0].keyFrame) { // Search for a gop for fusion from our gopCache gopForFusion = this.getGopForFusion_(nalUnits[0], track); if (gopForFusion) { gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the // new gop at the beginning gops.byteLength += gopForFusion.byteLength; gops.nalCount += gopForFusion.nalCount; gops.pts = gopForFusion.pts; gops.dts = gopForFusion.dts; gops.duration += gopForFusion.duration; } else { // If we didn't find a candidate gop fall back to keyrame-pulling gops = this.extendFirstKeyFrame_(gops); } } collectDtsInfo(track, gops); // First, we have to build the index from byte locations to // samples (that is, frames) in the video data track.samples = this.generateSampleTable_(gops); // Concatenate the video data and construct the mdat mdat = mp4.mdat(this.concatenateNalData_(gops)); // save all the nals in the last GOP into the gop cache this.gopCache_.unshift({ gop: gops.pop(), pps: track.pps, sps: track.sps }); // Keep a maximum of 6 GOPs in the cache this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits nalUnits = []; calculateTrackBaseMediaDecodeTime(track); this.trigger('timelineStartInfo', track.timelineStartInfo); moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of // throwing away hundreds of media segment fragments boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time sequenceNumber++; boxes.set(moof); boxes.set(mdat, moof.byteLength); this.trigger('data', {track: track, boxes: boxes}); this.resetStream_(); // Continue with the flush process now this.trigger('done', 'VideoSegmentStream'); }; this.resetStream_ = function() { clearDtsInfo(track); // reset config and pps because they may differ across segments // for instance, when we are rendition switching config = undefined; pps = undefined; }; // Search for a candidate Gop for gop-fusion from the gop cache and // return it or return null if no good candidate was found this.getGopForFusion_ = function (nalUnit) { var halfSecond = 45000, // Half-a-second in a 90khz clock allowableOverlap = 10000, // About 3 frames @ 30fps nearestDistance = Infinity, dtsDistance, nearestGopObj, currentGop, currentGopObj, i; // Search for the GOP nearest to the beginning of this nal unit for (i = 0; i < this.gopCache_.length; i++) { currentGopObj = this.gopCache_[i]; currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) { continue; } // Reject Gops that would require a negative baseMediaDecodeTime if (currentGop.dts < track.timelineStartInfo.dts) { continue; } // The distance between the end of the gop and the start of the nalUnit dtsDistance = (nalUnit.dts - currentGop.dts) - currentGop.duration; // Only consider GOPS that start before the nal unit and end within // a half-second of the nal unit if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) { // Always use the closest GOP we found if there is more than // one candidate if (!nearestGopObj || nearestDistance > dtsDistance) { nearestGopObj = currentGopObj; nearestDistance = dtsDistance; } } } if (nearestGopObj) { return nearestGopObj.gop; } return null; }; this.extendFirstKeyFrame_ = function(gops) { var h, i, currentGop, newGops; if (!gops[0][0].keyFrame) { // Remove the first GOP currentGop = gops.shift(); gops.byteLength -= currentGop.byteLength; gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the // first gop to cover the time period of the // frames we just removed gops[0][0].dts = currentGop.dts; gops[0][0].pts = currentGop.pts; gops[0][0].duration += currentGop.duration; } return gops; }; // Convert an array of nal units into an array of frames with each frame being // composed of the nal units that make up that frame // Also keep track of cummulative data about the frame from the nal units such // as the frame duration, starting pts, etc. this.groupNalsIntoFrames_ = function(nalUnits) { var i, currentNal, startPts, startDts, currentFrame = [], frames = []; currentFrame.byteLength = 0; for (i = 0; i < nalUnits.length; i++) { currentNal = nalUnits[i]; // Split on 'aud'-type nal units if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') { // Since the very first nal unit is expected to be an AUD // only push to the frames array when currentFrame is not empty if (currentFrame.length) { currentFrame.duration = currentNal.dts - currentFrame.dts; frames.push(currentFrame); } currentFrame = [currentNal]; currentFrame.byteLength = currentNal.data.byteLength; currentFrame.pts = currentNal.pts; currentFrame.dts = currentNal.dts; } else { // Specifically flag key frames for ease of use later if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') { currentFrame.keyFrame = true; } currentFrame.duration = currentNal.dts - currentFrame.dts; currentFrame.byteLength += currentNal.data.byteLength; currentFrame.push(currentNal); } } // For the last frame, use the duration of the previous frame if we // have nothing better to go on if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) { currentFrame.duration = frames[frames.length - 1].duration; } // Push the final frame frames.push(currentFrame); return frames; }; // Convert an array of frames into an array of Gop with each Gop being composed // of the frames that make up that Gop // Also keep track of cummulative data about the Gop from the frames such as the // Gop duration, starting pts, etc. this.groupFramesIntoGops_ = function(frames) { var i, currentFrame, currentGop = [], gops = []; // We must pre-set some of the values on the Gop since we // keep running totals of these values currentGop.byteLength = 0; currentGop.nalCount = 0; currentGop.duration = 0; currentGop.pts = frames[0].pts; currentGop.dts = frames[0].dts; // store some metadata about all the Gops gops.byteLength = 0; gops.nalCount = 0; gops.duration = 0; gops.pts = frames[0].pts; gops.dts = frames[0].dts; for (i = 0; i < frames.length; i++) { currentFrame = frames[i]; if (currentFrame.keyFrame) { // Since the very first frame is expected to be an keyframe // only push to the gops array when currentGop is not empty if (currentGop.length) { gops.push(currentGop); gops.byteLength += currentGop.byteLength; gops.nalCount += currentGop.nalCount; gops.duration += currentGop.duration; } currentGop = [currentFrame]; currentGop.nalCount = currentFrame.length; currentGop.byteLength = currentFrame.byteLength; currentGop.pts = currentFrame.pts; currentGop.dts = currentFrame.dts; currentGop.duration = currentFrame.duration; } else { currentGop.duration += currentFrame.duration; currentGop.nalCount += currentFrame.length; currentGop.byteLength += currentFrame.byteLength; currentGop.push(currentFrame); } } if (gops.length && currentGop.duration <= 0) { currentGop.duration = gops[gops.length - 1].duration; } gops.byteLength += currentGop.byteLength; gops.nalCount += currentGop.nalCount; gops.duration += currentGop.duration; // push the final Gop gops.push(currentGop); return gops; }; // generate the track's sample table from an array of gops this.generateSampleTable_ = function(gops, baseDataOffset) { var h, i, sample, currentGop, currentFrame, currentSample, dataOffset = baseDataOffset || 0, samples = []; for (h = 0; h < gops.length; h++) { currentGop = gops[h]; for (i = 0; i < currentGop.length; i++) { currentFrame = currentGop[i]; sample = createDefaultSample(); sample.dataOffset = dataOffset; sample.compositionTimeOffset = currentFrame.pts - currentFrame.dts; sample.duration = currentFrame.duration; sample.size = 4 * currentFrame.length; // Space for nal unit size sample.size += currentFrame.byteLength; if (currentFrame.keyFrame) { sample.flags.dependsOn = 2; } dataOffset += sample.size; samples.push(sample); } } return samples; }; // generate the track's raw mdat data from an array of gops this.concatenateNalData_ = function (gops) { var h, i, j, currentGop, currentFrame, currentNal, dataOffset = 0, nalsByteLength = gops.byteLength, numberOfNals = gops.nalCount, totalByteLength = nalsByteLength + 4 * numberOfNals, data = new Uint8Array(totalByteLength), view = new DataView(data.buffer); // For each Gop.. for (h = 0; h < gops.length; h++) { currentGop = gops[h]; // For each Frame.. for (i = 0; i < currentGop.length; i++) { currentFrame = currentGop[i]; // For each NAL.. for (j = 0; j < currentFrame.length; j++) { currentNal = currentFrame[j]; view.setUint32(dataOffset, currentNal.data.byteLength); dataOffset += 4; data.set(currentNal.data, dataOffset); dataOffset += currentNal.data.byteLength; } } } return data; }; }; VideoSegmentStream.prototype = new Stream(); /** * Store information about the start and end of the track and the * duration for each frame/sample we process in order to calculate * the baseMediaDecodeTime */ collectDtsInfo = function (track, data) { if (typeof data.pts === 'number') { if (track.timelineStartInfo.pts === undefined) { track.timelineStartInfo.pts = data.pts; } if (track.minSegmentPts === undefined) { track.minSegmentPts = data.pts; } else { track.minSegmentPts = Math.min(track.minSegmentPts, data.pts); } if (track.maxSegmentPts === undefined) { track.maxSegmentPts = data.pts; } else { track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts); } } if (typeof data.dts === 'number') { if (track.timelineStartInfo.dts === undefined) { track.timelineStartInfo.dts = data.dts; } if (track.minSegmentDts === undefined) { track.minSegmentDts = data.dts; } else { track.minSegmentDts = Math.min(track.minSegmentDts, data.dts); } if (track.maxSegmentDts === undefined) { track.maxSegmentDts = data.dts; } else { track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts); } } }; /** * Clear values used to calculate the baseMediaDecodeTime between * tracks */ clearDtsInfo = function (track) { delete track.minSegmentDts; delete track.maxSegmentDts; delete track.minSegmentPts; delete track.maxSegmentPts; }; /** * Calculate the track's baseMediaDecodeTime based on the earliest * DTS the transmuxer has ever seen and the minimum DTS for the * current track */ calculateTrackBaseMediaDecodeTime = function (track) { var oneSecondInPTS = 90000, // 90kHz clock scale, // Calculate the distance, in time, that this segment starts from the start // of the timeline (earliest time seen since the transmuxer initialized) timeSinceStartOfTimeline = track.minSegmentDts - track.timelineStartInfo.dts, // Calculate the first sample's effective compositionTimeOffset firstSampleCompositionOffset = track.minSegmentPts - track.minSegmentDts; // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where // we want the start of the first segment to be placed track.baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first track.baseMediaDecodeTime += timeSinceStartOfTimeline; // Subtract this segment's "compositionTimeOffset" so that the first frame of // this segment is displayed exactly at the `baseMediaDecodeTime` or at the // end of the previous segment track.baseMediaDecodeTime -= firstSampleCompositionOffset; // baseMediaDecodeTime must not become negative track.baseMediaDecodeTime = Math.max(0, track.baseMediaDecodeTime); if (track.type === 'audio') { // Audio has a different clock equal to the sampling_rate so we need to // scale the PTS values into the clock rate of the track scale = track.samplerate / oneSecondInPTS; track.baseMediaDecodeTime *= scale; track.baseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime); } }; /** * A Stream that can combine multiple streams (ie. audio & video) * into a single output segment for MSE. Also supports audio-only * and video-only streams. */ CoalesceStream = function(options, metadataStream) { // Number of Tracks per output segment // If greater than 1, we combine multiple // tracks into a single segment this.numberOfTracks = 0; this.metadataStream = metadataStream; if (typeof options.remux !== 'undefined') { this.remuxTracks = !!options.remux; } else { this.remuxTracks = true; } this.pendingTracks = []; this.videoTrack = null; this.pendingBoxes = []; this.pendingCaptions = []; this.pendingMetadata = []; this.pendingBytes = 0; this.emittedTracks = 0; CoalesceStream.prototype.init.call(this); // Take output from multiple this.push = function(output) { // buffer incoming captions until the associated video segment // finishes if (output.text) { return this.pendingCaptions.push(output); } // buffer incoming id3 tags until the final flush if (output.frames) { return this.pendingMetadata.push(output); } // Add this track to the list of pending tracks and store // important information required for the construction of // the final segment this.pendingTracks.push(output.track); this.pendingBoxes.push(output.boxes); this.pendingBytes += output.boxes.byteLength; if (output.track.type === 'video') { this.videoTrack = output.track; } if (output.track.type === 'audio') { this.audioTrack = output.track; } }; }; CoalesceStream.prototype = new Stream(); CoalesceStream.prototype.flush = function(flushSource) { var offset = 0, event = { captions: [], metadata: [], info: {} }, caption, id3, initSegment, timelineStartPts = 0, i; if (this.pendingTracks.length < this.numberOfTracks) { if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') { // Return because we haven't received a flush from a data-generating // portion of the segment (meaning that we have only recieved meta-data // or captions.) return; } else if (this.remuxTracks) { // Return until we have enough tracks from the pipeline to remux (if we // are remuxing audio and video into a single MP4) return; } else if (this.pendingTracks.length === 0) { // In the case where we receive a flush without any data having been // received we consider it an emitted track for the purposes of coalescing // `done` events. // We do this for the case where there is an audio and video track in the // segment but no audio data. (seen in several playlists with alternate // audio tracks and no audio present in the main TS segments.) this.emittedTracks++; if (this.emittedTracks >= this.numberOfTracks) { this.trigger('done'); this.emittedTracks = 0; } return; } } if (this.videoTrack) { timelineStartPts = this.videoTrack.timelineStartInfo.pts; VIDEO_PROPERTIES.forEach(function(prop) { event.info[prop] = this.videoTrack[prop]; }, this); } else if (this.audioTrack) { timelineStartPts = this.audioTrack.timelineStartInfo.pts; AUDIO_PROPERTIES.forEach(function(prop) { event.info[prop] = this.audioTrack[prop]; }, this); } if (this.pendingTracks.length === 1) { event.type = this.pendingTracks[0].type; } else { event.type = 'combined'; } this.emittedTracks += this.pendingTracks.length; initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array large enough to hold the init // segment and all tracks event.data = new Uint8Array(initSegment.byteLength + this.pendingBytes); // Create an init segment containing a moov // and track definitions event.data.set(initSegment); offset += initSegment.byteLength; // Append each moof+mdat (one per track) after the init segment for (i = 0; i < this.pendingBoxes.length; i++) { event.data.set(this.pendingBoxes[i], offset); offset += this.pendingBoxes[i].byteLength; } // Translate caption PTS times into second offsets into the // video timeline for the segment for (i = 0; i < this.pendingCaptions.length; i++) { caption = this.pendingCaptions[i]; caption.startTime = (caption.startPts - timelineStartPts); caption.startTime /= 90e3; caption.endTime = (caption.endPts - timelineStartPts); caption.endTime /= 90e3; event.captions.push(caption); } // Translate ID3 frame PTS times into second offsets into the // video timeline for the segment for (i = 0; i < this.pendingMetadata.length; i++) { id3 = this.pendingMetadata[i]; id3.cueTime = (id3.pts - timelineStartPts); id3.cueTime /= 90e3; event.metadata.push(id3); } // We add this to every single emitted segment even though we only need // it for the first event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state this.pendingTracks.length = 0; this.videoTrack = null; this.pendingBoxes.length = 0; this.pendingCaptions.length = 0; this.pendingBytes = 0; this.pendingMetadata.length = 0; // Emit the built segment this.trigger('data', event); // Only emit `done` if all tracks have been flushed and emitted if (this.emittedTracks >= this.numberOfTracks) { this.trigger('done'); this.emittedTracks = 0; } }; /** * A Stream that expects MP2T binary data as input and produces * corresponding media segments, suitable for use with Media Source * Extension (MSE) implementations that support the ISO BMFF byte * stream format, like Chrome. */ Transmuxer = function(options) { var self = this, hasFlushed = true, videoTrack, audioTrack; Transmuxer.prototype.init.call(this); options = options || {}; this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0; this.transmuxPipeline_ = {}; this.setupAacPipeline = function() { var pipeline = {}; this.transmuxPipeline_ = pipeline; pipeline.type = 'aac'; pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline pipeline.aacStream = new AacStream(); pipeline.adtsStream = new AdtsStream(); pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream); pipeline.headOfPipeline = pipeline.aacStream; pipeline.aacStream.pipe(pipeline.adtsStream); pipeline.aacStream.pipe(pipeline.metadataStream); pipeline.metadataStream.pipe(pipeline.coalesceStream); pipeline.metadataStream.on('timestamp', function(frame) { pipeline.aacStream.setTimestamp(frame.timeStamp); }); pipeline.aacStream.on('data', function(data) { var i; if (data.type === 'timed-metadata' && !pipeline.audioSegmentStream) { audioTrack = audioTrack || { timelineStartInfo: { baseMediaDecodeTime: self.baseMediaDecodeTime }, codec: 'adts', type: 'audio' }; // hook up the audio segment stream to the first track with aac data pipeline.coalesceStream.numberOfTracks++; pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack); // Set up the final part of the audio pipeline pipeline.adtsStream .pipe(pipeline.audioSegmentStream) .pipe(pipeline.coalesceStream); } }); // Re-emit any data coming from the coalesce stream to the outside world pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done')); }; this.setupTsPipeline = function() { var pipeline = {}; this.transmuxPipeline_ = pipeline; pipeline.type = 'ts'; pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline pipeline.packetStream = new m2ts.TransportPacketStream(); pipeline.parseStream = new m2ts.TransportParseStream(); pipeline.elementaryStream = new m2ts.ElementaryStream(); pipeline.adtsStream = new AdtsStream(); pipeline.h264Stream = new H264Stream(); pipeline.captionStream = new m2ts.CaptionStream(); pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream); pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams pipeline.packetStream .pipe(pipeline.parseStream) .pipe(pipeline.elementaryStream); // !!THIS ORDER IS IMPORTANT!! // demux the streams pipeline.elementaryStream .pipe(pipeline.h264Stream); pipeline.elementaryStream .pipe(pipeline.adtsStream); pipeline.elementaryStream .pipe(pipeline.metadataStream) .pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream pipeline.h264Stream.pipe(pipeline.captionStream) .pipe(pipeline.coalesceStream); pipeline.elementaryStream.on('data', function(data) { var i; if (data.type === 'metadata') { i = data.tracks.length; // scan the tracks listed in the metadata while (i--) { if (!videoTrack && data.tracks[i].type === 'video') { videoTrack = data.tracks[i]; videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime; } else if (!audioTrack && data.tracks[i].type === 'audio') { audioTrack = data.tracks[i]; audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime; } } // hook up the video segment stream to the first track with h264 data if (videoTrack && !pipeline.videoSegmentStream) { pipeline.coalesceStream.numberOfTracks++; pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack); pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo){ // When video emits timelineStartInfo data after a flush, we forward that // info to the AudioSegmentStream, if it exists, because video timeline // data takes precedence. if (audioTrack) { audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the // very earliest DTS we have seen in video because Chrome will // interpret any video track with a baseMediaDecodeTime that is // non-zero as a gap. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts); } }); // Set up the final part of the video pipeline pipeline.h264Stream .pipe(pipeline.videoSegmentStream) .pipe(pipeline.coalesceStream); } if (audioTrack && !pipeline.audioSegmentStream) { // hook up the audio segment stream to the first track with aac data pipeline.coalesceStream.numberOfTracks++; pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack); // Set up the final part of the audio pipeline pipeline.adtsStream .pipe(pipeline.audioSegmentStream) .pipe(pipeline.coalesceStream); } } }); // Re-emit any data coming from the coalesce stream to the outside world pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done')); }; // hook up the segment streams once track metadata is delivered this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) { var pipeline = this.transmuxPipeline_; this.baseMediaDecodeTime = baseMediaDecodeTime; if (audioTrack) { audioTrack.timelineStartInfo.dts = undefined; audioTrack.timelineStartInfo.pts = undefined; clearDtsInfo(audioTrack); audioTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime; } if (videoTrack) { if (pipeline.videoSegmentStream) { pipeline.videoSegmentStream.gopCache_ = []; } videoTrack.timelineStartInfo.dts = undefined; videoTrack.timelineStartInfo.pts = undefined; clearDtsInfo(videoTrack); videoTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime; } }; // feed incoming data to the front of the parsing pipeline this.push = function(data) { if (hasFlushed) { var isAac = isLikelyAacData(data); if (isAac && this.transmuxPipeline_.type !== 'aac') { this.setupAacPipeline(); } else if (!isAac && this.transmuxPipeline_.type !== 'ts') { this.setupTsPipeline(); } hasFlushed = false; } this.transmuxPipeline_.headOfPipeline.push(data); }; // flush any buffered data this.flush = function() { hasFlushed = true; // Start at the top of the pipeline and flush all pending work this.transmuxPipeline_.headOfPipeline.flush(); }; }; Transmuxer.prototype = new Stream(); module.exports = { Transmuxer: Transmuxer, VideoSegmentStream: VideoSegmentStream, AudioSegmentStream: AudioSegmentStream, AUDIO_PROPERTIES: AUDIO_PROPERTIES, VIDEO_PROPERTIES: VIDEO_PROPERTIES };
mit
alekitto/compressor-bundle
src/Preserver/CodePreserver.php
708
<?php namespace Kcs\CompressorBundle\Preserver; /** * Compression preserver for <code> tag * * @author Alessandro Chitolina <[email protected]> */ class CodePreserver extends AbstractTagPreserver { /** * Returns the block regex */ protected function getPattern() { return '#(<code[^>]*?>(?:.*?)</code>)#usi'; } /** * Returns the block temp replacement format for sprintf */ protected function getReplacementFormat() { return '%%%%%%~COMPRESS~CODE~%u~%%%%%%'; } /** * Returns the block replacement regex */ protected function getReplacementPattern() { return '#%%%~COMPRESS~CODE~(\d+?)~%%%#u'; } }
mit
scottohara/tvmanager
src/controllers/series-controller.ts
4603
/** * @file (Controllers) SeriesController * @author Scott O'Hara * @copyright 2010 Scott O'Hara, oharagroup.net * @license MIT */ /** * @module controllers/series-controller * @requires jquery * @requires models/program-model * @requires models/series-model * @requires controllers/view-controller */ import type { NavButtonEventHandler, SeriesListItem } from "controllers"; import $ from "jquery"; import Program from "models/program-model"; import Series from "models/series-model"; import SeriesView from "views/series-view.html"; import ViewController from "controllers/view-controller"; /** * @class SeriesController * @classdesc Controller for the series view * @extends ViewController * @this SeriesController * @property {SeriesListItem} listItem - a list item from the SeriesList or Schedule view * @property {Number} originalNowShowing - the now showing status of the series when the view is first loaded * @property {String} originalProgramId - the program id of the series when the view is first loaded * @property {HeaderFooter} header - the view header bar * @param {SeriesListItem} listItem - a list item from the SeriesList or Schedule view */ export default class SeriesController extends ViewController { private readonly listItem: SeriesListItem; private readonly originalNowShowing: number | null = null; private readonly originalProgramId: string | null = null; public constructor(listItem: SeriesListItem) { super(); // If the passed item has an index, we're editing an existing series if (Number(listItem.listIndex) >= 0) { this.listItem = listItem; this.originalNowShowing = this.listItem.series.nowShowing; this.originalProgramId = this.listItem.series.programId; } else { // Otherwise, we're adding a new series this.listItem = { series: new Series(null, `Series ${Number(listItem.sequence) + 1}`, null, (listItem.program as Program).id, String((listItem.program as Program).programName)) }; } } /** * @memberof SeriesController * @this SeriesController * @instance * @property {String} view - the view template HTML * @desc Returns the HTML for the controller's view */ public get view(): string { return SeriesView; } /** * @memberof SeriesController * @this SeriesController * @instance * @method setup * @desc Initialises the controller */ public async setup(): Promise<void> { // Setup the header this.header = { label: "Add/Edit Series", leftButton: { eventHandler: this.cancel.bind(this) as NavButtonEventHandler, label: "Cancel" }, rightButton: { eventHandler: this.save.bind(this) as NavButtonEventHandler, style: "confirmButton", label: "Save" } }; // Populate the list of programs const programs: Program[] = await Program.list(), options = programs.map((program: Program): JQuery => $("<option>").val(String(program.id)).text(String(program.programName))); $("#moveTo").append(options); // Set the series details $("#seriesName").val(String(this.listItem.series.seriesName)); $("#nowShowing").val(this.listItem.series.nowShowing ?? ""); $("#moveTo").val(String(this.listItem.series.programId)); } /** * @memberof SeriesController * @this SeriesController * @instance * @method contentShown * @desc Called after the controller content is visible */ public override contentShown(): void { // If we're adding a new series, focus and select the episode name if (undefined === this.listItem.listIndex) { $("#seriesName").select(); } } /** * @memberof SeriesController * @this SeriesController * @instance * @method save * @desc Saves the series details to the database and returns to the previous view */ private async save(): Promise<void> { // Get the series details this.listItem.series.seriesName = String($("#seriesName").val()); this.listItem.series.nowShowing = Number($("#nowShowing").val()) || null; this.listItem.series.programId = String($("#moveTo").val()); // Update the database and pop the view off the stack await this.listItem.series.save(); return this.appController.popView(this.listItem); } /** * @memberof SeriesController * @this SeriesController * @instance * @method cancel * @desc Reverts any changes and returns to the previous view */ private async cancel(): Promise<void> { // Revert to the original series details this.listItem.series.nowShowing = this.originalNowShowing; this.listItem.series.programId = this.originalProgramId; // Pop the view off the stack return this.appController.popView(); } }
mit
chatgris/Gaston
lib/gaston.rb
1527
# encoding: utf-8 require 'yaml' require 'singleton' require 'inflecto' class Gaston include Singleton require_relative 'gaston/configuration' require_relative 'gaston/builder' require_relative 'gaston/parse' if defined?(Rails) && defined?(Rails::Generators) require 'gaston/generators/gaston/config_generator' end # Parse yml config files, merge them, and store into # gaston::Store # # @since 0.0.1 # def store @store ||= Gaston::Builder.new(self.class, hash_from_files) end class << self # Define a configure block. # # Delegates to Gaston::Configuration # # @example Define the option. # Gaston.configure do |config| # config.env = :test # config.files = Dir[Rails.root.join("config/libraries/**/*.rb"] # end # # @param [ Proc ] block The block getting called. # # @since 0.0.1 # def configure(&block) self::Configuration.configure(&block) self.instance.store.each do |key, value| define_singleton_method key do value end end end end # self private # List config files. # # @since 0.0.1 # def files Gaston::Configuration.files end # Current enironment. # # @since 0.0.1 # def env Gaston::Configuration.env.to_sym end # Return one merged hash from yaml config files. # # @return [ Hash ] # # @since 0.0.2 # def hash_from_files @hash_from_files ||= Gaston::Parse.new(files, env).to_hash end end # Gaston
mit
nrodriguezm/ionic-login-firebase-email-social
src/pages/tabs/tabs.ts
370
import { Component } from '@angular/core'; import { IonicPage } from 'ionic-angular'; @IonicPage() @Component({ templateUrl: 'tabs.html' }) export class TabsPage { // this tells the tabs component which Pages // should be each tab's root Page tab1Root: any = 'HomePage'; tab2Root: any = 'ItemsPage'; tab3Root: any = 'ProfilePage'; constructor() { } }
mit
uditgupta002/LogisticRegression
src/LogisticRegression.py
11623
''' Created on Oct 31, 2017 @author: udit.gupta ''' import numpy as np import matplotlib.pyplot as plt import scipy from scipy import misc from lr_utils import load_dataset # Loading the data (cat/non-cat) train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset() # Example of a picture from our training set index = 25 plt.imshow(train_set_x_orig[index]) print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") + "' picture.") m_train = train_set_x_orig.shape[0] m_test = test_set_x_orig.shape[0] num_px = train_set_x_orig.shape[1] print ("Number of training examples: m_train = " + str(m_train)) print ("Number of testing examples: m_test = " + str(m_test)) print ("Height/Width of each image: num_px = " + str(num_px)) print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)") print ("train_set_x shape: " + str(train_set_x_orig.shape)) print ("train_set_y shape: " + str(train_set_y.shape)) print ("test_set_x shape: " + str(test_set_x_orig.shape)) print ("test_set_y shape: " + str(test_set_y.shape)) # Reshape the training and test examples # After reshaping the matrices we will have a flattened matrix of size (n_x,m). The transpose is done to obtain the column vectors of examples. # The trick is to retain the first dimension and flatten all the other dimensions. train_set_x_flatten = train_set_x_orig.reshape(m_train,-1).T test_set_x_flatten = test_set_x_orig.reshape(m_test,-1).T print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape)) print ("train_set_y shape: " + str(train_set_y.shape)) print ("test_set_x_flatten shape: " + str(test_set_x_flatten.shape)) print ("test_set_y shape: " + str(test_set_y.shape)) print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,:])) #One common pre-processing step in machine learning is to center and standardize your dataset, meaning that you substract the mean of the whole numpy array from each example, and then divide each example by the standard deviation of the whole numpy array. But for picture datasets, it is simpler and more convenient and works almost as well to just divide every row of the dataset by 255 (the maximum value of a pixel channel). train_set_x = train_set_x_flatten/255.0 test_set_x = test_set_x_flatten/255.0 """ The main steps for building a Neural Network are: 1) Define the model structure (such as number of input features) 2) Initialize the model's parameters 3) Loop: 3.1)Calculate current loss (forward propagation) 3.2)Calculate current gradient (backward propagation) 3.3)Update parameters (gradient descent) """ def sigmoid(z): """ Compute the sigmoid of z Arguments: z -- A scalar or numpy array of any size. Return: s -- sigmoid(z) """ s = 1 / (1 + np.exp(-z)) return s def initialize_with_zeros(dim): """ This function creates a vector of zeros of shape (1, dim) for w and initializes b to 0. The dimension for w is 1*n_x since we are training only one unit here. If we had multiple units to train, the size of W would have been (units on current layer * units_on_previous_layer) For image inputs, w will be of shape (num_px * num_px * 3, 1) Argument: dim -- size of the w vector we want (or number of parameters in this case) Returns: w -- initialized vector of shape (dim, 1) b -- initialized scalar (corresponds to the bias) """ w = np.zeros((1,dim)) b = 0 assert(w.shape == (1, dim)) assert(isinstance(b, float) or isinstance(b, int)) return w, b def propagate(w, b, X, Y): """ The cost function and its gradient for the propagation Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples) Return: cost -- negative log-likelihood cost for logistic regression dw -- gradient of the loss function with respect to w, thus same shape as w db -- gradient of the loss function with respect to b, thus same shape as b """ m = X.shape[1] # FORWARD PROPAGATION (FROM X TO COST) #Activation of the unit A = sigmoid((np.dot(w,X)) + b) # compute activation yloga = np.dot(np.log(A),Y.T) negyloga = np.dot(np.log(1-A),(1-Y.T)) cost = (-1)*(1 / m)*(yloga + negyloga) # compute cost # BACKWARD PROPAGATION (TO FIND GRAD) dz = A - Y dw = (1 / m)*np.dot(dz,X.T) db = (1 / m)*np.sum(dz) assert(dw.shape == w.shape) assert(db.dtype == float) cost = np.squeeze(cost) assert(cost.shape == ()) grads = {"dw": dw, "db": db} return grads, cost def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (1,num_px * num_px * 3) b -- bias, a scalar X -- data of shape (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples) num_iterations -- number of iterations of the optimization loop learning_rate -- learning rate of the gradient descent update rule print_cost -- True to print the loss every 100 steps Returns: params -- dictionary containing the weights w and bias b grads -- dictionary containing the gradients of the weights and bias with respect to the cost function costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve. """ costs = [] for i in range(num_iterations): #Cost and gradient calculation grads, cost = propagate(w,b,X,Y) # Retrieve derivatives from grads dw = grads["dw"] db = grads["db"] # update rule w = w - (learning_rate * dw) b = b - (learning_rate * db) # Record the costs if i % 100 == 0: costs.append(cost) # Printing the cost every 100 training examples if print_cost and i % 100 == 0: print ("Cost after iteration %i: %f" %(i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs def predict(w, b, X): ''' Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b) Arguments: w -- weights, a numpy array of size (1, num_px * num_px * 3) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Returns: Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X ''' m = X.shape[1] Y_prediction = np.zeros((1,m)) w = w.reshape(X.shape[0], 1) # Computed vector "A" predicting the probabilities of a cat being present in the picture A = sigmoid(np.dot(w.T,X) + b) for i in range(A.shape[1]): # Convert probabilities A[0,i] to actual predictions p[0,i] if (A[0,i] > 0.5): Y_prediction[0,i] = 1 else: Y_prediction[0,i] = 0 assert(Y_prediction.shape == (1, m)) return Y_prediction def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False): """ Builds the logistic regression model by calling the function we've implemented previously Arguments: X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train) Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train) X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test) Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test) num_iterations -- hyperparameter representing the number of iterations to optimize the parameters learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize() print_cost -- Set to true to print the cost every 100 iterations Returns: d -- dictionary containing information about the model. """ # initialize parameters with zeros w, b = initialize_with_zeros(X_train.shape[0]) # Gradient descent parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) # Retrieve parameters w and b from dictionary "parameters" w = parameters["w"] b = parameters["b"] # Predict test/train set examples Y_prediction_test = predict(w, b, X_test) Y_prediction_train = predict(w, b, X_train) # Print train/test Errors print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) d = {"costs": costs, "Y_prediction_test": Y_prediction_test, "Y_prediction_train" : Y_prediction_train, "w" : w, "b" : b, "learning_rate" : learning_rate, "num_iterations": num_iterations} return d d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True) # Plot learning curve (with costs) costs = np.squeeze(d['costs']) plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(d["learning_rate"])) plt.show() def prediction_example(): # Example of a picture that was wrongly classified. index = 1 plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3))) print ("y = " + str(test_set_y[0,index])) print(d["Y_prediction_test"][0,index]) print(", you predicted that it is a \"" + classes[int(d["Y_prediction_test"][0,index])].decode("utf-8") + "\" picture.") def try_different_learning_rates(): learning_rates = [0.01, 0.001, 0.0001] models = {} for i in learning_rates: print ("learning rate is: " + str(i)) models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False) print ('\n' + "-------------------------------------------------------" + '\n') for i in learning_rates: plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"])) plt.ylabel('cost') plt.xlabel('iterations') legend = plt.legend(loc='upper center', shadow=True) frame = legend.get_frame() frame.set_facecolor('0.90') plt.show() def try_custom_image_prediction(): #Custom image my_image = "cow1.jpeg" # change this to the name of your image file fname = "../images/" + my_image image = np.array(scipy.misc.imread(fname, flatten=False)) my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T my_image = my_image/255 my_predicted_image = predict(d["w"], d["b"], my_image) plt.imshow(image) print("y = " + str(np.squeeze(my_predicted_image)) + ", algorithm predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.") try_custom_image_prediction()
mit
alimanfoo/numcodecs
docs/conf.py
10126
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # numcodecs documentation build configuration file, created by # sphinx-quickstart on Mon May 2 21:40:09 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os from mock import Mock as MagicMock PY2 = sys.version_info[0] == 2 class Mock(MagicMock): @classmethod def __getattr__(cls, name): return Mock() MOCK_MODULES = ['msgpack'] if PY2: MOCK_MODULES.append('lzma') sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(os.path.abspath('..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.viewcode', 'numpydoc', 'sphinx_issues', ] numpydoc_show_class_members = False numpydoc_class_members_toctree = False issues_github_path = 'zarr-developers/numcodecs' # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'numcodecs' copyright = '2016, Alistair Miles' author = 'Alistair Miles' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. import numcodecs version = numcodecs.__version__ # The full version, including alpha/beta/rc tags. release = numcodecs.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. #html_title = 'numcodecs v@@' # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. #html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'numcodecsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'numcodecs.tex', 'numcodecs Documentation', 'Alistair Miles', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'numcodecs', 'numcodecs Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'numcodecs', 'numcodecs Documentation', author, 'numcodecs', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None}
mit
MirkoPizii/eat-n-drink
App/eatndrink/src/app/app.module.ts
3121
import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { EventlistPage } from "../pages/eventlist/eventlist"; import { MyeventPage } from "../pages/myevent/myevent"; import { CreateeventPage } from "../pages/createevent/createevent"; import { AngularFireModule } from "angularfire2"; import { AngularFireDatabaseModule } from "angularfire2/database"; import { AngularFireAuth } from "angularfire2/auth" import { Http, HttpModule } from '@angular/http'; import { IonicStorageModule } from "@ionic/storage"; import { Geolocation } from '@ionic-native/geolocation'; import { SearchPage } from "../pages/search/search"; import { SearchlistPage } from "../pages/searchlist/searchlist"; import { EventdetailsPage } from "../pages/eventdetails/eventdetails"; import { ShoweventPage } from "../pages/showevent/showevent"; import { AttendeeventPage } from "../pages/attendeevent/attendeevent"; import { LooparrayPipe } from '../pipes/looparray/looparray'; import { FeedbackPage } from "../pages/feedback/feedback"; import { InAppBrowser } from "@ionic-native/in-app-browser"; import { TranslateLoader, TranslateModule } from "@ngx-translate/core"; import { TranslateHttpLoader } from "@ngx-translate/http-loader"; import { EventPage } from "../pages/event/event"; export const firebaseConfig = { apiKey: "API_KEY", authDomain: "AUTH_DOMAIN", databaseURL: "DATABASE_URL", projectId: "PROJECT_ID", storageBucket: "STORAGE_BUCKET", messagingSenderId: "MESSAGING_SENDER_ID" }; export var global = { 'API_URL': 'https://API_URL/' }; export function createTranslateLoader(http: Http) { return new TranslateHttpLoader(http, './assets/i18n/', '.json'); } @NgModule({ declarations: [ MyApp, HomePage, EventlistPage, MyeventPage, CreateeventPage, SearchPage, SearchlistPage, EventdetailsPage, ShoweventPage, AttendeeventPage, LooparrayPipe, FeedbackPage, ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), IonicStorageModule.forRoot(), TranslateModule.forRoot(), AngularFireModule.initializeApp(firebaseConfig), AngularFireDatabaseModule, HttpModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: (createTranslateLoader), deps: [Http] } }), ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage, EventlistPage, MyeventPage, CreateeventPage, SearchPage, SearchlistPage, EventdetailsPage, ShoweventPage, AttendeeventPage, FeedbackPage, ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, AngularFireAuth, IonicStorageModule, Geolocation, InAppBrowser, ] }) export class AppModule {}
mit
jaryway/api
Api.Lanxin/Logging/LoggerFactory.cs
1214
 using Api.Lanxin.Logging.Null; namespace Api.Lanxin.Logging { /// <summary> /// /// </summary> public static class LoggerFactory { private static ILoggerFactoryAdapter _loggerFactoryAdapter; /// <summary> /// /// </summary> /// <param name="loggerFactoryAdapter"></param> public static void InitializeLogFactory(ILoggerFactoryAdapter loggerFactoryAdapter) { _loggerFactoryAdapter = loggerFactoryAdapter; } /// <summary> /// 获取logger /// </summary> /// <returns>/</returns> public static ILogger GetLogger() { return LoggerFactory.GetLogger("logger"); } /// <summary> /// 依据LoggerName获取 /// </summary> /// <param name="loggerName">日志名称(例如:log4net的logger配置名称)</param> /// <returns>/</returns> public static ILogger GetLogger(string loggerName) { if (_loggerFactoryAdapter == null) _loggerFactoryAdapter = new NullLoggerFactoryAdapter(); return _loggerFactoryAdapter.GetLogger(loggerName); } } }
mit
Xeltor/ovale
dist/AzeriteEssence.lua
4004
local __exports = LibStub:NewLibrary("ovale/AzeriteEssence", 80300) if not __exports then return end local __class = LibStub:GetLibrary("tslib").newClass local aceEvent = LibStub:GetLibrary("AceEvent-3.0", true) local pairs = pairs local tostring = tostring local ipairs = ipairs local sort = table.sort local insert = table.insert local concat = table.concat local C_AzeriteEssence = C_AzeriteEssence __exports.OvaleAzeriteEssenceClass = __class(nil, { constructor = function(self, ovale, ovaleDebug) self.self_essences = {} self.debugOptions = { azeraitessences = { name = "Azerite essences", type = "group", args = { azeraitessences = { name = "Azerite essences", type = "input", multiline = 25, width = "full", get = function(info) return self:DebugEssences() end } } } } self.OnInitialize = function() self.module:RegisterEvent("AZERITE_ESSENCE_CHANGED", self.UpdateEssences) self.module:RegisterEvent("AZERITE_ESSENCE_UPDATE", self.UpdateEssences) self.module:RegisterEvent("PLAYER_ENTERING_WORLD", self.UpdateEssences) end self.OnDisable = function() self.module:UnregisterEvent("AZERITE_ESSENCE_CHANGED") self.module:UnregisterEvent("AZERITE_ESSENCE_UPDATE") self.module:UnregisterEvent("PLAYER_ENTERING_WORLD") end self.UpdateEssences = function(e) self.tracer:Debug("UpdateEssences after event %s", e) self.self_essences = {} for _, mileStoneInfo in pairs(C_AzeriteEssence.GetMilestones() or {}) do if mileStoneInfo.ID and mileStoneInfo.unlocked and mileStoneInfo.slot ~= nil then local essenceId = C_AzeriteEssence.GetMilestoneEssence(mileStoneInfo.ID) if essenceId then local essenceInfo = C_AzeriteEssence.GetEssenceInfo(essenceId) local essenceData = { ID = essenceId, name = essenceInfo.name, rank = essenceInfo.rank, slot = mileStoneInfo.slot } self.self_essences[essenceId] = essenceData self.tracer:Debug("Found essence {ID: %d, name: %s, rank: %d, slot: %d}", essenceData.ID, essenceData.name, essenceData.rank, essenceData.slot) end end end end self.module = ovale:createModule("OvaleAzeriteEssence", self.OnInitialize, self.OnDisable, aceEvent) self.tracer = ovaleDebug:create("OvaleAzeriteEssence") for k, v in pairs(self.debugOptions) do ovaleDebug.defaultOptions.args[k] = v end end, IsMajorEssence = function(self, essenceId) local essence = self.self_essences[essenceId] if essence then return essence.slot == 0 and true or false end return false end, IsMinorEssence = function(self, essenceId) return self.self_essences[essenceId] ~= nil and true or false end, EssenceRank = function(self, essenceId) local essence = self.self_essences[essenceId] return essence ~= nil and essence.rank or 0 end, DebugEssences = function(self) local output = {} local array = {} for k, v in pairs(self.self_essences) do insert(array, tostring(v.name) .. ": " .. tostring(k) .. " (slot:" .. v.slot .. " | rank:" .. v.rank .. ")") end sort(array) for _, v in ipairs(array) do output[#output + 1] = v end return concat(output, "\n") end, })
mit
raincityrockcamp/ladydude
resources/lang/en/passwords.php
1081
<?php /** * Password Reset Translations * * PHP version 5.6.3 * * @category Translations * @package Resources\Lang\En * @author Taylor Otwell <[email protected]> * @license http://opensource.org/licenses/MIT MIT License * @link https://laravel.com/docs Laravel Documentation */ return [ /* |-------------------------------------------------------------------------- | Password Reset Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | has failed, such as for an invalid token or invalid new password. | */ 'password' => 'Passwords must be at least six characters and match the confirmation.', 'reset' => 'Your password has been reset!', 'sent' => 'We have e-mailed your password reset link!', 'token' => 'This password reset token is invalid.', 'user' => "We can't find a user with that e-mail address.", ];
mit
vixriihi/Ilmari
src/app/model/Property.ts
1515
/** * API documentation * To use this api you need an access token. To get the token, send a post request with your email address to api-users resource and one will be send to your. See below for information on how to use this api and if you have any questions you can contact us at [email protected]. Place refer to [schema.laji.fi](http://schema.laji.fi/) for more information about the used vocabulary * * OpenAPI spec version: 0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ export interface Property { /** * property name */ property?: string; /** * short property name */ shortName?: string; /** * label for the property */ label?: string; /** * comment for the property */ comment?: string; range: Array<string>; domain: Array<string>; /** * min occurrence */ minOccurs?: string; /** * max occurrence */ maxOccurs?: string; /** * is required (interpreted from occurrence fields) */ required?: boolean; /** * is an array (interpreted from occurrence fields) */ hasMany?: boolean; /** * has multiple languages */ multiLang?: boolean; /** * range object can be embedded */ embedded?: boolean; /** * Property position in the class */ sortOrder?: number; }
mit
Pmovil/CN1WindowsPort
src/java/nio/charset/Charset_2.cs
1381
// Automatically generated by xmlvm2csharp (do not edit). using org.xmlvm; namespace java.nio.charset { public class Charset_22: global::java.lang.Object,global::java.security.PrivilegedAction { private global::java.lang.Thread _fval_2t; public void @this(global::java.lang.Thread n1){ //XMLVM_BEGIN_WRAPPER[java.nio.charset.Charset$2: void <init>(java.lang.Thread)] global::System.Object _r0_o = null; global::System.Object _r1_o = null; _r0_o = this; _r1_o = n1; ((global::java.nio.charset.Charset_22) _r0_o)._fval_2t = (global::java.lang.Thread) _r1_o; ((global::java.lang.Object) _r0_o).@this(); return; //XMLVM_END_WRAPPER[java.nio.charset.Charset$2: void <init>(java.lang.Thread)] } public virtual global::System.Object run(){ //XMLVM_BEGIN_WRAPPER[java.nio.charset.Charset$2: java.lang.ClassLoader run()] global::System.Object _r0_o = null; global::System.Object _r1_o = null; _r1_o = this; _r0_o = ((global::java.nio.charset.Charset_22) _r1_o)._fval_2t; _r0_o = ((global::java.lang.Thread) _r0_o).getContextClassLoader(); return (global::java.lang.ClassLoader) _r0_o; //XMLVM_END_WRAPPER[java.nio.charset.Charset$2: java.lang.ClassLoader run()] } //XMLVM_BEGIN_WRAPPER[java.nio.charset.Charset$2] //XMLVM_END_WRAPPER[java.nio.charset.Charset$2] } // end of class: Charset_22 } // end of namespace: java.nio.charset
mit
o2system/html
src/Element/TextContent.php
1377
<?php /** * This file is part of the O2System Framework package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ // ------------------------------------------------------------------------ namespace O2System\Html\Element; // ------------------------------------------------------------------------ use O2System\Spl\Iterators\ArrayIterator; /** * Class TextContent * * @package O2System\Html\Element */ class TextContent extends ArrayIterator { /** * TextContent::replace * * @param string $value * * @return array */ public function replace($value) { return $this->exchangeArray([ $value, ]); } // ------------------------------------------------------------------------ /** * TextContent::item * * @param string $index * * @return mixed */ public function item($index) { return $this->offsetGet($index); } // ------------------------------------------------------------------------ /** * TextContent::prepend * * @param string $value */ public function prepend($value) { parent::unshift($value); } }
mit
andrei-shabanski/grab-screen
grab_screen/exceptions.py
342
class Error(Exception): default_message = "Oops, something went wrong" def __init__(self, message=None): super(Error, self).__init__(message) self.message = message or self.default_message def __str__(self): return self.message class ScreenError(Error): pass class StorageError(Error): pass
mit
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2018-12-01/generated/azure_mgmt_network/models/vpn_client_parameters.rb
3214
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2018_12_01 module Models # # Vpn Client Parameters for package generation # class VpnClientParameters include MsRestAzure # @return [ProcessorArchitecture] VPN client Processor Architecture. # Possible values are: 'AMD64' and 'X86'. Possible values include: # 'Amd64', 'X86' attr_accessor :processor_architecture # @return [AuthenticationMethod] VPN client Authentication Method. # Possible values are: 'EAPTLS' and 'EAPMSCHAPv2'. Possible values # include: 'EAPTLS', 'EAPMSCHAPv2' attr_accessor :authentication_method # @return [String] The public certificate data for the radius server # authentication certificate as a Base-64 encoded string. Required only # if external radius authentication has been configured with EAPTLS # authentication. attr_accessor :radius_server_auth_certificate # @return [Array<String>] A list of client root certificates public # certificate data encoded as Base-64 strings. Optional parameter for # external radius based authentication with EAPTLS. attr_accessor :client_root_certificates # # Mapper for VpnClientParameters class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'VpnClientParameters', type: { name: 'Composite', class_name: 'VpnClientParameters', model_properties: { processor_architecture: { client_side_validation: true, required: false, serialized_name: 'processorArchitecture', type: { name: 'String' } }, authentication_method: { client_side_validation: true, required: false, serialized_name: 'authenticationMethod', type: { name: 'String' } }, radius_server_auth_certificate: { client_side_validation: true, required: false, serialized_name: 'radiusServerAuthCertificate', type: { name: 'String' } }, client_root_certificates: { client_side_validation: true, required: false, serialized_name: 'clientRootCertificates', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } } } } } end end end end
mit
teoreteetik/api-snippets
rest/sip-in/delete-credential-list-mapping/delete-credential-list-mapping.3.x.js
624
// Download the Node helper library from twilio.com/docs/node/install // These consts are your accountSid and authToken from https://www.twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); client.sip .domains('SD32a3c49700934481addd5ce1659f04d2') .credentialListMappings('CL32a3c49700934481addd5ce1659f04d2') .remove() .then(data => { console.log('Sid IP32a3c49700934481addd5ce1659f04d2 deleted successfully.'); }) .catch(err => { console.log(err.status); throw err.message; });
mit
forstermatth/LIIS
refman/search/variables_63.js
118
var searchData= [ ['css',['CSS',['../constants_8php.html#ad3c2e05f38fee8ac8cdc370fd4c84941',1,'constants.php']]] ];
mit
binarymax/datatype
datatype.js
3183
var exports = module.exports = {}; // -------------------------------------------------------------------------- // DataType definitions. Used for validation and casting var DataType = function(name,definition,validate,cast) { var self = this; self.name = name; self.definition = definition; self.validate = validate||function(val){return true;}; self.cast = cast||function(val){return val;}; exports[name] = function(description,required) { return new DataTypeClass(self,description,required); }; }; var DataTypeClass = function(datatype,description,required,defaultvalue) { var self = this; self.type = datatype.name; self.cast = datatype.cast; self.validate = datatype.validate; self.definition = datatype.definition; self.description = description||datatype.type; self.required = required?true:false; self.defaultvalue = defaultvalue||null; Object.defineProperty(self,"istype",{get:function(){return true;}}); }; // -------------------------------------------------------------------------- // Extended DataType creation method // params: // @datatype - the type object to create. Properties: // - "name" - the name of the datatype (required) // - "definition" - the textual definition (optional) // - "validate" - the validation function (optional) // - "cast" - the type casting function (optional) // - "defaultvalue" - the default value to set (optional) var type = function(datatype) { var type_not_found = "ERROR - A datatype was not provided"; if(!datatype) throw new Error(type_not_found); var type_name_not_valid = "ERROR - The datatype does not have a valid name"; if(typeof datatype.name !== 'string') throw new Error(type_name_not_valid); var type_exists = "ERROR - The datatype '"+datatype.name+"' already exists"; if(exports[datatype.name]) throw new Error(type_exists); var definition = (typeof datatype.definition === 'string') ? datatype.definition : datatype.name; var validate = (typeof datatype.validate === 'function') ? datatype.validate : function(){return true;}; var cast = (typeof datatype.cast === 'function') ? datatype.cast : function(val){return val;}; new DataType(datatype.name, definition, validate, cast); }; // -------------------------------------------------------------------------- // Extended DataType creation method // params: // @datatypes - an array of type objects to create var add = exports.add = function(datatypes) { var types_not_found = "ERROR - An array of datatypes was not provided"; if (typeof datatypes !== 'object') throw new Error(types_not_found); if (datatypes instanceof Array) { datatypes.map(type); } else { type(datatypes); } }; // -------------------------------------------------------------------------- // Verifies if an object is a datatype // params: // @object - The object to check var isType = exports.isType = function(object) { return (object && object instanceof DataTypeClass) ? true : false; }; // ============================================================================= // Declare default datatypes add(require('./defaults').defaults);
mit
jsweiler/xaml-layout
simplecanvas/simplecanvas/MainWindow.xaml.cs
664
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace simplecanvas { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } }
mit
blackdogcoin/blackdogcoin
src/qt/locale/bitcoin_it.ts
119705
<?xml version="1.0" ?><!DOCTYPE TS><TS language="it" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About blackdogcoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;blackdogcoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The blackdogcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Questo è un software sperimentale. Distribuito sotto la licenza software MIT/X11, vedi il file COPYING incluso oppure su http://www.opensource.org/licenses/mit-license.php. Questo prodotto include software sviluppato dal progetto OpenSSL per l&apos;uso del Toolkit OpenSSL (http://www.openssl.org/), software crittografico scritto da Eric Young ([email protected]) e software UPnP scritto da Thomas Bernard.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Fai doppio click per modificare o cancellare l&apos;etichetta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Crea un nuovo indirizzo</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia l&apos;indirizzo attualmente selezionato nella clipboard</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your blackdogcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>&amp;Copia l&apos;indirizzo</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a blackdogcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Cancella l&apos;indirizzo attualmente selezionato dalla lista</translation> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified blackdogcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Cancella</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Copia &amp;l&apos;etichetta</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Modifica</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Finestra passphrase</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Inserisci la passphrase</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nuova passphrase</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ripeti la passphrase</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Inserisci la passphrase per il portamonete.&lt;br/&gt;Per piacere usare unapassphrase di &lt;b&gt;10 o più caratteri casuali&lt;/b&gt;, o &lt;b&gt;otto o più parole&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Cifra il portamonete</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Sblocca il portamonete</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per decifrare il portamonete,</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decifra il portamonete</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Cambia la passphrase</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Inserisci la vecchia e la nuova passphrase per il portamonete.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Conferma la cifratura del portamonete</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Si è sicuri di voler cifrare il portamonete?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: qualsiasi backup del portafoglio effettuato precedentemente dovrebbe essere sostituito con il file del portafoglio criptato appena generato. Per ragioni di sicurezza, i backup precedenti del file del portafoglio non criptato diventeranno inservibili non appena si inizi ad usare il nuovo portafoglio criptato.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Attenzione: tasto Blocco maiuscole attivo.</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Portamonete cifrato</translation> </message> <message> <location line="-58"/> <source>blackdogcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Cifratura del portamonete fallita</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Cifratura del portamonete fallita a causa di un errore interno. Il portamonete non è stato cifrato.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Le passphrase inserite non corrispondono.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Sblocco del portamonete fallito</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La passphrase inserita per la decifrazione del portamonete è errata.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Decifrazione del portamonete fallita</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Passphrase del portamonete modificata con successo.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation>Firma il &amp;messaggio...</translation> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation>Sto sincronizzando con la rete...</translation> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation>&amp;Sintesi</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostra lo stato generale del portamonete</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transazioni</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Cerca nelle transazioni</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>&amp;Esci</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Chiudi applicazione</translation> </message> <message> <location line="+6"/> <source>Show information about blackdogcoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Informazioni su &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostra informazioni su Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opzioni...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifra il portamonete...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Portamonete...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambia la passphrase...</translation> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a blackdogcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for blackdogcoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>Backup portamonete in un&apos;altra locazione</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Cambia la passphrase per la cifratura del portamonete</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>Finestra &amp;Debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Apri la console di degugging e diagnostica</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Verifica messaggio...</translation> </message> <message> <location line="-202"/> <source>blackdogcoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+180"/> <source>&amp;About blackdogcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Mostra/Nascondi</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Impostazioni</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Aiuto</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation>Barra degli strumenti &quot;Tabs&quot;</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>blackdogcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to blackdogcoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About blackdogcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about blackdogcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Aggiornato</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>In aggiornamento...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Transazione inviata</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Transazione ricevuta</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantità: %2 Tipo: %3 Indirizzo: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid blackdogcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;sbloccato&lt;/b&gt;</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;bloccato&lt;/b&gt;</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation><numerusform>%n ora</numerusform><numerusform>%n ore</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n giorno</numerusform><numerusform>%n giorni</numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. blackdogcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>Avviso di rete</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>Quantità:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Byte:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>Priorità:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Commissione:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Low Output:</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation>no</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>Dopo Commissione:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation>Resto:</translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation>(de)seleziona tutto</translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>Modalità Albero</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>Modalità Lista</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>Conferme:</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Confermato</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>Priorità</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Copia l&apos;indirizzo</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia l&apos;etichetta</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Copia l&apos;ID transazione</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>Copia quantità</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>Copia commissione</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Copia dopo commissione</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Copia byte</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Copia priorità</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Copia low output</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Copia resto</translation> </message> <message> <location line="+317"/> <source>highest</source> <translation>massima</translation> </message> <message> <location line="+1"/> <source>high</source> <translation>alta</translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation>medio-alta</translation> </message> <message> <location line="+1"/> <source>medium</source> <translation>media</translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation>medio-bassa</translation> </message> <message> <location line="+1"/> <source>low</source> <translation>bassa</translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation>infima</translation> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation>si</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>resto da %1 (%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation>(resto)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Modifica l&apos;indirizzo</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Indirizzo</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>Nuovo indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nuovo indirizzo d&apos;invio</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Modifica indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Modifica indirizzo d&apos;invio</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>L&apos;indirizzo inserito &quot;%1&quot; è già in rubrica.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid blackdogcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Impossibile sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Generazione della nuova chiave non riuscita.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>blackdogcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opzioni</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principale</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Paga la &amp;commissione</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start blackdogcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start blackdogcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>Rete</translation> </message> <message> <location line="+6"/> <source>Automatically open the blackdogcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mappa le porte tramite l&apos;&amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the blackdogcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP del proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta del proxy (es. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Version:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versione SOCKS del proxy (es. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Finestra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Mostra solo un&apos;icona nel tray quando si minimizza la finestra</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizza sul tray invece che sulla barra delle applicazioni</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Riduci ad icona, invece di uscire dall&apos;applicazione quando la finestra viene chiusa. Quando questa opzione è attivata, l&apos;applicazione verrà chiusa solo dopo aver selezionato Esci nel menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizza alla chiusura</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Mostra</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Lingua Interfaccia Utente:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting blackdogcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unità di misura degli importi in:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Scegli l&apos;unità di suddivisione predefinita per l&apos;interfaccia e per l&apos;invio di monete</translation> </message> <message> <location line="+9"/> <source>Whether to show blackdogcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Mostra gli indirizzi nella lista delle transazioni</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation>Mostrare/non mostrare le funzionalita&apos; di controllo della moneta.</translation> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancella</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>predefinito</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting blackdogcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>L&apos;indirizzo proxy che hai fornito è invalido.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Modulo</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the blackdogcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>Saldo spendibile attuale</translation> </message> <message> <location line="+71"/> <source>Immature:</source> <translation>Immaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Importo scavato che non è ancora maturato</translation> </message> <message> <location line="+20"/> <source>Total:</source> <translation>Totale:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Saldo totale attuale</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transazioni recenti&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>fuori sincrono</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nome del client</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation>N/D</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versione client</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informazione</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Versione OpenSSL in uso</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempo di avvio</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rete</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Numero connessioni</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Block chain</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Numero attuale di blocchi</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Numero totale stimato di blocchi</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Ora dell blocco piu recente</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Apri</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the blackdogcoin-Qt help message to get a list with possible blackdogcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data di creazione</translation> </message> <message> <location line="-104"/> <source>blackdogcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>blackdogcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>File log del Debug</translation> </message> <message> <location line="+7"/> <source>Open the blackdogcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Svuota console</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the blackdogcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Usa le frecce direzionali per navigare la cronologia, and &lt;b&gt;Ctrl-L&lt;/b&gt; per cancellarla.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scrivi &lt;b&gt;help&lt;/b&gt; per un riassunto dei comandi disponibili</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Spedisci Bitcoin</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation>Funzionalità di Coin Control</translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation>Input...</translation> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation>selezionato automaticamente</translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation>Fondi insufficienti!</translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>Quantità:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Byte:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 BTC</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation>Priorità:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>Commissione:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Low Output:</translation> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>Dopo Commissione:</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Spedisci a diversi beneficiari in una volta sola</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Aggiungi beneficiario</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+16"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Conferma la spedizione</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Spedisci</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a blackdogcoin address (e.g. blackdogcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>Copia quantità</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>Copia commissione</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Copia dopo commissione</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Copia byte</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Copia priorità</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Copia low output</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Copia resto</translation> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Conferma la spedizione di bitcoin</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>L&apos;indirizzo del beneficiario non è valido, per cortesia controlla.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>L&apos;importo da pagare dev&apos;essere maggiore di 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>L&apos;importo è superiore al saldo attuale</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Il totale è superiore al saldo attuale includendo la commissione %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Trovato un indirizzo doppio, si può spedire solo una volta a ciascun indirizzo in una singola operazione.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid blackdogcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Importo:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Paga &amp;a:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Inserisci un&apos;etichetta per questo indirizzo, per aggiungerlo nella rubrica</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. blackdogcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Incollare l&apos;indirizzo dagli appunti</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a blackdogcoin address (e.g. blackdogcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Firme - Firma / Verifica un messaggio</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Firma il messaggio</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Puoi firmare messeggi con i tuoi indirizzi per dimostrare che sono tuoi. Fai attenzione a non firmare niente di vago, visto che gli attacchi di phishing potrebbero cercare di spingerti a mettere la tua firma su di loro. Firma solo dichiarazioni completamente dettagliate con cui sei d&apos;accordo.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. blackdogcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Incollare l&apos;indirizzo dagli appunti</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Inserisci qui il messaggio che vuoi firmare</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Copia la firma corrente nella clipboard</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this blackdogcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Reimposta tutti i campi della firma</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Inserisci l&apos;indirizzo per la firma, il messaggio (verifica di copiare esattamente anche i ritorni a capo, gli spazi, le tabulazioni, etc) e la firma qui sotto, per verificare il messaggio. Verifica che il contenuto della firma non sia più grande di quello del messaggio per evitare attacchi di tipo man-in-the-middle.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. blackdogcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified blackdogcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Reimposta tutti i campi della verifica messaggio</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a blackdogcoin address (e.g. blackdogcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clicca &quot;Firma il messaggio&quot; per ottenere la firma</translation> </message> <message> <location line="+3"/> <source>Enter blackdogcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>L&apos;indirizzo inserito non è valido.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Per favore controlla l&apos;indirizzo e prova ancora</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>L&apos;indirizzo bitcoin inserito non è associato a nessuna chiave.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Sblocco del portafoglio annullato.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>La chiave privata per l&apos;indirizzo inserito non è disponibile.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Firma messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Messaggio firmato.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Non è stato possibile decodificare la firma.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Per favore controlla la firma e prova ancora.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>La firma non corrisponde al sunto del messaggio.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verifica messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Messaggio verificato.</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation>in conflitto</translation> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/non confermato</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 conferme</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Stato</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, trasmesso attraverso %n nodo</numerusform><numerusform>, trasmesso attraverso %n nodi</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Sorgente</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generato</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Da</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>A</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>proprio indirizzo</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etichetta</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura in %n ulteriore blocco</numerusform><numerusform>matura in altri %n blocchi</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>non accettate</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Commissione transazione</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Importo netto</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Messaggio</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Commento</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID della transazione</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informazione di debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transazione</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Input</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>vero</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, non è stato ancora trasmesso con successo</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>sconosciuto</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Dettagli sulla transazione</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Questo pannello mostra una descrizione dettagliata della transazione</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Confermato (%1 conferme)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation>Offline</translation> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation>Non confermato:</translation> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>In conferma (%1 di %2 conferme raccomandate)</translation> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation>In conflitto</translation> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Immaturo (%1 conferme, sarà disponibile fra %2)</translation> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Questo blocco non è stato ricevuto da altri nodi e probabilmente non sarà accettato!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generati, ma non accettati</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ricevuto da</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento a te stesso</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(N / a)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stato della transazione. Passare con il mouse su questo campo per vedere il numero di conferme.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e ora in cui la transazione è stata ricevuta.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo di transazione.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Indirizzo di destinazione della transazione.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Importo rimosso o aggiunto al saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Tutti</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Oggi</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Questa settimana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Questo mese</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Il mese scorso</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Quest&apos;anno</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervallo...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>A te</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Altro</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Inserisci un indirizzo o un&apos;etichetta da cercare</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Importo minimo</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copia l&apos;indirizzo</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copia l&apos;ID transazione</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Modifica l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostra i dettagli della transazione</translation> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confermato</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervallo:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>a</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>blackdogcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Utilizzo:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or blackdogcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Lista comandi </translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Aiuto su un comando </translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>Opzioni: </translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: blackdogcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: blackdogcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Specifica il file portafoglio (nella cartella dati)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specifica la cartella dati </translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Imposta la dimensione cache del database in megabyte (predefinita: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Mantieni al massimo &lt;n&gt; connessioni ai peer (predefinite: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Connessione ad un nodo per ricevere l&apos;indirizzo del peer, e disconnessione</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Specifica il tuo indirizzo pubblico</translation> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Soglia di disconnessione dei peer di cattiva qualità (predefinita: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numero di secondi di sospensione che i peer di cattiva qualità devono trascorrere prima di riconnettersi (predefiniti: 86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv4: %s</translation> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accetta da linea di comando e da comandi JSON-RPC </translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>Esegui in background come demone e accetta i comandi </translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Utilizza la rete di prova </translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accetta connessioni dall&apos;esterno (predefinito: 1 se no -proxy o -connect)</translation> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv6, tornando su IPv4: %s</translation> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Attenzione: -paytxfee è molto alta. Questa è la commissione che si paga quando si invia una transazione.</translation> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong blackdogcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Attenzione: errore di lettura di wallet.dat! Tutte le chiave lette correttamente, ma i dati delle transazioni o le voci in rubrica potrebbero mancare o non essere corretti.</translation> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Attenzione: wallet.dat corrotto, dati salvati! Il wallet.dat originale salvato come wallet.{timestamp}.bak in %s; se il tuo bilancio o le transazioni non sono corrette dovresti ripristinare da un backup.</translation> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tenta di recuperare le chiavi private da un wallet.dat corrotto</translation> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>Opzioni creazione blocco:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>Connetti solo al nodo specificato</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Scopri proprio indirizzo IP (predefinito: 1 se in ascolto e no -externalip)</translation> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Impossibile mettersi in ascolto su una porta. Usa -listen=0 se vuoi usare questa opzione.</translation> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Buffer di ricezione massimo per connessione, &lt;n&gt;*1000 byte (predefinito: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Buffer di invio massimo per connessione, &lt;n&gt;*1000 byte (predefinito: 1000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Connetti solo a nodi nella rete &lt;net&gt; (IPv4, IPv6 o Tor)</translation> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>Opzioni SSL: (vedi il wiki di Bitcoin per le istruzioni di configurazione SSL)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Invia le informazioni di trace/debug alla console invece che al file debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Imposta dimensione minima del blocco in bytes (predefinita: 0)</translation> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Riduci il file debug.log all&apos;avvio del client (predefinito: 1 se non impostato -debug)</translation> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specifica il timeout di connessione in millisecondi (predefinito: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Usa UPnP per mappare la porta in ascolto (predefinito: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usa UPnP per mappare la porta in ascolto (predefinito: 1 when listening)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>Nome utente per connessioni JSON-RPC </translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Attenzione: questa versione è obsoleta, aggiornamento necessario!</translation> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrotto, salvataggio fallito</translation> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>Password per connessioni JSON-RPC </translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=blackdogcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;blackdogcoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Consenti connessioni JSON-RPC dall&apos;indirizzo IP specificato </translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Inviare comandi al nodo in esecuzione su &lt;ip&gt; (predefinito: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Esegui il comando quando il miglior block cambia(%s nel cmd è sostituito dall&apos;hash del blocco)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Esegui comando quando una transazione del portafoglio cambia (%s in cmd è sostituito da TxID)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Aggiorna il wallet all&apos;ultimo formato</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Impostare la quantità di chiavi di riserva a &lt;n&gt; (predefinita: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ripeti analisi della catena dei blocchi per cercare le transazioni mancanti dal portamonete </translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utilizzare OpenSSL (https) per le connessioni JSON-RPC </translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>File certificato del server (predefinito: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chiave privata del server (predefinito: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation>Questo messaggio di aiuto </translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. blackdogcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>blackdogcoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Impossibile collegarsi alla %s su questo computer (bind returned error %d, %s)</translation> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Consenti ricerche DNS per aggiungere nodi e collegare </translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Caricamento indirizzi...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Errore caricamento wallet.dat: Wallet corrotto</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of blackdogcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart blackdogcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Errore caricamento wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Indirizzo -proxy non valido: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rete sconosciuta specificata in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Versione -socks proxy sconosciuta richiesta: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Impossibile risolvere -bind address: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Impossibile risolvere indirizzo -externalip: &apos;%s&apos;</translation> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Importo non valido per -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Importo non valido</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Fondi insufficienti</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Caricamento dell&apos;indice del blocco...</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Elérendő csomópont megadása and attempt to keep the connection open</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. blackdogcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Caricamento portamonete...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Non è possibile retrocedere il wallet</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Non è possibile scrivere l&apos;indirizzo predefinito</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Ripetere la scansione...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Caricamento completato</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>Per usare la opzione %s</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>Errore</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Devi settare rpcpassword=&lt;password&gt; nel file di configurazione: %s Se il file non esiste, crealo con i permessi di amministratore</translation> </message> </context> </TS>
mit
sosedoff/net-ssh-session
lib/net/ssh/shell/subshell.rb
502
require 'net/ssh/shell/process' module Net; module SSH; class Shell class Subshell < Process protected def on_stdout(ch, data) if !output!(data) ch.on_data(&method(:look_for_finalize_initializer)) ch.send_data("export PS1=; echo #{manager.separator} $?\n") end end def look_for_finalize_initializer(ch, data) if data =~ /#{manager.separator} (\d+)/ ch.on_close(&@master_onclose) finished!($1) end end end end; end; end
mit
cuckata23/wurfl-data
data/samsung_sgh_s730g_ver1_suban41schr740c.php
221
<?php return array ( 'id' => 'samsung_sgh_s730g_ver1_suban41schr740c', 'fallback' => 'samsung_sgh_s730g_ver1', 'capabilities' => array ( 'model_name' => 'SCH-R740C', 'device_os_version' => '4.1', ), );
mit
mattyhansen/symfony2-rest-api
tests/unit/Starter/Content/Provider/ContentProviderTest.php
2237
<?php class ContentProviderTest extends \PHPUnit_Framework_TestCase { protected function setUp() { } protected function tearDown() { } // tests public function testCanConstruct() { $repo = $this->getMockRepository(); $provider = $this->getProvider($repo); static::assertInstanceOf( '\Starter\Content\Provider\ContentProvider', $provider ); } public function testCanGetWithValidId() { $data = ['anything']; $repo = $this->getMockRepository(); $repo->expects(static::once()) ->method('find') ->will(static::returnValue($data)); $provider = $this->getProvider($repo); static::assertEquals( $data, $provider->get(1) ); } public function testCantGetWithInvalidId() { $repo = $this->getMockRepository(); $repo->expects(static::once()) ->method('find') ->will(static::returnValue(null)); $provider = $this->getProvider($repo); static::assertNull($provider->get(100000)); } public function testCanGetAll() { $data = [1,2]; $repo = $this->getMockRepository(); $repo->expects(static::once()) ->method('findBy') ->will(static::returnValue($data)); $provider = $this->getProvider($repo); static::assertEquals( $data, $provider->all(1, 1) ); } /** * @return PHPUnit_Framework_MockObject_MockObject */ private function getMockRepository() { $repo = $this->getMockBuilder('Starter\Content\Repository\ContentRepository') ->disableOriginalConstructor() ->getMock(); return $repo; } /** * @param $repo * @return \Starter\Content\Provider\ContentProvider */ private function getProvider($repo) { $handler = $this->getMockBuilder('Starter\AppBundle\Form\Handler\FormHandler') ->disableOriginalConstructor() ->getMock(); $provider = new \Starter\Content\Provider\ContentProvider($repo, $handler); return $provider; } }
mit
flychao4837/learnlaravel5
app/Models/test/Page.php
216
<?php namespace App\Models\test; use Illuminate\Database\Eloquent\Model; class Page extends Model { public function hasManyComments() { return $this->hasMany('App\Models\test\Comment', 'page_id', 'id'); } }
mit
spuz/kathik
textpattern/css.php
269
<?php /* @deprecated @see ../css.php $HeadURL: https://textpattern.googlecode.com/svn/releases/4.5.4/source/textpattern/css.php $ $LastChangedRevision: 3189 $ */ if (!defined("txpath")) { define("txpath", dirname(__FILE__)); } require_once txpath.'/../css.php'; ?>
mit
austinkregel/laravel-auth-login
src/resources/views/security/password.blade.php
2582
@extends(config('kregel.auth-login.base-layout')) @section('content') <div class="container"> <div class="row"> <div class="col-md-4"> @include('auth-login::shared.menu') </div> <div class="col-md-8"> <div class="panel panel-default" style="padding:1rem;"> <h2 style="margin-top:0;">Update Password</h2> <div class="panel-body"> <form class="form-horizontal" role="form" action="{{ route('auth-login::update-security') }}" method="post"> {!! method_field('put') !!} {!! csrf_field() !!} <div class="form-group"> <label class="col-md-4 control-label">Current Password</label> <div class="col-md-6"> <input type="password" class="form-control" name="old_password"> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">New Password</label> <div class="col-md-6"> <input type="password" class="form-control" name="password"> </div> </div><!--v-component--> <div class="form-group"> <label class="col-md-4 control-label">Confirm Password</label> <div class="col-md-6"> <input type="password" class="form-control" name="confirm_password"> </div> </div><!--v-component--> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary waves-effect waves-light"> <span> <i class="fa fa-btn fa-save"></i> Update </span> </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
mit
smartpension/signable
lib/signable/template.rb
291
module Signable class Template < Signable::Base column :id column :fingerprint column :title embed :parties def save raise "not available" end def update raise "not available" end def delete raise "not available" end end end
mit
guyellis/http-status-check
test/lib/outAdapters/test.emailAdapter.js
2916
'use strict'; var should = require('chai').should(); var rewire = require('rewire'); var outAdapter = rewire('../../../lib/outAdapters/emailAdapter'); describe('outAdapters/emailAdapter/', function() { describe('organizeErrors()', function () { it('should put object properties into an array', function (done) { var organizeErrors = outAdapter.__get__('organizeErrors'); var errors = { one: 'one', two: 'two' }; var result = organizeErrors(errors); should.exist(result); Array.isArray(result).should.equal(true); result.length.should.equal(2); done(); }); }); describe('organizeErrors()', function () { it('should put string into an array', function (done) { var organizeErrors = outAdapter.__get__('organizeErrors'); var errors = 'one'; var result = organizeErrors(errors); should.exist(result); Array.isArray(result).should.equal(true); result.length.should.equal(1); result[0].should.equal('one'); done(); }); }); describe('writeResult()', function () { it('should increment success counter when successful', function (done) { outAdapter.writeResult('success', {verbose: true}); //var failHits = outAdapter.__get__('failHits'); var successHits = outAdapter.__get__('successHits'); successHits.should.be.above(0); done(); }); }); describe('writeResult()', function () { it('should increment fail counter when unsuccessful', function (done) { outAdapter.writeResult('fail', {errors: 'some error'}); var failHits = outAdapter.__get__('failHits'); //var successHits = outAdapter.__get__('successHits'); failHits.should.be.above(0); done(); }); }); describe('writeResult()', function () { it('should increment disabled counter when url is disabled', function (done) { outAdapter.writeResult('disabled', {verbose: true}); var disableHits = outAdapter.__get__('disableHits'); disableHits.should.be.above(0); done(); }); }); describe('writeResult()', function () { it('should throw an exception if an unrecognized result type is passed', function (done) { var exceptionThrown = false; try { outAdapter.writeResult('unknown', {errors: 'some error'}); } catch (e) { exceptionThrown = true; } exceptionThrown.should.equal(true); done(); }); }); // Error: Unsupported configuration, downgrade Nodemailer to v0.7.1 to use it // describe('done()', function () { // it('should call console.log()', function (done) { // var logCallCount = 0; // outAdapter.__set__('console', { // log: function() { // logCallCount++; // } // }); // // outAdapter.done(); // logCallCount.should.equal(4); // done(); // }); // }); });
mit
billpatrianakos/coverage-web
server/controllers/agents.js
446
// Agents Controller // ================= // Responsible for routing and // business logic for agent signup. 'use strict'; var express = require('express'), AgentController = express.Router(), Agent = require(__dirname + '/../models/agent'); // RESTful Route / AgentController.route('/?') // GET / // ----- // Render all agents .get(function(req, res, next) { // }); module.exports = AgentController;
mit
CS2103AUG2016-W10-C3/main
src/test/java/seedu/address/testutil/TypicalTestTasks.java
3012
package seedu.address.testutil; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.ToDo; import seedu.address.model.task.*; /** * */ public class TypicalTestTasks { public static TestTask alice, benson, carl, daniel, elle, fiona, george, hoon, ida; public TypicalTestTasks() { try { alice = new TaskBuilder().withName("Alice Pauline").withAddress("123, Jurong West Ave 6, #08-111") .withDescription("alice's description").withTime("12-10-2016") .withTags("friends").build(); benson = new TaskBuilder().withName("Benson Meier").withAddress("311, Clementi Ave 2, #02-25") .withDescription("johnd's description").withTime("12-10-2016") .withTags("owesMoney", "friends").build(); carl = new TaskBuilder().withName("Carl Kurz").withTime("12-10-2016") .withDescription("heinz's description").withAddress("wall street").build(); daniel = new TaskBuilder().withName("Daniel Meier").withTime("12-10-2016") .withDescription("cornelia's description").withAddress("10th street").build(); elle = new TaskBuilder().withName("Elle Meyer").withTime("12-10-2016") .withDescription("werner's description").withAddress("michegan ave").build(); fiona = new TaskBuilder().withName("Fiona Kunz").withTime("12-10-2016") .withDescription("lydia's description").withAddress("little tokyo").build(); george = new TaskBuilder().withName("George Best").withTime("12-10-2016") .withDescription("anna's description").withAddress("4th street").build(); //Manually added hoon = new TaskBuilder().withName("Hoon Meier").withTime("12-10-2016").withDescription("stefan's description") .withAddress("little india").build(); ida = new TaskBuilder().withName("Ida Mueller").withTime("12-10-2016").withDescription("hans's description") .withAddress("chicago ave").build(); } catch (IllegalValueException e) { e.printStackTrace(); assert false : "not possible"; } } public static void loadToDoWithSampleData(ToDo ab) { try { ab.addTask(new Task(alice)); ab.addTask(new Task(benson)); ab.addTask(new Task(carl)); ab.addTask(new Task(daniel)); ab.addTask(new Task(elle)); ab.addTask(new Task(fiona)); ab.addTask(new Task(george)); } catch (UniqueTaskList.DuplicateTaskException e) { assert false : "not possible"; } } public TestTask[] getTypicalTask() { return new TestTask[]{alice, benson, carl, daniel, elle, fiona, george}; } public ToDo getTypicalToDo(){ ToDo ab = new ToDo(); loadToDoWithSampleData(ab); return ab; } }
mit
AliBrahem/AfrikIsol
src/Acme/DemoBundle/Controller/DemoController.php
1543
{% extends "FOSUserBundle::layout.html.twig" %} {% trans_default_domain 'FOSUserBundle' %} {% block fos_user_content %} {% if error %} <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div> {% endif %} <form action="{{ path("fos_user_security_check") }}" method="post"> <input type="hidden" name="_csrf_token" value="{{ csrf_token }}" /> <div class="form-group has-feedback"> <input type="text" id="username" class="form-control" name="_username" value="{{ last_username }}" required="required" /> <span class="glyphicon glyphicon-envelope form-control-feedback"></span> </div> <div class="form-group has-feedback"> <input type="password" id="password" class="form-control" placeholder="Password" name="_password" required="required" /> <span class="glyphicon glyphicon-lock form-control-feedback"></span> </div> <div class="row"> <div class="col-xs-8"> <div class="checkbox icheck"> <input type="checkbox" id="remember_me" name="_remember_me" value="on" /> <label for="remember_me">{{ 'security.login.remember_me'|trans }}</label> </div> </div><!-- /.col --> <div class="col-xs-4"> <button type="submit" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans }}" class="btn btn-primary btn-block btn-flat"/> </div><!-- /.col --> </div> </form> {% endblock fos_user_content %}
mit
dafrito/Sparks
js/Presenter.js
8005
// Sparks.Presenter Sparks.PresenterHierarchies = {}; Sparks.Presenters = {}; Sparks.get_presenter = function get_presenter(name) { if(name instanceof Array) { for(var i in name) { var presenter = Sparks.get_presenter(name[i]); if(presenter) return presenter; } return; } if(typeof name !== "string") return name; return Sparks.Presenters[name]; } Sparks.get_presenter_hierarchy = function get_presenter_hierarchy(name) { if(typeof name !== "string") return name; return Sparks.PresenterHierarchies[name]; } //Sparks.attach_presenter = function attach_presenter(that, presenter, dont_save) { Sparks.attach_presenter = function attach_presenter(that) { presenters = Sparks.get_args(arguments, 1); for(var i in presenters) { var parent = Sparks.get_presenter(presenters[i]); if(parent) break; } that.presenter = that.presenter || Sparks.presenter({parent:parent}); var presented, dont_save = false; that.output = function output(parent) { if(!dont_save && presented) { if(presented.fired && Sparks.get_parent(presented.result)) Sparks.remove_element(presented.result); return presented; } return presented = that.presenter.present_to_parent(that, MochiKit.DOM.getElement(parent)); } that.output_to_parent = function output_to_parent(parent) { return Sparks.append_child_nodes(parent, that); } that.output_to_placeholder = function output_to_placeholder(placeholder, creator) { if(!dont_save && presented && presented.placeholdered) { return Sparks.swap_dom(placeholder, presented); } else { var placeholder_parent = Sparks.get_parent(placeholder); var old = placeholder; if(placeholder_parent) { placeholder = creator ? creator(placeholder_parent) : Sparks.create_valid_child(placeholder_parent); } presented = that.presenter.present_to_placeholder(that, placeholder); Sparks.swap_dom(old, placeholder); return presented; } }; return that; } Sparks.working_or_child = function working_or_child(working) { return working || Sparks.create_valid_child(); } Sparks.is_presenter = Sparks.izzer("Presenter"); Sparks.presenter = function presenter(options) { if(typeof options === "string") options = {hierarchy:options}; options = options || {}; var that = Sparks.event_source("Presenter"); if(options.parent) { that.parent = options.parent; that.hierarchy = that.parent.hierarchy; } else { that.hierarchy = Sparks.get_presenter_hierarchy(options.hierarchy) || Sparks.PresenterHierarchies["NakedContent"]; } that.manual_append = options.manual_append; that.present_to_parent = function present_to_parent(item, parent) { return that.present_to_placeholder(item, Sparks.create_valid_child(parent)); } that.present_to_placeholder = function present_to_placeholder(item, placeholder) { var presented = Sparks.deferred(); Sparks.add_listener(item, function item_listener(item) { if(!Sparks.is_event_source(item)) return draw(item, placeholder).forward_to(presented); item.lock.acquire().add_listener(function lock_listener() { var drawing = draw(item, placeholder); drawing.forward_to(presented); drawing.add_finalizer(item.lock.release); }); }); return presented; } function draw(item, placeholder) { var drawing = Sparks.deferred({timer:true}); var predraw = Sparks.chain_results({values:that.get_predrawers(), initial:item}); predraw.add_listener(function predraw_listener() { item = arguments.length > 1 ? Sparks.get_args(arguments) : (arguments[0] || item); var original = item; item = Sparks.Tree.bounce({ node:that.hierarchy, original:item, action:coerce, validator:Sparks.operator.truth, working:placeholder }); item = Sparks.get_root(item); Sparks.map_call(that.get_postdrawers(), item, original); drawing.callback(item); }); predraw.forward_to(drawing, "errback"); return drawing; } function coerce(working, leaf_name, original) { var processor = that.get_processor(leaf_name) || default_processor; if(processor) var output = processor(working, original, leaf_name); if(!output) return; return process_element(output, working, original, leaf_name, that.get_post_processors(leaf_name)); } function process_element(output, working, original, leaf_name, post_processors) { if(output instanceof Array) { Sparks.map(output, function array_processor(elem) { process_element(elem, working, original, leaf_name, post_processors); }); return working; } output = Sparks.output(output, working); function post_process(output) { if(!that.manual_append && working && output !== working) { var out = Sparks.get_root(output, function validator(elem) { return elem !== working && !Sparks.is_ancestor(working, elem); }); if(out && out !== working) Sparks.construct_to_child(working, out); } for(var i in post_processors) { var post_processor = post_processors[i]; if(output instanceof Array) { for(var j in output) post_processor(output[j], working, original, name); } else { post_processor(output, working, original, name); } } }; Sparks.add_listener(output, post_process); return output; } // Getters and setters for pre- and post-drawers, processors, and post-processors. that.predrawers = options.predrawers ? Sparks.coerce_array(options.predrawers).slice() : []; that.postdrawers = options.postdrawers ? Sparks.coerce_array(options.postdrawers).slice() : []; var post_processors = {}; var processors = {}; var default_processor; that.set_processor = function set_processor(name) { return processors[name] = Sparks.obj_func.apply(null, Sparks.get_args(arguments, 1)); return function remover() { delete processors[name]; } } that.set_default_processor = function set_default_processor(name) { if(typeof name !== "string") return default_processor = Sparks.obj_func.apply(null, arguments); if(!processors[name]) processors[name] = Sparks.obj_func.apply(null, Sparks.get_args(arguments, 1)); } that.add_post_processor = function add_post_processor(name, post_processor) { if(typeof arguments[0] !== "string") { return that.add_post_processors_to( Sparks.operator.truth, Sparks.obj_func.apply(null, Sparks.get_args(arguments)) ); } post_processors[name] = post_processors[name] || []; var pos = post_processors[name].push( Sparks.obj_func.apply(null, Sparks.get_args(arguments, 1)) ); return function remover() { delete post_processors[name][pos - 1]; } } that.add_post_processors_to = function add_post_processors_to(tester) { var post_processor = Sparks.obj_func.apply(null, Sparks.get_args(arguments, 1)); tester = Sparks.string_tester(tester); var detachers = Sparks.map(that.hierarchy, function hierarchy_adder(name) { return tester(name) && that.add_post_processor(name, post_processor); }); return function remover() { while(detachers.length) (detachers.shift() || Sparks.noop)(); } } that.add_postdrawer = Sparks.listener_adder(that.postdrawers); that.add_predrawer = Sparks.listener_adder(that.predrawers); that.get_predrawers = function get_predrawers(name) { var predrawers = that.predrawers || []; if(that.parent) predrawers = predrawers.concat(that.parent.get_predrawers() || []); return predrawers; } that.get_postdrawers = function get_postdrawers(name) { var postdrawers = that.postdrawers || []; if(that.parent) postdrawers = postdrawers.concat(that.parent.get_postdrawers() || []); return postdrawers; } that.get_processor = function get_processor(name) { var processor = processors[name]; if(!processor && that.parent) return that.parent.get_processor(name); return processor; } that.get_post_processors = function get_post_processors(name) { var post_pxrs = post_processors[name] || []; if(that.parent) post_pxrs = post_pxrs.concat(that.parent.get_post_processors(name) || []); return post_pxrs; } return that; }
mit
omuleanu/ValueInjecter
ValueInjecter/InternalUtils.cs
868
using System; using System.Reflection; namespace Omu.ValueInjecter { internal static class InternalUtils { internal static PropertyInfo GetProperty(this Type type, string name) { return type.GetTypeInfo().GetProperty(name); } internal static MethodInfo GetMethod(this Type type, string name) { return type.GetTypeInfo().GetMethod(name); } internal static PropertyInfo[] GetProperties(this Type type, BindingFlags flags) { return type.GetTypeInfo().GetProperties(flags); } internal static Type[] GetInterfaces(this Type type) { return type.GetTypeInfo().GetInterfaces(); } internal static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } } }
mit
JasonSJ/LeetCode-js
Javascript/Pascal's Triangle.js
444
/** * @param {number} numRows * @return {number[][]} */ var generate = function(numRows) { var triangle = [], i, j; for(i = 0; i < numRows ; i++) { triangle[i] = []; for(j = 0; j <= parseInt(i/2); j++) { if(j === 0) { triangle[i][i-j] = triangle[i][j] = 1; } else { triangle[i][i-j] = triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]; } } } return triangle; };
mit
viblo/pymunk
pymunk/_pickle.py
1855
import copy from typing import Any, ClassVar, Dict, List, Tuple, TypeVar T = TypeVar("T", bound="PickleMixin") _State = Dict[str, List[Tuple[str, Any]]] class PickleMixin: """PickleMixin is used to provide base functionality for pickle/unpickle and copy. """ _pickle_attrs_init: ClassVar[List[str]] = [] _pickle_attrs_general: ClassVar[List[str]] = [] _pickle_attrs_skip: ClassVar[List[str]] = [] def __getstate__(self) -> _State: """Return the state of this object This method allows the usage of the :mod:`copy` and :mod:`pickle` modules with this class. """ d: _State = { "init": [], # arguments for init "general": [], # general attributes "custom": [], # custom attributes set by user "special": [], # attributes needing special handling } for a in type(self)._pickle_attrs_init: d["init"].append((a, self.__getattribute__(a))) for a in type(self)._pickle_attrs_general: d["general"].append((a, self.__getattribute__(a))) for k, v in self.__dict__.items(): if k[0] != "_": d["custom"].append((k, v)) return d def __setstate__(self, state: _State) -> None: """Unpack this object from a saved state. This method allows the usage of the :mod:`copy` and :mod:`pickle` modules with this class. """ init_attrs: List[str] = [] init_args = [v for k, v in state["init"]] self.__init__(*init_args) # type: ignore for k, v in state["general"]: self.__setattr__(k, v) for k, v in state["custom"]: self.__setattr__(k, v) def copy(self: T) -> T: """Create a deep copy of this object.""" return copy.deepcopy(self)
mit
banzai-inc/react-d3
tests/barchart-tests.js
1966
'use strict'; var expect = require('chai').expect; describe('BarChart', function() { it('renders barchart', function() { var React = require('react/addons'); var BarChart = require('../src/barchart').BarChart; var generate = require('./utils/datagen').generateArrayOfNumbers; var TestUtils = React.addons.TestUtils; // Render a barchart using array data var data = generate(5); var barchart = TestUtils.renderIntoDocument( <BarChart data={data} width={400} height={200} /> ); // Verify that it has rendered the main chart svg var barchartGroup = TestUtils.findRenderedDOMComponentWithClass( barchart, 'rd3-barchart'); expect(barchartGroup).to.exist; expect(barchartGroup.tagName).to.equal('G'); // Verify that it has the same number of bars as the array's length var bars = TestUtils.scryRenderedDOMComponentsWithTag( barchart, 'rect'); expect(bars.length).to.equal(data.length); }); it('renders barchart with negative values', function() { var React = require('react/addons'); var BarChart = require('../src/barchart').BarChart; var generate = require('./utils/datagen').generateArrayOfNumbers; var TestUtils = React.addons.TestUtils; // Render a barchart using array data var data = generate(5); // Set a few values to negative numbers data[1] = -100; data[3] = -150; var barchart = TestUtils.renderIntoDocument( <BarChart data={data} width={400} height={200} /> ); // Verify that it has rendered the main chart svg var barchartGroup = TestUtils.findRenderedDOMComponentWithClass( barchart, 'rd3-barchart'); expect(barchartGroup).to.exist; expect(barchartGroup.tagName).to.equal('G'); // Verify that it has the same number of bars as the array's length var bars = TestUtils.scryRenderedDOMComponentsWithTag( barchart, 'rect'); expect(bars.length).to.equal(data.length); }); });
mit