repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
SubZero0/DiscordNet-Docs
src/DiscordNet/Query/Wrappers/MethodInfoWrapper.cs
481
using System.Reflection; namespace DiscordNet.Query { public class MethodInfoWrapper : BaseInfoWrapper { public MethodInfo Method { get; private set; } public TypeInfoWrapper Parent { get; private set; } public string Namespace { get { return Parent.Namespace; } } public MethodInfoWrapper(TypeInfoWrapper parent, MethodInfo method) { Parent = parent; Method = method; } } }
gpl-3.0
sonald/sos2
src/lib.rs
6801
#![feature(lang_items)] #![feature(global_allocator)] #![feature(allocator_api)] #![feature(const_fn)] #![feature(unique)] #![feature(asm)] #![feature(range_contains)] #![feature(alloc, collections)] #![feature(naked_functions)] #![feature(core_intrinsics)] #![feature(core_slice_ext)] // stabled since 1.17 #![feature(field_init_shorthand)] #![feature(drop_types_in_const)] #![no_std] extern crate rlibc; extern crate multiboot2; extern crate spin; extern crate x86_64; extern crate kheap_allocator; extern crate alloc; #[macro_use] extern crate collections; #[macro_use] extern crate bitflags; extern crate bit_field; #[macro_use] extern crate lazy_static; #[macro_use] mod kern; // make syscall_dispatch exported pub use kern::syscall_dispatch; use kern::console as con; use con::Console; use con::LogLevel::*; use kern::driver::serial; use kern::memory; use kern::interrupts; use kheap_allocator as kheap; use kern::driver::video::{Framebuffer, Point, Rgba}; use kern::task; use kern::syscall; #[global_allocator] static GLOBAL_ALLOCATOR: kheap::Allocator = kheap::Allocator; #[allow(dead_code)] fn busy_wait () { for _ in 1..500000 { kern::util::cpu_relax(); } } /// test rgb framebuffer drawing fn display(fb: &mut Framebuffer) { let w = fb.width as i32; let h = fb.height as i32; for g in 0..1 { fb.fill_rect_grad(Point{x:0, y: 0}, w, h, Rgba(0x0000ff00), Rgba(255<<16)); fb.draw_line(Point{x: 530, y: 120}, Point{x: 330, y: 10}, Rgba(0xeeeeeeee)); fb.draw_line(Point{x: 330, y: 120}, Point{x: 530, y: 10}, Rgba(0xeeeeeeee)); fb.draw_line(Point{x: 300, y: 10}, Point{x: 500, y: 100}, Rgba(0xeeeeeeee)); fb.draw_line(Point{x: 300, y: 10}, Point{x: 400, y: 220}, Rgba(0xeeeeeeee)); fb.draw_line(Point{x: 100, y: 220}, Point{x: 300, y: 100}, Rgba(0xeeeeeeee)); fb.draw_line(Point{x: 100, y: 220}, Point{x: 300, y: 10}, Rgba(0xeeeeeeee)); for r in (100..150).filter(|x| x % 5 == 0) { fb.draw_circle(Point{x: 200, y: 200}, r, Rgba::from(0, g as u8, 0xff)); } fb.spread_circle(Point{x: 400, y: 100}, 90, Rgba::from(0, g as u8, 0xee)); fb.draw_rect(Point{x:199, y: 199}, 202, 102, Rgba::from(0x00, g as u8, 0xff)); fb.fill_rect(Point{x:200, y: 200}, 200, 100, Rgba::from(0x80, g as u8, 0x80)); fb.draw_rect(Point{x:199, y: 309}, 302, 102, Rgba::from(0x00, g as u8, 0xff)); fb.fill_rect(Point{x:200, y: 310}, 300, 100, Rgba::from(0xa0, g as u8, 0x80)); fb.draw_rect(Point{x:199, y: 419}, 392, 102, Rgba::from(0x00, g as u8, 0xff)); fb.fill_rect(Point{x:200, y: 420}, 390, 100, Rgba::from(0xe0, g as u8, 0x80)); fb.draw_char(Point{x:300, y: 550}, b'A', Rgba(0x000000ff), Rgba(0x00ff0000)); fb.draw_str(Point{x:40, y: 550}, b"Loading SOS...", Rgba(0x000000ff), Rgba(0x00ff0000)); fb.blit_copy(Point{x: 200, y: 100}, Point{x: 40, y: 550}, 200, 20); fb.blit_copy(Point{x: 150, y: 150}, Point{x: 50, y: 50}, 350, 350); printk!(Debug, "loop {}\n\r", g); } } fn test_kheap_allocator() { for _ in 0..10 { let mut v = vec![1,2,3,4]; let b = alloc::boxed::Box::new(0xcafe); printk!(Debug, "v = {:?}, b = {:?}\n\r", v, b); let vs = vec!["Loading", "SOS2", "\n\r"]; for s in vs { printk!(Debug, "{} ", s); } for i in 1..0x1000 * 40 { v.push(i); } } loop {} } extern { static _start: u64; static _end: u64; static kern_stack_top: u64; } #[no_mangle] pub extern fn kernel_main(mb2_header: usize) { unsafe { let mut com1 = serial::COM1.lock(); com1.init(); } con::clear(); printk!(Info, "Loading SOS2....\n\r"); let mbinfo = unsafe { multiboot2::load(mb2_header) }; printk!(Info, "{:#?}\n\r", mbinfo); let (pa, pe, sp_top) = unsafe { (&_start as *const _ as u64, &_end as *const _ as u64, &kern_stack_top as *const _ as u64) }; printk!(Debug, "_start {:#X}, _end {:#X}, sp top: {:#X}\n\r", pa, pe, sp_top); let fb = mbinfo.framebuffer_tag().expect("framebuffer tag is unavailale"); let mm = memory::init(mbinfo); //if cfg!(feature = "test") { test_kheap_allocator(); } { let mut mm = mm.lock(); interrupts::init(&mut mm); if cfg!(feature = "test") { interrupts::test_idt(); } } if fb.frame_type == multiboot2::FramebufferType::Rgb { use kern::arch::cpu; //NOTE: if I dont use console in timer, then there is no reason to disable IF here. let oflags = unsafe { cpu::push_flags() }; let mut fb = Framebuffer::new(&fb); //if cfg!(feature = "test") { display(&mut fb); } { let mut term = con::tty1.lock(); *term = Console::new_with_fb(fb); } con::clear(); println!("framebuffer console init.\n\r"); //if cfg!(feature = "test") { for b in 1..127u8 { print!("{}", b as char); } } unsafe { cpu::pop_flags(oflags); } } task::init(); loop { kern::util::cpu_relax(); } } /// Get a stack trace /// TODO: extract symbol names from kernel elf unsafe fn stack_trace() { use core::mem; let mut rbp: usize; asm!("" : "={rbp}"(rbp) : : : "intel", "volatile"); println!("backtrace: {:>016x}", rbp); //Maximum 64 frames let active_table = memory::paging::ActivePML4Table::new(); for _frame in 0..64 { if let Some(rip_rbp) = rbp.checked_add(mem::size_of::<usize>()) { if active_table.translate(rbp).is_some() && active_table.translate(rip_rbp).is_some() { let rip = *(rip_rbp as *const usize); if rip == 0 { println!(" {:>016x}: EMPTY RETURN", rbp); break; } println!(" {:>016x}: ret rip {:>016x}", rbp, rip); rbp = *(rbp as *const usize); } else { println!(" {:>016x}: Invalid", rbp); break; } } else { println!(" {:>016x}: RBP OVERFLOW", rbp); } } } #[lang = "eh_personality"] extern fn eh_personality() {} #[lang = "panic_fmt"] #[no_mangle] pub extern fn panic_fmt(fmt: core::fmt::Arguments, file: &'static str, line: u32) -> ! { printk!(Critical, "\n\rPanic at {}:{}\n\r", file, line); printk!(Critical, " {}\n\r", fmt); unsafe { stack_trace(); } loop { unsafe { asm!("hlt":::: "volatile"); } } } #[lang = "eh_unwind_resume"] #[no_mangle] pub extern fn rust_eh_unwind_resume() { } /// dummy, this should never gets called #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn _Unwind_Resume() -> ! { loop {} }
gpl-3.0
nexdatas/recselector
nxsrecconfig/Converter.py
10979
#!/usr/bin/env python # This file is part of nxsrecconfig - NeXus Sardana Recorder Settings # # Copyright (C) 2014-2017 DESY, Jan Kotanski <jkotan@mail.desy.de> # # nexdatas is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # nexdatas is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with nexdatas. If not, see <http://www.gnu.org/licenses/>. # """ Selection version converter """ import json class ConverterXtoY(object): """ virtual selection version converter """ def __init__(self): """ constructor """ #: (:obj:`dict` <:obj:`str`, :obj:`str`>) names to convert self.names = {} def convert(self, selection): """ converts selection to the current selector version :param selection: selection dictionary object :type selection: :obj:`dict` <:obj:`str`, `any`> """ for old, new in self.names.items(): if old in list(selection.keys()): selection[new] = selection.pop(old) class Converter2to3(ConverterXtoY): """ Selection converter from version 2 to 3 """ def __init__(self): """ converter """ super(Converter2to3, self).__init__() #: (:obj:`dict` <:obj:`str`, :obj:`str`>) names to convert self.names = { "PreselectedDataSources": "PreselectingDataSources", "InitDataSources": "DataSourcePreselection", } def seltoint(self, jselelem): """ converters list/dict of elements to dictionary with logical values :param jselelem: json list or dict selection element :type jselelem: :obj:`str` :returns: json dictionary :rtype: :obj:`str` """ sel = json.loads(jselelem) if isinstance(sel, dict): return json.dumps( dict((key, True if vl else None) for key, vl in sel.items())) elif isinstance(sel, (list, tuple)): return json.dumps(dict((key, True) for key in sel)) def convert(self, selection): """ converts selection from version 2 to 3 :param selection: selection dictionary object :type selection: :obj:`dict` <:obj:`str`, `any`> """ super(Converter2to3, self).convert(selection) if 'ComponentPreselection' in selection.keys(): selection["ComponentPreselection"] = self.seltoint( selection["ComponentPreselection"]) if 'DataSourcePreselection' in selection.keys(): selection["DataSourcePreselection"] = self.seltoint( selection["DataSourcePreselection"]) if 'MntGrpConfiguration' not in selection.keys(): selection['MntGrpConfiguration'] = '' class Converter3to2(ConverterXtoY): """ Selection converter from version 3 to 2 """ def __init__(self): """ constructor """ super(Converter3to2, self).__init__() #: (:obj:`dict` <:obj:`str`, :obj:`str`>) names to convert self.names = { "PreselectingDataSources": "PreselectedDataSources", "DataSourcePreselection": "InitDataSources", } def seltobool(self, jselelem): """ converters dictioanry with None/True/False values to dictionary with True/False values :param jselelem: json dictionary selection element :type jselelem: :obj:`str` :returns: converter json dictionary :rtype: :obj:`str` """ sel = json.loads(jselelem) return json.dumps( dict((key, vl is not None) for key, vl in sel.items())) def seltolist(self, jselelem): """ converters dictioanry with None/True/False values to list of elementes with walue True :param jselelem: json dictionary selection element :type jselelem: :obj:`str` :returns: converter json dictionary :rtype: :obj:`str` """ sel = json.loads(jselelem) return json.dumps([key for key, vl in sel.items() if vl]) def convert(self, selection): """ converts selection from version 3 to 2 :param selection: selection dictionary object :type selection: :obj:`dict` <:obj:`str`, `any`> """ super(Converter3to2, self).convert(selection) if 'ComponentPreselection' in selection.keys(): selection["ComponentPreselection"] = self.seltobool( selection["ComponentPreselection"]) if 'InitDataSources' in selection.keys(): selection['InitDataSources'] = self.seltolist( selection['InitDataSources']) if 'MntGrpConfiguration' in selection.keys(): selection.pop('MntGrpConfiguration') class Converter1to2(ConverterXtoY): """ Selection converter from version 1 to 2 """ def __init__(self): """ constructor """ super(Converter1to2, self).__init__() #: (:obj:`dict` <:obj:`str`, :obj:`str`>) names to convert self.names = { "AutomaticComponentGroup": "ComponentPreselection", "AutomaticDataSources": "PreselectedDataSources", "ComponentGroup": "ComponentSelection", "DataSourceGroup": "DataSourceSelection", "DataRecord": "UserData", "HiddenElements": "UnplottedComponents", "DynamicLinks": "DefaultDynamicLinks", "DynamicPath": "DefaultDynamicPath" } #: (:obj:`dict` <:obj:`str`, :obj:`str`>) names of properties self.pnames = { "Labels": "label", "LabelPaths": "nexus_path", "LabelLinks": "link", "LabelTypes": "data_type", "LabelShapes": "shape", } def convert(self, selection): """ converts selection from version 1 to 2 :param selection: selection dictionary object :type selection: :obj:`dict` <:obj:`str`, `any`> """ super(Converter1to2, self).convert(selection) props = {} for var, pn in self.pnames.items(): if var in list(selection.keys()): props[pn] = json.loads(selection.pop(var)) selection["ChannelProperties"] = json.dumps(props) class Converter2to1(ConverterXtoY): """ Selection converter from version 2 to 1 """ def __init__(self): """ constructor """ super(Converter2to1, self).__init__() #: (:obj:`dict` <:obj:`str`, :obj:`str`>) names of properties self.pnames = { "Labels": "label", "LabelPaths": "nexus_path", "LabelLinks": "link", "LabelTypes": "data_type", "LabelShapes": "shape", } #: (:obj:`dict` <:obj:`str`, :obj:`str`>) names to convert self.names = { "ComponentSelection": "ComponentGroup", "ComponentPreselection": "AutomaticComponentGroup", "PreselectedDataSources": "AutomaticDataSources", "DataSourceSelection": "DataSourceGroup", "UserData": "DataRecord", "UnplottedComponents": "HiddenElements", "DefaultDynamicLinks": "DynamicLinks", "DefaultDynamicPath": "DynamicPath" } def convert(self, selection): """ converts selection from version 2 to 1 :param selection: selection dictionary object :type selection: :obj:`dict` <:obj:`str`, `any`> """ super(Converter2to1, self).convert(selection) if "ChannelProperties" in selection: props = json.loads(selection["ChannelProperties"]) for var, pn in self.pnames.items(): if pn in props: selection[var] = json.dumps(props.pop(pn)) selection.pop("ChannelProperties") if "Version" in selection: selection.pop("Version") class Converter(object): """ selection version converter """ def __init__(self, ver): """ contstructor :param ver: the required selection version :type ver: :obj:`str` """ sver = ver.split(".") #: (:obj:`int`) major selection version self.majorversion = int(sver[0]) #: (:obj:`int`) minor selection version self.minorversion = int(sver[1]) #: (:obj:`int`) patch selection version self.patchversion = int(sver[2]) #: (:obj:`list` <:class:`ConverterXtoY`>) converter up sequence self.up = [Converter1to2(), Converter2to3()] #: (:obj:`list` <:class:`ConverterXtoY`>) converter down sequence self.down = [Converter2to1(), Converter3to2()] def allkeys(self, selection): """ :param selection: selection dictionary object :type selection: nxsrecconfig.Selection.Selection :returns: selection keys :rtype: :obj:`set` """ lkeys = set() for cv in self.up: lkeys.update(set(cv.names.keys())) lkeys.update(set(cv.names.values())) ak = set(selection.keys()) ak.update(lkeys) return ak def convert(self, selection): """ converts selection from any version to any other :param selection: selection dictionary object :type selection: :obj:`dict` <:obj:`str`, `any`> """ major, _, _ = self.version(selection) if major == self.majorversion: return if major < self.majorversion: for i in range(major - 1, self.majorversion - 1): self.up[i].convert(selection) elif major > self.majorversion: for i in range(major - 2, self.majorversion - 2, -1): self.down[i].convert(selection) selection["Version"] = "%s.%s.%s" % ( self.majorversion, self.minorversion, self.patchversion) @classmethod def version(cls, selection): """ fetches selection version and converts it into (major, minor, patch) :param selection: selection dictionary object :type selection: nxsrecconfig.Selection.Selection :returns: (major, minor, patch) tuple with integers :rtype: (:obj:`int` , :obj:`int` , :obj:`int`) """ major = 1 minor = 0 patch = 0 if 'Version' in selection: ver = selection['Version'] sver = ver.split(".") major = int(sver[0]) minor = int(sver[1]) patch = int(sver[2]) return major, minor, patch
gpl-3.0
konnorb/arpeggiate
admin/add.php
540
<?php require '../app/start.php'; if (!empty($_POST)){ $artist = $_POST['artist']; $title = $_POST['title']; $slug = $_POST['slug']; $content = $_POST['content']; $insertPage = $db->prepare(" INSERT INTO songs (artist, title, slug, content, created) VALUES (:artist, :title, :slug, :content, NOW()) "); $insertPage->execute([ 'artist' => $artist, 'title' => $title, 'slug' => $slug, 'content' => $content, ]); header('Location: ' . BASE_URL . '/admin/index.php'); } require VIEW_ROOT . '/admin/add.php'; ?>
gpl-3.0
maxon887/Cross
Editor/Sources/PropertyViews/FileHandler.cpp
1791
#include "FileHandler.h" #include "FileExplorer.h" #include "CrossEditor.h" #include <QDragEnterEvent> #include <QMimeData> #include <QMessageBox> #include <QFileInfo> FileHandler::FileHandler(QWidget* parent) : QLineEdit(parent) { } QString FileHandler::GetFile() { return file_path; } void FileHandler::SetFile(const QString& filename) { file_path = filename; QFileInfo info = QFileInfo(filename); setText(info.fileName()); FileChanged.Emit(filename); } void FileHandler::SetFileExtension(const QString& ext) { file_extension = ext; } void FileHandler::dragEnterEvent(QDragEnterEvent *event) { drop_accepted = false; const QMimeData* data = event->mimeData(); QList<QUrl> urls = data->urls(); if(file_extension == "") { event->ignore(); QMessageBox* msgBox = new QMessageBox(this); msgBox->setText("Something goes wrong"); msgBox->setInformativeText("File extension not specified for this handle"); msgBox->setIcon(QMessageBox::Icon::Warning); msgBox->show(); return; } if(urls.size() != 1) { event->ignore(); QMessageBox* msgBox = new QMessageBox(this); msgBox->setText("Something goes wrong"); msgBox->setInformativeText("File Handler can contain only one file"); msgBox->setIcon(QMessageBox::Icon::Warning); msgBox->show(); return; } QString filename = urls.at(0).fileName(); if(filename.endsWith("." + file_extension)) { drop_accepted = true; event->accept(); } } void FileHandler::dragMoveEvent(QDragMoveEvent *event) { if(drop_accepted) { event->accept(); } } void FileHandler::dropEvent(QDropEvent *event) { const QMimeData* data = event->mimeData(); QList<QUrl> urls = data->urls(); QString filename = urls.at(0).toLocalFile(); filename = editor->GetFileExplorer()->GetRelativePath(filename); SetFile(filename); }
gpl-3.0
soprasteria/dad
client/src/modules/languages/languages.actions.js
394
import { generateEntitiesActions } from '../utils/entities'; import LanguagesConstants from './languages.constants'; // Action when authenticated user successfully get his profile information const receiveLanguage = (language) => { return { type: LanguagesConstants.SELECT_LANGUAGE, language }; }; export default { ...generateEntitiesActions('languages'), receiveLanguage };
gpl-3.0
curiosag/ftc
RSyntaxTextArea/src/main/java/org/fife/ui/rtextarea/RTextAreaEditorKit.java
72968
/* * 08/13/2004 * * RTextAreaEditorKit.java - The editor kit used by RTextArea. * * This library is distributed under a modified BSD license. See the included * RSyntaxTextArea.License.txt file for details. */ package org.fife.ui.rtextarea; import java.awt.*; import java.awt.event.*; import java.io.*; import java.text.BreakIterator; import java.text.DateFormat; import java.util.Date; import javax.swing.*; import javax.swing.text.*; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities; /** * An extension of <code>DefaultEditorKit</code> that adds functionality found * in <code>RTextArea</code>. * * @author Robert Futrell * @version 0.1 */ // FIXME: Replace Utilities calls with custom versions (in RSyntaxUtilities) to // cut down on all of the modelToViews, as each call causes // a getTokenList => expensive! public class RTextAreaEditorKit extends DefaultEditorKit { /** * The name of the action that begins recording a macro. */ public static final String rtaBeginRecordingMacroAction = "RTA.BeginRecordingMacroAction"; /** * The name of the action to decrease the font size. */ public static final String rtaDecreaseFontSizeAction = "RTA.DecreaseFontSizeAction"; /** * The name of the action that deletes the current line. */ public static final String rtaDeleteLineAction = "RTA.DeleteLineAction"; /** * The name of the action to delete the word before the caret. */ public static final String rtaDeletePrevWordAction = "RTA.DeletePrevWordAction"; /** * The name of the action taken to delete the remainder of the line (from * the caret position to the end of the line). */ public static final String rtaDeleteRestOfLineAction = "RTA.DeleteRestOfLineAction"; /** * The name of the action that completes the word at the caret position * with the last word in the document that starts with the text up to the * caret. */ public static final String rtaDumbCompleteWordAction = "RTA.DumbCompleteWordAction"; /** * The name of the action that ends recording a macro. */ public static final String rtaEndRecordingMacroAction = "RTA.EndRecordingMacroAction"; /** * The name of the action to increase the font size. */ public static final String rtaIncreaseFontSizeAction = "RTA.IncreaseFontSizeAction"; /** * The name of the action that inverts the case of the current selection. */ public static final String rtaInvertSelectionCaseAction = "RTA.InvertCaseAction"; /** * The name of the action to join two lines. */ public static final String rtaJoinLinesAction = "RTA.JoinLinesAction"; /** * Action to move a line down. */ public static final String rtaLineDownAction = "RTA.LineDownAction"; /** * Action to move a line up. */ public static final String rtaLineUpAction = "RTA.LineUpAction"; /** * The name of the action to make the current selection lower-case. */ public static final String rtaLowerSelectionCaseAction = "RTA.LowerCaseAction"; /** * Action to select the next occurrence of the selected text. */ public static final String rtaNextOccurrenceAction = "RTA.NextOccurrenceAction"; /** * Action to select the previous occurrence of the selected text. */ public static final String rtaPrevOccurrenceAction = "RTA.PrevOccurrenceAction"; /** * Action to jump to the next bookmark. */ public static final String rtaNextBookmarkAction = "RTA.NextBookmarkAction"; /** * Action to display the paste history popup. */ public static final String clipboardHistoryAction = "RTA.PasteHistoryAction"; /** * Action to jump to the previous bookmark. */ public static final String rtaPrevBookmarkAction = "RTA.PrevBookmarkAction"; /** * The name of the action that "plays back" the last macro. */ public static final String rtaPlaybackLastMacroAction = "RTA.PlaybackLastMacroAction"; /** * The name of the action for "redoing" the last action undone. */ public static final String rtaRedoAction = "RTA.RedoAction"; /** * The name of the action to scroll the text area down one line * without changing the caret's position. */ public static final String rtaScrollDownAction = "RTA.ScrollDownAction"; /** * The name of the action to scroll the text area up one line * without changing the caret's position. */ public static final String rtaScrollUpAction = "RTA.ScrollUpAction"; /** * The name of the action for "paging up" with the selection. */ public static final String rtaSelectionPageUpAction = "RTA.SelectionPageUpAction"; /** * The name of the action for "paging down" with the selection. */ public static final String rtaSelectionPageDownAction = "RTA.SelectionPageDownAction"; /** * The name of the action for "paging left" with the selection. */ public static final String rtaSelectionPageLeftAction = "RTA.SelectionPageLeftAction"; /** * The name of the action for "paging right" with the selection. */ public static final String rtaSelectionPageRightAction = "RTA.SelectionPageRightAction"; /** * The name of the action for inserting a time/date stamp. */ public static final String rtaTimeDateAction = "RTA.TimeDateAction"; /** * Toggles whether the current line has a bookmark, if this text area * is in an {@link RTextScrollPane}. */ public static final String rtaToggleBookmarkAction = "RTA.ToggleBookmarkAction"; /** * The name of the action taken when the user hits the Insert key (thus * toggling between insert and overwrite modes). */ public static final String rtaToggleTextModeAction = "RTA.ToggleTextModeAction"; /** * The name of the action for "undoing" the last action done. */ public static final String rtaUndoAction = "RTA.UndoAction"; /** * The name of the action for unselecting any selected text in the text * area. */ public static final String rtaUnselectAction = "RTA.UnselectAction"; /** * The name of the action for making the current selection upper-case. */ public static final String rtaUpperSelectionCaseAction = "RTA.UpperCaseAction"; /** * The actions that <code>RTextAreaEditorKit</code> adds to those of * the default editor kit. */ private static final RecordableTextAction[] defaultActions = { new BeginAction(beginAction, false), new BeginAction(selectionBeginAction, true), new BeginLineAction(beginLineAction, false), new BeginLineAction(selectionBeginLineAction, true), new BeginRecordingMacroAction(), new BeginWordAction(beginWordAction, false), new BeginWordAction(selectionBeginWordAction, true), new ClipboardHistoryAction(), new CopyAction(), new CutAction(), new DefaultKeyTypedAction(), new DeleteLineAction(), new DeleteNextCharAction(), new DeletePrevCharAction(), new DeletePrevWordAction(), new DeleteRestOfLineAction(), new DumbCompleteWordAction(), new EndAction(endAction, false), new EndAction(selectionEndAction, true), new EndLineAction(endLineAction, false), new EndLineAction(selectionEndLineAction, true), new EndRecordingMacroAction(), new EndWordAction(endWordAction, false), new EndWordAction(endWordAction, true), new InsertBreakAction(), new InsertContentAction(), new InsertTabAction(), new InvertSelectionCaseAction(), new JoinLinesAction(), new LowerSelectionCaseAction(), new LineMoveAction(rtaLineUpAction, -1), new LineMoveAction(rtaLineDownAction, 1), new NextBookmarkAction(rtaNextBookmarkAction, true), new NextBookmarkAction(rtaPrevBookmarkAction, false), new NextVisualPositionAction(forwardAction, false, SwingConstants.EAST), new NextVisualPositionAction(backwardAction, false, SwingConstants.WEST), new NextVisualPositionAction(selectionForwardAction, true, SwingConstants.EAST), new NextVisualPositionAction(selectionBackwardAction, true, SwingConstants.WEST), new NextVisualPositionAction(upAction, false, SwingConstants.NORTH), new NextVisualPositionAction(downAction, false, SwingConstants.SOUTH), new NextVisualPositionAction(selectionUpAction, true, SwingConstants.NORTH), new NextVisualPositionAction(selectionDownAction, true, SwingConstants.SOUTH), new NextOccurrenceAction(rtaNextOccurrenceAction), new PreviousOccurrenceAction(rtaPrevOccurrenceAction), new NextWordAction(nextWordAction, false), new NextWordAction(selectionNextWordAction, true), new PageAction(rtaSelectionPageLeftAction, true, true), new PageAction(rtaSelectionPageRightAction, false, true), new PasteAction(), new PlaybackLastMacroAction(), new PreviousWordAction(previousWordAction, false), new PreviousWordAction(selectionPreviousWordAction, true), new RedoAction(), new ScrollAction(rtaScrollUpAction, -1), new ScrollAction(rtaScrollDownAction, 1), new SelectAllAction(), new SelectLineAction(), new SelectWordAction(), new SetReadOnlyAction(), new SetWritableAction(), new ToggleBookmarkAction(), new ToggleTextModeAction(), new UndoAction(), new UnselectAction(), new UpperSelectionCaseAction(), new VerticalPageAction(pageUpAction, -1, false), new VerticalPageAction(pageDownAction, 1, false), new VerticalPageAction(rtaSelectionPageUpAction, -1, true), new VerticalPageAction(rtaSelectionPageDownAction, 1, true) }; /** * The amount of characters read at a time when reading a file. */ private static final int READBUFFER_SIZE = 32768; /** * Constructor. */ public RTextAreaEditorKit() { super(); } /** * Creates an icon row header to use in the gutter for a text area. * * @param textArea The text area. * @return The icon row header. */ public IconRowHeader createIconRowHeader(RTextArea textArea) { return new IconRowHeader(textArea); } /** * Creates a line number list to use in the gutter for a text area. * * @param textArea The text area. * @return The line number list. */ public LineNumberList createLineNumberList(RTextArea textArea) { return new LineNumberList(textArea); } /** * Fetches the set of commands that can be used * on a text component that is using a model and * view produced by this kit. * * @return the command list */ @Override public Action[] getActions() { return defaultActions; } /** * Inserts content from the given stream, which will be * treated as plain text. This method is overridden merely * so we can increase the number of characters read at a time. * * @param in The stream to read from * @param doc The destination for the insertion. * @param pos The location in the document to place the * content &gt;= 0. * @exception IOException on any I/O error * @exception BadLocationException if pos represents an invalid * location within the document. */ @Override public void read(Reader in, Document doc, int pos) throws IOException, BadLocationException { char[] buff = new char[READBUFFER_SIZE]; int nch; boolean lastWasCR = false; boolean isCRLF = false; boolean isCR = false; int last; boolean wasEmpty = (doc.getLength() == 0); // Read in a block at a time, mapping \r\n to \n, as well as single // \r's to \n's. If a \r\n is encountered, \r\n will be set as the // newline string for the document, if \r is encountered it will // be set as the newline character, otherwise the newline property // for the document will be removed. while ((nch = in.read(buff, 0, buff.length)) != -1) { last = 0; for (int counter = 0; counter < nch; counter++) { switch (buff[counter]) { case '\r': if (lastWasCR) { isCR = true; if (counter == 0) { doc.insertString(pos, "\n", null); pos++; } else { buff[counter - 1] = '\n'; } } else { lastWasCR = true; } break; case '\n': if (lastWasCR) { if (counter > (last + 1)) { doc.insertString(pos, new String(buff, last, counter - last - 1), null); pos += (counter - last - 1); } // else nothing to do, can skip \r, next write will // write \n lastWasCR = false; last = counter; isCRLF = true; } break; default: if (lastWasCR) { isCR = true; if (counter == 0) { doc.insertString(pos, "\n", null); pos++; } else { buff[counter - 1] = '\n'; } lastWasCR = false; } break; } // End of switch (buff[counter]). } // End of for (int counter = 0; counter < nch; counter++). if (last < nch) { if(lastWasCR) { if (last < (nch - 1)) { doc.insertString(pos, new String(buff, last, nch - last - 1), null); pos += (nch - last - 1); } } else { doc.insertString(pos, new String(buff, last, nch - last), null); pos += (nch - last); } } } // End of while ((nch = in.read(buff, 0, buff.length)) != -1). if (lastWasCR) { doc.insertString(pos, "\n", null); isCR = true; } if (wasEmpty) { if (isCRLF) { doc.putProperty(EndOfLineStringProperty, "\r\n"); } else if (isCR) { doc.putProperty(EndOfLineStringProperty, "\r"); } else { doc.putProperty(EndOfLineStringProperty, "\n"); } } } /** * Creates a beep. */ public static class BeepAction extends RecordableTextAction { public BeepAction() { super(beepAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } @Override public final String getMacroID() { return beepAction; } } /** * Moves the caret to the beginning of the document. */ public static class BeginAction extends RecordableTextAction { private boolean select; public BeginAction(String name, boolean select) { super(name); this.select = select; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (select) textArea.moveCaretPosition(0); else textArea.setCaretPosition(0); } @Override public final String getMacroID() { return getName(); } } /** * Toggles the position of the caret between the beginning of the line, * and the first non-whitespace character on the line. */ public static class BeginLineAction extends RecordableTextAction { private Segment currentLine = new Segment(); // For speed. private boolean select; public BeginLineAction(String name, boolean select) { super(name); this.select = select; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int newPos = 0; try { // Is line wrap enabled? if (textArea.getLineWrap()) { int offs = textArea.getCaretPosition(); // TODO: Replace Utilities call with custom version // to cut down on all of the modelToViews, as each call // causes TokenList => expensive! int begOffs = Utilities.getRowStart(textArea, offs); // TODO: line wrap doesn't currently toggle between // the first non-whitespace char and the actual start // of the line line the no-line-wrap version does. newPos = begOffs; } // No line wrap - optimized for performance! else { // We use the elements instead of calling // getLineOfOffset(), etc. to speed things up just a // tad (i.e. micro-optimize). int caretPosition = textArea.getCaretPosition(); Document document = textArea.getDocument(); Element map = document.getDefaultRootElement(); int currentLineNum = map.getElementIndex(caretPosition); Element currentLineElement = map.getElement(currentLineNum); int currentLineStart = currentLineElement.getStartOffset(); int currentLineEnd = currentLineElement.getEndOffset(); int count = currentLineEnd - currentLineStart; if (count>0) { // If there are chars in the line... document.getText(currentLineStart, count, currentLine); int firstNonWhitespace = getFirstNonWhitespacePos(); firstNonWhitespace = currentLineStart + (firstNonWhitespace - currentLine.offset); if (caretPosition!=firstNonWhitespace) { newPos = firstNonWhitespace; } else { newPos = currentLineStart; } } else { // Empty line (at end of the document only). newPos = currentLineStart; } } if (select) { textArea.moveCaretPosition(newPos); } else { textArea.setCaretPosition(newPos); } //e.consume(); } catch (BadLocationException ble) { /* Shouldn't ever happen. */ UIManager.getLookAndFeel().provideErrorFeedback(textArea); ble.printStackTrace(); } } private final int getFirstNonWhitespacePos() { int offset = currentLine.offset; int end = offset + currentLine.count - 1; int pos = offset; char[] array = currentLine.array; char currentChar = array[pos]; while ((currentChar=='\t' || currentChar==' ') && (++pos<end)) currentChar = array[pos]; return pos; } @Override public final String getMacroID() { return getName(); } } /** * Action that begins recording a macro. */ public static class BeginRecordingMacroAction extends RecordableTextAction { public BeginRecordingMacroAction() { super(rtaBeginRecordingMacroAction); } public BeginRecordingMacroAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RTextArea.beginRecordingMacro(); } @Override public boolean isRecordable() { return false; // Never record the recording of a macro! } @Override public final String getMacroID() { return rtaBeginRecordingMacroAction; } } /** * Positions the caret at the beginning of the word. */ protected static class BeginWordAction extends RecordableTextAction { private boolean select; protected BeginWordAction(String name, boolean select) { super(name); this.select = select; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { try { int offs = textArea.getCaretPosition(); int begOffs = getWordStart(textArea, offs); if (select) textArea.moveCaretPosition(begOffs); else textArea.setCaretPosition(begOffs); } catch (BadLocationException ble) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } @Override public final String getMacroID() { return getName(); } protected int getWordStart(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getWordStart(textArea, offs); } } /** * Action for displaying a popup with a list of recently pasted text * snippets. */ public static class ClipboardHistoryAction extends RecordableTextAction { private ClipboardHistory clipboardHistory; public ClipboardHistoryAction() { super(clipboardHistoryAction); clipboardHistory = ClipboardHistory.get(); } public ClipboardHistoryAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); clipboardHistory = ClipboardHistory.get(); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Window owner = SwingUtilities.getWindowAncestor(textArea); ClipboardHistoryPopup popup = new ClipboardHistoryPopup(owner, textArea); popup.setContents(clipboardHistory.getHistory()); popup.setVisible(true); } @Override public final String getMacroID() { return clipboardHistoryAction; } } /** * Action for copying text. */ public static class CopyAction extends RecordableTextAction { public CopyAction() { super(DefaultEditorKit.copyAction); } public CopyAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.copy(); textArea.requestFocusInWindow(); } @Override public final String getMacroID() { return DefaultEditorKit.copyAction; } } /** * Action for cutting text. */ public static class CutAction extends RecordableTextAction { public CutAction() { super(DefaultEditorKit.cutAction); } public CutAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.cut(); textArea.requestFocusInWindow(); } @Override public final String getMacroID() { return DefaultEditorKit.cutAction; } } /** * Action for decreasing the font size. */ public static class DecreaseFontSizeAction extends RecordableTextAction { protected float decreaseAmount; protected static final float MINIMUM_SIZE = 2.0f; public DecreaseFontSizeAction() { super(rtaDecreaseFontSizeAction); initialize(); } public DecreaseFontSizeAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); initialize(); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Font font = textArea.getFont(); float oldSize = font.getSize2D(); float newSize = oldSize - decreaseAmount; if (newSize>=MINIMUM_SIZE) { // Shrink by decreaseAmount. font = font.deriveFont(newSize); textArea.setFont(font); } else if (oldSize>MINIMUM_SIZE) { // Can't shrink by full decreaseAmount, but can shrink a // little bit. font = font.deriveFont(MINIMUM_SIZE); textArea.setFont(font); } else { // Our font size must be at or below MINIMUM_SIZE. UIManager.getLookAndFeel().provideErrorFeedback(textArea); } textArea.requestFocusInWindow(); } @Override public final String getMacroID() { return rtaDecreaseFontSizeAction; } protected void initialize() { decreaseAmount = 1.0f; } } /** * The action to use when no actions in the input/action map meet the key * pressed. This is actually called from the keymap I believe. */ public static class DefaultKeyTypedAction extends RecordableTextAction { private Action delegate; public DefaultKeyTypedAction() { super(DefaultEditorKit.defaultKeyTypedAction, null, null, null, null); delegate = new DefaultEditorKit.DefaultKeyTypedAction(); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { // DefaultKeyTypedAction *is* different across different JVM's // (at least the OSX implementation must be different - Alt+Numbers // inputs symbols such as '[', '{', etc., which is a *required* // feature on MacBooks running with non-English input, such as // German or Swedish Pro). So we can't just copy the // implementation, we must delegate to it. delegate.actionPerformed(e); } @Override public final String getMacroID() { return DefaultEditorKit.defaultKeyTypedAction; } } /** * Deletes the current line(s). */ public static class DeleteLineAction extends RecordableTextAction { public DeleteLineAction() { super(RTextAreaEditorKit.rtaDeleteLineAction, null, null, null, null); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } int selStart = textArea.getSelectionStart(); int selEnd = textArea.getSelectionEnd(); try { int line1 = textArea.getLineOfOffset(selStart); int startOffs = textArea.getLineStartOffset(line1); int line2 = textArea.getLineOfOffset(selEnd); int endOffs = textArea.getLineEndOffset(line2); // Don't remove the last line if no actual chars are selected if (line2>line1) { if (selEnd==textArea.getLineStartOffset(line2)) { endOffs = selEnd; } } textArea.replaceRange(null, startOffs, endOffs); } catch (BadLocationException ble) { ble.printStackTrace(); // Never happens } } @Override public final String getMacroID() { return RTextAreaEditorKit.rtaDeleteLineAction; } } /** * Deletes the character of content that follows the current caret * position. */ public static class DeleteNextCharAction extends RecordableTextAction { public DeleteNextCharAction() { super(DefaultEditorKit.deleteNextCharAction, null, null, null, null); } public DeleteNextCharAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { boolean beep = true; if ((textArea != null) && (textArea.isEditable())) { try { Document doc = textArea.getDocument(); Caret caret = textArea.getCaret(); int dot = caret.getDot(); int mark = caret.getMark(); if (dot != mark) { doc.remove(Math.min(dot, mark), Math.abs(dot - mark)); beep = false; } else if (dot < doc.getLength()) { int delChars = 1; if (dot < doc.getLength() - 1) { String dotChars = doc.getText(dot, 2); char c0 = dotChars.charAt(0); char c1 = dotChars.charAt(1); if (c0 >= '\uD800' && c0 <= '\uDBFF' && c1 >= '\uDC00' && c1 <= '\uDFFF') { delChars = 2; } } doc.remove(dot, delChars); beep = false; } } catch (BadLocationException bl) { } } if (beep) UIManager.getLookAndFeel().provideErrorFeedback(textArea); textArea.requestFocusInWindow(); } @Override public final String getMacroID() { return DefaultEditorKit.deleteNextCharAction; } } /** * Deletes the character of content that precedes the current caret * position. */ public static class DeletePrevCharAction extends RecordableTextAction { public DeletePrevCharAction() { super(deletePrevCharAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { boolean beep = true; if ((textArea != null) && (textArea.isEditable())) { try { Document doc = textArea.getDocument(); Caret caret = textArea.getCaret(); int dot = caret.getDot(); int mark = caret.getMark(); if (dot != mark) { doc.remove(Math.min(dot, mark), Math.abs(dot - mark)); beep = false; } else if (dot > 0) { int delChars = 1; if (dot > 1) { String dotChars = doc.getText(dot - 2, 2); char c0 = dotChars.charAt(0); char c1 = dotChars.charAt(1); if (c0 >= '\uD800' && c0 <= '\uDBFF' && c1 >= '\uDC00' && c1 <= '\uDFFF') { delChars = 2; } } doc.remove(dot - delChars, delChars); beep = false; } } catch (BadLocationException bl) { } } if (beep) UIManager.getLookAndFeel().provideErrorFeedback(textArea); } @Override public final String getMacroID() { return DefaultEditorKit.deletePrevCharAction; } } /** * Action that deletes the previous word in the text area. */ public static class DeletePrevWordAction extends RecordableTextAction { public DeletePrevWordAction() { super(rtaDeletePrevWordAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } try { int end = textArea.getSelectionStart(); int start = getPreviousWordStart(textArea, end); if (end>start) { textArea.getDocument().remove(start, end-start); } } catch (BadLocationException ex) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } @Override public String getMacroID() { return rtaDeletePrevWordAction; } /** * Returns the starting offset to delete. Exists so subclasses can * override. */ protected int getPreviousWordStart(RTextArea textArea, int end) throws BadLocationException { return Utilities.getPreviousWord(textArea, end); } } /** * Action that deletes all text from the caret position to the end of the * caret's line. */ public static class DeleteRestOfLineAction extends RecordableTextAction { public DeleteRestOfLineAction() { super(rtaDeleteRestOfLineAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { try { // We use the elements instead of calling getLineOfOffset(), // etc. to speed things up just a tad (i.e. micro-optimize). Document document = textArea.getDocument(); int caretPosition = textArea.getCaretPosition(); Element map = document.getDefaultRootElement(); int currentLineNum = map.getElementIndex(caretPosition); Element currentLineElement = map.getElement(currentLineNum); // Always take -1 as we don't want to remove the newline. int currentLineEnd = currentLineElement.getEndOffset()-1; if (caretPosition<currentLineEnd) { document.remove(caretPosition, currentLineEnd-caretPosition); } } catch (BadLocationException ble) { ble.printStackTrace(); } } @Override public final String getMacroID() { return rtaDeleteRestOfLineAction; } } /** * Finds the most recent word in the document that matches the "word" up * to the current caret position, and auto-completes the rest. Repeatedly * calling this action at the same location in the document goes one * match back each time it is called. */ public static class DumbCompleteWordAction extends RecordableTextAction { private int lastWordStart; private int lastDot; private int searchOffs; private String lastPrefix; public DumbCompleteWordAction() { super(rtaDumbCompleteWordAction); lastWordStart = searchOffs = lastDot = -1; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { return; } try { int dot = textArea.getCaretPosition(); if (dot == 0) { return; } int curWordStart = getWordStart(textArea, dot); if (lastWordStart!=curWordStart || dot!=lastDot) { lastPrefix = textArea.getText(curWordStart,dot-curWordStart); // Utilities.getWordStart() treats spans of whitespace and // single non-letter chars as "words." if (!isAcceptablePrefix(lastPrefix)) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } lastWordStart = dot - lastPrefix.length(); // searchOffs = lastWordStart; //searchOffs = getWordStart(textArea, lastWordStart); searchOffs = Math.max(lastWordStart - 1, 0); } while (searchOffs > 0) { int wordStart = 0; try { wordStart = getPreviousWord(textArea, searchOffs); } catch (BadLocationException ble) { // No more words. Sometimes happens for example if the // document starts off with whitespace - then searchOffs // is > 0 but there are no more words wordStart = BreakIterator.DONE; } if (wordStart==BreakIterator.DONE) { UIManager.getLookAndFeel().provideErrorFeedback( textArea); break; } int end = getWordEnd(textArea, wordStart); String word = textArea.getText(wordStart, end - wordStart); searchOffs = wordStart; if (word.startsWith(lastPrefix)) { textArea.replaceRange(word, lastWordStart, dot); lastDot = textArea.getCaretPosition(); // Maybe shifted break; } } } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); } } @Override public final String getMacroID() { return getName(); } protected int getPreviousWord(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getPreviousWord(textArea, offs); } protected int getWordEnd(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getWordEnd(textArea, offs); } protected int getWordStart(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getWordStart(textArea, offs); } /** * <code>Utilities.getWordStart()</code> treats spans of whitespace and * single non-letter chars as "words." This method is used to filter * that kind of thing out - non-words should not be suggested by this * action. * * @param prefix The prefix characters before the caret. * @return Whether the prefix could be part of a "word" in the context * of the text area's current content. */ protected boolean isAcceptablePrefix(String prefix) { return prefix.length() > 0 && Character.isLetter(prefix.charAt(prefix.length()-1)); } } /** * Moves the caret to the end of the document. */ public static class EndAction extends RecordableTextAction { private boolean select; public EndAction(String name, boolean select) { super(name); this.select = select; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int dot = getVisibleEnd(textArea); if (select) textArea.moveCaretPosition(dot); else textArea.setCaretPosition(dot); } @Override public final String getMacroID() { return getName(); } protected int getVisibleEnd(RTextArea textArea) { return textArea.getDocument().getLength(); } } /** * Positions the caret at the end of the line. */ public static class EndLineAction extends RecordableTextAction { private boolean select; public EndLineAction(String name, boolean select) { super(name); this.select = select; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int offs = textArea.getCaretPosition(); int endOffs = 0; try { if (textArea.getLineWrap()) { // Must check per character, since one logical line may be // many physical lines. // FIXME: Replace Utilities call with custom version to // cut down on all of the modelToViews, as each call causes // a getTokenList => expensive! endOffs = Utilities.getRowEnd(textArea, offs); } else { Element root = textArea.getDocument().getDefaultRootElement(); int line = root.getElementIndex(offs); endOffs = root.getElement(line).getEndOffset() - 1; } if (select) { textArea.moveCaretPosition(endOffs); } else { textArea.setCaretPosition(endOffs); } } catch (Exception ex) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } @Override public final String getMacroID() { return getName(); } } /** * Action that ends recording a macro. */ public static class EndRecordingMacroAction extends RecordableTextAction { public EndRecordingMacroAction() { super(rtaEndRecordingMacroAction); } public EndRecordingMacroAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RTextArea.endRecordingMacro(); } @Override public final String getMacroID() { return rtaEndRecordingMacroAction; } @Override public boolean isRecordable() { return false; // Never record the recording of a macro! } } /** * Positions the caret at the end of the word. */ protected static class EndWordAction extends RecordableTextAction { private boolean select; protected EndWordAction(String name, boolean select) { super(name); this.select = select; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { try { int offs = textArea.getCaretPosition(); int endOffs = getWordEnd(textArea, offs); if (select) textArea.moveCaretPosition(endOffs); else textArea.setCaretPosition(endOffs); } catch (BadLocationException ble) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } @Override public final String getMacroID() { return getName(); } protected int getWordEnd(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getWordEnd(textArea, offs); } } /** * Action for increasing the font size. */ public static class IncreaseFontSizeAction extends RecordableTextAction { protected float increaseAmount; protected static final float MAXIMUM_SIZE = 40.0f; public IncreaseFontSizeAction() { super(rtaIncreaseFontSizeAction); initialize(); } public IncreaseFontSizeAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); initialize(); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Font font = textArea.getFont(); float oldSize = font.getSize2D(); float newSize = oldSize + increaseAmount; if (newSize<=MAXIMUM_SIZE) { // Grow by increaseAmount. font = font.deriveFont(newSize); textArea.setFont(font); } else if (oldSize<MAXIMUM_SIZE) { // Can't grow by full increaseAmount, but can grow a // little bit. font = font.deriveFont(MAXIMUM_SIZE); textArea.setFont(font); } else { // Our font size must be at or bigger than MAXIMUM_SIZE. UIManager.getLookAndFeel().provideErrorFeedback(textArea); } textArea.requestFocusInWindow(); } @Override public final String getMacroID() { return rtaIncreaseFontSizeAction; } protected void initialize() { increaseAmount = 1.0f; } } /** * Action for when the user presses the Enter key. */ public static class InsertBreakAction extends RecordableTextAction { public InsertBreakAction() { super(DefaultEditorKit.insertBreakAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } textArea.replaceSelection("\n"); } @Override public final String getMacroID() { return DefaultEditorKit.insertBreakAction; } /* * Overridden for Sun bug 4515750. Sun fixed this in a more complicated * way, but I'm not sure why. See BasicTextUI#getActionMap() and * BasicTextUI.TextActionWrapper. */ @Override public boolean isEnabled() { JTextComponent tc = getTextComponent(null); return (tc==null || tc.isEditable()) ? super.isEnabled() : false; } } /** * Action taken when content is to be inserted. */ public static class InsertContentAction extends RecordableTextAction { public InsertContentAction() { super(DefaultEditorKit.insertContentAction, null, null, null, null); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } String content = e.getActionCommand(); if (content != null) textArea.replaceSelection(content); else UIManager.getLookAndFeel().provideErrorFeedback(textArea); } @Override public final String getMacroID() { return DefaultEditorKit.insertContentAction; } } /** * Places a tab character into the document. If there is a selection, it * is removed before the tab is added. */ public static class InsertTabAction extends RecordableTextAction { public InsertTabAction() { super(insertTabAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } textArea.replaceSelection("\t"); } @Override public final String getMacroID() { return DefaultEditorKit.insertTabAction; } } /** * Action to invert the selection's case. */ public static class InvertSelectionCaseAction extends RecordableTextAction { public InvertSelectionCaseAction() { super(rtaInvertSelectionCaseAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } String selection = textArea.getSelectedText(); if (selection!=null) { StringBuilder buffer = new StringBuilder(selection); int length = buffer.length(); for (int i=0; i<length; i++) { char c = buffer.charAt(i); if (Character.isUpperCase(c)) buffer.setCharAt(i, Character.toLowerCase(c)); else if (Character.isLowerCase(c)) buffer.setCharAt(i, Character.toUpperCase(c)); } textArea.replaceSelection(buffer.toString()); } textArea.requestFocusInWindow(); } @Override public final String getMacroID() { return getName(); } } /** * Action to join the current line and the following line. */ public static class JoinLinesAction extends RecordableTextAction { public JoinLinesAction() { super(rtaJoinLinesAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } try { Caret c = textArea.getCaret(); int caretPos = c.getDot(); Document doc = textArea.getDocument(); Element map = doc.getDefaultRootElement(); int lineCount = map.getElementCount(); int line = map.getElementIndex(caretPos); if (line==lineCount-1) { UIManager.getLookAndFeel(). provideErrorFeedback(textArea); return; } Element lineElem = map.getElement(line); caretPos = lineElem.getEndOffset() - 1; c.setDot(caretPos); // Gets rid of any selection. doc.remove(caretPos, 1); // Should be '\n'. } catch (BadLocationException ble) { /* Shouldn't ever happen. */ ble.printStackTrace(); } textArea.requestFocusInWindow(); } @Override public final String getMacroID() { return getName(); } } /** * Action that moves a line up or down. */ public static class LineMoveAction extends RecordableTextAction { private int moveAmt; public LineMoveAction(String name, int moveAmt) { super(name); this.moveAmt = moveAmt; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } try { int caret = textArea.getCaretPosition(); Document doc = textArea.getDocument(); Element root = doc.getDefaultRootElement(); int line = root.getElementIndex(caret); if (moveAmt==-1 && line>0) { moveLineUp(textArea, line); } else if (moveAmt==1 && line<root.getElementCount()-1) { moveLineDown(textArea, line); } else { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } } catch (BadLocationException ble) { // Never happens. ble.printStackTrace(); UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } } @Override public final String getMacroID() { return getName(); } private final void moveLineDown(RTextArea textArea, int line) throws BadLocationException { Document doc = textArea.getDocument(); Element root = doc.getDefaultRootElement(); Element elem = root.getElement(line); int start = elem.getStartOffset(); int end = elem.getEndOffset(); int caret = textArea.getCaretPosition(); int caretOffset = caret - start; String text = doc.getText(start, end-start); doc.remove(start, end-start); Element elem2 = root.getElement(line); // not "line+1" - removed. //int start2 = elem2.getStartOffset(); int end2 = elem2.getEndOffset(); doc.insertString(end2, text, null); elem = root.getElement(line+1); textArea.setCaretPosition(elem.getStartOffset()+caretOffset); } private final void moveLineUp(RTextArea textArea, int line) throws BadLocationException { Document doc = textArea.getDocument(); Element root = doc.getDefaultRootElement(); int lineCount = root.getElementCount(); Element elem = root.getElement(line); int start = elem.getStartOffset(); int end = line==lineCount-1 ? elem.getEndOffset()-1 : elem.getEndOffset(); int caret = textArea.getCaretPosition(); int caretOffset = caret - start; String text = doc.getText(start, end-start); if (line==lineCount-1) { start--; // Remove previous line's ending \n } doc.remove(start, end-start); Element elem2 = root.getElement(line-1); int start2 = elem2.getStartOffset(); //int end2 = elem2.getEndOffset(); if (line==lineCount-1) { text += '\n'; } doc.insertString(start2, text, null); //caretOffset = Math.min(start2+caretOffset, end2-1); textArea.setCaretPosition(start2+caretOffset); } } /** * Action to make the selection lower-case. */ public static class LowerSelectionCaseAction extends RecordableTextAction { public LowerSelectionCaseAction() { super(rtaLowerSelectionCaseAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } String selection = textArea.getSelectedText(); if (selection!=null) textArea.replaceSelection(selection.toLowerCase()); textArea.requestFocusInWindow(); } @Override public final String getMacroID() { return getName(); } } /** * Action that moves the caret to the next (or previous) bookmark. */ public static class NextBookmarkAction extends RecordableTextAction { private boolean forward; public NextBookmarkAction(String name, boolean forward) { super(name); this.forward = forward; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Gutter gutter = RSyntaxUtilities.getGutter(textArea); if (gutter!=null) { try { GutterIconInfo[] bookmarks = gutter.getBookmarks(); if (bookmarks.length==0) { UIManager.getLookAndFeel(). provideErrorFeedback(textArea); return; } GutterIconInfo moveTo = null; int curLine = textArea.getCaretLineNumber(); if (forward) { for (int i=0; i<bookmarks.length; i++) { GutterIconInfo bookmark = bookmarks[i]; int offs = bookmark.getMarkedOffset(); int line = textArea.getLineOfOffset(offs); if (line>curLine) { moveTo = bookmark; break; } } if (moveTo==null) { // Loop back to beginning moveTo = bookmarks[0]; } } else { for (int i=bookmarks.length-1; i>=0; i--) { GutterIconInfo bookmark = bookmarks[i]; int offs = bookmark.getMarkedOffset(); int line = textArea.getLineOfOffset(offs); if (line<curLine) { moveTo = bookmark; break; } } if (moveTo==null) { // Loop back to end moveTo = bookmarks[bookmarks.length-1]; } } int offs = moveTo.getMarkedOffset(); if (textArea instanceof RSyntaxTextArea) { RSyntaxTextArea rsta = (RSyntaxTextArea)textArea; if (rsta.isCodeFoldingEnabled()) { rsta.getFoldManager(). ensureOffsetNotInClosedFold(offs); } } int line = textArea.getLineOfOffset(offs); offs = textArea.getLineStartOffset(line); textArea.setCaretPosition(offs); } catch (BadLocationException ble) { // Never happens UIManager.getLookAndFeel(). provideErrorFeedback(textArea); ble.printStackTrace(); } } } @Override public final String getMacroID() { return getName(); } } /** * Selects the next occurrence of the text last selected. */ public static class NextOccurrenceAction extends RecordableTextAction { public NextOccurrenceAction(String name) { super(name); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { String selectedText = textArea.getSelectedText(); if (selectedText == null || selectedText.length() == 0) { selectedText = RTextArea.getSelectedOccurrenceText(); if (selectedText == null || selectedText.length() == 0) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } } SearchContext context = new SearchContext(selectedText); if (!SearchEngine.find(textArea, context).wasFound()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } RTextArea.setSelectedOccurrenceText(selectedText); } @Override public final String getMacroID() { return getName(); } } /** * Action to move the selection and/or caret. Constructor indicates * direction to use. */ public static class NextVisualPositionAction extends RecordableTextAction { private boolean select; private int direction; public NextVisualPositionAction(String nm, boolean select, int dir) { super(nm); this.select = select; this.direction = dir; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Caret caret = textArea.getCaret(); int dot = caret.getDot(); /* * Move to the beginning/end of selection on a "non-shifted" * left- or right-keypress. We shouldn't have to worry about * navigation filters as, if one is being used, it let us get * to that position before. */ if (!select) { switch (direction) { case SwingConstants.EAST: int mark = caret.getMark(); if (dot!=mark) { caret.setDot(Math.max(dot, mark)); return; } break; case SwingConstants.WEST: mark = caret.getMark(); if (dot!=mark) { caret.setDot(Math.min(dot, mark)); return; } break; default: } } Position.Bias[] bias = new Position.Bias[1]; Point magicPosition = caret.getMagicCaretPosition(); try { if(magicPosition == null && (direction == SwingConstants.NORTH || direction == SwingConstants.SOUTH)) { Rectangle r = textArea.modelToView(dot); magicPosition = new Point(r.x, r.y); } NavigationFilter filter = textArea.getNavigationFilter(); if (filter != null) { dot = filter.getNextVisualPositionFrom(textArea, dot, Position.Bias.Forward, direction, bias); } else { dot = textArea.getUI().getNextVisualPositionFrom( textArea, dot, Position.Bias.Forward, direction, bias); } if (select) caret.moveDot(dot); else caret.setDot(dot); if(magicPosition != null && (direction == SwingConstants.NORTH || direction == SwingConstants.SOUTH)) { caret.setMagicCaretPosition(magicPosition); } } catch (BadLocationException ble) { ble.printStackTrace(); } } @Override public final String getMacroID() { return getName(); } } /** * Positions the caret at the next word. */ public static class NextWordAction extends RecordableTextAction { private boolean select; public NextWordAction(String name, boolean select) { super(name); this.select = select; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int offs = textArea.getCaretPosition(); int oldOffs = offs; Element curPara = Utilities.getParagraphElement(textArea, offs); try { offs = getNextWord(textArea, offs); if(offs >= curPara.getEndOffset() && oldOffs != curPara.getEndOffset() - 1) { // we should first move to the end of current paragraph // http://bugs.sun.com/view_bug.do?bug_id=4278839 offs = curPara.getEndOffset() - 1; } } catch (BadLocationException ble) { int end = textArea.getDocument().getLength(); if (offs != end) { if(oldOffs != curPara.getEndOffset() - 1) offs = curPara.getEndOffset() - 1; else offs = end; } } if (select) textArea.moveCaretPosition(offs); else textArea.setCaretPosition(offs); } @Override public final String getMacroID() { return getName(); } protected int getNextWord(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getNextWord(textArea, offs); } } /** * Pages one view to the left or right. */ static class PageAction extends RecordableTextAction { private boolean select; private boolean left; public PageAction(String name, boolean left, boolean select) { super(name); this.select = select; this.left = left; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int selectedIndex; Rectangle visible = new Rectangle(); textArea.computeVisibleRect(visible); if (left) visible.x = Math.max(0, visible.x - visible.width); else visible.x += visible.width; selectedIndex = textArea.getCaretPosition(); if(selectedIndex != -1) { if (left) { selectedIndex = textArea.viewToModel( new Point(visible.x, visible.y)); } else { selectedIndex = textArea.viewToModel( new Point(visible.x + visible.width - 1, visible.y + visible.height - 1)); } Document doc = textArea.getDocument(); if ((selectedIndex != 0) && (selectedIndex > (doc.getLength()-1))) { selectedIndex = doc.getLength()-1; } else if(selectedIndex < 0) { selectedIndex = 0; } if (select) textArea.moveCaretPosition(selectedIndex); else textArea.setCaretPosition(selectedIndex); } } @Override public final String getMacroID() { return getName(); } } /** * Action for pasting text. */ public static class PasteAction extends RecordableTextAction { public PasteAction() { super(DefaultEditorKit.pasteAction); } public PasteAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.paste(); textArea.requestFocusInWindow(); } @Override public final String getMacroID() { return DefaultEditorKit.pasteAction; } } /** * "Plays back" the last macro recorded. */ public static class PlaybackLastMacroAction extends RecordableTextAction { public PlaybackLastMacroAction() { super(rtaPlaybackLastMacroAction); } public PlaybackLastMacroAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.playbackLastMacro(); } @Override public boolean isRecordable() { return false; // Don't record macro playbacks. } @Override public final String getMacroID() { return rtaPlaybackLastMacroAction; } } /** * Select the previous occurrence of the text last selected. */ public static class PreviousOccurrenceAction extends RecordableTextAction { public PreviousOccurrenceAction(String name) { super(name); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { String selectedText = textArea.getSelectedText(); if (selectedText == null || selectedText.length() == 0) { selectedText = RTextArea.getSelectedOccurrenceText(); if (selectedText == null || selectedText.length() == 0) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } } SearchContext context = new SearchContext(selectedText); context.setSearchForward(false); if (!SearchEngine.find(textArea, context).wasFound()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } RTextArea.setSelectedOccurrenceText(selectedText); } @Override public final String getMacroID() { return getName(); } } /** * Positions the caret at the beginning of the previous word. */ public static class PreviousWordAction extends RecordableTextAction { private boolean select; public PreviousWordAction(String name, boolean select) { super(name); this.select = select; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int offs = textArea.getCaretPosition(); boolean failed = false; try { Element curPara = Utilities.getParagraphElement(textArea, offs); offs = getPreviousWord(textArea, offs); if(offs < curPara.getStartOffset()) { offs = Utilities.getParagraphElement(textArea, offs). getEndOffset() - 1; } } catch (BadLocationException bl) { if (offs != 0) offs = 0; else failed = true; } if (!failed) { if (select) textArea.moveCaretPosition(offs); else textArea.setCaretPosition(offs); } else UIManager.getLookAndFeel().provideErrorFeedback(textArea); } @Override public final String getMacroID() { return getName(); } protected int getPreviousWord(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getPreviousWord(textArea, offs); } } /** * Re-does the last action undone. */ public static class RedoAction extends RecordableTextAction { public RedoAction() { super(rtaRedoAction); } public RedoAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (textArea.isEnabled() && textArea.isEditable()) { textArea.redoLastAction(); textArea.requestFocusInWindow(); } } @Override public final String getMacroID() { return rtaRedoAction; } } /** * Scrolls the text area one line up or down, without changing * the caret position. */ public static class ScrollAction extends RecordableTextAction { private int delta; public ScrollAction(String name, int delta) { super(name); this.delta = delta; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Container parent = textArea.getParent(); if (parent instanceof JViewport) { JViewport viewport = (JViewport)parent; Point p = viewport.getViewPosition(); p.y += delta*textArea.getLineHeight(); if (p.y<0) { p.y = 0; } else { Rectangle viewRect = viewport.getViewRect(); int visibleEnd = p.y + viewRect.height; if (visibleEnd>=textArea.getHeight()) { p.y = textArea.getHeight() - viewRect.height; } } viewport.setViewPosition(p); } } @Override public final String getMacroID() { return getName(); } } /** * Selects the entire document. */ public static class SelectAllAction extends RecordableTextAction { public SelectAllAction() { super(selectAllAction); } public SelectAllAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Document doc = textArea.getDocument(); textArea.setCaretPosition(0); textArea.moveCaretPosition(doc.getLength()); } @Override public final String getMacroID() { return DefaultEditorKit.selectAllAction; } } /** * Selects the line around the caret. */ public static class SelectLineAction extends RecordableTextAction { private Action start; private Action end; public SelectLineAction() { super(selectLineAction); start = new BeginLineAction("pigdog", false); end = new EndLineAction("pigdog", true); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { start.actionPerformed(e); end.actionPerformed(e); } @Override public final String getMacroID() { return DefaultEditorKit.selectLineAction; } } /** * Selects the word around the caret. */ public static class SelectWordAction extends RecordableTextAction { protected Action start; protected Action end; public SelectWordAction() { super(selectWordAction); createActions(); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { start.actionPerformed(e); end.actionPerformed(e); } protected void createActions() { start = new BeginWordAction("pigdog", false); end = new EndWordAction("pigdog", true); } @Override public final String getMacroID() { return DefaultEditorKit.selectWordAction; } } /** * Puts the text area into read-only mode. */ public static class SetReadOnlyAction extends RecordableTextAction { public SetReadOnlyAction() { super(readOnlyAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.setEditable(false); } @Override public final String getMacroID() { return DefaultEditorKit.readOnlyAction; } @Override public boolean isRecordable() { return false; // Why would you want to record this? } } /** * Puts the text area into writable (from read-only) mode. */ public static class SetWritableAction extends RecordableTextAction { public SetWritableAction() { super(writableAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.setEditable(true); } @Override public final String getMacroID() { return DefaultEditorKit.writableAction; } @Override public boolean isRecordable() { return false; // Why would you want to record this? } } /** * The action for inserting a time/date stamp. */ public static class TimeDateAction extends RecordableTextAction { public TimeDateAction() { super(rtaTimeDateAction); } public TimeDateAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } Date today = new Date(); DateFormat timeDateStamp = DateFormat.getDateTimeInstance(); String dateString = timeDateStamp.format(today); textArea.replaceSelection(dateString); } @Override public final String getMacroID() { return rtaTimeDateAction; } } /** * Toggles whether the current line has a bookmark. */ public static class ToggleBookmarkAction extends RecordableTextAction { public ToggleBookmarkAction() { super(rtaToggleBookmarkAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Gutter gutter = RSyntaxUtilities.getGutter(textArea); if (gutter!=null) { int line = textArea.getCaretLineNumber(); try { gutter.toggleBookmark(line); } catch (BadLocationException ble) { // Never happens UIManager.getLookAndFeel(). provideErrorFeedback(textArea); ble.printStackTrace(); } } } @Override public final String getMacroID() { return rtaToggleBookmarkAction; } } /** * The action for the insert key toggling insert/overwrite modes. */ public static class ToggleTextModeAction extends RecordableTextAction { public ToggleTextModeAction() { super(rtaToggleTextModeAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int textMode = textArea.getTextMode(); if (textMode==RTextArea.INSERT_MODE) textArea.setTextMode(RTextArea.OVERWRITE_MODE); else textArea.setTextMode(RTextArea.INSERT_MODE); } @Override public final String getMacroID() { return rtaToggleTextModeAction; } } /** * Undoes the last action done. */ public static class UndoAction extends RecordableTextAction { public UndoAction() { super(rtaUndoAction); } public UndoAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (textArea.isEnabled() && textArea.isEditable()) { textArea.undoLastAction(); textArea.requestFocusInWindow(); } } @Override public final String getMacroID() { return rtaUndoAction; } } /** * Removes the selection, if any. */ public static class UnselectAction extends RecordableTextAction { public UnselectAction() { super(rtaUnselectAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.setCaretPosition(textArea.getCaretPosition()); } @Override public final String getMacroID() { return rtaUnselectAction; } } /** * Action to make the selection upper-case. */ public static class UpperSelectionCaseAction extends RecordableTextAction { public UpperSelectionCaseAction() { super(rtaUpperSelectionCaseAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } String selection = textArea.getSelectedText(); if (selection!=null) textArea.replaceSelection(selection.toUpperCase()); textArea.requestFocusInWindow(); } @Override public final String getMacroID() { return getName(); } } /** * Scrolls up/down vertically. The select version of this action extends * the selection, instead of simply moving the caret. */ public static class VerticalPageAction extends RecordableTextAction { private boolean select; private int direction; public VerticalPageAction(String name, int direction, boolean select) { super(name); this.select = select; this.direction = direction; } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Rectangle visible = textArea.getVisibleRect(); Rectangle newVis = new Rectangle(visible); int selectedIndex = textArea.getCaretPosition(); int scrollAmount = textArea.getScrollableBlockIncrement( visible, SwingConstants.VERTICAL, direction); int initialY = visible.y; Caret caret = textArea.getCaret(); Point magicPosition = caret.getMagicCaretPosition(); int yOffset; if (selectedIndex!=-1) { try { Rectangle dotBounds = textArea.modelToView(selectedIndex); int x = (magicPosition != null) ? magicPosition.x : dotBounds.x; int h = dotBounds.height; yOffset = direction * ((int)Math.ceil(scrollAmount/(double)h)-1)*h; newVis.y = constrainY(textArea, initialY+yOffset, yOffset, visible.height); int newIndex; if (visible.contains(dotBounds.x, dotBounds.y)) { // Dot is currently visible, base the new // location off the old, or newIndex = textArea.viewToModel( new Point(x, constrainY(textArea, dotBounds.y + yOffset, 0, 0))); } else { // Dot isn't visible, choose the top or the bottom // for the new location. if (direction == -1) { newIndex = textArea.viewToModel(new Point( x, newVis.y)); } else { newIndex = textArea.viewToModel(new Point( x, newVis.y + visible.height)); } } newIndex = constrainOffset(textArea, newIndex); if (newIndex != selectedIndex) { // Make sure the new visible location contains // the location of dot, otherwise Caret will // cause an additional scroll. adjustScrollIfNecessary(textArea, newVis, initialY, newIndex); if (select) textArea.moveCaretPosition(newIndex); else textArea.setCaretPosition(newIndex); } } catch (BadLocationException ble) { } } // End of if (selectedIndex!=-1). else { yOffset = direction * scrollAmount; newVis.y = constrainY(textArea, initialY + yOffset, yOffset, visible.height); } if (magicPosition != null) caret.setMagicCaretPosition(magicPosition); textArea.scrollRectToVisible(newVis); } private int constrainY(JTextComponent textArea, int y, int vis, int screenHeight) { if (y < 0) y = 0; else if (y + vis > textArea.getHeight()) { //y = Math.max(0, textArea.getHeight() - vis); y = Math.max(0, textArea.getHeight()-screenHeight); } return y; } private int constrainOffset(JTextComponent text, int offset) { Document doc = text.getDocument(); if ((offset != 0) && (offset > doc.getLength())) offset = doc.getLength(); if (offset < 0) offset = 0; return offset; } private void adjustScrollIfNecessary(JTextComponent text, Rectangle visible, int initialY, int index) { try { Rectangle dotBounds = text.modelToView(index); if (dotBounds.y < visible.y || (dotBounds.y > (visible.y + visible.height)) || (dotBounds.y + dotBounds.height) > (visible.y + visible.height)) { int y; if (dotBounds.y < visible.y) y = dotBounds.y; else y = dotBounds.y + dotBounds.height - visible.height; if ((direction == -1 && y < initialY) || (direction == 1 && y > initialY)) // Only adjust if won't cause scrolling upward. visible.y = y; } } catch (BadLocationException ble) {} } @Override public final String getMacroID() { return getName(); } } }
gpl-3.0
gohdan/DFC
known_files/hashes/hostcmsfiles/shop/pay/handler2.php
47
HostCMS 6.7 = 440fdb1bc12074ff34b30a7c9ce85d13
gpl-3.0
qwert789/bebop-net
ARDroneSDK3/swig/eARCOMMANDS_JUMPINGSUMO_MEDIARECORDEVENT_PICTUREEVENTCHANGED_EVENT.cs
706
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.7 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ public enum eARCOMMANDS_JUMPINGSUMO_MEDIARECORDEVENT_PICTUREEVENTCHANGED_EVENT { ARCOMMANDS_JUMPINGSUMO_MEDIARECORDEVENT_PICTUREEVENTCHANGED_EVENT_TAKEN = 0, ARCOMMANDS_JUMPINGSUMO_MEDIARECORDEVENT_PICTUREEVENTCHANGED_EVENT_FAILED, ARCOMMANDS_JUMPINGSUMO_MEDIARECORDEVENT_PICTUREEVENTCHANGED_EVENT_MAX }
gpl-3.0
lejubila/piGardenWeb
vendor/backpack/crud/src/resources/views/inc/form_save_buttons.blade.php
1127
<div id="saveActions" class="form-group"> <input type="hidden" name="save_action" value="{{ $saveAction['active']['value'] }}"> <div class="btn-group"> <button type="submit" class="btn btn-success"> <span class="fa fa-save" role="presentation" aria-hidden="true"></span> &nbsp; <span data-value="{{ $saveAction['active']['value'] }}">{{ $saveAction['active']['label'] }}</span> </button> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aira-expanded="false"> <span class="caret"></span> <span class="sr-only">&#x25BC;</span> </button> <ul class="dropdown-menu"> @foreach( $saveAction['options'] as $value => $label) <li><a href="javascript:void(0);" data-value="{{ $value }}">{{ $label }}</a></li> @endforeach </ul> </div> <a href="{{ $crud->hasAccess('list') ? url($crud->route) : url()->previous() }}" class="btn btn-default"><span class="fa fa-ban"></span> &nbsp;{{ trans('backpack::crud.cancel') }}</a> </div>
gpl-3.0
robertwbrandt/ZarafaAdmin
www/kopano-ooo.php
6185
<?php /* * Kopano Out of Office form * * Created by: Bob Brandt (http://brandt.ie) * Created on: 2016-04-23 * * GNU GENERAL PUBLIC LICENSE * Version 2, June 1991 * ------------------------------------------------------------------------- * Copyright (C) 2013 Bob Brandt * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Turn off all error reporting //error_reporting(0); // Report all PHP errors error_reporting(-1); header("Expires: Tue, 01 Jan 2000 00:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // The following is needed to display loading screen using Progressive Rendering ob_start(); // not needed if output_buffering is on in php.ini ob_implicit_flush(); // implicitly calls flush() after every ob_flush() $buffer = ini_get('output_buffering'); // retrive the buffer size from the php.ini file if (!is_numeric($buffer)) $buffer = 8192; $username = ""; if (isset($_GET['username'])) $username = $_GET['username']; if (isset($_POST['username'])) $username = $_POST['username']; $fullname = ""; if (isset($_GET['fullname'])) $fullname = $_GET['fullname']; if (isset($_POST['fullname'])) $fullname = $_POST['fullname']; $email = ""; if (isset($_GET['email'])) $email = $_GET['email']; if (isset($_POST['email'])) $email = $_POST['email']; ?> <html><head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta http-equiv="Content-Type" charset="utf-8"> <link rel="stylesheet" href="zarafaadmin.css"> <!-- https://jqueryui.com/datepicker/ --> <link rel="stylesheet" href="jquery-ui.css"> <script src="jquery-1.10.2.js"></script> <script src="jquery-ui.js"></script> <script> $(function() { $( "#ooo-from" ).datepicker({ dateFormat: 'dd-mm-yy' }); $( "#ooo-until" ).datepicker({ dateFormat: 'dd-mm-yy' }); }); $(document).keydown(function (e) { if(e.keyCode==27){ gotoRefer(); } }); function setMode() { var mode = document.getElementById("ooo-mode").value; if (mode == 1) { document.getElementById("ooo-from").disabled = false; document.getElementById("ooo-until").disabled = false; document.getElementById("ooo-subject").disabled = false; document.getElementById("ooo-message").disabled = false; document.getElementById("ooo-from").style.backgroundColor = "white"; document.getElementById("ooo-until").style.backgroundColor = "white"; document.getElementById("ooo-subject").style.backgroundColor = "white"; document.getElementById("ooo-message").style.backgroundColor = "white"; document.getElementById("ooo-mode").style.color = "green"; } else { document.getElementById("ooo-from").disabled = true; document.getElementById("ooo-until").disabled = true; document.getElementById("ooo-subject").disabled = true; document.getElementById("ooo-message").disabled = true; document.getElementById("ooo-from").style.backgroundColor = "lightgrey"; document.getElementById("ooo-until").style.backgroundColor = "lightgrey"; document.getElementById("ooo-subject").style.backgroundColor = "lightgrey"; document.getElementById("ooo-message").style.backgroundColor = "lightgrey"; document.getElementById("ooo-subject").value = "Out of Office"; document.getElementById("ooo-message").value = ""; document.getElementById("ooo-mode").style.color = "red"; } } function gotoRefer() { window.location.href = "<?=$_SERVER['HTTP_REFERER']?>"; } </script> <title>Kopano (Un)Set Out of Office</title> </head> <body onload="setMode()"> <form action="./zarafa-action.php" method="get"> <input type="hidden" name="action" value="ooo"/> <input type="hidden" name="username" value="<?=$username?>"/> <input type="hidden" name="fullname" value="<?=$fullname?>"/> <input type="hidden" name="email" value="<?=$email?>"/> <input type="hidden" name="referer" value="<?=$_SERVER['HTTP_REFERER']?>"/> <p class="ooo-title">Set/Unset Out-of-Office for <?=$fullname?> (<?=$email?>)</p> <table id="ooo-table" align="center"> <tr> <td>&nbsp;</td> <td> <select name="mode" id="ooo-mode" style="width: 100%;" onchange="setMode()"> <option value="0" selected="selected">Disable Out-of-Office</option> <option value="1"> Enable Out-of-Office</option> </select> </td> <td align="right">From:</td> <td><input id="ooo-from" name="from"/></td> <td align="right">Until:</td> <td><input id="ooo-until" name="until"/></td> </tr> <tr> <td>&nbsp;</td> <td align="right" colspan="2">Subject:</td> <td colspan="3"><input type="text" name="subject" id="ooo-subject" value="Out of Office" style="width: 100%;"/></td> </tr> <tr> <td>&nbsp;</td> <td colspan="5" align="left">AutoReply only once to each sender with the following text:</td> </tr> <tr> <td>&nbsp;</td> <td colspan="5"> <textarea rows="4" cols="50" name="message" id="ooo-message" style="width: 100%; resize: none;"></textarea> </td> </tr> <tr> <td>&nbsp;</td> <td align="left"><input id="ooo-cancel" type="button" value="Cancel" onclick="gotoRefer()"/></td> <td colspan="3"></td> <td align="right"><input id="ooo-submit" type="submit" value="Submit"/></td> </tr> </table> </form> </body></html>
gpl-3.0
smile901122/lintcode
最接近0的子数组和 Subarray Sum Closest.cpp
1308
class Solution { public: /** * @param nums: A list of integers * @return: A list of integers includes the index of the first number * and the index of the last number */ vector<int> subarraySumClosest(vector<int> nums){ // write your code here if(nums.empty()) return nums; vector<int> res; const int size = nums.size(); vector<pair<int, int> > sum_index(size + 1); for(int i = 0; i < size; ++i) { sum_index[i + 1].first = sum_index[i].first + nums[i]; sum_index[i + 1].second = i + 1; } sort(sum_index.begin(), sum_index.end()); int min_diff = INT_MAX; int closest_index = 1; for(int i = 1; i < size + 1; ++i) { int sum_diff = sum_index[i].first - sum_index[i - 1].first; if(min_diff > sum_diff) { min_diff = sum_diff; closest_index = i; } } int left = min(sum_index[closest_index - 1].second, sum_index[closest_index].second); int right = max(sum_index[closest_index - 1].second, sum_index[closest_index].second) - 1; res.push_back(left); res.push_back(right); return res; } };
gpl-3.0
lavanyaj/mpsim
MPSimulationTest.cc
767
#include "MpWorkload.h" #include "MPSimulation.h" #include <assert.h> #include <iostream> // std::cout int main(int argc, char *argv[]) { std::cout << "usage ./MPSimulationTest cap1.txt tm1.txt 200 1" << std::endl; Workload w; assert(argc >= 4); w.parseCapFile(argv[1]); w.parseTmFile(argv[2]); std::cout << "Setting up simulation.\n"; MPSimulation s(w.getHops(), w.getHopNames(), w.getPaths(), w.getFlowToPathId());; std::cout << "--------------------\n---------------\n"; std::cout << "Simulation starts.\n"; if (argc == 5) { int seed = atoi(argv[4]); s.run(atoi(argv[3]), seed); } else s.run(atoi(argv[3]), -1); std::cout << "--------------------\n---------------\n"; std::cout << "Simulation ends.\n"; return 0; }
gpl-3.0
sdeleeuw/contagement
posts/models/post.py
828
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from content.models import Item class PostQuerySet(models.QuerySet): def filter_owner(self, user): return self.all() if user.is_superuser else self.filter(owner=user) class Post(Item): TEXT_FORMAT_CHOICES = ( ('text/plain', _('Plain Text')), ('text/markdown', _('Markdown')), ('text/html', _('HTML')), ) objects = PostQuerySet.as_manager() text = models.TextField(blank=True) text_format = models.CharField(max_length=64, choices=TEXT_FORMAT_CHOICES, default='text/plain') def as_html(self): import posts.services.post return posts.services.post.render_html(self) def get_thumbnail_url(self): return ''
gpl-3.0
nvdnkpr/joola.io.analytics
routes/login.js
2427
exports.index = function (req, res) { res.render('login', { title: 'Joola Analytics' }); }; exports.checkLoginNeeded = function (next) { joola.logger.info('Check login needed...'); var getter = (joola.config.get('engine:secure') ? require('https') : require('http')); console.log('test'); var options = { host: joola.config.get('engine:host'), port: joola.config.get('engine:port'), path: '/loginNeeded', rejectUnauthorized: false }; getter.get(options,function (response) { var body = response.on('data', function (chunk) { body += chunk; }); response.on('end', function () { var responseToken = body.replace('[object Object]', ''); responseToken = JSON.parse(responseToken); if (!responseToken['needed']) { joola.logger.info('Login not needed.'); next(false); } else { joola.logger.info('Login needed.'); next(true); } }); }).on('error', function (ex) { joola.logger.error('Failed to check login: ' + ex.message) next(false); }); }; exports.login = function (req, res) { joola.logger.info('Login request for username [' + req.body.username + ']'); var getter = (joola.config.get('engine:secure') ? require('https') : require('http')); var options = { host: joola.config.get('engine:host'), port: joola.config.get('engine:port'), path: '/loginSSO?authToken=' + joola.config.get('engine:authToken') + '&username=' + req.body.username + '&password=' + req.body.password, rejectUnauthorized: false }; getter.get(options,function (response) { var body = response.on('data', function (chunk) { body += chunk; }); response.on('end', function () { var responseToken = body.replace('[object Object]', ''); responseToken = JSON.parse(responseToken); if (!responseToken['joola-token']) { joola.logger.error('Login failed for username [' + req.body.username + '].'); res.redirect('/login/?error=1'); return; } joola.logger.info('Login success for username [' + responseToken.user.displayName + ']'); req.session.token = responseToken['joola-token']; res.redirect('/'); }); }).on('error', function (e) { joola.logger.error('Login failed for username [' + req.body.username + ']: ' + e.message); res.redirect('/login/?error=1'); }); };
gpl-3.0
PlayUAV/ardupilot
libraries/AP_HAL_Linux/RCOutput_Navio.cpp
3799
#include <AP_HAL.h> #if CONFIG_HAL_BOARD == HAL_BOARD_LINUX #include "RCOutput_Navio.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <dirent.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <math.h> using namespace Linux; #define PWM_CHAN_COUNT 13 static const AP_HAL::HAL& hal = AP_HAL_BOARD_DRIVER; void LinuxRCOutput_Navio::init(void* machtnicht) { _i2c_sem = hal.i2c->get_semaphore(); if (_i2c_sem == NULL) { hal.scheduler->panic(PSTR("PANIC: RCOutput_Navio did not get " "valid I2C semaphore!")); return; // never reached } // Set the initial frequency set_freq(0, 50); } void LinuxRCOutput_Navio::set_freq(uint32_t chmask, uint16_t freq_hz) { if (!_i2c_sem->take(10)) { return; } // Put PCA9685 to sleep (required to write prescaler) hal.i2c->writeRegister(PCA9685_ADDRESS, PCA9685_RA_MODE1, PCA9685_MODE1_SLEEP_BIT); // Calculate and write prescale value to match frequency uint8_t prescale = round(24576000.f / 4096.f / freq_hz) - 1; hal.i2c->writeRegister(PCA9685_ADDRESS, PCA9685_RA_PRE_SCALE, prescale); // Reset all channels uint8_t data[4] = {0x00, 0x00, 0x00, 0x00}; hal.i2c->writeRegisters(PCA9685_ADDRESS, PCA9685_RA_ALL_LED_ON_L, 4, data); // Enable external clocking hal.i2c->writeRegister(PCA9685_ADDRESS, PCA9685_RA_MODE1, PCA9685_MODE1_SLEEP_BIT | PCA9685_MODE1_EXTCLK_BIT); // Restart the device to apply new settings and enable auto-incremented write hal.i2c->writeRegister(PCA9685_ADDRESS, PCA9685_RA_MODE1, PCA9685_MODE1_RESTART_BIT | PCA9685_MODE1_AI_BIT); _frequency = freq_hz; _i2c_sem->give(); } uint16_t LinuxRCOutput_Navio::get_freq(uint8_t ch) { return _frequency; } void LinuxRCOutput_Navio::enable_ch(uint8_t ch) { } void LinuxRCOutput_Navio::disable_ch(uint8_t ch) { write(ch, 0); } void LinuxRCOutput_Navio::write(uint8_t ch, uint16_t period_us) { if(ch >= PWM_CHAN_COUNT){ return; } if (!_i2c_sem->take_nonblocking()) { return; } uint16_t length; if (period_us == 0) length = 0; else length = round((period_us * 4096) / (1000000.f / _frequency)) - 1; uint8_t data[2] = {length & 0xFF, length >> 8}; uint8_t status = hal.i2c->writeRegisters(PCA9685_ADDRESS, PCA9685_RA_LED0_OFF_L + 4 * (ch + 3), 2, data); _i2c_sem->give(); } void LinuxRCOutput_Navio::write(uint8_t ch, uint16_t* period_us, uint8_t len) { for (int i = 0; i < len; i++) write(ch + i, period_us[i]); } uint16_t LinuxRCOutput_Navio::read(uint8_t ch) { if (!_i2c_sem->take_nonblocking()) { return 0; } uint8_t data[4] = {0x00, 0x00, 0x00, 0x00}; hal.i2c->readRegisters(PCA9685_ADDRESS, PCA9685_RA_LED0_ON_L + 4 * (ch + 3), 4, data); uint16_t length = data[2] + ((data[3] & 0x0F) << 8); uint16_t period_us = (length + 1) * (1000000.f / _frequency) / 4096.f; _i2c_sem->give(); return length == 0 ? 0 : period_us; } void LinuxRCOutput_Navio::read(uint16_t* period_us, uint8_t len) { for (int i = 0; i < len; i++) period_us[i] = read(0 + i); } #endif // CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_NAVIO
gpl-3.0
alexyoung/wingman
test/functional/storage_controller_test.rb
2317
require 'test_helper' class StorageControllerTest < ActionController::TestCase def setup generate_fixtures @request.accept = 'application/json' end def teardown destroy_fixtures end test 'access control session fail' do @request.accept = 'text/html' post :create, { 'collection' => 'tasks', 'data' => '{"id":111111,"name":"do this"}' }, :identity_url => nil assert_redirected_to new_openid_url end test 'access control account hack' do @request.accept = 'text/javascript' @task.name = 'Example Task Updated' json = @task.attributes json['id'] = json['_id'] put :update, { 'collection' => 'tasks', 'data' => json.to_json }, :identity_url => 'https://example.com/fake' assert_response :unauthorized end test 'create' do post :create, { 'collection' => 'tasks', 'data' => '{"id":111111,"name":"do this"}' }, :identity_url => @user.identity_url assert_response :success end test 'update' do @task.name = 'Example Task Updated' json = @task.attributes json['id'] = json['_id'] put :update, { 'collection' => 'tasks', 'data' => json.to_json }, :identity_url => @user.identity_url assert_response :success end test 'update not found' do put :update, { 'collection' => 'tasks', 'data' => { '_id' => 1, 'name' => 'test' }.to_json }, :identity_url => @user.identity_url assert_response :error end test 'set_key_value create' do json = { 'key' => 'test', 'value' => [1, 2, 3, 4] }.to_json put :set_key_value, { 'data' => json, 'collection' => 'collections' }, :identity_url => @user.identity_url assert_response :success assert_equal [1, 2, 3, 4], Collection.find(:first, :conditions => { :key => 'test' }).value end test 'set_key_value update' do json = { 'key' => "project_tasks_#{@project.id}", 'value' => [@project.id, 1] }.to_json put :set_key_value, { 'data' => json, 'collection' => 'collections' }, :identity_url => @user.identity_url assert_response :success assert_equal [@project.id, 1], Collection.find(:first, :conditions => { :key => "project_tasks_#{@project.id}" }).value end test 'destroy' do delete :destroy, { 'id' => @task.id, 'collection' => 'tasks' }, :identity_url => @user.identity_url assert_response :success end end
gpl-3.0
molpopgen/libsequence
Sequence/Sites.hpp
2921
/* Copyright (C) 2003-2009 Kevin Thornton, krthornt[]@[]uci.edu Remove the brackets to email me. This file is part of libsequence. libsequence is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. libsequence is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License long with libsequence. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SITES_H #define SITES_H /*! \file Sites.hpp @brief class Sequence::Sites calculates the length of a pairwise alignment between coding sequences in terms of site degeneracy. Used by Sequence::Comeron95 */ /*! \class Sequence::Sites Sequence/Sites.hpp \ingroup kaks This class calculates the length of each sequence in a pairwise comparison in terms of site degeneracy. The 4 values computed are:\n 1.) L0 -- the number of non-degenerate sites in the comparison.\n 2.) L2S -- the number of two-fold degenerate sites in the comparison for which transitions are synonymous.\n 3.) L2V -- the number of two-fold degenerate sites in the comparison for which transversion are synonymous.\n 4.) L4 -- the number of fourfold degenerate sites in the comparison.\n \n In order to count these numbers, one has to know how degenerate each codon is, which is why objects of this type must be constructed with objects of type Sequence::RedundancyCom95. @author Kevin Thornton @short Calculate length statistics for divergence calculations */ #include <string> #include <memory> namespace Sequence { class Seq; class RedundancyCom95; class Sites { private: struct SitesImpl; std::unique_ptr<SitesImpl> impl; public: explicit Sites (); explicit Sites(const Sequence::Seq & seq1, const Sequence::Seq & seq2, const RedundancyCom95 & sitesObj, int maxdiffs = 3); Sites(Sites &&) = default; void operator()(const Sequence::Seq & seq1, const Sequence::Seq & seq2, const RedundancyCom95 & sitesObj, int maxdiffs = 3); ~Sites (void); /*! \return alignment length in terms of non-degenerate sites */ double L0(void) const; /*! \return alignment length in terms of transitional-degenerate sites */ double L2S(void) const; /*! \return alignment length in terms of transversional-degenerate sites */ double L2V(void) const; /*! \return alignment length in terms of fourfold-degenerate sites */ double L4(void) const; }; } #endif
gpl-3.0
CoPhi/cophiproofreader
src/main/java/eu/himeros/cophi/text/model/Word.java
2242
/* * This file is part of eu.himeros_CoPhiProofReader_war_1.0-SNAPSHOT * * Copyright (C) 2013 federico[DOT]boschetti[DOT]73[AT]gmail[DOT]com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.himeros.cophi.text.model; import eu.himeros.cophi.core.model.*; /** * * @author federico[DOT]boschetti[DOT]73[AT]gmail[DOT]com */ public abstract class Word<T> implements TextualUnit, Logical, Atom<T> { protected Physical<Component<?>> backingComponent; protected T content; /** * Get the physical component this logical component is based on. * * @return the backing component. */ @Override public Physical<Component<?>> getBackingComponent() { return backingComponent; } /** * Set the physical component this logical component is based on. * * @param backingComponent the backing component. */ @Override public void setBackingComponent(Physical component) { //backingComponent = (Physical<Component<?>>)component; } /** * Get the content of this word. It can be a simple string, but it can be a * complex structures with linguistic analyses. * * @return the content of this word. */ @Override public T getContent() { return content; } /** * Set the content of this word. * * @param content the content of this word. */ @Override public void setContent(T content) { this.content = content; } /** * Return true. * * @return true. */ @Override public boolean isAtomic() { return atomic; } }
gpl-3.0
sklarman/grakn
grakn-engine/src/main/java/ai/grakn/engine/tasks/mock/EndlessExecutionMockTask.java
1541
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.engine.tasks.mock; import ai.grakn.engine.TaskId; import ai.grakn.engine.tasks.TaskCheckpoint; import java.time.Duration; /** * Mocked task that will never end * * @author alexandraorth, Felix Chapman */ public class EndlessExecutionMockTask extends MockBackgroundTask { @Override protected void executeStartInner(TaskId id) { // Never return until stopped if (!cancelled.get()) { synchronized (sync) { try { sync.wait(Duration.ofMinutes(5).toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } } } } @Override protected void executeResumeInner(TaskCheckpoint checkpoint) {} public void pause() {} }
gpl-3.0
linuxwhatelse/plugin.audio.linuxwhatelse.gmusic
addon/routes/__init__.py
386
from addon.routes import home # noqa from addon.routes import listen_now # noqa from addon.routes import top_charts # noqa from addon.routes import new_releases # noqa from addon.routes import my_library # noqa from addon.routes import browse_stations # noqa from addon.routes import generic # noqa from addon.routes import actions # noqa from addon.routes import files # noqa
gpl-3.0
MyCoRe-Org/mycore
mycore-base/src/main/java/org/mycore/frontend/jersey/filter/MCRCacheFilter.java
7449
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.jersey.filter; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.ws.rs.HttpMethod; import javax.ws.rs.Produces; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.container.ResourceInfo; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.ext.RuntimeDelegate; import org.apache.http.HttpStatus; import org.apache.logging.log4j.LogManager; import org.mycore.frontend.jersey.MCRCacheControl; import org.mycore.frontend.jersey.access.MCRRequestScopeACL; public class MCRCacheFilter implements ContainerResponseFilter { private static final RuntimeDelegate.HeaderDelegate<CacheControl> HEADER_DELEGATE = RuntimeDelegate.getInstance() .createHeaderDelegate(CacheControl.class); @Context private ResourceInfo resourceInfo; private CacheControl getCacheConrol(MCRCacheControl cacheControlAnnotation) { CacheControl cc = new CacheControl(); if (cacheControlAnnotation != null) { cc.setMaxAge( (int) cacheControlAnnotation.maxAge().unit().toSeconds(cacheControlAnnotation.maxAge().time())); cc.setSMaxAge( (int) cacheControlAnnotation.sMaxAge().unit().toSeconds(cacheControlAnnotation.sMaxAge().time())); Optional.ofNullable(cacheControlAnnotation.private_()) .filter(MCRCacheControl.FieldArgument::active) .map(MCRCacheControl.FieldArgument::fields) .map(Stream::of) .ifPresent(s -> { cc.setPrivate(true); cc.getPrivateFields().addAll(s.collect(Collectors.toList())); }); if (cacheControlAnnotation.public_()) { cc.getCacheExtension().put("public", null); } cc.setNoTransform(cacheControlAnnotation.noTransform()); cc.setNoStore(cacheControlAnnotation.noStore()); Optional.ofNullable(cacheControlAnnotation.noCache()) .filter(MCRCacheControl.FieldArgument::active) .map(MCRCacheControl.FieldArgument::fields) .map(Stream::of) .ifPresent(s -> { cc.setNoCache(true); cc.getNoCacheFields().addAll(s.collect(Collectors.toList())); }); cc.setMustRevalidate(cacheControlAnnotation.mustRevalidate()); cc.setProxyRevalidate(cacheControlAnnotation.proxyRevalidate()); } else { cc.setNoTransform(false); //should have been default } return cc; } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { CacheControl cc; String currentCacheControl = requestContext.getHeaderString(HttpHeaders.CACHE_CONTROL); if (currentCacheControl != null) { if (responseContext.getHeaderString(HttpHeaders.AUTHORIZATION) == null) { return; } cc = CacheControl.valueOf(currentCacheControl); } else { //from https://developer.mozilla.org/en-US/docs/Glossary/cacheable if (!requestContext.getMethod().equals(HttpMethod.GET) && !requestContext.getMethod().equals(HttpMethod.HEAD)) { return; } boolean statusCacheable = IntStream .of(HttpStatus.SC_OK, HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION, HttpStatus.SC_NO_CONTENT, HttpStatus.SC_PARTIAL_CONTENT, HttpStatus.SC_MULTIPLE_CHOICES, HttpStatus.SC_MOVED_PERMANENTLY, HttpStatus.SC_NOT_FOUND, HttpStatus.SC_METHOD_NOT_ALLOWED, HttpStatus.SC_GONE, HttpStatus.SC_REQUEST_URI_TOO_LONG, HttpStatus.SC_NOT_IMPLEMENTED) .anyMatch(i -> i == responseContext.getStatus()); if (!statusCacheable) { return; } cc = getCacheConrol(resourceInfo.getResourceMethod().getAnnotation(MCRCacheControl.class)); } MCRRequestScopeACL aclProvider = MCRRequestScopeACL.getInstance(requestContext); if (aclProvider.isPrivate()) { cc.setPrivate(true); cc.getPrivateFields().clear(); } boolean isPrivate = cc.isPrivate() && cc.getPrivateFields().isEmpty(); boolean isNoCache = cc.isNoCache() && cc.getNoCacheFields().isEmpty(); if (responseContext.getHeaderString(HttpHeaders.AUTHORIZATION) != null) { addAuthorizationHeaderException(cc, isPrivate, isNoCache); } String headerValue = HEADER_DELEGATE.toString(cc); LogManager.getLogger() .debug(() -> "Cache-Control filter: " + requestContext.getUriInfo().getPath() + " " + headerValue); responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, headerValue); if (Stream.of(resourceInfo.getResourceClass(), resourceInfo.getResourceMethod()) .map(t -> t.getAnnotation(Produces.class)) .filter(Objects::nonNull) .map(Produces::value) .flatMap(Stream::of) .distinct() .count() > 1) { //resource may produce differenct MediaTypes, we have to set Vary header List<String> varyHeaders = Optional.ofNullable(responseContext.getHeaderString(HttpHeaders.VARY)) .map(Object::toString) .map(s -> s.split(",")) .map(Stream::of) .orElseGet(Stream::empty) .collect(Collectors.toList()); if (!varyHeaders.contains(HttpHeaders.ACCEPT)) { varyHeaders.add(HttpHeaders.ACCEPT); } responseContext.getHeaders().putSingle(HttpHeaders.VARY, varyHeaders.stream().collect(Collectors.joining(","))); } } private void addAuthorizationHeaderException(CacheControl cc, boolean isPrivate, boolean isNoCache) { cc.setPrivate(true); if (!cc.getPrivateFields().contains(HttpHeaders.AUTHORIZATION) && !isPrivate) { cc.getPrivateFields().add(HttpHeaders.AUTHORIZATION); } cc.setNoCache(true); if (!cc.getNoCacheFields().contains(HttpHeaders.AUTHORIZATION) && !isNoCache) { cc.getNoCacheFields().add(HttpHeaders.AUTHORIZATION); } } }
gpl-3.0
criticalmanufacturing/cmf.dev.i18n
src/writers/writer.interface.ts
269
export interface Writer { run(): FileOutputInformation[]; } export interface FileOutputInformation { /** * Relative file path where to write the file to. */ file: string; /** * Content of the file to write. */ content: Buffer; }
gpl-3.0
gerddie/mia
mia/core/cmdlineparser.hh
20691
/* -*- mia-c++ -*- * * This file is part of MIA - a toolbox for medical image analysis * Copyright (c) Leipzig, Madrid 1999-2017 Gert Wollny * * MIA is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MIA; if not, see <http://www.gnu.org/licenses/>. * */ #ifndef mia_core_cmdlineparser_hh #define mia_core_cmdlineparser_hh //#include <miaconfig.h> #include <vector> #include <map> #include <memory> #include <sstream> #include <iostream> #include <string> #include <iterator> #include <mia/core/cmdparamoption.hh> #include <mia/core/dictmap.hh> #include <mia/core/flagstring.hh> #include <mia/core/handlerbase.hh> #include <mia/core/selftestcmdoption.hh> NS_MIA_BEGIN /// the string defining the name of the help options extern EXPORT_CORE const char *g_help_optiongroup; /** holds the history info of a certain program call */ typedef std::map<std::string, std::string> CHistoryRecord; /** holds the name of the program and the associated history record */ typedef std::pair<std::string, CHistoryRecord> CHistoryEntry; /** \ingroup cmdline \brief program description entry identifiers These enumerates identify the parts of the program description */ enum EProgramDescriptionEntry { pdi_group = 0, /*<! The group the program belongs to, in the help the program will be described in this section */ pdi_short = 1, /*<! A sgort description of the program, this will be the head line in the unix man page. */ pdi_description = 2, /*<! The full description of the program */ pdi_example_descr = 3, /*<! description of the example that follows */ pdi_example_code = 4, /*<! The example command line without the program name */ pdi_author = 5 /*<! Author name (if other than main MIA contributer(s) */ }; extern const std::map<EProgramDescriptionEntry, const char *> g_DescriptionEntryNames; /** \ingroup cmdline \brief the map that holds a basic program description Map of strings to provied information about the program The following values should be provied: (1) the program section, (2) A short description of the program - this will become the whatis entry in the man page, (3) A long description of the program (4) A text describing an example usage (5) The actual exampel call without the program name. This information is used by the auto-help system to create man-pages and a cross-referenced help of all the programs. */ typedef std::map<EProgramDescriptionEntry, const char *> SProgramDescription; /** \ingroup cmdline \brief Command line option that translates a string to a set of flags. */ class CCmdFlagOption: public CCmdOption { public: /** Constructor of the command option \param[in,out] val variable to hold the parsed option value - pass in the default value - \param map the lookup table for the option \param short_opt short option name (or 0) \param long_opt long option name (must not be NULL) \param long_help long help string (must not be NULL) \param short_help short help string \param flags if this is set to true, extra checking will be done weather the option is really set */ CCmdFlagOption(int& val, const CFlagString& map, char short_opt, const char *long_opt, const char *long_help, const char *short_help, CCmdOptionFlags flags = CCmdOptionFlags::none); private: virtual bool do_set_value(const char *str_value); virtual size_t do_get_needed_args() const; virtual void do_write_value(std::ostream& os) const; virtual void do_get_long_help(std::ostream& os) const; virtual const std::string do_get_value_as_string() const; int& m_value; const CFlagString m_map; }; /** \ingroup cmdline \brief The class to hold the list of options This class holds all the user defined and default command line option, handles the parsing and the printing of help. \todo the whole command line option class structure needs a code cleanup */ class EXPORT_CORE CCmdOptionList { public: /** This enum describes the type of help information that has been requested */ enum EHelpRequested { hr_no = 0, /**< no help has been requested */ hr_help, /**< standard help output has been requested */ hr_help_xml, /**< XML-formatted help has been requested */ hr_usage, /**< a short usage description has been requested */ hr_version, /**< The version information has been requested */ hr_copyright, /**< The long copyright information has been requested */ hr_selftest /**< The selftest was run */ }; /** Constructor creates the options list and adds some defaut options like --help, --verbose, --copyright, and --usage \param description give a description of the program */ CCmdOptionList(const SProgramDescription& description); /// cleanup ~CCmdOptionList(); /** add a new option to the option list \param opt the option to add */ void add(PCmdOption opt); /** Add a new option to an option group \param group option group to add this option to \param opt the option to add */ void add(const std::string& group, PCmdOption opt); /** Add a selftest option. The selftest option runs the given self test and then exists. Additional parameters given on the command line are ignored. The option is set within the group \a Test and provides the long optionb name \a --selftest. \param [out] test_result stores the result returned by running by running the test suite \param callback the test functor that must have CSelftestCallback as a base class */ void add_selftest(int& test_result, CSelftestCallback *callback); /** the work routine, can take the arguemnts straight from \a main This version parses the command line and allows for additional arguments that can be read by get_remaining(). \param argc number of arguments \param args array of arguments strings \param additional_type will is a help string to describe the type of free parameters \param additional_help If you use a plug-in handler to process the free parameters then pass the pointer to the according plug-in handler here, so that the help system can create proper documentation */ EHelpRequested parse(size_t argc, char *args[], const std::string& additional_type, const CPluginHandlerBase *additional_help = NULL) __attribute__((warn_unused_result)); /** the work routine, can take the arguemnts straight from \a main This version parses the command line and allows for additional arguments that can be read by get_remaining(). \param argc number of arguments \param args array of arguments strings \param additional_type will is a help string to describe the type of free parameters \param additional_help If you use a plug-in handler to process the free parameters then pass the pointer to the according plug-in handler here, so that the help system can create proper documentation */ EHelpRequested parse(size_t argc, const char *args[], const std::string& additional_type, const CPluginHandlerBase *additional_help = NULL) __attribute__((warn_unused_result)); /** the work routine, can take the arguemnts straight from \a main This version parses doesn't allow additional parameters. \param argc number of arguments \param args array of arguments strings */ EHelpRequested parse(size_t argc, char *args[]) __attribute__((warn_unused_result)); /** the work routine, can take the arguemnts straight from \a main This version parses doesn't allow additional parameters. \param argc number of arguments \param args array of arguments strings */ EHelpRequested parse(size_t argc, const char *args[]) __attribute__((warn_unused_result)); /// \returns a vector of the remaining arguments const std::vector<std::string>& get_remaining() const; /** \returns the values of all arguments as a history record to support tracking of changes on data worked on by \a mia */ CHistoryRecord get_values() const; /** Set the option group to add subsequent options to @param group */ void set_group(const std::string& group); /** Set the output stream for help/usage messages \param os new output stream */ void set_logstream(std::ostream& os); /** This function sets a flag that indicates that data written to stdout is an actual result */ void set_stdout_is_result(); private: EHelpRequested do_parse(size_t argc, const char *args[], bool has_additional, const CPluginHandlerBase *additional_help) __attribute__((warn_unused_result)); int handle_shortargs(const char *arg, size_t argc, const char *args[]); struct CCmdOptionListData *m_impl; }; // implementation of template classes and functions /** \ingroup cmdline \brief Create a standard option that sets a value of the give type Create a standard option that translates a string given on the command line into a value. The translation back-end is implemented with CTParameter. \tparam T the type of thevalue, it must support to be read from (operator >>) and written (operator << ) to a stream, as the back-end uses these opterator to translate. \param[in,out] value at input the default value, at output the parsed value if it was given. \param short_opt short option name (or 0) \param long_opt long option name (must not be NULL) \param help long help string (must not be NULL) \param flags add flags like whether the optionis required to be set \returns the option warped into a boost::shared_ptr */ template <typename T> PCmdOption make_opt(T& value, const char *long_opt, char short_opt, const char *help, CCmdOptionFlags flags = CCmdOptionFlags::none) { bool required = has_flag(flags, CCmdOptionFlags::required); return PCmdOption(new CParamOption( short_opt, long_opt, new CTParameter<T>(value, required, help))); } /** \ingroup cmdline \brief Create an option of a scalar value that can have boundaries If the given value does not fit into the range an exception will be thrown \tparam T type of the value to be parsed, supported are float, double, long, int, short, unsigned long, unsigned int, unsigned short. \param value value variable to hold the parsed option value - pass in the default value - \param bflags boundary flags \param bounds vector containing the boundaries of the allowed parameter range (depends on bflags) \param short_opt short option name (or 0) \param long_opt long option name (must not be NULL) \param help long help string (must not be NULL) \param flags add flags like whether the optionis required to be set \returns the option warped into a \a boost::shared_ptr */ template <typename T> PCmdOption make_opt(T& value, EParameterBounds bflags, const std::vector<T>& bounds, const char *long_opt, char short_opt, const char *help, CCmdOptionFlags flags = CCmdOptionFlags::none) { bool required = has_flag(flags, CCmdOptionFlags::required); return PCmdOption(new CParamOption( short_opt, long_opt, new TBoundedParameter<T>(value, bflags, bounds, required, help))); } /** \ingroup cmdline \brief Create an option that represents a flag. It is always assumed to be not set if the according option is not given at the command line \param[out] value the boolean that carries the result \param long_opt long option name (must not be NULL) \param short_opt short option name (or 0) \param help help string (must not be NULL) \param flags option flags \returns the option warped into a \a boost::shared_ptr */ PCmdOption make_opt(bool& value, const char *long_opt, char short_opt, const char *help, CCmdOptionFlags flags = CCmdOptionFlags::none); /** \ingroup cmdline \brief Create a table lookup option Create an option that uses a table to translate between the string given on the command line and the actual value. \tparam T the type of the value \param[in,out] value variable to hold the parsed and translated option value. At entry, the value must be set to a valid dictionary entry. \param map the lookup table for the option \param long_opt long option name (must not be NULL) \param short_opt short option name (or 0) \param help help string (must not be NULL) \returns the option warped into a \a boost::shared_ptr */ template <typename T> PCmdOption make_opt(T& value, const TDictMap<T>& map, const char *long_opt, char short_opt, const char *help) { return PCmdOption(new CParamOption( short_opt, long_opt, new CDictParameter<T>(value, map, help))); } /** \ingroup cmdline \brief Create a flag lookup option \param[in,out] value at input it holds the default value, at output, if the command line option was givem this value is replaced by the parsed and translated option value, \param map the lookup table for the option flags \param long_opt long option name (must not be NULL) \param short_opt short option name (or 0) \param long_help long help string (must not be NULL) \param short_help short help string \param flags add flags like whether the optionis required to be set \returns the option warped into a \a boost::shared_ptr \remark Probably unnecessary */ PCmdOption make_opt(int& value, const CFlagString& map, const char *long_opt, char short_opt, const char *long_help, const char *short_help, CCmdOptionFlags flags = CCmdOptionFlags::none); /** \ingroup cmdline \brief Create an option to set a string Create an option that holds a string \param[in,out] value at input it holds the default value, at output, if the command line option was givem this value is replaced by the parsed and translated option value, \param long_opt long option name (must not be NULL) \param short_opt short option name (or 0) \param long_help long help string (must not be NULL) \param flags add flags like whether the optionis required to be set \param plugin_hint if the string will later be used to create an object by using plug-in then pass a pointer to the corresponding plug-in handler to give a hint the help system about this connection. \returns the option warped into a \a boost::shared_ptr */ PCmdOption make_opt(std::string& value, const char *long_opt, char short_opt, const char *long_help, CCmdOptionFlags flags = CCmdOptionFlags::none, const CPluginHandlerBase *plugin_hint = NULL); /** \ingroup cmdline \brief Create an oüption that only takes values from a pre-defined set Create an option that can only take values from a given set. \tparam T the type of the value to be set \param[in,out] value at input it holds the default value, at output, if the command line option was givem this value is replaced by the parsed and translated option value, \param valid_set the set of allowed values \param long_opt long option name (must not be NULL) \param short_opt short option name (or 0) \param help long help string (must not be NULL) \param flags option flags indicating whether the option is required \returns the option warped into a \a boost::shared_ptr */ template <typename T> PCmdOption make_opt(T& value, const std::set<T>& valid_set, const char *long_opt, char short_opt, const char *help, CCmdOptionFlags flags = CCmdOptionFlags::none) { bool required = has_flag(flags, CCmdOptionFlags::required); return PCmdOption(new CParamOption( short_opt, long_opt, new CSetParameter<T>(value, valid_set, help, required))); } /** \ingroup cmdline \brief Create a command line option that creates uses a factory to create an object based on the given description Create a command line option that creates uses a factory to create the value based on the command line arguments given, \tparam T the non-pointer type of the value \param[out] value at output, if the command line option was givem this value is replaced by the parsed and translated option value. If not given but the default_values was given then this default initializer is used to create the actual value. If no default value was givem and the option is not given at the command line, then the value is not touched. \param default_value default value if parameter is not given \param long_opt long option name \param short_opt short option char, set to 0 of none givn \param help the help string for thie option \param flags indicates whether theoption is required \remark although passing in an initialized pointer and and empty default_value would act like the the initializer string was used for the pointer, it is better to pass an empty shared pointer in order to avoid unnecessary initializations of the pointer is later overwritten. */ template <typename T> PCmdOption make_opt(typename std::shared_ptr<T>& value, const char *default_value, const char *long_opt, char short_opt, const char *help, CCmdOptionFlags flags = CCmdOptionFlags::none) { bool required = has_flag(flags, CCmdOptionFlags::required); typedef typename FactoryTrait<T>::type F; return PCmdOption(new CParamOption( short_opt, long_opt, new TFactoryParameter<F>(value, default_value, required, help))); } /** \ingroup cmdline \brief Create a command line option that creates uses a factory to create an object based on the given description Create a command line option that uses a TFactoryPluginHandler to create the actual value hold by a std::unique_ptr. \tparam T the non-pointer type of the value \param[out] value at output, if the command line option was given this value is replaced by the parsed and translated option value. If not given but the default_values was given then this default initializer is used to create the actual value. \param default_value default value if parameter is not given \param long_opt long option name \param short_opt short option char, set to 0 of none givn \param help the help string for thie option \param flags option flags indicating whether the option is required \remark although passing in an initialized pointer and and empty default_value would act like the the initializer string was used for the pointer, it is better to pass an empty shared pointer in order to avoid unnecessary initializations of the pointer is later overwritten. */ template <typename T> PCmdOption make_opt(typename std::unique_ptr<T>& value, const char *default_value, const char *long_opt, char short_opt, const char *help, CCmdOptionFlags flags = CCmdOptionFlags::none) { bool required = has_flag(flags, CCmdOptionFlags::required); typedef typename FactoryTrait<T>::type F; return PCmdOption(new CParamOption( short_opt, long_opt, new TFactoryParameter<F>(value, default_value, required, help))); } NS_MIA_END #endif
gpl-3.0
glaxx/tomahawk
lang/tomahawk_is.ts
201248
<?xml version="1.0" ?><!DOCTYPE TS><TS language="is" version="2.0"> <context> <name>ACLJobDelegate</name> <message> <location filename="../src/libtomahawk/jobview/AclJobItem.cpp" line="67"/> <source>Allow %1 to connect and stream from you?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/jobview/AclJobItem.cpp" line="83"/> <source>Allow Streaming</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/jobview/AclJobItem.cpp" line="86"/> <source>Deny Access</source> <translation type="unfinished"/> </message> </context> <context> <name>ACLJobItem</name> <message> <location filename="../src/libtomahawk/jobview/AclJobItem.cpp" line="185"/> <source>%applicationName needs you to decide whether %1 is allowed to connect.</source> <translation type="unfinished"/> </message> </context> <context> <name>AccountFactoryWrapper</name> <message> <location filename="../src/libtomahawk/accounts/AccountFactoryWrapper.cpp" line="42"/> <source>Add Account</source> <translation type="unfinished"/> </message> </context> <context> <name>AccountFactoryWrapperDelegate</name> <message> <location filename="../src/libtomahawk/accounts/AccountFactoryWrapperDelegate.cpp" line="103"/> <source>Online</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/AccountFactoryWrapperDelegate.cpp" line="108"/> <source>Connecting...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/AccountFactoryWrapperDelegate.cpp" line="113"/> <source>Offline</source> <translation type="unfinished"/> </message> </context> <context> <name>AccountListWidget</name> <message> <location filename="../src/tomahawk/widgets/AccountListWidget.cpp" line="64"/> <source>Connections</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/widgets/AccountListWidget.cpp" line="72"/> <location filename="../src/tomahawk/widgets/AccountListWidget.cpp" line="243"/> <source>Connect &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/widgets/AccountListWidget.cpp" line="242"/> <source>Disconnect &amp;All</source> <translation type="unfinished"/> </message> </context> <context> <name>AccountWidget</name> <message> <location filename="../src/tomahawk/widgets/AccountWidget.cpp" line="131"/> <source>Invite</source> <translation type="unfinished"/> </message> </context> <context> <name>AccountsToolButton</name> <message> <location filename="../src/tomahawk/widgets/AccountsToolButton.cpp" line="90"/> <source>Configure Accounts</source> <translation type="unfinished"/> </message> </context> <context> <name>ActionCollection</name> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="65"/> <source>&amp;Listen Along</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="68"/> <source>Stop &amp;Listening Along</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="72"/> <source>&amp;Follow in Real-Time</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="77"/> <source>&amp;Listen Privately</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="82"/> <source>&amp;Load Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="83"/> <source>&amp;Load Station</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="84"/> <source>&amp;Rename Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="85"/> <source>&amp;Rename Station</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="86"/> <source>&amp;Copy Playlist Link</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="87"/> <source>&amp;Play</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="91"/> <source>&amp;Stop</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="92"/> <source>&amp;Previous Track</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="95"/> <source>&amp;Next Track</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="98"/> <source>&amp;Quit</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="112"/> <source>U&amp;pdate Collection</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="113"/> <source>Fully &amp;Rescan Collection</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="116"/> <source>&amp;Configure %applicationName...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="132"/> <source>About &amp;%applicationName...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="143"/> <source>%applicationName 0.8</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="111"/> <source>Import Playlist...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="114"/> <source>Show Offline Friends</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="119"/> <source>Minimize</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="121"/> <source>Zoom</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="123"/> <source>Enter Full Screen</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="126"/> <source>Hide Menu Bar</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="130"/> <source>Diagnostics...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="134"/> <source>&amp;Legal Information...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="136"/> <source>&amp;View Logfile</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="139"/> <source>Check For Updates...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="145"/> <source>Report a Bug</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="146"/> <source>Get Support</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="147"/> <source>Help Us Translate</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="157"/> <source>&amp;Controls</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="172"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="179"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="188"/> <location filename="../src/libtomahawk/ActionCollection.cpp" line="258"/> <source>What&apos;s New in ...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="214"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ActionCollection.cpp" line="231"/> <source>Main Menu</source> <translation type="unfinished"/> </message> </context> <context> <name>AlbumInfoWidget</name> <message> <location filename="../src/libtomahawk/viewpages/AlbumViewPage.cpp" line="62"/> <source>Album Details</source> <translation type="unfinished"/> </message> </context> <context> <name>AlbumModel</name> <message> <location filename="../src/libtomahawk/playlist/AlbumModel.cpp" line="61"/> <location filename="../src/libtomahawk/playlist/AlbumModel.cpp" line="98"/> <source>All albums from %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/AlbumModel.cpp" line="100"/> <source>All albums</source> <translation type="unfinished"/> </message> </context> <context> <name>ArtistInfoWidget</name> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.ui" line="50"/> <source>Top Albums</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.ui" line="110"/> <source>Top Hits</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.ui" line="76"/> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.ui" line="136"/> <source>Show More</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.ui" line="173"/> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.cpp" line="147"/> <source>Biography</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.ui" line="267"/> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.cpp" line="148"/> <source>Related Artists</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.cpp" line="94"/> <source>Sorry, we could not find any albums for this artist!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.cpp" line="73"/> <source>Sorry, we could not find any related artists!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.cpp" line="115"/> <source>Sorry, we could not find any top hits for this artist!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.cpp" line="146"/> <source>Music</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.cpp" line="185"/> <source>Songs</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/ArtistViewPage.cpp" line="201"/> <source>Albums</source> <translation type="unfinished"/> </message> </context> <context> <name>AudioControls</name> <message> <location filename="../src/tomahawk/AudioControls.cpp" line="109"/> <location filename="../src/tomahawk/AudioControls.cpp" line="341"/> <source>Shuffle</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/AudioControls.cpp" line="110"/> <location filename="../src/tomahawk/AudioControls.cpp" line="342"/> <source>Repeat</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/AudioControls.cpp" line="339"/> <source>Time Elapsed</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/AudioControls.cpp" line="340"/> <source>Time Remaining</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/AudioControls.cpp" line="345"/> <source>Playing from %1</source> <translation type="unfinished"/> </message> </context> <context> <name>AudioEngine</name> <message> <location filename="../src/libtomahawk/audio/AudioEngine.cpp" line="912"/> <source>Sorry, %applicationName couldn&apos;t find the track &apos;%1&apos; by %2</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/audio/AudioEngine.cpp" line="936"/> <source>Sorry, %applicationName couldn&apos;t find the artist &apos;%1&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/audio/AudioEngine.cpp" line="962"/> <source>Sorry, %applicationName couldn&apos;t find the album &apos;%1&apos; by %2</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/audio/AudioEngine.cpp" line="999"/> <source>Sorry, couldn&apos;t find any playable tracks</source> <translation type="unfinished"/> </message> </context> <context> <name>CaptionLabel</name> <message> <location filename="../src/libtomahawk/widgets/CaptionLabel.cpp" line="71"/> <source>Close</source> <translation type="unfinished"/> </message> </context> <context> <name>CategoryAddItem</name> <message> <location filename="../src/tomahawk/sourcetree/items/CategoryItems.cpp" line="65"/> <source>Create new Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/CategoryItems.cpp" line="68"/> <source>Create new Station</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/CategoryItems.cpp" line="186"/> <location filename="../src/tomahawk/sourcetree/items/CategoryItems.cpp" line="295"/> <source>New Station</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/CategoryItems.cpp" line="186"/> <location filename="../src/tomahawk/sourcetree/items/CategoryItems.cpp" line="295"/> <source>%1 Station</source> <translation type="unfinished"/> </message> </context> <context> <name>CategoryItem</name> <message> <location filename="../src/tomahawk/sourcetree/items/CategoryItems.cpp" line="391"/> <source>Playlists</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/CategoryItems.cpp" line="393"/> <source>Stations</source> <translation type="unfinished"/> </message> </context> <context> <name>ClearButton</name> <message> <location filename="../src/libtomahawk/widgets/searchlineedit/ClearButton.cpp" line="38"/> <source>Clear</source> <translation type="unfinished"/> </message> </context> <context> <name>CollectionItem</name> <message> <location filename="../src/tomahawk/sourcetree/items/CollectionItem.cpp" line="38"/> <source>Collection</source> <translation type="unfinished"/> </message> </context> <context> <name>CollectionViewPage</name> <message> <location filename="../src/libtomahawk/viewpages/CollectionViewPage.cpp" line="83"/> <source>Sorry, there are no albums in this collection!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/CollectionViewPage.cpp" line="95"/> <source>Artists</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/CollectionViewPage.cpp" line="96"/> <source>Albums</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/CollectionViewPage.cpp" line="97"/> <source>Songs</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/CollectionViewPage.cpp" line="125"/> <source>Download All</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/CollectionViewPage.cpp" line="430"/> <source>After you have scanned your music collection you will find your tracks right here.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/CollectionViewPage.cpp" line="433"/> <source>This collection is empty.</source> <translation type="unfinished"/> </message> </context> <context> <name>ColumnItemDelegate</name> <message> <location filename="../src/libtomahawk/playlist/ColumnItemDelegate.cpp" line="191"/> <source>Unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>ColumnView</name> <message> <location filename="../src/libtomahawk/playlist/ColumnView.cpp" line="284"/> <source>Sorry, your filter &apos;%1&apos; did not match any results.</source> <translation type="unfinished"/> </message> </context> <context> <name>ColumnViewPreviewWidget</name> <message> <location filename="../src/libtomahawk/playlist/ColumnViewPreviewWidget.cpp" line="111"/> <source>Composer:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/ColumnViewPreviewWidget.cpp" line="118"/> <source>Duration:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/ColumnViewPreviewWidget.cpp" line="125"/> <source>Bitrate:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/ColumnViewPreviewWidget.cpp" line="132"/> <source>Year:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/ColumnViewPreviewWidget.cpp" line="139"/> <source>Age:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/ColumnViewPreviewWidget.cpp" line="217"/> <source>%1 kbps</source> <translation type="unfinished"/> </message> </context> <context> <name>ContextView</name> <message> <location filename="../src/libtomahawk/playlist/ContextView.cpp" line="139"/> <source>Playlist Details</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/ContextView.cpp" line="273"/> <source>This playlist is currently empty.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/ContextView.cpp" line="275"/> <source>This playlist is currently empty. Add some tracks to it and enjoy the music!</source> <translation type="unfinished"/> </message> </context> <context> <name>DelegateConfigWrapper</name> <message> <location filename="../src/libtomahawk/accounts/DelegateConfigWrapper.cpp" line="39"/> <source>%1 Config</source> <comment>Window title for account config windows</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/DelegateConfigWrapper.cpp" line="60"/> <source>About</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/DelegateConfigWrapper.cpp" line="92"/> <source>Delete Account</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/DelegateConfigWrapper.cpp" line="121"/> <source>Config Error</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/DelegateConfigWrapper.cpp" line="177"/> <source>About this Account</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/DelegateConfigWrapper.cpp" line="230"/> <source>Your config is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>DiagnosticsDialog</name> <message> <location filename="../src/tomahawk/dialogs/DiagnosticsDialog.ui" line="20"/> <source>Tomahawk Diagnostics</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/DiagnosticsDialog.ui" line="42"/> <source>&amp;Copy to Clipboard</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/DiagnosticsDialog.ui" line="49"/> <source>Open &amp;Log-file</source> <translation type="unfinished"/> </message> </context> <context> <name>DownloadManager</name> <message> <location filename="../src/libtomahawk/DownloadManager.cpp" line="286"/> <source>%applicationName finished downloading %1 by %2.</source> <translation type="unfinished"/> </message> </context> <context> <name>EchonestSteerer</name> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="63"/> <source>Steer this station:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="86"/> <source>Much less</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="87"/> <source>Less</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="88"/> <source>A bit less</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="89"/> <source>Keep at current</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="90"/> <source>A bit more</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="91"/> <source>More</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="92"/> <source>Much more</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="95"/> <source>Tempo</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="96"/> <source>Loudness</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="97"/> <source>Danceability</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="98"/> <source>Energy</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="99"/> <source>Song Hotttnesss</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="100"/> <source>Artist Hotttnesss</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="101"/> <source>Artist Familiarity</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="102"/> <source>By Description</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="110"/> <source>Enter a description</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="117"/> <source>Apply steering command</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestSteerer.cpp" line="123"/> <source>Reset all steering commands</source> <translation type="unfinished"/> </message> </context> <context> <name>FilterHeader</name> <message> <location filename="../src/libtomahawk/widgets/FilterHeader.cpp" line="29"/> <source>Filter...</source> <translation type="unfinished"/> </message> </context> <context> <name>GlobalActionManager</name> <message> <location filename="../src/libtomahawk/GlobalActionManager.cpp" line="127"/> <source>Resolver installation from file %1 failed.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/GlobalActionManager.cpp" line="135"/> <source>Install plug-in</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/GlobalActionManager.cpp" line="136"/> <source>&lt;b&gt;%1&lt;/b&gt; %2&lt;br/&gt;by &lt;b&gt;%3&lt;/b&gt;&lt;br/&gt;&lt;br/&gt;You are attempting to install a %applicationName plug-in from an unknown source. Plug-ins from untrusted sources may put your data at risk.&lt;br/&gt;Do you want to install this plug-in?</source> <translation type="unfinished"/> </message> </context> <context> <name>HatchetAccountConfig</name> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.ui" line="33"/> <source>Connect to your Hatchet account</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.ui" line="43"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;a href=&quot;http://blog.hatchet.is&quot;&gt;Learn More&lt;/a&gt; and/or &lt;a href=&quot;http://hatchet.is/register&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#0000ff;&quot;&gt;Create Account&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.ui" line="78"/> <source>Enter One-time Password (OTP)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.ui" line="86"/> <source>Username</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.ui" line="93"/> <source>Hatchet username</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.ui" line="100"/> <source>Password:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.ui" line="113"/> <source>Hatchet password</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.ui" line="154"/> <source>Login</source> <translation type="unfinished"/> </message> </context> <context> <name>HeaderWidget</name> <message> <location filename="../src/libtomahawk/widgets/HeaderWidget.ui" line="73"/> <source>Refresh</source> <translation type="unfinished"/> </message> </context> <context> <name>HistoryWidget</name> <message> <location filename="../src/libtomahawk/widgets/HistoryWidget.cpp" line="46"/> <source>Recently Played Tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/widgets/HistoryWidget.cpp" line="49"/> <source>Your recently played tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/widgets/HistoryWidget.cpp" line="51"/> <source>%1&apos;s recently played tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/widgets/HistoryWidget.cpp" line="57"/> <source>Sorry, we could not find any recent plays!</source> <translation type="unfinished"/> </message> </context> <context> <name>HostDialog</name> <message> <location filename="../src/tomahawk/dialogs/HostDialog.ui" line="17"/> <source>Host Settings</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/HostDialog.ui" line="35"/> <source>Configure your external IP address or host name here. Make sure to manually forward the selected port to this host on your router.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/HostDialog.ui" line="53"/> <source>Static Host Name:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/HostDialog.ui" line="69"/> <source>Static Port:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/HostDialog.ui" line="106"/> <source>Automatically detect external IP address</source> <translation type="unfinished"/> </message> </context> <context> <name>InboxItem</name> <message> <location filename="../src/tomahawk/sourcetree/items/InboxItem.cpp" line="35"/> <source>Inbox</source> <translation type="unfinished"/> </message> </context> <context> <name>InboxJobItem</name> <message> <location filename="../src/libtomahawk/jobview/InboxJobItem.cpp" line="67"/> <source>Sent %1 by %2 to %3.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/jobview/InboxJobItem.cpp" line="72"/> <source>%1 sent you %2 by %3.</source> <translation type="unfinished"/> </message> </context> <context> <name>InboxPage</name> <message> <location filename="../src/libtomahawk/playlist/InboxView.cpp" line="84"/> <source>Inbox Details</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/InboxView.cpp" line="93"/> <source>Your friends have not shared any recommendations with you yet. Connect with them and share your musical gems!</source> <translation type="unfinished"/> </message> </context> <context> <name>IndexingJobItem</name> <message> <location filename="../src/libtomahawk/jobview/IndexingJobItem.cpp" line="33"/> <source>Indexing Music Library</source> <translation type="unfinished"/> </message> </context> <context> <name>LastFmConfig</name> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.ui" line="38"/> <source>Scrobble tracks to Last.fm</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.ui" line="47"/> <source>Username:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.ui" line="57"/> <source>Password:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.ui" line="73"/> <source>Test Login</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.ui" line="80"/> <source>Import Playback History</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.ui" line="87"/> <source>Synchronize Loved Tracks</source> <translation type="unfinished"/> </message> </context> <context> <name>LatchedStatusItem</name> <message> <location filename="../src/libtomahawk/jobview/LatchedStatusItem.cpp" line="33"/> <source>%1 is listening along with you!</source> <translation type="unfinished"/> </message> </context> <context> <name>LoadPlaylist</name> <message> <location filename="../src/tomahawk/dialogs/LoadPlaylistDialog.ui" line="14"/> <source>Load Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/LoadPlaylistDialog.ui" line="20"/> <source>Enter the URL of the hosted playlist (e.g. .xspf format) or click the button to select a local M3U of XSPF playlist to import.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/LoadPlaylistDialog.ui" line="35"/> <source>Playlist URL</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/LoadPlaylistDialog.ui" line="42"/> <source>Enter URL...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/LoadPlaylistDialog.ui" line="55"/> <source>...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/LoadPlaylistDialog.ui" line="64"/> <source>Automatically Update (upon changes to hosted playlist)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/LoadPlaylistDialog.ui" line="79"/> <source>To import a playlist from Spotify, Rdio, Beats, etc. - simply drag the link into Tomahawk.</source> <translation type="unfinished"/> </message> </context> <context> <name>LoadPlaylistDialog</name> <message> <location filename="../src/tomahawk/dialogs/LoadPlaylistDialog.cpp" line="56"/> <source>Load Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/LoadPlaylistDialog.cpp" line="56"/> <source>Playlists (*.xspf *.m3u *.jspf)</source> <translation type="unfinished"/> </message> </context> <context> <name>LovedTracksItem</name> <message> <location filename="../src/tomahawk/sourcetree/items/LovedTracksItem.cpp" line="58"/> <source>Top Loved Tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/LovedTracksItem.cpp" line="60"/> <source>Favorites</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/LovedTracksItem.cpp" line="86"/> <source>Sorry, we could not find any of your Favorites!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/LovedTracksItem.cpp" line="89"/> <source>The most loved tracks from all your friends</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/LovedTracksItem.cpp" line="95"/> <source>All of your loved tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/LovedTracksItem.cpp" line="97"/> <source>All of %1&apos;s loved tracks</source> <translation type="unfinished"/> </message> </context> <context> <name>MetadataEditor</name> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="30"/> <source>Tags</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="39"/> <source>Title:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="49"/> <source>Title...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="56"/> <source>Artist:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="66"/> <source>Artist...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="73"/> <source>Album:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="83"/> <source>Album...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="90"/> <source>Track Number:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="119"/> <source>Duration:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="129"/> <source>00.00</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="136"/> <source>Year:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="162"/> <source>Bitrate:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="183"/> <source>File</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="189"/> <source>File Name:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="199"/> <source>File Name...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="206"/> <source>File Size...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="212"/> <source>File size...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="219"/> <source>File Size:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="235"/> <source>Back</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.ui" line="245"/> <source>Forward</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.cpp" line="185"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.cpp" line="185"/> <source>Could not write tags to file: %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/filemetadata/MetadataEditor.cpp" line="396"/> <source>Properties</source> <translation type="unfinished"/> </message> </context> <context> <name>NetworkActivityWidget</name> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.ui" line="39"/> <source>Trending Tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.ui" line="79"/> <source>Hot Playlists</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.ui" line="113"/> <source>Trending Artists</source> <translation type="unfinished"/> </message> </context> <context> <name>PlayableModel</name> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="50"/> <source>Artist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="50"/> <source>Title</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="50"/> <source>Composer</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="50"/> <source>Album</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="50"/> <source>Track</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="50"/> <source>Duration</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="50"/> <source>Download</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="51"/> <source>Bitrate</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="51"/> <source>Age</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="51"/> <source>Year</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="51"/> <source>Size</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="51"/> <source>Origin</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="51"/> <source>Accuracy</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="896"/> <source>Perfect match</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="897"/> <source>Very good match</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="898"/> <source>Good match</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="899"/> <source>Vague match</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="900"/> <source>Bad match</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="901"/> <source>Very bad match</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="902"/> <source>Not available</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="903"/> <source>Searching...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="51"/> <location filename="../src/libtomahawk/playlist/PlayableModel.cpp" line="392"/> <source>Name</source> <translation type="unfinished"/> </message> </context> <context> <name>PlaylistItemDelegate</name> <message> <location filename="../src/libtomahawk/playlist/PlaylistItemDelegate.cpp" line="146"/> <location filename="../src/libtomahawk/playlist/PlaylistItemDelegate.cpp" line="283"/> <source>Download %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlaylistItemDelegate.cpp" line="294"/> <location filename="../src/libtomahawk/playlist/PlaylistItemDelegate.cpp" line="309"/> <source>View in Finder</source> <translation type="unfinished"/> </message> </context> <context> <name>PlaylistModel</name> <message> <location filename="../src/libtomahawk/playlist/PlaylistModel.cpp" line="144"/> <source>A playlist you created %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlaylistModel.cpp" line="149"/> <location filename="../src/libtomahawk/playlist/PlaylistModel.cpp" line="156"/> <source>A playlist by %1, created %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlaylistModel.cpp" line="205"/> <source>All tracks by %1 on album %2</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/PlaylistModel.cpp" line="232"/> <source>All tracks by %1</source> <translation type="unfinished"/> </message> </context> <context> <name>ProxyDialog</name> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="17"/> <source>Proxy Settings</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="37"/> <source>Hostname of proxy server</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="44"/> <source>Host</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="51"/> <source>Port</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="71"/> <source>Proxy login</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="78"/> <source>User</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="85"/> <source>Password</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="95"/> <source>Proxy password</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="102"/> <source>No Proxy Hosts: (Overrides system proxy)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="110"/> <source>localhost *.example.com (space separated)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/ProxyDialog.ui" line="127"/> <source>Use proxy for DNS lookups?</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message numerus="yes"> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="262"/> <source>%n year(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="264"/> <source>%n year(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="270"/> <source>%n month(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="272"/> <source>%n month(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="278"/> <source>%n week(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="280"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="286"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="288"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="294"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="296"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="302"/> <source>%1 minutes ago</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="304"/> <source>%1 minutes</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/TomahawkUtils.cpp" line="308"/> <source>just now</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/Account.cpp" line="38"/> <source>Friend Finders</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/Account.cpp" line="40"/> <source>Music Finders</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/Account.cpp" line="43"/> <source>Status Updaters</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="550"/> <source>Songs </source> <comment>Beginning of a sentence summary</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="579"/> <source>No configured filters!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="593"/> <source> and </source> <comment>Inserted between items in a list of two</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="595"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="604"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="608"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="624"/> <source>, </source> <comment>Inserted between items in a list</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="597"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="606"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="622"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="629"/> <source>.</source> <comment>Inserted when ending a sentence summary</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="610"/> <source>, and </source> <comment>Inserted between the last two items in a list of more than two</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="621"/> <source>and </source> <comment>Inserted before the last item in a list</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="629"/> <source>and </source> <comment>Inserted before the sorting summary in a sentence summary</comment> <translation type="unfinished"/> </message> </context> <context> <name>QSQLiteResult</name> <message> <location filename="../src/libtomahawk/database/TomahawkSqlQuery.cpp" line="91"/> <source>No query</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/database/TomahawkSqlQuery.cpp" line="92"/> <source>Parameter count mismatch</source> <translation type="unfinished"/> </message> </context> <context> <name>QueueItem</name> <message> <location filename="../src/tomahawk/sourcetree/items/QueueItem.cpp" line="39"/> <source>Queue</source> <translation type="unfinished"/> </message> </context> <context> <name>QueueView</name> <message> <location filename="../src/libtomahawk/playlist/QueueView.ui" line="41"/> <source>Open Queue</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/QueueView.cpp" line="39"/> <source>Queue Details</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/QueueView.cpp" line="49"/> <source>Queue</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/QueueView.cpp" line="53"/> <source>The queue is currently empty. Drop something to enqueue it!</source> <translation type="unfinished"/> </message> </context> <context> <name>ResolverConfigDelegate</name> <message> <location filename="../src/tomahawk/ResolverConfigDelegate.cpp" line="111"/> <source>Not found: %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/ResolverConfigDelegate.cpp" line="114"/> <source>Failed to load: %1</source> <translation type="unfinished"/> </message> </context> <context> <name>ScannerStatusItem</name> <message> <location filename="../src/libtomahawk/jobview/ScannerStatusItem.cpp" line="55"/> <source>Scanning Collection</source> <translation type="unfinished"/> </message> </context> <context> <name>ScriptCollectionHeader</name> <message> <location filename="../src/libtomahawk/widgets/ScriptCollectionHeader.cpp" line="48"/> <source>Reload Collection</source> <translation type="unfinished"/> </message> </context> <context> <name>SearchLineEdit</name> <message> <location filename="../src/libtomahawk/widgets/searchlineedit/SearchLineEdit.cpp" line="58"/> <source>Search</source> <translation type="unfinished"/> </message> </context> <context> <name>SearchWidget</name> <message> <location filename="../src/libtomahawk/viewpages/SearchViewPage.h" line="54"/> <source>Search: %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SearchViewPage.h" line="55"/> <source>Results for &apos;%1&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SearchViewPage.ui" line="41"/> <location filename="../src/libtomahawk/viewpages/SearchViewPage.cpp" line="146"/> <source>Songs</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SearchViewPage.ui" line="67"/> <location filename="../src/libtomahawk/viewpages/SearchViewPage.ui" line="127"/> <location filename="../src/libtomahawk/viewpages/SearchViewPage.ui" line="187"/> <source>Show More</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SearchViewPage.ui" line="101"/> <location filename="../src/libtomahawk/viewpages/SearchViewPage.cpp" line="158"/> <source>Artists</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SearchViewPage.ui" line="161"/> <location filename="../src/libtomahawk/viewpages/SearchViewPage.cpp" line="188"/> <source>Albums</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SearchViewPage.cpp" line="65"/> <source>Sorry, we could not find any artists!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SearchViewPage.cpp" line="86"/> <source>Sorry, we could not find any albums!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SearchViewPage.cpp" line="108"/> <source>Sorry, we could not find any songs!</source> <translation type="unfinished"/> </message> </context> <context> <name>Servent</name> <message> <location filename="../src/libtomahawk/network/Servent.cpp" line="1003"/> <source>Automatically detecting external IP failed: Could not parse JSON response.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/network/Servent.cpp" line="1016"/> <source>Automatically detecting external IP failed: %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SettingsDialog</name> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="265"/> <source>Collection</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="268"/> <source>Advanced</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="165"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="138"/> <source>Install Plug-In...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="326"/> <source>Some changed settings will not take effect until Tomahawk is restarted</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="260"/> <source>Configure the accounts and services used by Tomahawk to search and retrieve music, find your friends and update your status.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="221"/> <source>MP3</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="222"/> <source>FLAC</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="223"/> <source>M4A</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="224"/> <source>MP4</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="260"/> <source>Plug-Ins</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="265"/> <source>Manage how Tomahawk finds music on your computer.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="268"/> <source>Configure Tomahawk&apos;s advanced settings, including network connectivity settings, browser interaction and more.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="273"/> <source>Downloads</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="273"/> <source>Configure Tomahawk&apos;s integrated download manager.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="443"/> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="457"/> <source>Open Directory</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="551"/> <source>Install resolver from file</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="553"/> <source>Tomahawk Resolvers (*.axe *.js);;All files (*)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="570"/> <source>Delete all Access Control entries?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="571"/> <source>Do you really want to delete all Access Control entries? You will be asked for a decision again for each peer that you connect to.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/SettingsDialog.cpp" line="326"/> <source>Information</source> <translation type="unfinished"/> </message> </context> <context> <name>Settings_Accounts</name> <message> <location filename="../src/tomahawk/dialogs/Settings_Accounts.ui" line="57"/> <source>Filter by Capability:</source> <translation type="unfinished"/> </message> </context> <context> <name>Settings_Advanced</name> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="38"/> <source>Remote Peer Connection Method</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="44"/> <source>Active (your host needs to be directly reachable)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="51"/> <source>UPnP / Automatic Port Forwarding (recommended)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="69"/> <source>Manual Port Forwarding</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="82"/> <source>Host Settings...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="110"/> <source>SOCKS Proxy</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="116"/> <source>Use SOCKS Proxy</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="145"/> <source>Proxy Settings...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="171"/> <source>Other Settings</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="180"/> <source>Allow web browsers to interact with Tomahawk (recommended)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="193"/> <source>Allow other computers to interact with Tomahawk (not recommended yet)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="206"/> <source>Send Tomahawk Crash Reports</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="216"/> <source>Show Notifications on song change</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Advanced.ui" line="244"/> <source>Clear All Access Control Entries</source> <translation type="unfinished"/> </message> </context> <context> <name>Settings_Collection</name> <message> <location filename="../src/tomahawk/dialogs/Settings_Collection.ui" line="38"/> <source>Folders to scan for music:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Collection.ui" line="53"/> <source>Due to the unique way Tomahawk works, your music files must at least have Artist &amp; Title metadata/ID3 tags to be added to your Collection.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Collection.ui" line="76"/> <source>+</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Collection.ui" line="83"/> <source>-</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Collection.ui" line="109"/> <source>The Echo Nest supports keeping track of your catalog metadata and using it to craft personalized radios. Enabling this option will allow you (and all your friends) to create automatic playlists and stations based on your personal taste profile.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Collection.ui" line="115"/> <source>Upload Collection info to enable personalized &quot;User Radio&quot;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Collection.ui" line="128"/> <source>Watch for changes (automatically update Collection)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Collection.ui" line="137"/> <source>Time between scans (in seconds):</source> <translation type="unfinished"/> </message> </context> <context> <name>Settings_Downloads</name> <message> <location filename="../src/tomahawk/dialogs/Settings_Downloads.ui" line="26"/> <source>Some Plug-Ins enable you to purchase and/or download music directly in Tomahawk. Set your preferences for the download format and location:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Downloads.ui" line="49"/> <source>Folder to download music to:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Downloads.ui" line="68"/> <source>Browse...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/dialogs/Settings_Downloads.ui" line="79"/> <source>Preferred download format:</source> <translation type="unfinished"/> </message> </context> <context> <name>SlideSwitchButton</name> <message> <location filename="../src/tomahawk/widgets/SlideSwitchButton.cpp" line="46"/> <source>On</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/widgets/SlideSwitchButton.cpp" line="47"/> <source>Off</source> <translation type="unfinished"/> </message> </context> <context> <name>SocialWidget</name> <message> <location filename="../src/tomahawk/widgets/SocialWidget.ui" line="28"/> <source>Facebook</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/widgets/SocialWidget.ui" line="38"/> <source>Twitter</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/widgets/SocialWidget.cpp" line="71"/> <source>Tweet</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/widgets/SocialWidget.cpp" line="169"/> <source>Listening to &quot;%1&quot; by %2. %3</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/widgets/SocialWidget.cpp" line="171"/> <source>Listening to &quot;%1&quot; by %2 on &quot;%3&quot;. %4</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/widgets/SocialWidget.cpp" line="202"/> <source>%1 characters left</source> <translation type="unfinished"/> </message> </context> <context> <name>SourceDelegate</name> <message> <location filename="../src/tomahawk/sourcetree/SourceDelegate.cpp" line="232"/> <source>All available tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceDelegate.cpp" line="340"/> <source>Drop to send tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceDelegate.cpp" line="403"/> <location filename="../src/tomahawk/sourcetree/SourceDelegate.cpp" line="431"/> <source>Show</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceDelegate.cpp" line="405"/> <location filename="../src/tomahawk/sourcetree/SourceDelegate.cpp" line="433"/> <source>Hide</source> <translation type="unfinished"/> </message> </context> <context> <name>SourceInfoWidget</name> <message> <location filename="../src/libtomahawk/viewpages/SourceViewPage.ui" line="30"/> <source>Recent Albums</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SourceViewPage.ui" line="74"/> <source>Latest Additions</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SourceViewPage.ui" line="88"/> <source>Recently Played Tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SourceViewPage.cpp" line="70"/> <source>New Additions</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SourceViewPage.cpp" line="73"/> <source>My recent activity</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/SourceViewPage.cpp" line="77"/> <source>Recent activity from %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SourceItem</name> <message> <location filename="../src/tomahawk/sourcetree/items/SourceItem.cpp" line="80"/> <location filename="../src/tomahawk/sourcetree/items/SourceItem.cpp" line="586"/> <source>Latest Additions</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/SourceItem.cpp" line="85"/> <source>History</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/SourceItem.cpp" line="149"/> <source>SuperCollection</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/SourceItem.cpp" line="589"/> <source>Latest additions to your collection</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/SourceItem.cpp" line="591"/> <source>Latest additions to %1&apos;s collection</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/SourceItem.cpp" line="595"/> <source>Sorry, we could not find any recent additions!</source> <translation type="unfinished"/> </message> </context> <context> <name>SourceTreeView</name> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="245"/> <source>&amp;Copy Link</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="253"/> <source>&amp;Delete %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="257"/> <source>Add to my Playlists</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="259"/> <source>Add to my Automatic Playlists</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="261"/> <source>Add to my Stations</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="249"/> <source>&amp;Export Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="403"/> <source>playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="407"/> <source>automatic playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="411"/> <source>station</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="440"/> <source>Would you like to delete the %1 &lt;b&gt;&quot;%2&quot;&lt;/b&gt;?</source> <comment>e.g. Would you like to delete the playlist named Foobar?</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="442"/> <source>Delete</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="547"/> <source>Save XSPF</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourceTreeView.cpp" line="548"/> <source>Playlists (*.xspf)</source> <translation type="unfinished"/> </message> </context> <context> <name>SourcesModel</name> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="96"/> <source>Group</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="99"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="102"/> <source>Collection</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="105"/> <source>Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="108"/> <source>Automatic Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="111"/> <source>Station</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="311"/> <source>Cloud Collections</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="300"/> <source>Discover</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="301"/> <source>Open Pages</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="303"/> <source>Your Music</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/SourcesModel.cpp" line="312"/> <source>Friends</source> <translation type="unfinished"/> </message> </context> <context> <name>SpotifyConfig</name> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="69"/> <source>Configure your Spotify account</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="101"/> <source>Username or Facebook Email</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="129"/> <source>Log In</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="136"/> <source>Right click on any %applicationNames playlist to sync it to Spotify.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="153"/> <source>Select All</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="166"/> <source>Sync Starred tracks to Loved tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="179"/> <source>High Quality Streams</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="189"/> <source>Delete %applicationName playlist when removing synchronization</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="196"/> <source>Use this to force Spotify to never announce listening data to Social Networks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="199"/> <source>Always run in Private Mode</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="146"/> <source>Spotify playlists to keep in sync:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="91"/> <source>Username:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.ui" line="108"/> <source>Password:</source> <translation type="unfinished"/> </message> </context> <context> <name>SpotifyPlaylistUpdater</name> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyPlaylistUpdater.cpp" line="351"/> <source>Delete associated Spotify playlist?</source> <translation type="unfinished"/> </message> </context> <context> <name>TemporaryPageItem</name> <message> <location filename="../src/tomahawk/sourcetree/items/TemporaryPageItem.cpp" line="54"/> <source>Copy Artist Link</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/TemporaryPageItem.cpp" line="61"/> <source>Copy Album Link</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/sourcetree/items/TemporaryPageItem.cpp" line="68"/> <source>Copy Track Link</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::AccountDelegate</name> <message> <location filename="../src/libtomahawk/accounts/AccountDelegate.cpp" line="199"/> <source>Add Account</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/AccountDelegate.cpp" line="249"/> <location filename="../src/libtomahawk/accounts/AccountDelegate.cpp" line="666"/> <source>Remove</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/AccountDelegate.cpp" line="363"/> <source>%1 downloads</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/AccountDelegate.cpp" line="567"/> <source>Online</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/AccountDelegate.cpp" line="572"/> <source>Connecting...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/AccountDelegate.cpp" line="577"/> <source>Offline</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::AccountModel</name> <message> <location filename="../src/libtomahawk/accounts/AccountModel.cpp" line="564"/> <source>Manual Install Required</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/AccountModel.cpp" line="567"/> <source>Unfortunately, automatic installation of this resolver is not available or disabled for your platform.&lt;br /&gt;&lt;br /&gt;Please use &quot;Install from file&quot; above, by fetching it from your distribution or compiling it yourself. Further instructions can be found here:&lt;br /&gt;&lt;br /&gt;http://www.tomahawk-player.org/resolvers/%1</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::GoogleWrapper</name> <message> <location filename="../src/accounts/google/GoogleWrapper.cpp" line="91"/> <source>Configure this Google Account</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/google/GoogleWrapper.cpp" line="92"/> <source>Google Address:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/google/GoogleWrapper.cpp" line="93"/> <source>Enter your Google login to connect with your friends using %applicationName!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/google/GoogleWrapper.cpp" line="94"/> <source>username@gmail.com</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/google/GoogleWrapper.cpp" line="101"/> <source>You may need to change your %1Google Account Settings%2 to login.</source> <comment>%1 is &lt;a href&gt;, %2 is &lt;/a&gt;</comment> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::GoogleWrapperFactory</name> <message> <location filename="../src/accounts/google/GoogleWrapper.h" line="44"/> <source>Login to directly connect to your Google Talk contacts that also use %applicationName.</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::GoogleWrapperSip</name> <message> <location filename="../src/accounts/google/GoogleWrapper.cpp" line="61"/> <source>Enter Google Address</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/google/GoogleWrapper.cpp" line="69"/> <source>Add Friend</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/google/GoogleWrapper.cpp" line="70"/> <source>Enter Google Address:</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::HatchetAccountConfig</name> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.cpp" line="128"/> <source>Logged in as: %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.cpp" line="134"/> <source>Log out</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.cpp" line="156"/> <source>Log in</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/hatchet/account/HatchetAccountConfig.cpp" line="181"/> <source>Continue</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::HatchetAccountFactory</name> <message> <location filename="../src/accounts/hatchet/account/HatchetAccount.h" line="51"/> <source>Connect to Hatchet to capture your playback data, sync your playlists to Android and more.</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::LastFmAccountFactory</name> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmAccount.h" line="52"/> <source>Scrobble your tracks to last.fm, and find freely downloadable tracks to play</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::LastFmConfig</name> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="99"/> <source>Testing...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="121"/> <source>Test Login</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="131"/> <source>Importing %1</source> <comment>e.g. Importing 2012/01/01</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="134"/> <source>Importing History...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="203"/> <source>History Incomplete. Resume</source> <extracomment>Text on a button that resumes import</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="208"/> <source>Playback History Imported</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="231"/> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="247"/> <source>Failed</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="236"/> <source>Success</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="253"/> <source>Could not contact server</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="267"/> <source>Synchronizing...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmConfig.cpp" line="431"/> <source>Synchronization Finished</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::ResolverAccountFactory</name> <message> <location filename="../src/libtomahawk/accounts/ResolverAccount.cpp" line="119"/> <source>Resolver installation error: cannot open bundle.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/ResolverAccount.cpp" line="125"/> <source>Resolver installation error: incomplete bundle.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/ResolverAccount.cpp" line="163"/> <source>Resolver installation error: bad metadata in bundle.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/ResolverAccount.cpp" line="199"/> <source>Resolver installation error: platform mismatch.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/ResolverAccount.cpp" line="211"/> <source>Resolver installation error: Tomahawk %1 or newer is required.</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::SpotifyAccount</name> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccount.cpp" line="520"/> <source>Sync with Spotify</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccount.cpp" line="524"/> <source>Re-enable syncing with Spotify</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccount.cpp" line="532"/> <source>Create local copy</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccount.cpp" line="548"/> <source>Subscribe to playlist changes</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccount.cpp" line="552"/> <source>Re-enable playlist subscription</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccount.cpp" line="556"/> <source>Stop subscribing to changes</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccount.cpp" line="576"/> <source>Enable Spotify collaborations</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccount.cpp" line="578"/> <source>Disable Spotify collaborations</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccount.cpp" line="534"/> <source>Stop syncing with Spotify</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::SpotifyAccountConfig</name> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.cpp" line="202"/> <source>Logging in...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.cpp" line="239"/> <source>Failed: %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.cpp" line="282"/> <source>Logged in as %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.cpp" line="284"/> <source>Log Out</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.cpp" line="302"/> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccountConfig.cpp" line="314"/> <source>Log In</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::SpotifyAccountFactory</name> <message> <location filename="../src/libtomahawk/accounts/spotify/SpotifyAccount.h" line="71"/> <source>Play music from and sync your playlists with Spotify Premium</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::TelepathyConfigStorage</name> <message> <location filename="../src/libtomahawk/accounts/configstorage/telepathy/TelepathyConfigStorage.cpp" line="79"/> <source>the KDE instant messaging framework</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/configstorage/telepathy/TelepathyConfigStorage.cpp" line="96"/> <source>KDE Instant Messaging Accounts</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::XmppAccountFactory</name> <message> <location filename="../src/accounts/xmpp/XmppAccount.h" line="53"/> <source>Login to connect to your Jabber/XMPP contacts that also use %applicationName.</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::XmppConfigWidget</name> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.cpp" line="73"/> <source>Account provided by %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.cpp" line="157"/> <source>You forgot to enter your username!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.cpp" line="165"/> <source>Your Xmpp Id should look like an email address</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.cpp" line="171"/> <source> Example: username@jabber.org</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::ZeroconfAccount</name> <message> <location filename="../src/accounts/zeroconf/ZeroconfAccount.cpp" line="63"/> <location filename="../src/accounts/zeroconf/ZeroconfAccount.cpp" line="64"/> <source>Local Network</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Accounts::ZeroconfFactory</name> <message> <location filename="../src/accounts/zeroconf/ZeroconfAccount.h" line="45"/> <source>Local Network</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/zeroconf/ZeroconfAccount.h" line="46"/> <source>Automatically connect to Tomahawk users on the same local network.</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Collection</name> <message> <location filename="../src/libtomahawk/collection/Collection.cpp" line="87"/> <location filename="../src/libtomahawk/collection/Collection.cpp" line="101"/> <source>Collection</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::ContextMenu</name> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="127"/> <source>&amp;Play</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="130"/> <source>Download</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="133"/> <location filename="../src/libtomahawk/ContextMenu.cpp" line="275"/> <location filename="../src/libtomahawk/ContextMenu.cpp" line="326"/> <source>Add to &amp;Queue</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="146"/> <source>Add to &amp;Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="167"/> <source>Send to &amp;Friend</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="181"/> <source>Continue Playback after this &amp;Track</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="183"/> <source>Stop Playback after this &amp;Track</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="190"/> <location filename="../src/libtomahawk/ContextMenu.cpp" line="494"/> <source>&amp;Love</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="204"/> <source>View Similar Tracks to &quot;%1&quot;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="283"/> <location filename="../src/libtomahawk/ContextMenu.cpp" line="334"/> <source>&amp;Go to &quot;%1&quot;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="209"/> <location filename="../src/libtomahawk/ContextMenu.cpp" line="213"/> <location filename="../src/libtomahawk/ContextMenu.cpp" line="286"/> <source>Go to &quot;%1&quot;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="219"/> <source>&amp;Copy Track Link</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="239"/> <source>Mark as &amp;Listened</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="243"/> <source>&amp;Remove Items</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="243"/> <source>&amp;Remove Item</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="294"/> <source>Copy Album &amp;Link</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="342"/> <source>Copy Artist &amp;Link</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="489"/> <source>Un-&amp;Love</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ContextMenu.cpp" line="222"/> <source>Properties...</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::DatabaseCommand_AllAlbums</name> <message> <location filename="../src/libtomahawk/database/DatabaseCommand_AllAlbums.cpp" line="119"/> <source>Unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::DropJobNotifier</name> <message> <location filename="../src/libtomahawk/utils/DropJobNotifier.cpp" line="73"/> <source>playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/DropJobNotifier.cpp" line="76"/> <source>artist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/DropJobNotifier.cpp" line="79"/> <source>track</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/DropJobNotifier.cpp" line="82"/> <source>album</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/DropJobNotifier.cpp" line="105"/> <source>Fetching %1 from database</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/DropJobNotifier.cpp" line="109"/> <source>Parsing %1 %2</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::DynamicControlList</name> <message> <location filename="../src/libtomahawk/playlist/dynamic/widgets/DynamicControlList.cpp" line="84"/> <source>Save Settings</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::DynamicModel</name> <message> <location filename="../src/libtomahawk/playlist/dynamic/DynamicModel.cpp" line="173"/> <location filename="../src/libtomahawk/playlist/dynamic/DynamicModel.cpp" line="302"/> <source>Could not find a playable track. Please change the filters or try again.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/DynamicModel.cpp" line="231"/> <source>Failed to generate preview with the desired filters</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::DynamicSetupWidget</name> <message> <location filename="../src/libtomahawk/playlist/dynamic/widgets/DynamicSetupWidget.cpp" line="53"/> <source>Type:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/widgets/DynamicSetupWidget.cpp" line="67"/> <source>Generate</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::DynamicView</name> <message> <location filename="../src/libtomahawk/playlist/dynamic/DynamicView.cpp" line="146"/> <source>Add some filters above to seed this station!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/DynamicView.cpp" line="151"/> <source>Press Generate to get started!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/DynamicView.cpp" line="153"/> <source>Add some filters above, and press Generate to get started!</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::DynamicWidget</name> <message> <location filename="../src/libtomahawk/playlist/dynamic/widgets/DynamicWidget.cpp" line="479"/> <source>Station ran out of tracks! Try tweaking the filters for a new set of songs to play.</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::EchonestControl</name> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="165"/> <source>Similar To</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="166"/> <source>Limit To</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="170"/> <source>Artist name</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="193"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="266"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="289"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="376"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="397"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="468"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="491"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="516"/> <source>is</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="214"/> <source>from user</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="223"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="765"/> <source>No users with Echo Nest Catalogs enabled. Try enabling option in Collection settings</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="244"/> <source>similar to</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="246"/> <source>Enter any combination of song name and artist here...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="267"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="290"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="332"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="338"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="344"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="350"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="356"/> <source>Less</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="267"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="290"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="332"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="338"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="344"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="350"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="356"/> <source>More</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="313"/> <source>0 BPM</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="313"/> <source>500 BPM</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="319"/> <source>0 secs</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="319"/> <source>3600 secs</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="325"/> <source>-100 dB</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="325"/> <source>100 dB</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="362"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="369"/> <source>-180%1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="362"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="369"/> <source>180%1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="378"/> <source>Major</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="379"/> <source>Minor</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="399"/> <source>C</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="400"/> <source>C Sharp</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="401"/> <source>D</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="402"/> <source>E Flat</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="403"/> <source>E</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="404"/> <source>F</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="405"/> <source>F Sharp</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="406"/> <source>G</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="407"/> <source>A Flat</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="408"/> <source>A</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="409"/> <source>B Flat</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="410"/> <source>B</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="429"/> <source>Ascending</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="430"/> <source>Descending</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="433"/> <source>Tempo</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="434"/> <source>Duration</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="435"/> <source>Loudness</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="436"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="986"/> <source>Artist Familiarity</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="437"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="985"/> <source>Artist Hotttnesss</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="438"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="986"/> <source>Song Hotttnesss</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="439"/> <source>Latitude</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="440"/> <source>Longitude</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="441"/> <source>Mode</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="442"/> <source>Key</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="443"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="985"/> <source>Energy</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="444"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="984"/> <source>Danceability</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="492"/> <source>is not</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="495"/> <source>Studio</source> <comment>Song type: The song was recorded in a studio.</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="496"/> <source>Live</source> <comment>Song type: The song was a life performance.</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="497"/> <source>Acoustic</source> <comment>Song type</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="498"/> <source>Electric</source> <comment>Song type</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="499"/> <source>Christmas</source> <comment>Song type: A christmas song</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="519"/> <source>Focused</source> <comment>Distribution: Songs that are tightly clustered around the seeds</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="520"/> <source>Wandering</source> <comment>Distribution: Songs from a broader range of artists</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="536"/> <source>Classics</source> <comment>Genre preset: songs intended to introduce the genre to a novice listener</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="537"/> <source>Popular</source> <comment>Genre preset: most popular songs being played in the genre today</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="538"/> <source>Emerging</source> <comment>Genre preset: songs that are more popular than expected, but which are unfamiliar to most listeners</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="541"/> <source>Best</source> <comment>Genre preset: optimal collection of songs</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="542"/> <source>Mix</source> <comment>Genre preset: a varying collection of songs</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="569"/> <source>At Least</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="570"/> <source>At Most</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="953"/> <source>only by ~%1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="955"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="982"/> <source>similar to ~%1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="959"/> <source>with genre ~%1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="967"/> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="978"/> <source>from no one</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="971"/> <source>You</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="972"/> <source>from my radio</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="974"/> <source>from %1 radio</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="984"/> <source>Variety</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="987"/> <source>Adventurousness</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="993"/> <source>very low</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="995"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="997"/> <source>moderate</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="999"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1001"/> <source>very high</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1002"/> <source>with %1 %2</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1006"/> <source>about %1 BPM</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1010"/> <source>about %n minute(s) long</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1014"/> <source>about %1 dB</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1018"/> <source>at around %1%2 %3</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1025"/> <source>in %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1032"/> <source>in a %1 key</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1044"/> <source>sorted in %1 %2 order</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1051"/> <source>with a %1 mood</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1058"/> <source>in a %1 style</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1065"/> <source>where genre is %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1078"/> <source>where song type is %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1080"/> <source>where song type is not %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1088"/> <source>with a %1 distribution</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1100"/> <source>preset to %1 collection of %2 genre songs</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1102"/> <source>an optimal</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1104"/> <source>a mixed</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1108"/> <source>classic</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1113"/> <source>popular</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestControl.cpp" line="1115"/> <source>emerging</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::GroovesharkParser</name> <message> <location filename="../src/libtomahawk/utils/GroovesharkParser.cpp" line="239"/> <source>Error fetching Grooveshark information from the network!</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::InfoSystem::ChartsPlugin</name> <message> <location filename="../src/infoplugins/generic/charts/ChartsPlugin.cpp" line="578"/> <source>Artists</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/charts/ChartsPlugin.cpp" line="580"/> <source>Albums</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/charts/ChartsPlugin.cpp" line="582"/> <source>Tracks</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::InfoSystem::FdoNotifyPlugin</name> <message> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="271"/> <source>on</source> <comment>'on' is followed by an album name</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="274"/> <source>%1%4 %2%3.</source> <comment>%1 is a title, %2 is an artist and %3 is replaced by either the previous message or nothing, %4 is the preposition used to link track and artist ('by' in english)</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="215"/> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="278"/> <source>by</source> <comment>preposition to link track and artist</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="130"/> <source>The current track could not be resolved. %applicationName will pick back up with the next resolvable track from this source.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="138"/> <source>%applicationName is stopped.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="211"/> <source>%1 sent you %2%4 %3.</source> <comment>%1 is a nickname, %2 is a title, %3 is an artist, %4 is the preposition used to link track and artist ('by' in english)</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="222"/> <source>%1 sent you &quot;%2&quot; by %3.</source> <comment>%1 is a nickname, %2 is a title, %3 is an artist</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="287"/> <source>on &quot;%1&quot;</source> <comment>%1 is an album name</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="289"/> <source>&quot;%1&quot; by %2%3.</source> <comment>%1 is a title, %2 is an artist and %3 is replaced by either the previous message or nothing</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/linux/fdonotify/FdoNotifyPlugin.cpp" line="314"/> <source>%applicationName - Now Playing</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::InfoSystem::LastFmInfoPlugin</name> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmInfoPlugin.cpp" line="461"/> <source>Top Tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmInfoPlugin.cpp" line="464"/> <source>Loved Tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmInfoPlugin.cpp" line="467"/> <source>Hyped Tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmInfoPlugin.cpp" line="473"/> <source>Top Artists</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/accounts/lastfm/LastFmInfoPlugin.cpp" line="476"/> <source>Hyped Artists</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::InfoSystem::NewReleasesPlugin</name> <message> <location filename="../src/infoplugins/generic/newreleases/NewReleasesPlugin.cpp" line="602"/> <source>Albums</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::InfoSystem::SnoreNotifyPlugin</name> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="87"/> <source>Notify User</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="88"/> <source>Now Playing</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="89"/> <source>Unresolved track</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="90"/> <source>Playback Stopped</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="91"/> <source>You received a Song recommendation</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="124"/> <source>The current track could not be resolved. %applicationName will pick back up with the next resolvable track from this source.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="132"/> <source>%applicationName stopped playback.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="202"/> <source>on</source> <comment>'on' is followed by an album name</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="204"/> <source>%1%4 %2%3.</source> <comment>%1 is a title, %2 is an artist and %3 is replaced by either the previous message or nothing, %4 is the preposition used to link track and artist ('by' in english)</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="208"/> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="270"/> <source>by</source> <comment>preposition to link track and artist</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="217"/> <source>on &quot;%1&quot;</source> <comment>%1 is an album name</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="219"/> <source>&quot;%1&quot; by %2%3.</source> <comment>%1 is a title, %2 is an artist and %3 is replaced by either the previous message or nothing</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="266"/> <source>%1 sent you %2%4 %3.</source> <comment>%1 is a nickname, %2 is a title, %3 is an artist, %4 is the preposition used to link track and artist ('by' in english)</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/infoplugins/generic/snorenotify/SnoreNotifyPlugin.cpp" line="277"/> <source>%1 sent you &quot;%2&quot; by %3.</source> <comment>%1 is a nickname, %2 is a title, %3 is an artist</comment> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::ItunesParser</name> <message> <location filename="../src/libtomahawk/utils/ItunesParser.cpp" line="182"/> <source>Error fetching iTunes information from the network!</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::JSPFLoader</name> <message> <location filename="../src/libtomahawk/utils/JspfLoader.cpp" line="150"/> <source>New Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/JspfLoader.cpp" line="176"/> <source>Failed to save tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/JspfLoader.cpp" line="176"/> <source>Some tracks in the playlist do not contain an artist and a title. They will be ignored.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/JspfLoader.cpp" line="201"/> <source>XSPF Error</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/JspfLoader.cpp" line="201"/> <source>This is not a valid XSPF playlist.</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::JSResolver</name> <message> <location filename="../src/libtomahawk/resolvers/JSResolver.cpp" line="373"/> <source>Script Resolver Warning: API call %1 returned data synchronously.</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::LatchManager</name> <message> <location filename="../src/libtomahawk/LatchManager.cpp" line="96"/> <source>&amp;Catch Up</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/LatchManager.cpp" line="133"/> <location filename="../src/libtomahawk/LatchManager.cpp" line="166"/> <source>&amp;Listen Along</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::LocalCollection</name> <message> <location filename="../src/libtomahawk/database/LocalCollection.cpp" line="42"/> <source>Your Collection</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::RemoteCollection</name> <message> <location filename="../src/libtomahawk/network/RemoteCollection.cpp" line="36"/> <source>Collection of %1</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::ScriptCollection</name> <message> <location filename="../src/libtomahawk/resolvers/ScriptCollection.cpp" line="78"/> <source>%1 Collection</source> <comment>Name of a collection based on a script pluginsc, e.g. Subsonic Collection</comment> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::ScriptEngine</name> <message> <location filename="../src/libtomahawk/resolvers/ScriptEngine.cpp" line="94"/> <source>Resolver Error: %1:%2 %3</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/resolvers/ScriptEngine.cpp" line="112"/> <source>SSL Error</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/resolvers/ScriptEngine.cpp" line="113"/> <source>You have asked Tomahawk to connect securely to &lt;b&gt;%1&lt;/b&gt;, but we can&apos;t confirm that your connection is secure:&lt;br&gt;&lt;br&gt;&lt;b&gt;%2&lt;/b&gt;&lt;br&gt;&lt;br&gt;Do you want to trust this connection?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/resolvers/ScriptEngine.cpp" line="120"/> <source>Trust certificate</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::ShortenedLinkParser</name> <message> <location filename="../src/libtomahawk/utils/ShortenedLinkParser.cpp" line="104"/> <source>Network error parsing shortened link!</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Source</name> <message> <location filename="../src/libtomahawk/Source.cpp" line="550"/> <source>Scanning (%L1 tracks)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/Source.cpp" line="535"/> <source>Checking</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/Source.cpp" line="540"/> <source>Syncing</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/Source.cpp" line="545"/> <source>Importing</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/Source.cpp" line="735"/> <source>Saving (%1%)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/Source.cpp" line="822"/> <source>Online</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/Source.cpp" line="826"/> <source>Offline</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::SpotifyParser</name> <message> <location filename="../src/libtomahawk/utils/SpotifyParser.cpp" line="280"/> <source>Error fetching Spotify information from the network!</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Track</name> <message> <location filename="../src/libtomahawk/Track.cpp" line="558"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/Track.cpp" line="566"/> <source>You</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/Track.cpp" line="568"/> <source>you</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/Track.cpp" line="581"/> <source>and</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../src/libtomahawk/Track.cpp" line="581"/> <source>%n other(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location filename="../src/libtomahawk/Track.cpp" line="584"/> <source>%n people</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location filename="../src/libtomahawk/Track.cpp" line="588"/> <source>loved this track</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/Track.cpp" line="590"/> <source>sent you this track %1</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Widgets::ChartsPage</name> <message> <location filename="../src/viewpages/charts/ChartsWidget.h" line="130"/> <source>Charts</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Widgets::Dashboard</name> <message> <location filename="../src/viewpages/dashboard/Dashboard.h" line="96"/> <source>Feed</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/dashboard/Dashboard.h" line="97"/> <source>An overview of your friends&apos; recent activity</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Widgets::DashboardWidget</name> <message> <location filename="../src/viewpages/dashboard/Dashboard.cpp" line="78"/> <source>Recently Played Tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/dashboard/Dashboard.cpp" line="72"/> <source>Feed</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Widgets::NetworkActivity</name> <message> <location filename="../src/viewpages/networkactivity/NetworkActivity.h" line="57"/> <source>Trending</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivity.h" line="58"/> <source>What&apos;s hot amongst your friends</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Widgets::NetworkActivityWidget</name> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.cpp" line="71"/> <source>Charts</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.cpp" line="82"/> <source>Last Week</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.cpp" line="88"/> <source>Loved Tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.cpp" line="90"/> <source>Top Loved</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.cpp" line="93"/> <source>Recently Loved</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.cpp" line="108"/> <source>Sorry, we are still loading the charts.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.cpp" line="131"/> <source>Sorry, we couldn&apos;t find any trending tracks.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.cpp" line="79"/> <source>Last Month</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.cpp" line="76"/> <source>Last Year</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/networkactivity/NetworkActivityWidget.cpp" line="73"/> <source>Overall</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Widgets::NewReleasesPage</name> <message> <location filename="../src/viewpages/newreleases/NewReleasesWidget.h" line="120"/> <source>New Releases</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::Widgets::WhatsNew_0_8</name> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNew_0_8.h" line="89"/> <source>What&apos;s new in 0.8?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNew_0_8.h" line="90"/> <source>An overview of the changes and additions since 0.7.</source> <translation type="unfinished"/> </message> </context> <context> <name>Tomahawk::XspfUpdater</name> <message> <location filename="../src/libtomahawk/playlist/XspfUpdater.cpp" line="60"/> <source>Automatically update from XSPF</source> <translation type="unfinished"/> </message> </context> <context> <name>TomahawkApp</name> <message> <location filename="../src/tomahawk/TomahawkApp.cpp" line="525"/> <source>You</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkApp.cpp" line="613"/> <source>Tomahawk is updating the database. Please wait, this may take a minute!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkApp.cpp" line="620"/> <source>Tomahawk</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkApp.cpp" line="731"/> <source>Updating database </source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkApp.cpp" line="738"/> <source>Updating database %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkApp.cpp" line="788"/> <source>Automatically detecting external IP failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>TomahawkSettings</name> <message> <location filename="../src/libtomahawk/TomahawkSettings.cpp" line="386"/> <source>Local Network</source> <translation type="unfinished"/> </message> </context> <context> <name>TomahawkTrayIcon</name> <message> <location filename="../src/tomahawk/TomahawkTrayIcon.cpp" line="181"/> <source>&amp;Stop Playback after current Track</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkTrayIcon.cpp" line="76"/> <location filename="../src/tomahawk/TomahawkTrayIcon.cpp" line="115"/> <source>Hide Tomahawk Window</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkTrayIcon.cpp" line="120"/> <source>Show Tomahawk Window</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkTrayIcon.cpp" line="201"/> <source>Currently not playing.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkTrayIcon.cpp" line="262"/> <source>Play</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkTrayIcon.cpp" line="290"/> <source>Pause</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkTrayIcon.cpp" line="320"/> <source>&amp;Love</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkTrayIcon.cpp" line="328"/> <source>Un-&amp;Love</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkTrayIcon.cpp" line="179"/> <source>&amp;Continue Playback after current Track</source> <translation type="unfinished"/> </message> </context> <context> <name>TomahawkWindow</name> <message> <location filename="../src/tomahawk/TomahawkWindow.ui" line="14"/> <source>Tomahawk</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="307"/> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="601"/> <source>Back</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="310"/> <source>Go back one page</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="317"/> <source>Forward</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="320"/> <source>Go forward one page</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="237"/> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1533"/> <source>Hide Menu Bar</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="237"/> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1527"/> <source>Show Menu Bar</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="360"/> <source>&amp;Main Menu</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="608"/> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="958"/> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="970"/> <source>Play</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="614"/> <source>Next</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="627"/> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1019"/> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1026"/> <source>Love</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1014"/> <source>Unlove</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1150"/> <source>Exit Full Screen</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1168"/> <source>Enter Full Screen</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1247"/> <source>This is not a valid XSPF playlist.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1251"/> <source>Some tracks in the playlist do not contain an artist and a title. They will be ignored.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1263"/> <source>Failed to load JSPF playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1270"/> <source>Sorry, there is a problem accessing your audio device or the desired track, current track will be skipped.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1279"/> <source>Station</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1281"/> <source>Create New Station</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1281"/> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1316"/> <source>Name:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1314"/> <source>Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1316"/> <source>Create New Playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="949"/> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1347"/> <source>Pause</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="337"/> <source>Search</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1369"/> <source>&amp;Play</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1401"/> <source>%1 by %2</source> <comment>track, artist name</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1402"/> <source>%1 - %2</source> <comment>current track, some window title</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1413"/> <source>&lt;h2&gt;&lt;b&gt;Tomahawk %1&lt;br/&gt;(%2)&lt;/h2&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1417"/> <source>&lt;h2&gt;&lt;b&gt;Tomahawk %1&lt;/h2&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1421"/> <source>Copyright 2010 - 2015</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1422"/> <source>Thanks to:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/TomahawkWindow.cpp" line="1429"/> <source>About Tomahawk</source> <translation type="unfinished"/> </message> </context> <context> <name>TrackDetailView</name> <message> <location filename="../src/libtomahawk/playlist/TrackDetailView.cpp" line="79"/> <source>Marked as Favorite</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/TrackDetailView.cpp" line="97"/> <source>Alternate Sources:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/TrackDetailView.cpp" line="175"/> <source>Unknown Release-Date</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/TrackDetailView.cpp" line="266"/> <source>on %1</source> <translation type="unfinished"/> </message> </context> <context> <name>TrackInfoWidget</name> <message> <location filename="../src/libtomahawk/viewpages/TrackViewPage.cpp" line="52"/> <source>Similar Tracks</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/TrackViewPage.cpp" line="53"/> <source>Sorry, but we could not find similar tracks for this song!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/viewpages/TrackViewPage.ui" line="60"/> <source>Top Hits</source> <translation type="unfinished"/> </message> </context> <context> <name>TrackView</name> <message> <location filename="../src/libtomahawk/playlist/TrackView.cpp" line="692"/> <source>Sorry, your filter &apos;%1&apos; did not match any results.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransferStatusItem</name> <message> <location filename="../src/libtomahawk/jobview/TransferStatusItem.cpp" line="68"/> <source>from</source> <comment>streaming artist - track from friend</comment> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/jobview/TransferStatusItem.cpp" line="68"/> <source>to</source> <comment>streaming artist - track to friend</comment> <translation type="unfinished"/> </message> </context> <context> <name>Type selector</name> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="77"/> <source>Artist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="77"/> <source>Artist Description</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="78"/> <source>User Radio</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="78"/> <source>Song</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="79"/> <source>Genre</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="79"/> <source>Mood</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="80"/> <source>Style</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="80"/> <source>Adventurousness</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="81"/> <source>Variety</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="81"/> <source>Tempo</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="82"/> <source>Duration</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="82"/> <source>Loudness</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="83"/> <source>Danceability</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="83"/> <source>Energy</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="84"/> <source>Artist Familiarity</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="84"/> <source>Artist Hotttnesss</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="85"/> <source>Song Hotttnesss</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="85"/> <source>Longitude</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="86"/> <source>Latitude</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="86"/> <source>Mode</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="87"/> <source>Key</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="87"/> <source>Sorting</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="88"/> <source>Song Type</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="88"/> <source>Distribution</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/playlist/dynamic/echonest/EchonestGenerator.cpp" line="89"/> <source>Genre Preset</source> <translation type="unfinished"/> </message> </context> <context> <name>ViewManager</name> <message> <location filename="../src/libtomahawk/ViewManager.cpp" line="83"/> <source>Inbox</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/ViewManager.cpp" line="84"/> <source>Listening suggestions from your friends</source> <translation type="unfinished"/> </message> </context> <context> <name>WhatsNewWidget_0_8</name> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="86"/> <source>WHAT&apos;S NEW</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="96"/> <source>If you are reading this it likely means you have already noticed the biggest change since our last release - a shiny new interface and design. New views, fonts, icons, header images and animations at every turn. Below you can find an overview of the functional changes and additions since 0.7 too:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="174"/> <source>Inbox</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="213"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Send tracks to your friends just by dragging it onto their avatar in the Tomahawk sidebar. Check out what your friends think you should listen to in your inbox.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="230"/> <source>Universal Link Support</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="253"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Love that your friends and influencers are posting music links but hate that they are links for music services you don&apos;t use? Just drag Rdio, Deezer, Beats or other music service URLs into your Tomahawk queue or playlists and have them automatically play from your preferred source.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="270"/> <source>Beats Music</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="296"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Beats Music (recently aquired by Apple) is now supported. This means that Beats Music subscribers can also benefit by resolving other music service links so they stream from their Beats Music account. Welcome aboard!&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="313"/> <source>Google Music</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="336"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Google Music is another of our latest supported services - both for the music you&apos;ve uploaded to Google Music as well as their full streaming catalog for Google Play Music All Access subscribers. Not only is all of your Google Play Music a potential source for streaming - your entire online collection is browseable too.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="376"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Tomahawk for Android is now in beta! The majority of the same resolvers are supported in the Android app - plus a couple of additional ones in Rdio &amp;amp; Deezer. &lt;a href=&quot;http://hatchet.is/register&quot;&gt;Create a Hatchet account&lt;/a&gt; to sync all of your playlists from your desktop to your mobile. Find current and future music influencers and follow them to discover and hear what they love. Just like on the desktop, Tomahawk on Android can open other music service links and play them from yours. Even when you are listening to other music apps, Tomahawk can capture all of that playback data and add it to your Hatchet profile.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="396"/> <source>Connectivity</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="419"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Tomahawk now supports IPv6 and multiple local IP addresses. This improves the discoverability and connection between Tomahawk users - particularly large local networks often found in work and university settings. The more friends, the more music, the more playlists and the more curation from those people whose musical tastes you value. Sit back and just Listen Along!&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/viewpages/whatsnew_0_8/WhatsNewWidget_0_8.ui" line="353"/> <source>Android</source> <translation type="unfinished"/> </message> </context> <context> <name>XMPPBot</name> <message> <location filename="../src/tomahawk/xmppbot/XmppBot.cpp" line="315"/> <source> Terms for %1: </source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/xmppbot/XmppBot.cpp" line="317"/> <source>No terms found, sorry.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/xmppbot/XmppBot.cpp" line="350"/> <source> Hotttness for %1: %2 </source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/xmppbot/XmppBot.cpp" line="366"/> <source> Familiarity for %1: %2 </source> <translation type="unfinished"/> </message> <message> <location filename="../src/tomahawk/xmppbot/XmppBot.cpp" line="384"/> <source> Lyrics for &quot;%1&quot; by %2: %3 </source> <translation type="unfinished"/> </message> </context> <context> <name>XSPFLoader</name> <message> <location filename="../src/libtomahawk/utils/XspfLoader.cpp" line="48"/> <source>Failed to parse contents of XSPF playlist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/XspfLoader.cpp" line="50"/> <source>Some playlist entries were found without artist and track name, they will be omitted</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/XspfLoader.cpp" line="52"/> <source>Failed to fetch the desired playlist from the network, or the desired file does not exist</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libtomahawk/utils/XspfLoader.cpp" line="239"/> <source>New Playlist</source> <translation type="unfinished"/> </message> </context> <context> <name>XmlConsole</name> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.ui" line="14"/> <source>Xml stream console</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.ui" line="33"/> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="60"/> <source>Filter</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.ui" line="43"/> <source>Save log</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="62"/> <source>Disabled</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="65"/> <source>By JID</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="68"/> <source>By namespace uri</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="71"/> <source>By all attributes</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="76"/> <source>Visible stanzas</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="79"/> <source>Information query</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="83"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="87"/> <source>Presence</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="91"/> <source>Custom</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="107"/> <source>Close</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="357"/> <source>Save XMPP log to file</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmlConsole.cpp" line="358"/> <source>OpenDocument Format (*.odf);;HTML file (*.html);;Plain text (*.txt)</source> <translation type="unfinished"/> </message> </context> <context> <name>XmppConfigWidget</name> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="20"/> <source>Xmpp Configuration</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="104"/> <source>Enter your XMPP login to connect with your friends using %applicationName!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="196"/> <source>Configure</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="211"/> <source>Login Information</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="58"/> <source>Configure this Jabber/XMPP account</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="231"/> <source>XMPP ID:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="247"/> <source>e.g. user@jabber.org</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="260"/> <source>Password:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="288"/> <source>An account with this name already exists!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="310"/> <source>Advanced Xmpp Settings</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="330"/> <source>Server:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="353"/> <source>Port:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="399"/> <source>Lots of servers don&apos;t support this (e.g. GTalk, jabber.org)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="402"/> <source>Display currently playing track</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/XmppConfigWidget.ui" line="409"/> <source>Enforce secure connection</source> <translation type="unfinished"/> </message> </context> <context> <name>XmppSipPlugin</name> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="380"/> <source>User Interaction</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="383"/> <source>Host is unknown</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="386"/> <source>Item not found</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="389"/> <source>Authorization Error</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="392"/> <source>Remote Stream Error</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="395"/> <source>Remote Connection failed</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="398"/> <source>Internal Server Error</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="401"/> <source>System shutdown</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="404"/> <source>Conflict</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="419"/> <source>Unknown</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="800"/> <source>Do you want to add &lt;b&gt;%1&lt;/b&gt; to your friend list?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="407"/> <source>No Compression Support</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="189"/> <source>Enter Jabber ID</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="410"/> <source>No Encryption Support</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="413"/> <source>No Authorization Support</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="416"/> <source>No Supported Feature</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="487"/> <source>Add Friend</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="488"/> <source>Enter Xmpp ID:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="640"/> <source>Add Friend...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="645"/> <source>XML Console...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="691"/> <source>I&apos;m sorry -- I&apos;m just an automatic presence used by Tomahawk Player (http://gettomahawk.com). If you are getting this message, the person you are trying to reach is probably not signed on, so please try again later!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/xmpp/sip/XmppSip.cpp" line="799"/> <source>Authorize User</source> <translation type="unfinished"/> </message> </context> <context> <name>ZeroconfConfig</name> <message> <location filename="../src/accounts/zeroconf/ConfigWidget.ui" line="55"/> <source>Local Network configuration</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/zeroconf/ConfigWidget.ui" line="77"/> <source>This plugin will automatically find other users running %applicationName on your local network</source> <translation type="unfinished"/> </message> <message> <location filename="../src/accounts/zeroconf/ConfigWidget.ui" line="84"/> <source>Connect automatically when %applicationName starts</source> <translation type="unfinished"/> </message> </context> </TS>
gpl-3.0
Sleeksnap/sleeksnap
src/org/sleeksnap/gui/options/HotkeyPanel.java
17230
/** * Sleeksnap, the open source cross-platform screenshot uploader * Copyright (C) 2012 Nikki <nikki@nikkii.us> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sleeksnap.gui.options; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.IOException; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.KeyStroke; import org.json.JSONObject; import org.sleeksnap.Configuration; import org.sleeksnap.gui.OptionPanel; import org.sleeksnap.impl.Language; import org.sleeksnap.util.Util; import com.sun.jna.Platform; /** * An OptionSubPanel for Hotkeys * * @author Nikki * */ @SuppressWarnings({ "serial" }) public class HotkeyPanel extends OptionSubPanel { private OptionPanel parent; private Configuration configuration; private JLabel fullscreenLabel; private JLabel hotkeySettingsLabel; private JLabel cropLabel; private JLabel clipboardLabel; private JLabel activeLabel; private JLabel noteLabel; private JLabel optionsLabel; private JLabel fileLabel; private JButton fullHotkeyButton; private JButton cropHotkeyButton; private JButton clipboardHotkeyButton; private JButton activeHotkeyButton; private JButton fileHotkeyButton; private JButton optionsHotkeyButton; private JButton hotkeyResetButton; private JButton hotkeySaveButton; public HotkeyPanel(OptionPanel parent) { this.parent = parent; this.configuration = parent.getSnapper().getConfiguration(); } @Override public void initComponents() { fullHotkeyButton = new JButton(); cropHotkeyButton = new JButton(); clipboardHotkeyButton = new JButton(); activeHotkeyButton = new JButton(); fileHotkeyButton = new JButton(); optionsHotkeyButton = new JButton(); hotkeySettingsLabel = new JLabel(); fullscreenLabel = new JLabel(); cropLabel = new JLabel(); clipboardLabel = new JLabel(); activeLabel = new JLabel(); fileLabel = new JLabel(); optionsLabel = new JLabel(); noteLabel = new JLabel(); hotkeyResetButton = new JButton(); hotkeySaveButton = new JButton(); hotkeySettingsLabel.setText("Hotkey settings (click the button to change)"); fullscreenLabel.setText("Fullscreen shot:"); fullHotkeyButton.setText(Language.getString("hotkeyNotSet")); fullHotkeyButton.addKeyListener(new HotkeyChangeListener(fullHotkeyButton)); cropLabel.setText("Crop shot:"); cropHotkeyButton.setText(Language.getString("hotkeyNotSet")); cropHotkeyButton.addKeyListener(new HotkeyChangeListener(cropHotkeyButton)); clipboardLabel.setText("Clipboard upload:"); clipboardHotkeyButton.setText(Language.getString("hotkeyNotSet")); clipboardHotkeyButton.addKeyListener(new HotkeyChangeListener(clipboardHotkeyButton)); fileLabel.setText("File upload:"); fileHotkeyButton.setText(Language.getString("hotkeyNotSet")); fileHotkeyButton.addKeyListener(new HotkeyChangeListener(fileHotkeyButton)); activeLabel.setText("Active window:"); activeHotkeyButton.setText(Language.getString("hotkeyNotSet")); activeHotkeyButton.addKeyListener(new HotkeyChangeListener(activeHotkeyButton)); optionsLabel.setText("Open settings:"); optionsHotkeyButton.setText(Language.getString("hotkeyNotSet")); optionsHotkeyButton.addKeyListener(new HotkeyChangeListener(optionsHotkeyButton)); noteLabel.setText("Note: All hotkeys are temporarily disabled when you click a button"); hotkeyResetButton.setText("Reset"); hotkeyResetButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadCurrentHotkeys(); hotkeySaveButton.setEnabled(false); hotkeyResetButton.setEnabled(false); } }); hotkeySaveButton.setText("Save"); hotkeySaveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { savePreferences(); } }); hotkeyResetButton.setEnabled(false); hotkeySaveButton.setEnabled(false); javax.swing.GroupLayout hotkeyPanelLayout = new javax.swing.GroupLayout( this); this.setLayout(hotkeyPanelLayout); hotkeyPanelLayout .setHorizontalGroup(hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( hotkeyPanelLayout .createSequentialGroup() .addGroup( hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( hotkeyPanelLayout .createSequentialGroup() .addContainerGap() .addComponent( hotkeySettingsLabel)) .addGroup( hotkeyPanelLayout .createSequentialGroup() .addGap(19, 19, 19) .addGroup( hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent( cropLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( fullscreenLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( clipboardLabel, javax.swing.GroupLayout.Alignment.LEADING) .addComponent( activeLabel, javax.swing.GroupLayout.Alignment.LEADING) .addComponent( fileLabel, javax.swing.GroupLayout.Alignment.LEADING) .addComponent( optionsLabel, javax.swing.GroupLayout.Alignment.LEADING)) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup( hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent( optionsHotkeyButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( activeHotkeyButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( fileHotkeyButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( clipboardHotkeyButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( cropHotkeyButton, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE) .addComponent( fullHotkeyButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(50, Short.MAX_VALUE)) .addGroup( javax.swing.GroupLayout.Alignment.TRAILING, hotkeyPanelLayout .createSequentialGroup() .addContainerGap(313, Short.MAX_VALUE) .addComponent(hotkeySaveButton) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(hotkeyResetButton) .addContainerGap()) .addGroup( hotkeyPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(noteLabel) .addContainerGap(137, Short.MAX_VALUE))); hotkeyPanelLayout.setVerticalGroup(hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( hotkeyPanelLayout .createSequentialGroup() .addContainerGap() .addComponent(hotkeySettingsLabel) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup( hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent( fullscreenLabel) .addComponent( fullHotkeyButton)) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup( hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cropLabel) .addComponent( cropHotkeyButton)) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup( hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent( clipboardLabel) .addComponent( clipboardHotkeyButton)) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup( hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(fileLabel) .addComponent( fileHotkeyButton)) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup( hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent( activeLabel) .addComponent( activeHotkeyButton)) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup( hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent( optionsLabel) .addComponent( optionsHotkeyButton)) .addGap(40, 40, 40) .addComponent(noteLabel) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED, 202, Short.MAX_VALUE) .addGroup( hotkeyPanelLayout .createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent( hotkeyResetButton) .addComponent( hotkeySaveButton)) .addContainerGap())); } public void loadCurrentHotkeys() { JSONObject keys = configuration.getJSONObject("hotkeys"); if (keys == null) { return; } if (keys.has("full")) { fullHotkeyButton.setText(getButtonText(keys.getString("full"))); } else { fullHotkeyButton.setText(Language.getString("hotkeyNotSet")); } if (keys.has("crop")) { cropHotkeyButton.setText(getButtonText(keys.getString("crop"))); } else { cropHotkeyButton.setText(Language.getString("hotkeyNotSet")); } if (keys.has("clipboard")) { clipboardHotkeyButton.setText(getButtonText(keys.getString("clipboard"))); } else { clipboardHotkeyButton.setText(Language.getString("hotkeyNotSet")); } if (keys.has("options")) { optionsHotkeyButton.setText(getButtonText(keys.getString("options"))); } else { optionsHotkeyButton.setText(Language.getString("hotkeyNotSet")); } if (keys.has("file")) { fileHotkeyButton.setText(getButtonText(keys.getString("file"))); } else { fileHotkeyButton.setText(Language.getString("hotkeyNotSet")); } if (Platform.isWindows() || Platform.isLinux()) { if (keys.has("active")) { activeHotkeyButton.setText(getButtonText(keys.getString("active"))); } else { activeHotkeyButton.setText(Language.getString("hotkeyNotSet")); } } else { activeHotkeyButton.setText("Unavailable"); activeHotkeyButton.setEnabled(false); } } public void savePreferences() { JSONObject keys = new JSONObject(); String full = fullHotkeyButton.getText(); if (!full.equals(Language.getString("hotkeyNotSet"))) { keys.put("full", getFormattedKeyStroke(full)); } String crop = cropHotkeyButton.getText(); if (!crop.equals(Language.getString("hotkeyNotSet"))) { keys.put("crop", getFormattedKeyStroke(crop)); } String clipboard = clipboardHotkeyButton.getText(); if (!clipboard.equals(Language.getString("hotkeyNotSet"))) { keys.put("clipboard", getFormattedKeyStroke(clipboard)); } String active = activeHotkeyButton.getText(); if (!active.equals(Language.getString("hotkeyNotSet"))) { keys.put("active", getFormattedKeyStroke(active)); } String file = fileHotkeyButton.getText(); if (!file.equals(Language.getString("hotkeyNotSet"))) { keys.put("file", getFormattedKeyStroke(file)); } String options = optionsHotkeyButton.getText(); if (!options.equals(Language.getString("hotkeyNotSet"))) { keys.put("options", getFormattedKeyStroke(options)); } configuration.put("hotkeys", keys); try { configuration.save(); } catch (IOException e) { e.printStackTrace(); } hotkeySaveButton.setEnabled(false); hotkeyResetButton.setEnabled(false); } public class HotkeyChangeListener extends KeyAdapter { private JButton button; public HotkeyChangeListener(JButton button) { this.button = button; } @Override public void keyPressed(KeyEvent e) { // If the key is unknown/a function key if (e.getKeyCode() == 0 || e.getKeyCode() == KeyEvent.VK_ALT || e.getKeyCode() == KeyEvent.VK_CONTROL || e.getKeyCode() == KeyEvent.VK_SHIFT || e.getKeyCode() == KeyEvent.VK_META) { return; } // Consume any keys that may cause tab changes/other undesired // behavior e.consume(); } @Override public void keyReleased(KeyEvent e) { if (parent.getSnapper().getKeyManager().hasKeysBound()) { parent.getSnapper().getKeyManager().resetKeys(); } // If the key is unknown/a function key if (e.getKeyCode() == 0 || e.getKeyCode() == KeyEvent.VK_ALT || e.getKeyCode() == KeyEvent.VK_CONTROL || e.getKeyCode() == KeyEvent.VK_SHIFT || e.getKeyCode() == KeyEvent.VK_META) { return; } button.setText(formatKeyStroke(KeyStroke.getKeyStrokeForEvent(e))); if (!hotkeyResetButton.isEnabled()) { hotkeyResetButton.setEnabled(true); } if (!hotkeySaveButton.isEnabled()) { hotkeySaveButton.setEnabled(true); } } } public static String formatKeyStroke(KeyStroke stroke) { if (stroke == null) { return Language.getString("hotkeyNotSet"); } String s = stroke.toString(); s = s.replace("released ", ""); s = s.replace("typed ", ""); s = s.replace("pressed ", ""); StringBuilder out = new StringBuilder(); String[] split = s.split(" "); for (int i = 0; i < split.length; i++) { String str = split[i]; if (str.contains("_")) { str = str.replace('_', ' '); } out.append(Util.ucwords(str)); if (i != (split.length - 1)) { out.append(" + "); } } return out.toString(); } public static String getFormattedKeyStroke(String s) { String[] split = s.split(" \\+ "); StringBuilder out = new StringBuilder(); for (int i = 0; i < split.length; i++) { if (i == (split.length - 1)) { out.append(split[i].toUpperCase().replace(' ', '_')); } else { out.append(split[i].toLowerCase()); out.append(" "); } } return out.toString(); } private String getButtonText(String stroke) { return formatKeyStroke(KeyStroke.getKeyStroke(stroke)); } }
gpl-3.0
dsolimando/Hot
hot-framework/src/test/resources/be/solidx/hot/test/mvc/f4.js
30
function f4() { return true }
gpl-3.0
M4thx/Melon-SelfBot
src/main/java/com/outlook/m4thx/melonselfbot/commands/EmoteCommand.java
2420
package com.outlook.m4thx.melonselfbot.commands; import com.outlook.m4thx.melonselfbot.commands.api.CommandContext; import com.outlook.m4thx.melonselfbot.commands.api.CommandExecutor; public class EmoteCommand implements CommandExecutor { @Override public void execute(CommandContext context) { String full = String.join(" ", context.args()); char[] chars = full.toCharArray(); StringBuilder sb = new StringBuilder(); for(int i = 0; i < chars.length; i++) { char currentChar = chars[i]; if(currentChar == ' ') { sb.append(" "); continue; } /* List<Emote> found = context.getMessage().getJDA().getEmotesByName("regional_indicator_" + currentChar, true); if(!found.isEmpty()) { sb.append(found.get(0).getAsMention()); continue; } */ char lower = Character.toLowerCase(currentChar); if((lower == 'a') || (lower == 'b') || (lower == 'c') || (lower == 'd') || (lower == 'e') || (lower == 'f') || (lower == 'g') || (lower == 'h') || (lower == 'i') || (lower == 'j') || (lower == 'k') || (lower == 'l') || (lower == 'm') || (lower == 'n') || (lower == 'o') || (lower == 'p') || (lower == 'q') || (lower == 'r') || (lower == 's') || (lower == 't') || (lower == 'u') || (lower == 'v') || (lower == 'w') || (lower == 'x') || (lower == 'y') || (lower == 'z')) { sb.append(":regional_indicator_" + lower + ":"); continue; } if(lower == '0') { sb.append(":zero:"); continue; } if(lower == '1') { if(i < chars.length - 1 && chars[i+1] == '0') { sb.append(":keycap_ten:"); i++; } else { sb.append(":one:"); } continue; } if(lower == '2') { sb.append(":two:"); continue; } if(lower == '3') { sb.append(":three:"); continue; } if(lower == '4') { sb.append(":four:"); continue; } if(lower == '5') { sb.append(":five:"); continue; } if(lower == '6') { sb.append(":six:"); continue; } if(lower == '7') { sb.append(":seven:"); continue; } if(lower == '8') { sb.append(":eight:"); continue; } if(lower == '9') { sb.append(":nine:"); continue; } sb.append(currentChar); } context.getMessage().editMessage(sb.toString()).queue(); } }
gpl-3.0
00-Evan/shattered-pixel-dungeon
desktop/src/main/java/com/shatteredpixel/shatteredpixeldungeon/desktop/DesktopLaunchValidator.java
3443
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2021 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.desktop; import com.badlogic.gdx.utils.SharedLibraryLoader; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.util.ArrayList; public class DesktopLaunchValidator { //Validates that the launching JVM is correctly configured // and attempts to launch a new one if it is not // returns false if current JVM is invalid and should be killed. public static boolean verifyValidJVMState(String[] args){ //mac computers require the -XstartOnFirstThread JVM argument if (SharedLibraryLoader.isMac){ // If XstartOnFirstThread is present and enabled, we can return true if ("1".equals(System.getenv("JAVA_STARTED_ON_FIRST_THREAD_" + ManagementFactory.getRuntimeMXBean().getName().split("@")[0]))) { return true; } // Check if we are the relaunched process, if so return true to avoid looping. // The game will likely crash, but that's unavoidable at this point. if ("true".equals(System.getProperty("shpdRelaunched"))){ System.err.println("Error: Could not verify new process is running on the first thread. Trying to run the game anyway..."); return true; } // Relaunch a new jvm process with the same arguments, plus -XstartOnFirstThread String sep = System.getProperty("file.separator"); ArrayList<String> jvmArgs = new ArrayList<>(); jvmArgs.add(System.getProperty("java.home") + sep + "bin" + sep + "java"); jvmArgs.add("-XstartOnFirstThread"); jvmArgs.add("-DshpdRelaunched=true"); jvmArgs.addAll(ManagementFactory.getRuntimeMXBean().getInputArguments()); jvmArgs.add("-cp"); jvmArgs.add(System.getProperty("java.class.path")); jvmArgs.add(DesktopLauncher.class.getName()); System.err.println("Error: ShatteredPD must start on the first thread in order to work on macOS."); System.err.println(" To avoid this error, run the game with the \"-XstartOnFirstThread\" argument"); System.err.println(" Now attempting to relaunch the game on the first thread automatically:\n"); try { Process process = new ProcessBuilder(jvmArgs).redirectErrorStream(true).start(); BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; //Relay console output from the relaunched process while ((line = out.readLine()) != null) { if (line.toLowerCase().startsWith("error")){ System.err.println(line); } else { System.out.println(line); } } process.waitFor(); } catch (Exception e) { e.printStackTrace(); } return false; } return true; } }
gpl-3.0
hmenke/espresso
src/core/ComFixed.hpp
3355
/* Copyright (C) 2017-2018 The ESPResSo project This file is part of ESPResSo. ESPResSo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ESPResSo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CORE_COMFIXED_HPP #define CORE_COMFIXED_HPP #include "Vector.hpp" #include "utils/keys.hpp" #include <boost/mpi/collectives/all_reduce.hpp> #include <boost/mpi/communicator.hpp> #include <unordered_map> #include <vector> template <typename ParticleRange> class ComFixed { public: using TypeIndex = std::unordered_map<int, int>; private: TypeIndex m_type_index; std::vector<Vector3d> local_type_forces(ParticleRange &particles) const { std::vector<Vector3d> ret(m_type_index.size(), Vector3d{}); for (auto const &p : particles) { /* Check if type is of interest */ auto it = m_type_index.find(p.p.type); if (it != m_type_index.end()) { ret[it->second] += Vector3d{p.f.f}; } } return ret; } std::vector<double> local_type_masses(ParticleRange &particles) const { std::vector<double> ret(m_type_index.size(), 0.); for (auto const &p : particles) { /* Check if type is of interest */ auto it = m_type_index.find(p.p.type); if (it != m_type_index.end()) { ret[it->second] += p.p.mass; } } return ret; } public: template <typename Container> void set_fixed_types(Container const &c) { m_type_index.clear(); int i = 0; for (auto const &t : c) { m_type_index[t] = i++; } } std::vector<int> get_fixed_types() const { return Utils::keys(m_type_index); } void apply(boost::mpi::communicator const &comm, ParticleRange &particles) const { /* Bail out early if there is nothing to do. */ if (m_type_index.empty()) return; auto const local_forces = local_type_forces(particles); auto const local_masses = local_type_masses(particles); /* Total forces and masses of the types. */ std::vector<Vector3d> forces(m_type_index.size(), Vector3d{}); std::vector<double> masses(m_type_index.size(), 0.0); /* Add contributions from all nodes and redistribute them to all. */ boost::mpi::all_reduce(comm, local_forces.data(), local_forces.size(), forces.data(), std::plus<Vector3d>{}); boost::mpi::all_reduce(comm, local_masses.data(), local_masses.size(), masses.data(), std::plus<double>{}); for (auto &p : particles) { /* Check if type is of interest */ auto it = m_type_index.find(p.p.type); if (it != m_type_index.end()) { auto const mass_frac = p.p.mass / masses[it->second]; auto const &type_force = forces[it->second]; for (int i = 0; i < 3; i++) { p.f.f[i] -= mass_frac * type_force[i]; } } } } }; #endif
gpl-3.0
huangchuping/bug
Sys/ThinkPHP/ThinkPHP.php
2147
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // ThinkPHP 入口文件 if(!ini_get('session.use_trans_sid')){ ini_set('session.use_trans_sid',1); } // 记录开始运行时间 $GLOBALS['_beginTime'] = microtime(TRUE); // 记录内存初始使用 define('MEMORY_LIMIT_ON',function_exists('memory_get_usage')); if(MEMORY_LIMIT_ON) $GLOBALS['_startUseMems'] = memory_get_usage(); // 系统目录定义 defined('THINK_PATH') or define('THINK_PATH', dirname(__FILE__).'/'); defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']).'/'); defined('APP_DEBUG') or define('APP_DEBUG',false); // 是否调试模式 define('ROOT', APP_PATH); $document = str_replace("\\", '/', $_SERVER['PHP_SELF']); $index_end = substr($document,1); $index = str_replace('/'.$index_end,'',$document); $item_end = strstr($document,'/index.php'); $item = str_replace($item_end,'',$document); define('INDEX', $index); define('ITEM', $item); define('DOMAIN',$_SERVER['SERVER_NAME']); if(defined('ENGINE_NAME')) { defined('ENGINE_PATH') or define('ENGINE_PATH',THINK_PATH.'Extend/Engine/'); require ENGINE_PATH.strtolower(ENGINE_NAME).'.php'; }else{ defined('RUNTIME_PATH') or define('RUNTIME_PATH',APP_PATH.'Runtime/'); $runtime = defined('MODE_NAME')?'~'.strtolower(MODE_NAME).'_runtime.php':'~runtime.php'; defined('RUNTIME_FILE') or define('RUNTIME_FILE',RUNTIME_PATH.$runtime); if(!APP_DEBUG && is_file(RUNTIME_FILE)) { // 部署模式直接载入运行缓存 require RUNTIME_FILE; }else{ // 加载运行时文件 require THINK_PATH.'Common/runtime.php'; } }
gpl-3.0
jeroenwalter/Badaap-Comic-Reader
app/view/About.js
2863
/* This file is part of Badaap Comic Reader. Copyright (c) 2012 Jeroen Walter Badaap Comic Reader is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Badaap Comic Reader is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Badaap Comic Reader. If not, see <http://www.gnu.org/licenses/>. */ Ext.define('Comic.view.About', { extend: 'Ext.form.Panel', xtype: 'aboutview', config: { items: [ { xtype: 'fieldset', title: 'About', items: [ { xtype: 'textfield', name: 'title', label: 'Title', value: 'Badaap Comic Reader', readOnly: true }, { xtype: 'textfield', name: 'version', label: 'Version', value: '0.4', readOnly: true }, { xtype: 'textfield', name: 'copyright', label: 'Copyright', value: 'Copyright (c) 2012 Jeroen Walter', readOnly: true, }, { xtype: 'textfield', name: 'website', label: 'Website', value: 'http://www.badaap.nl/', //html: '<a href="http://www.badaap.nl/Badaap Comic Reader" target=_blank>http://www.badaap.nl/</a>', readOnly: true }, { xtype: 'textfield', name: 'manual', label: 'Manual', value: '', html: '<a href="manual/index.html">Open the manual</a>', readOnly: true }, ] }, { xtype: 'fieldset', title: 'License', instructions: 'Badaap Comic Reader is free software: you can redistribute it and/or modify<br/>\ it under the terms of the GNU General Public License as published by<br/>\ the Free Software Foundation, either version 3 of the License, or<br/>\ (at your option) any later version.<br/>\ <br/>\ Badaap Comic Reader is distributed in the hope that it will be useful,<br/>\ but WITHOUT ANY WARRANTY; without even the implied warranty of<br/>\ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br/>\ GNU General Public License for more details.<br/>\ <br/>\ You should have received a copy of the GNU General Public License<br/>\ along with Badaap Comic Reader. If not, see http://www.gnu.org/licenses/.', } ] } });
gpl-3.0
raulperula/uco_student
computer_graphics/practices/src/p3/pract3.4.cpp
3364
#ifdef WIN32 #include<windows.h> #endif #ifdef WIN32 #include<windows.h> #endif #include<GL/gl.h> #include<GL/glut.h> #include<fstream> #ifndef WIN32 #include <iostream> #endif #include <math.h> #include <stdlib.h> #define An 640 #define Al 480 #define GL_PI 3.14159265f using namespace std; void mi_Inicio(void) { glClearColor(1.0f,1.0f,1.0f,0.0f); //Selecciona el color de fondo glColor3f(1.0f, 0.0f, 0.0f); //El color a dibujar glMatrixMode (GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, (double) An, 0.0, (double) Al); glPointSize(3.0); } void setWindow(float left,float right,float bottom,float top){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(left,right,bottom,top); } void setViewport(int left,int right,int bottom,int top){ glViewport(left,bottom,right-left,top-bottom); } void drawPolyLineFile(char* archivo){ int i,j; fstream entrada; entrada.open(archivo,ios ::in); //abre el archivo if(entrada.fail()) return; GLint numpolys, numLineas, x, y; entrada >> numpolys; for(j=0;j<numpolys;j++){ entrada >> numLineas; glBegin(GL_LINE_STRIP); glColor3f(1.0f, 0.0f, 0.0f); //El color a dibujar for(i=0;i<numLineas;i++){ entrada >>x >> y; glVertex2i(x,y); } glEnd(); } glFlush(); entrada.close(); } void miDibujo(void){ glClear(GL_COLOR_BUFFER_BIT); //Limpia la pantalla //Dibuja las líneas de separación de las ventanas glColor3f(0.0f, 0.0f, 1.0f); //El color a dibujar setWindow(0.0,640.0,0.0,480.0); setViewport(0,640,0,480); glBegin(GL_LINES); glVertex2i(0,240); glVertex2i(640,240); glVertex2i(320,0); glVertex2i(320,480); glEnd(); glFlush(); glColor3f(1.0f, 0.0f, 0.0f); //El color a dibujar //Esquina inferior izquierda setWindow(0.0,640.0,0.0,480.0); glViewport(0,0,320,240); drawPolyLineFile("dino.dat"); //Esquina inferior derecha setWindow(0.0,320,0.0,240.0); glViewport(320,0,640,240); drawPolyLineFile("dino.dat"); //Esquina superior izquierda setWindow(-10.0,240.0,320.0,600.0); glViewport(0,240,320,480); drawPolyLineFile("dino.dat"); //Superior derecha setWindow(160.0,480.0,37.5,277.5); glViewport(320,240,640,480); drawPolyLineFile("dino.dat"); } int main(int argc, char **argv){ glutInit(&argc, argv); //Inicializa toolkit glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); //Selec. el modo pantalla glutInitWindowSize(An,Al); //Selecciona el tamaño de la ventana glutInitWindowPosition(100, 250); //Posiciona la ventana en la pantalla glutCreateWindow("Practica 3.1: Puerto de vista");//Abre ventana en pantalla glutDisplayFunc(miDibujo); //Registra la función de redibujar mi_Inicio(); glutMainLoop(); //Bucle continuo return 0; }
gpl-3.0
peerrabe/laravel-ecommerce
modules/mage2/ecommerce/resources/views/admin/tax-group/_fields.blade.php
751
@include('mage2-ecommerce::forms.text',['name' => 'name' , 'label' => 'Name']) <?php $values = []; ?> @if(isset($model)) <?php $values = $model->taxRules->pluck('id')->toArray(); ?> @endif @include('mage2-ecommerce::forms.select',['name' => 'tax_rules[]' , 'attributes' => ['class' => 'select2 form-control','multiple' => true], 'label' => 'Tax Rule', 'options' => $taxRulesOptions, 'values' => $values]) @push('scripts') <script> $(function() { jQuery('.select2').select2(); }) </script> @endpush
gpl-3.0
Pumpuli/multitheftauto
MTA10_Server/mods/deathmatch/logic/CMarker.cpp
12618
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: mods/deathmatch/logic/CMarker.cpp * PURPOSE: Marker entity class * DEVELOPERS: Christian Myhre Lundheim <> * Jax <> * Kevin Whiteside <> * lil_Toady <> * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #include "StdInc.h" CMarker::CMarker ( CMarkerManager* pMarkerManager, CColManager* pColManager, CElement* pParent, CXMLNode* pNode ) : CPerPlayerEntity ( pParent, pNode ) { // Init m_pMarkerManager = pMarkerManager; m_pColManager = pColManager; m_iType = CElement::MARKER; SetTypeName ( "marker" ); m_ucType = TYPE_CHECKPOINT; m_fSize = 4.0f; m_Color = SColorRGBA ( 255, 255, 255, 255 ); m_bHasTarget = false; m_ucIcon = ICON_NONE; // Create our collision object m_pCollision = new CColCircle ( pColManager, NULL, m_vecPosition, m_fSize, NULL, true ); m_pCollision->SetCallback ( this ); m_pCollision->SetAutoCallEvent ( false ); // Add us to the marker manager pMarkerManager->AddToList ( this ); UpdateSpatialData (); } CMarker::~CMarker ( void ) { // Delete our collision object if ( m_pCollision ) delete m_pCollision; // Unlink from manager Unlink (); } void CMarker::Unlink ( void ) { // Remove us from the marker manager m_pMarkerManager->RemoveFromList ( this ); } bool CMarker::ReadSpecialData ( void ) { // Grab the "posX" data if ( !GetCustomDataFloat ( "posX", m_vecPosition.fX, true ) ) { CLogger::ErrorPrintf ( "Bad/missing 'posX' attribute in <marker> (line %u)\n", m_uiLine ); return false; } // Grab the "posY" data if ( !GetCustomDataFloat ( "posY", m_vecPosition.fY, true ) ) { CLogger::ErrorPrintf ( "Bad/missing 'posY' attribute in <marker> (line %u)\n", m_uiLine ); return false; } // Grab the "posZ" data if ( !GetCustomDataFloat ( "posZ", m_vecPosition.fZ, true ) ) { CLogger::ErrorPrintf ( "Bad/missing 'posZ' attribute in <marker> (line %u)\n", m_uiLine ); return false; } // Set the position in the col object if ( m_pCollision ) m_pCollision->SetPosition ( m_vecPosition ); // Grab the "type" data char szBuffer [128]; if ( GetCustomDataString ( "type", szBuffer, 128, true ) ) { // Convert it to a type m_ucType = static_cast < unsigned char > ( CMarkerManager::StringToType ( szBuffer ) ); if ( m_ucType == CMarker::TYPE_INVALID ) { CLogger::LogPrintf ( "WARNING: Unknown 'type' value specified in <marker>; defaulting to \"default\" (line %u)\n", m_uiLine ); m_ucType = CMarker::TYPE_CHECKPOINT; } } else { m_ucType = CMarker::TYPE_CHECKPOINT; } // Grab the "color" data if ( GetCustomDataString ( "color", szBuffer, 128, true ) ) { // Convert the HTML-style color to RGB if ( !XMLColorToInt ( szBuffer, m_Color.R, m_Color.G, m_Color.B, m_Color.A ) ) { CLogger::ErrorPrintf ( "Bad 'color' specified in <marker> (line %u)\n", m_uiLine ); return false; } } else { SetColor ( SColorRGBA( 255, 0, 0, 255 ) ); } float fSize; if ( GetCustomDataFloat ( "size", fSize, true ) ) m_fSize = fSize; int iTemp; if ( GetCustomDataInt ( "dimension", iTemp, true ) ) m_usDimension = static_cast < unsigned short > ( iTemp ); if ( GetCustomDataInt ( "interior", iTemp, true ) ) m_ucInterior = static_cast < unsigned char > ( iTemp ); // Success return true; } void CMarker::SetPosition ( const CVector& vecPosition ) { // Remember our last position m_vecLastPosition = m_vecPosition; // Different from our current position? if ( m_vecPosition != vecPosition ) { // Set the new position m_vecPosition = vecPosition; if ( m_pCollision ) m_pCollision->SetPosition ( vecPosition ); UpdateSpatialData (); // We need to make sure the time context is replaced // before that so old packets don't arrive after this. GenerateSyncTimeContext (); // Tell all the players that know about us CBitStream BitStream; BitStream.pBitStream->Write ( m_ID ); BitStream.pBitStream->Write ( vecPosition.fX ); BitStream.pBitStream->Write ( vecPosition.fY ); BitStream.pBitStream->Write ( vecPosition.fZ ); BitStream.pBitStream->Write ( GetSyncTimeContext () ); BroadcastOnlyVisible ( CLuaPacket ( SET_ELEMENT_POSITION, *BitStream.pBitStream ) ); } } void CMarker::SetTarget ( const CVector* pTargetVector ) { // Got a target vector? if ( pTargetVector ) { // Different from our current target if ( !m_bHasTarget || m_vecTarget != *pTargetVector ) { // Is this a marker type that has a destination? if ( m_ucType == CMarker::TYPE_CHECKPOINT || m_ucType == CMarker::TYPE_RING ) { // Set the target position m_bHasTarget = true; m_vecTarget = *pTargetVector; // Tell everyone that knows about this marker CBitStream BitStream; BitStream.pBitStream->Write ( m_ID ); BitStream.pBitStream->Write ( static_cast < unsigned char > ( 1 ) ); BitStream.pBitStream->Write ( m_vecTarget.fX ); BitStream.pBitStream->Write ( m_vecTarget.fY ); BitStream.pBitStream->Write ( m_vecTarget.fZ ); BroadcastOnlyVisible ( CLuaPacket ( SET_MARKER_TARGET, *BitStream.pBitStream ) ); } else { // Reset the target position m_bHasTarget = false; } } } else { // Not already without target? if ( m_bHasTarget ) { // Reset the target position m_bHasTarget = false; // Is this a marker type that has a destination? if ( m_ucType == CMarker::TYPE_CHECKPOINT || m_ucType == CMarker::TYPE_RING ) { // Tell everyone that knows about this marker CBitStream BitStream; BitStream.pBitStream->Write ( m_ID ); BitStream.pBitStream->Write ( static_cast < unsigned char > ( 0 ) ); BroadcastOnlyVisible ( CLuaPacket ( SET_MARKER_TARGET, *BitStream.pBitStream ) ); } } } } void CMarker::SetMarkerType ( unsigned char ucType ) { // Different from our current type? if ( ucType != m_ucType ) { // Set the new type unsigned char ucOldType = m_ucType; m_ucType = ucType; UpdateCollisionObject ( ucOldType ); // Tell all players CBitStream BitStream; BitStream.pBitStream->Write ( m_ID ); BitStream.pBitStream->Write ( ucType ); BroadcastOnlyVisible ( CLuaPacket ( SET_MARKER_TYPE, *BitStream.pBitStream ) ); // Is the new type not a checkpoint or a ring? Remove the target if ( ucType != CMarker::TYPE_CHECKPOINT && ucType != CMarker::TYPE_RING ) { m_bHasTarget = false; } } } void CMarker::SetSize ( float fSize ) { // Different from our current size? if ( fSize != m_fSize ) { // Set the new size and update the col object m_fSize = fSize; UpdateCollisionObject ( m_ucType ); // Tell all players CBitStream BitStream; BitStream.pBitStream->Write ( m_ID ); BitStream.pBitStream->Write ( fSize ); BroadcastOnlyVisible ( CLuaPacket ( SET_MARKER_SIZE, *BitStream.pBitStream ) ); } } void CMarker::SetColor ( const SColor color ) { // Different from our current color? if ( color != m_Color ) { // Set the new color m_Color = color; // Tell all the players CBitStream BitStream; BitStream.pBitStream->Write ( m_ID ); BitStream.pBitStream->Write ( color.B ); BitStream.pBitStream->Write ( color.G ); BitStream.pBitStream->Write ( color.R ); BitStream.pBitStream->Write ( color.A ); BroadcastOnlyVisible ( CLuaPacket ( SET_MARKER_COLOR, *BitStream.pBitStream ) ); } } void CMarker::SetIcon ( unsigned char ucIcon ) { if ( m_ucIcon != ucIcon ) { m_ucIcon = ucIcon; // Tell everyone that knows about this marker CBitStream BitStream; BitStream.pBitStream->Write ( m_ID ); BitStream.pBitStream->Write ( m_ucIcon ); BroadcastOnlyVisible ( CLuaPacket ( SET_MARKER_ICON, *BitStream.pBitStream ) ); } } void CMarker::Callback_OnCollision ( CColShape& Shape, CElement& Element ) { // Matching interior? if ( GetInterior () == Element.GetInterior () ) { // Call the marker hit event CLuaArguments Arguments; Arguments.PushElement ( &Element ); // Hit element Arguments.PushBoolean ( GetDimension () == Element.GetDimension () ); // Matching dimension? CallEvent ( "onMarkerHit", Arguments ); if ( IS_PLAYER ( &Element ) ) { CLuaArguments Arguments2; Arguments2.PushElement ( this ); // marker Arguments2.PushBoolean ( GetDimension () == Element.GetDimension () ); // Matching dimension? Element.CallEvent ( "onPlayerMarkerHit", Arguments2 ); } } } void CMarker::Callback_OnLeave ( CColShape& Shape, CElement& Element ) { // Matching interior? if ( GetInterior () == Element.GetInterior () ) { // Call the marker hit event CLuaArguments Arguments; Arguments.PushElement ( &Element ); // Hit element Arguments.PushBoolean ( GetDimension () == Element.GetDimension () ); // Matching dimension? CallEvent ( "onMarkerLeave", Arguments ); if ( IS_PLAYER ( &Element ) ) { CLuaArguments Arguments2; Arguments2.PushElement ( this ); // marker Arguments2.PushBoolean ( GetDimension () == Element.GetDimension () ); // Matching dimension? Element.CallEvent ( "onPlayerMarkerLeave", Arguments2 ); } } } void CMarker::Callback_OnCollisionDestroy ( CColShape* pCollision ) { if ( pCollision == m_pCollision ) m_pCollision = NULL; } void CMarker::UpdateCollisionObject ( unsigned char ucOldType ) { // Different type than before? if ( m_ucType != ucOldType ) { // Are we becomming a checkpoint? Make the col object a circle. If we're becomming something and we were a checkpoint, make the col object a sphere. // lil_Toady: Simply deleting the colshape may cause a dangling pointer in CColManager if we're in DoHitDetection loop if ( m_ucType == CMarker::TYPE_CHECKPOINT ) { if ( m_pCollision ) g_pGame->GetElementDeleter()->Delete ( m_pCollision ); m_pCollision = new CColCircle ( m_pColManager, NULL, m_vecPosition, m_fSize, NULL ); } else if ( ucOldType == CMarker::TYPE_CHECKPOINT ) { if ( m_pCollision ) g_pGame->GetElementDeleter()->Delete ( m_pCollision ); m_pCollision = new CColSphere ( m_pColManager, NULL, m_vecPosition, m_fSize, NULL ); } m_pCollision->SetCallback ( this ); m_pCollision->SetAutoCallEvent ( false ); } // Set the radius after the size if ( m_ucType == CMarker::TYPE_CHECKPOINT ) { static_cast < CColCircle* > ( m_pCollision )->SetRadius ( m_fSize ); } else { static_cast < CColSphere* > ( m_pCollision )->SetRadius ( m_fSize ); } } CSphere CMarker::GetWorldBoundingSphere ( void ) { return CSphere ( GetPosition (), GetSize () ); }
gpl-3.0
mwishoff/mattsWork
AMOS - JavaScriptOS/bin/SchedulerProcess3.js
978
/** * Created by Matt on 4/14/2016. */ var SchedulerProcess3 = function(counter) { switch(counter) { case 0: console.log("case 0 Processes 3"); OS.FS.create("file", "file Content"); //this.program_counter++; break; case 1: console.log("case 1 Processes 3"); OS.FS.create("file", "file Content"); //this.program_counter++; break; case 2: console.log("case 2 Processes 3"); OS.FS.create("file", "file Content"); //this.program_counter++; break; case 3: console.log("case 3 Processes 3"); OS.FS.create("file", "file Content"); //this.program_counter++; break; default: this.state = "Stop"; this.program_counter = 0; } }; Processes.listOfProcesses.push(new Process("SchedulerProcess3",SchedulerProcess3));
gpl-3.0
SpaceGame-ETSII/spacegame
core/src/com/tfg/spacegame/utils/enums/TypeEnemy.java
146
package com.tfg.spacegame.utils.enums; public enum TypeEnemy { TYPE1, TYPE2, TYPE3, TYPE4, TYPE5, RED, BLUE, YELLOW, GREEN, ORANGE, PURPLE }
gpl-3.0
oeru/techblog
drupal8/modules/views_timelinejs/src/TimelineJS/Timeline.php
2094
<?php namespace Drupal\views_timelinejs\TimelineJS; use Drupal\views_timelinejs\TimelineJS\EraInterface; use Drupal\views_timelinejs\TimelineJS\SlideInterface; use Drupal\views_timelinejs\TimelineJS\TimelineInterface; /** * Defines a TimelineJS3 timeline. */ class Timeline implements TimelineInterface { /** * The timeline scale. * * @var string */ protected $scale = 'human'; /** * The timeline's title slide. * * @var SlideInterface */ protected $title_slide; /** * The timeline's array of event slides. * * @var array */ protected $events = array(); /** * The timeline's array of eras. * * @var array */ protected $eras = array(); /** * {@inheritdoc} */ public function setTitleSlide(SlideInterface $slide) { $this->title_slide = $slide; } /** * {@inheritdoc} */ public function getTitleSlide() { return $this->title_slide; } /** * {@inheritdoc} */ public function addEvent(SlideInterface $slide) { $this->events[] = $slide; } /** * {@inheritdoc} */ public function getEvents() { return $this->events; } /** * {@inheritdoc} */ public function addEra(EraInterface $era) { $this->eras[] = $era; } /** * {@inheritdoc} */ public function getEras() { return $this->eras; } /** * {@inheritdoc} */ public function setScaleToHuman() { $this->scale = 'human'; } /** * {@inheritdoc} */ public function setScaleToCosomological() { $this->scale = 'cosomological'; } /** * {@inheritdoc} */ public function getScale() { return $this->scale; } /** * {@inheritdoc} */ public function buildArray() { $timeline = array('scale' => $this->scale); if (!empty($this->title_slide)) { $timeline['title'] = $this->title_slide->buildArray(); } foreach ($this->events as $event) { $timeline['events'][] = $event->buildArray(); } foreach ($this->eras as $era) { $timeline['eras'][] = $era->buildArray(); } return $timeline; } }
gpl-3.0
anikanovs/iskatel
Iskatel.Web/Controllers/ManageController.cs
14124
using System; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Iskatel.Web.Models; namespace Iskatel.Web.Controllers { [Authorize] public class ManageController : Controller { private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public ManageController() { } public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) { UserManager = userManager; SignInManager = signInManager; } public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } // // GET: /Manage/Index public async Task<ActionResult> Index(ManageMessageId? message) { ViewBag.StatusMessage = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var userId = User.Identity.GetUserId(); var model = new IndexViewModel { HasPassword = HasPassword(), PhoneNumber = await UserManager.GetPhoneNumberAsync(userId), TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId), Logins = await UserManager.GetLoginsAsync(userId), BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey) { ManageMessageId? message; var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } message = ManageMessageId.RemoveLoginSuccess; } else { message = ManageMessageId.Error; } return RedirectToAction("ManageLogins", new { Message = message }); } // // GET: /Manage/AddPhoneNumber public ActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number); if (UserManager.SmsService != null) { var message = new IdentityMessage { Destination = model.Number, Body = "Your security code is: " + code }; await UserManager.SmsService.SendAsync(message); } return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> EnableTwoFactorAuthentication() { await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true); var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> DisableTwoFactorAuthentication() { await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false); var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", "Manage"); } // // GET: /Manage/VerifyPhoneNumber public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber) { var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber); // Send an SMS through the SMS provider to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess }); } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "Failed to verify phone"); return View(model); } // // POST: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> RemovePhoneNumber() { var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null); if (!result.Succeeded) { return RedirectToAction("Index", new { Message = ManageMessageId.Error }); } var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess }); } // // GET: /Manage/ChangePassword public ActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } // // GET: /Manage/SetPassword public ActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> SetPassword(SetPasswordViewModel model) { if (ModelState.IsValid) { var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Manage/ManageLogins public async Task<ActionResult> ManageLogins(ManageMessageId? message) { ViewBag.StatusMessage = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user == null) { return View("Error"); } var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()); var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList(); ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public ActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId()); } // // GET: /Manage/LinkLoginCallback public async Task<ActionResult> LinkLoginCallback() { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); if (loginInfo == null) { return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login); return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } protected override void Dispose(bool disposing) { if (disposing && _userManager != null) { _userManager.Dispose(); _userManager = null; } base.Dispose(disposing); } #region Helpers // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private bool HasPassword() { var user = UserManager.FindById(User.Identity.GetUserId()); if (user != null) { return user.PasswordHash != null; } return false; } private bool HasPhoneNumber() { var user = UserManager.FindById(User.Identity.GetUserId()); if (user != null) { return user.PhoneNumber != null; } return false; } public enum ManageMessageId { AddPhoneSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } #endregion } }
gpl-3.0
whitireia/moodle
mod/dialogue/version.php
1204
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Code fragment to define the module version etc. * This fragment is called by /admin/index.php * * @package mod-dialogue * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $module->version = 2011110900; $module->requires = 2010112400; // Requires this Moodle version 2.x $module->release = '2.0.4+'; // Human-friendly version name $module->maturity = MATURITY_STABLE; // this version's maturity level $module->cron = 60; ?>
gpl-3.0
Lux-Vacuos/Voxel
voxel-universal/src/main/java/net/luxvacuos/voxel/universal/ecs/components/ChunkLoader.java
1675
/* * This file is part of Voxel * * Copyright (C) 2016-2018 Lux Vacuos * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package net.luxvacuos.voxel.universal.ecs.components; import com.hackhalo2.nbt.CompoundBuilder; import com.hackhalo2.nbt.exceptions.NBTException; import com.hackhalo2.nbt.tags.TagCompound; import net.luxvacuos.lightengine.universal.ecs.components.LEComponent; public class ChunkLoader implements LEComponent { private int chunkRadius = 10; public ChunkLoader() { } public ChunkLoader(int chunkRadius) { this.chunkRadius = chunkRadius; } @Override public void load(TagCompound compound) throws NBTException { if(compound.hasTagByName("ChunkRadius")) { this.chunkRadius = compound.getInt("ChunkRadius"); } } @Override public TagCompound save() { return new CompoundBuilder().start("ChunkLoaderCompound").addInteger("ChunkRadius", this.chunkRadius).build(); } public int getChunkRadius() { return this.chunkRadius; } public void setChunkRadius(int chunkRadius) { this.chunkRadius = chunkRadius; } }
gpl-3.0
deep9/zurmo
app/protected/modules/reports/tests/unit/ReportToExportAdapterTest.php
47468
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2012 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207, * Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com. ********************************************************************************/ /** * Test RedBeanModelAttributeValueToExportValueAdapter functions. */ class ReportToExportAdapterTest extends ZurmoBaseTest { public $freeze = false; public static function setUpBeforeClass() { parent::setUpBeforeClass(); $super = SecurityTestHelper::createSuperAdmin(); } public function setUp() { parent::setUp(); Yii::app()->user->userModel = User::getByUsername('super'); DisplayAttributeForReportForm::resetCount(); $freeze = false; if (RedBeanDatabase::isFrozen()) { RedBeanDatabase::unfreeze(); $freeze = true; } $this->freeze = $freeze; } public function teardown() { if ($this->freeze) { RedBeanDatabase::freeze(); } parent::teardown(); } public function testGetDataWithNoRelationsSet() { $values = array( 'Test1', 'Test2', 'Test3', 'Sample', 'Demo', ); $customFieldData = CustomFieldData::getByName('ReportTestDropDown'); $customFieldData->serializedData = serialize($values); $saved = $customFieldData->save(); $this->assertTrue($saved); $report = new Report(); //for fullname attribute (derived attribute) $reportModelTestItem = new ReportModelTestItem(); $reportModelTestItem->firstName = 'xFirst'; $reportModelTestItem->lastName = 'xLast'; $displayAttribute1 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute1->setModelAliasUsingTableAliasName('model1'); $displayAttribute1->attributeIndexOrDerivedType = 'FullName'; //for boolean attribute $reportModelTestItem->boolean = true; $displayAttribute2 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute2->setModelAliasUsingTableAliasName('model1'); $displayAttribute2->attributeIndexOrDerivedType = 'boolean'; //for date attribute $reportModelTestItem->date = '2013-02-12'; $displayAttribute3 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute3->setModelAliasUsingTableAliasName('model1'); $displayAttribute3->attributeIndexOrDerivedType = 'date'; //for datetime attribute $reportModelTestItem->dateTime = '2013-02-12 10:15:00'; $displayAttribute4 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute4->setModelAliasUsingTableAliasName('model1'); $displayAttribute4->attributeIndexOrDerivedType = 'dateTime'; //for float attribute $reportModelTestItem->float = 10.5; $displayAttribute5 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute5->setModelAliasUsingTableAliasName('model1'); $displayAttribute5->attributeIndexOrDerivedType = 'float'; //for integer attribute $reportModelTestItem->integer = 10; $displayAttribute6 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute6->setModelAliasUsingTableAliasName('model1'); $displayAttribute6->attributeIndexOrDerivedType = 'integer'; //for phone attribute $reportModelTestItem->phone = '7842151012'; $displayAttribute7 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute7->setModelAliasUsingTableAliasName('model1'); $displayAttribute7->attributeIndexOrDerivedType = 'phone'; //for string attribute $reportModelTestItem->string = 'xString'; $displayAttribute8 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute8->setModelAliasUsingTableAliasName('model1'); $displayAttribute8->attributeIndexOrDerivedType = 'string'; //for textArea attribute $reportModelTestItem->textArea = 'xtextAreatest'; $displayAttribute9 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute9->setModelAliasUsingTableAliasName('model1'); $displayAttribute9->attributeIndexOrDerivedType = 'textArea'; //for url attribute $reportModelTestItem->url = 'http://www.test.com'; $displayAttribute10 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute10->setModelAliasUsingTableAliasName('model1'); $displayAttribute10->attributeIndexOrDerivedType = 'url'; //for dropdown attribute $reportModelTestItem->dropDown->value = $values[1]; $displayAttribute11 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute11->setModelAliasUsingTableAliasName('model1'); $displayAttribute11->attributeIndexOrDerivedType = 'dropDown'; //for currency attribute $currencies = Currency::getAll(); $currencyValue = new CurrencyValue(); $currencyValue->value = 100; $currencyValue->currency = $currencies[0]; $this->assertEquals('USD', $currencyValue->currency->code); $reportModelTestItem->currencyValue = $currencyValue; $displayAttribute12 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute12->setModelAliasUsingTableAliasName('model1'); $displayAttribute12->attributeIndexOrDerivedType = 'currencyValue'; //for primaryAddress attribute $reportModelTestItem->primaryAddress->street1 = 'someString'; $displayAttribute13 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute13->setModelAliasUsingTableAliasName('model1'); $displayAttribute13->attributeIndexOrDerivedType = 'primaryAddress___street1'; //for primaryEmail attribute $reportModelTestItem->primaryEmail->emailAddress = "test@someString.com"; $displayAttribute14 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute14->setModelAliasUsingTableAliasName('model1'); $displayAttribute14->attributeIndexOrDerivedType = 'primaryEmail___emailAddress'; //for multiDropDown attribute $customFieldValue = new CustomFieldValue(); $customFieldValue->value = 'Multi 1'; $reportModelTestItem->multiDropDown->values->add($customFieldValue); $customFieldValue = new CustomFieldValue(); $customFieldValue->value = 'Multi 2'; $reportModelTestItem->multiDropDown->values->add($customFieldValue); $displayAttribute15 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute15->setModelAliasUsingTableAliasName('model1'); $displayAttribute15->attributeIndexOrDerivedType = 'multiDropDown'; //for tagCloud attribute $customFieldValue = new CustomFieldValue(); $customFieldValue->value = 'Cloud 2'; $reportModelTestItem->tagCloud->values->add($customFieldValue); $customFieldValue = new CustomFieldValue(); $customFieldValue->value = 'Cloud 3'; $reportModelTestItem->tagCloud->values->add($customFieldValue); $displayAttribute16 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute16->setModelAliasUsingTableAliasName('model1'); $displayAttribute16->attributeIndexOrDerivedType = 'tagCloud'; //for radioDropDown attribute $reportModelTestItem->radioDropDown->value = $values[1]; $displayAttribute17 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute17->setModelAliasUsingTableAliasName('model1'); $displayAttribute17->attributeIndexOrDerivedType = 'radioDropDown'; //for likeContactState $reportModelTestItem7 = new ReportModelTestItem7; $reportModelTestItem7->name = 'someName'; $reportModelTestItem->likeContactState = $reportModelTestItem7; $displayAttribute18 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute18->setModelAliasUsingTableAliasName('model1'); $displayAttribute18->attributeIndexOrDerivedType = 'likeContactState'; //for dynamic user attribute $reportModelTestItem->owner = Yii::app()->user->userModel; $displayAttribute19 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute19->setModelAliasUsingTableAliasName('model1'); $displayAttribute19->attributeIndexOrDerivedType = 'owner__User'; $saved = $reportModelTestItem->save(); $this->assertTrue($saved); $tempId = 1; $reportResultsRowData = new ReportResultsRowData(array( $displayAttribute1, $displayAttribute2, $displayAttribute3, $displayAttribute4, $displayAttribute5, $displayAttribute6, $displayAttribute7, $displayAttribute8, $displayAttribute9, $displayAttribute10, $displayAttribute11, $displayAttribute12, $displayAttribute13, $displayAttribute14, $displayAttribute15, $displayAttribute16, $displayAttribute17, $displayAttribute18, $displayAttribute19), $tempId); $reportResultsRowData->addModelAndAlias($reportModelTestItem, 'model1'); $adapter = new ReportToExportAdapter($reportResultsRowData, $report); $compareHeaderData = array( 'Name', 'Boolean', 'Date', 'Date Time', 'Float', 'Integer', 'Phone', 'String', 'Text Area', 'Url', 'Drop Down', 'Currency Value', 'Currency Value Currency', 'Primary Address >> Street 1', 'Primary Email >> Email Address', 'Multi Drop Down', 'Tag Cloud', 'Radio Drop Down', 'A name for a state', 'Owner'); $compareRowData = array( 'xFirst xLast', 1, '2013-02-12', '2013-02-12 10:15:00', 10.5, 10, '7842151012', 'xString', 'xtextAreatest', 'http://www.test.com', 'Test2', '$100.00', 'USD', 'someString', 'test@someString.com', 'Multi 1,Multi 2', 'Cloud 2,Cloud 3', 'Test2', 'someName', 'super'); $this->assertEquals($compareHeaderData, $adapter->getHeaderData()); $this->assertEquals($compareRowData, $adapter->getData()); } /** * @depends testGetDataWithNoRelationsSet */ public function testExportRelationAttributes() { $values = array( 'Test1', 'Test2', 'Test3', 'Sample', 'Demo', ); $customFieldData = CustomFieldData::getByName('ReportTestDropDown'); $customFieldData->serializedData = serialize($values); $saved = $customFieldData->save(); assert('$saved'); // Not Coding Standard $report = new Report(); //for fullname attribute $reportModelTestItem = new ReportModelTestItem(); $reportModelTestItem->firstName = 'xFirst'; $reportModelTestItem->lastName = 'xLast'; $displayAttribute1 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute1->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute1->attributeIndexOrDerivedType = 'hasMany2___FullName'; //for boolean attribute $reportModelTestItem->boolean = true; $displayAttribute2 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute2->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute2->attributeIndexOrDerivedType = 'hasMany2___boolean'; //for date attribute $reportModelTestItem->date = '2013-02-12'; $displayAttribute3 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute3->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute3->attributeIndexOrDerivedType = 'hasMany2___date'; //for datetime attribute $reportModelTestItem->dateTime = '2013-02-12 10:15:00'; $displayAttribute4 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute4->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute4->attributeIndexOrDerivedType = 'hasMany2___dateTime'; //for float attribute $reportModelTestItem->float = 10.5; $displayAttribute5 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute5->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute5->attributeIndexOrDerivedType = 'hasMany2___float'; //for integer attribute $reportModelTestItem->integer = 10; $displayAttribute6 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute6->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute6->attributeIndexOrDerivedType = 'hasMany2___integer'; //for phone attribute $reportModelTestItem->phone = '7842151012'; $displayAttribute7 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute7->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute7->attributeIndexOrDerivedType = 'hasMany2___phone'; //for string attribute $reportModelTestItem->string = 'xString'; $displayAttribute8 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute8->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute8->attributeIndexOrDerivedType = 'hasMany2___string'; //for textArea attribute $reportModelTestItem->textArea = 'xtextAreatest'; $displayAttribute9 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute9->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute9->attributeIndexOrDerivedType = 'hasMany2___textArea'; //for url attribute $reportModelTestItem->url = 'http://www.test.com'; $displayAttribute10 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute10->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute10->attributeIndexOrDerivedType = 'hasMany2___url'; //for dropdown attribute $reportModelTestItem->dropDown->value = $values[1]; $displayAttribute11 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute11->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute11->attributeIndexOrDerivedType = 'hasMany2___dropDown'; //for currency attribute $currencies = Currency::getAll(); $currencyValue = new CurrencyValue(); $currencyValue->value = 100; $currencyValue->currency = $currencies[0]; $this->assertEquals('USD', $currencyValue->currency->code); $reportModelTestItem->currencyValue = $currencyValue; $displayAttribute12 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute12->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute12->attributeIndexOrDerivedType = 'hasMany2___currencyValue'; //for primaryAddress attribute $reportModelTestItem->primaryAddress->street1 = 'someString'; $displayAttribute13 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute13->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute13->attributeIndexOrDerivedType = 'hasMany2___primaryAddress___street1'; //for primaryEmail attribute $reportModelTestItem->primaryEmail->emailAddress = "test@someString.com"; $displayAttribute14 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute14->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute14->attributeIndexOrDerivedType = 'hasMany2___primaryEmail___emailAddress'; //for multiDropDown attribute $customFieldValue = new CustomFieldValue(); $customFieldValue->value = 'Multi 1'; $reportModelTestItem->multiDropDown->values->add($customFieldValue); $customFieldValue = new CustomFieldValue(); $customFieldValue->value = 'Multi 2'; $reportModelTestItem->multiDropDown->values->add($customFieldValue); $displayAttribute15 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute15->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute15->attributeIndexOrDerivedType = 'hasMany2___multiDropDown'; //for tagCloud attribute $customFieldValue = new CustomFieldValue(); $customFieldValue->value = 'Cloud 2'; $reportModelTestItem->tagCloud->values->add($customFieldValue); $customFieldValue = new CustomFieldValue(); $customFieldValue->value = 'Cloud 3'; $reportModelTestItem->tagCloud->values->add($customFieldValue); $displayAttribute16 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute16->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute16->attributeIndexOrDerivedType = 'hasMany2___tagCloud'; //for radioDropDown attribute $reportModelTestItem->radioDropDown->value = $values[1]; $displayAttribute17 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute17->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute17->attributeIndexOrDerivedType = 'hasMany2___radioDropDown'; //for likeContactState $reportModelTestItem7 = new ReportModelTestItem7; $reportModelTestItem7->name = 'someName'; $reportModelTestItem->likeContactState = $reportModelTestItem7; $displayAttribute18 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute18->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute18->attributeIndexOrDerivedType = 'hasMany2___likeContactState'; //for dynamic user attribute $reportModelTestItem->owner = Yii::app()->user->userModel; $displayAttribute19 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem2', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute19->setModelAliasUsingTableAliasName('relatedModel'); $displayAttribute19->attributeIndexOrDerivedType = 'hasMany2___owner__User'; $saved = $reportModelTestItem->save(); $this->assertTrue($saved); $tempId = 1; $reportResultsRowData = new ReportResultsRowData(array( $displayAttribute1, $displayAttribute2, $displayAttribute3, $displayAttribute4, $displayAttribute5, $displayAttribute6, $displayAttribute7, $displayAttribute8, $displayAttribute9, $displayAttribute10, $displayAttribute11, $displayAttribute12, $displayAttribute13, $displayAttribute14, $displayAttribute15, $displayAttribute16, $displayAttribute17, $displayAttribute18, $displayAttribute19), $tempId); $reportResultsRowData->addModelAndAlias($reportModelTestItem, 'relatedModel'); $adapter = new ReportToExportAdapter($reportResultsRowData, $report); $compareHeaderData = array('Name', 'Reports Tests Module >> Boolean', 'Reports Tests Module >> Date', 'Reports Tests Module >> Date Time', 'Reports Tests Module >> Float', 'Reports Tests Module >> Integer', 'Reports Tests Module >> Phone', 'Reports Tests Module >> String', 'Reports Tests Module >> Text Area', 'Reports Tests Module >> Url', 'Reports Tests Module >> Drop Down', 'Reports Tests Module >> Currency Value', 'Reports Tests Module >> Currency Value Currency', 'Reports Tests Module >> Primary Address >> Street 1', 'Reports Tests Module >> Primary Email >> Email Address', 'Reports Tests Module >> Multi Drop Down', 'Reports Tests Module >> Tag Cloud', 'Reports Tests Module >> Radio Drop Down', 'Reports Tests Module >> A name for a state', 'Reports Tests Module >> Owner'); $compareRowData = array('xFirst xLast', 1, '2013-02-12', '2013-02-12 10:15:00', 10.5, 10, '7842151012', 'xString', 'xtextAreatest', 'http://www.test.com', 'Test2', '$100.00', 'USD', 'someString', 'test@someString.com', 'Multi 1,Multi 2', 'Cloud 2,Cloud 3', 'Test2', 'someName', 'super'); $this->assertEquals($compareHeaderData, $adapter->getHeaderData()); $this->assertEquals($compareRowData, $adapter->getData()); //for MANY-MANY Relationship //for name attribute $reportModelTestItem = new ReportModelTestItem3(); $reportModelTestItem->name = 'xFirst'; $displayAttribute1 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute1->setModelAliasUsingTableAliasName('relatedModel1'); $displayAttribute1->attributeIndexOrDerivedType = 'hasOne___hasMany3___name'; //for somethingOn3 attribute $reportModelTestItem->somethingOn3 = 'somethingOn3'; $displayAttribute2 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute2->setModelAliasUsingTableAliasName('relatedModel1'); $displayAttribute2->attributeIndexOrDerivedType = 'hasOne___hasMany3___somethingOn3'; $reportResultsRowData = new ReportResultsRowData(array( $displayAttribute1, $displayAttribute2), 4); $reportResultsRowData->addModelAndAlias($reportModelTestItem, 'relatedModel1'); $adapter = new ReportToExportAdapter($reportResultsRowData, $report); $compareHeaderData = array('ReportModelTestItem2 >> ReportModelTestItem3s >> Name', 'ReportModelTestItem2 >> ReportModelTestItem3s >> Something On 3'); $compareRowData = array('xFirst', 'somethingOn3'); $this->assertEquals($compareHeaderData, $adapter->getHeaderData()); $this->assertEquals($compareRowData, $adapter->getData()); } /** * @depends testExportRelationAttributes */ public function testExportSummationAttributes() { $report = new Report(); //for date summation $displayAttribute1 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute1->attributeIndexOrDerivedType = 'date__Maximum'; $displayAttribute1->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute1->columnAliasName == 'col0'); $displayAttribute2 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute2->attributeIndexOrDerivedType = 'date__Minimum'; $displayAttribute2->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute2->columnAliasName == 'col1'); //for dateTime summation $displayAttribute3 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute3->attributeIndexOrDerivedType = 'dateTime__Minimum'; $displayAttribute3->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute3->columnAliasName == 'col2'); $displayAttribute4 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute4->attributeIndexOrDerivedType = 'dateTime__Minimum'; $displayAttribute4->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute4->columnAliasName == 'col3'); //for createdDateTime summation $displayAttribute5 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute5->attributeIndexOrDerivedType = 'createdDateTime__Maximum'; $displayAttribute5->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute5->columnAliasName == 'col4'); $displayAttribute6 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute6->attributeIndexOrDerivedType = 'createdDateTime__Minimum'; $displayAttribute6->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute6->columnAliasName == 'col5'); //for modifiedDateTime summation $displayAttribute7 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute7->attributeIndexOrDerivedType = 'modifiedDateTime__Maximum'; $displayAttribute7->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute7->columnAliasName == 'col6'); $displayAttribute8 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute8->attributeIndexOrDerivedType = 'modifiedDateTime__Minimum'; $displayAttribute8->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute8->columnAliasName == 'col7'); //for float summation $displayAttribute9 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute9->attributeIndexOrDerivedType = 'float__Minimum'; $displayAttribute9->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute9->columnAliasName == 'col8'); $displayAttribute10 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute10->attributeIndexOrDerivedType = 'float__Maximum'; $displayAttribute10->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute10->columnAliasName == 'col9'); $displayAttribute11 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute11->attributeIndexOrDerivedType = 'float__Summation'; $displayAttribute11->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute11->columnAliasName == 'col10'); $displayAttribute12 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute12->attributeIndexOrDerivedType = 'float__Average'; $displayAttribute12->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute12->columnAliasName == 'col11'); //for integer summation $displayAttribute13 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute13->attributeIndexOrDerivedType = 'integer__Minimum'; $displayAttribute13->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute13->columnAliasName == 'col12'); $displayAttribute14 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute14->attributeIndexOrDerivedType = 'integer__Maximum'; $displayAttribute14->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute14->columnAliasName == 'col13'); $displayAttribute15 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute15->attributeIndexOrDerivedType = 'integer__Summation'; $displayAttribute15->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute15->columnAliasName == 'col14'); $displayAttribute16 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute16->attributeIndexOrDerivedType = 'integer__Average'; $displayAttribute16->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute16->columnAliasName == 'col15'); //for currency summation $displayAttribute17 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute17->attributeIndexOrDerivedType = 'currencyValue__Minimum'; $displayAttribute17->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute17->columnAliasName == 'col16'); $displayAttribute18 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute18->attributeIndexOrDerivedType = 'currencyValue__Maximum'; $displayAttribute18->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute18->columnAliasName == 'col17'); $displayAttribute19 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute19->attributeIndexOrDerivedType = 'currencyValue__Summation'; $displayAttribute19->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute19->columnAliasName == 'col18'); $displayAttribute20 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute20->attributeIndexOrDerivedType = 'currencyValue__Average'; $displayAttribute20->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute20->columnAliasName == 'col19'); $tempId = 1; $reportResultsRowData = new ReportResultsRowData(array( $displayAttribute1, $displayAttribute2, $displayAttribute3, $displayAttribute4, $displayAttribute5, $displayAttribute6, $displayAttribute7, $displayAttribute8, $displayAttribute9, $displayAttribute10, $displayAttribute11, $displayAttribute12, $displayAttribute13, $displayAttribute14, $displayAttribute15, $displayAttribute16, $displayAttribute17, $displayAttribute18, $displayAttribute19, $displayAttribute20), $tempId); $reportResultsRowData->addSelectedColumnNameAndValue('col0', '2013-02-14'); $reportResultsRowData->addSelectedColumnNameAndValue('col1', '2013-02-12'); $reportResultsRowData->addSelectedColumnNameAndValue('col2', '2013-02-14 00:00:00'); $reportResultsRowData->addSelectedColumnNameAndValue('col3', '2013-02-12 00:59:00'); $reportResultsRowData->addSelectedColumnNameAndValue('col4', '2013-02-14 00:00:00'); $reportResultsRowData->addSelectedColumnNameAndValue('col5', '2013-02-12 00:59:00'); $reportResultsRowData->addSelectedColumnNameAndValue('col6', '2013-02-14 00:00:00'); $reportResultsRowData->addSelectedColumnNameAndValue('col7', '2013-02-12 00:59:00'); $reportResultsRowData->addSelectedColumnNameAndValue('col8', 18.45); $reportResultsRowData->addSelectedColumnNameAndValue('col9', 19.41); $reportResultsRowData->addSelectedColumnNameAndValue('col10', 192.15); $reportResultsRowData->addSelectedColumnNameAndValue('col11', 180.21); $reportResultsRowData->addSelectedColumnNameAndValue('col12', 2000); $reportResultsRowData->addSelectedColumnNameAndValue('col13', 5000); $reportResultsRowData->addSelectedColumnNameAndValue('col14', 1000); $reportResultsRowData->addSelectedColumnNameAndValue('col15', 9000); $reportResultsRowData->addSelectedColumnNameAndValue('col16', 5000); $reportResultsRowData->addSelectedColumnNameAndValue('col17', 6000); $reportResultsRowData->addSelectedColumnNameAndValue('col18', 7000); $reportResultsRowData->addSelectedColumnNameAndValue('col19', 8000); $adapter = new ReportToExportAdapter($reportResultsRowData, $report); $compareHeaderData = array('Date -(Max)', 'Date -(Min)', 'Date Time -(Min)', 'Date Time -(Min)', 'Created Date Time -(Max)', 'Created Date Time -(Min)', 'Modified Date Time -(Max)', 'Modified Date Time -(Min)', 'Float -(Min)', 'Float -(Max)', 'Float -(Sum)', 'Float -(Avg)', 'Integer -(Min)', 'Integer -(Max)', 'Integer -(Sum)', 'Integer -(Avg)', 'Currency Value -(Min)', 'Currency Value -(Min) Currency', 'Currency Value -(Max)', 'Currency Value -(Max) Currency', 'Currency Value -(Sum)', 'Currency Value -(Sum) Currency', 'Currency Value -(Avg)', 'Currency Value -(Avg) Currency'); $compareRowData = array('2013-02-14', '2013-02-12', '2013-02-14 00:00:00', '2013-02-12 00:59:00', '2013-02-14 00:00:00', '2013-02-12 00:59:00', '2013-02-14 00:00:00', '2013-02-12 00:59:00', 18.45, 19.41, 192.15, 180.21, 2000, 5000, 1000, 9000, '5,000', 'Mixed Currency', '6,000', 'Mixed Currency', '7,000', 'Mixed Currency','8,000', 'Mixed Currency'); $this->assertEquals($compareHeaderData, $adapter->getHeaderData()); $this->assertEquals($compareRowData, $adapter->getData()); } /** * Test for viaSelect and viaModel together * @depends testExportSummationAttributes */ public function testViaSelectAndViaModelTogether() { $reportModelTestItem = new ReportModelTestItem(); $report = new Report(); //viaSelect attribute $displayAttribute1 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_SUMMATION); $displayAttribute1->attributeIndexOrDerivedType = 'integer__Minimum'; $displayAttribute1->madeViaSelectInsteadOfViaModel = true; $this->assertTrue($displayAttribute1->columnAliasName == 'col0'); //viaModel attribute $reportModelTestItem->boolean = true; $displayAttribute2 = new DisplayAttributeForReportForm('ReportsTestModule', 'ReportModelTestItem', Report::TYPE_ROWS_AND_COLUMNS); $displayAttribute2->setModelAliasUsingTableAliasName('model1'); $displayAttribute2->attributeIndexOrDerivedType = 'boolean'; $reportResultsRowData = new ReportResultsRowData(array( $displayAttribute1, $displayAttribute2), 4); $reportResultsRowData->addSelectedColumnNameAndValue('col0', 9000); $reportResultsRowData->addModelAndAlias($reportModelTestItem, 'model1'); $adapter = new ReportToExportAdapter($reportResultsRowData, $report); $compareHeaderData = array('Integer -(Min)', 'Boolean'); $compareRowData = array(9000, true); $this->assertEquals($compareHeaderData, $adapter->getHeaderData()); $this->assertEquals($compareRowData, $adapter->getData()); } } ?>
gpl-3.0
UnknownStudio/ChinaCraft
src/main/java/unstudio/chinacraft/item/combat/ModelArmor.java
3903
package unstudio.chinacraft.item.combat; import java.util.List; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import unstudio.chinacraft.common.ChinaCraft; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import unstudio.chinacraft.util.ItemLoreHelper; public class ModelArmor extends ItemArmor { @SideOnly(Side.CLIENT) protected IIcon itemIcon; @SideOnly(Side.CLIENT) private ModelBiped armorModel; private String textureName; private int textureType; public ModelArmor(ArmorMaterial armorMaterial, String name, String textureName, int textureType, int type, int render_idx) { super(armorMaterial, render_idx, type); setUnlocalizedName(name); this.textureName = textureName; this.textureType = textureType; setMaxStackSize(1); setCreativeTab(ChinaCraft.tabTool); } @Override @SideOnly(Side.CLIENT) public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemstack, int armorSlot) { if (armorModel != null) { armorModel.bipedHead.showModel = armorSlot == 0; armorModel.bipedHeadwear.showModel = false; armorModel.bipedBody.showModel = armorSlot == 1 || armorSlot == 2; armorModel.bipedRightArm.showModel = armorSlot == 1; armorModel.bipedLeftArm.showModel = armorSlot == 1; armorModel.bipedRightLeg.showModel = armorSlot == 2 || armorSlot == 3; armorModel.bipedLeftLeg.showModel = armorSlot == 2 || armorSlot == 3; armorModel.isSneak = entityLiving.isSneaking(); armorModel.isRiding = entityLiving.isRiding(); armorModel.isChild = entityLiving.isChild(); armorModel.heldItemRight = 0; armorModel.aimedBow = false; EntityPlayer player = (EntityPlayer) entityLiving; ItemStack held_item = player.getEquipmentInSlot(0); if (held_item != null) { armorModel.heldItemRight = 1; if (player.getItemInUseCount() > 0) { EnumAction enumaction = held_item.getItemUseAction(); if (enumaction == EnumAction.bow) { armorModel.aimedBow = true; } else if (enumaction == EnumAction.block) { armorModel.heldItemRight = 3; } } } } return armorModel; } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconRegister) { this.itemIcon = iconRegister.registerIcon("chinacraft:" + getUnlocalizedName().substring(5)); } @SideOnly(Side.CLIENT) @Override public IIcon getIcon(ItemStack stack, int pass) { return this.itemIcon; } @Override @SideOnly(Side.CLIENT) public String getArmorTexture(ItemStack stack, Entity entity, int slot, String layer) { if (textureType == 0) { return String.format("chinacraft:textures/models/armor/%s.png", textureName); } return String.format("chinacraft:textures/models/armor/%s_layer_%d.png", textureName, slot == 2 ? 2 : 1); } @SideOnly(Side.CLIENT) public void setArmorModel(ModelBiped armorModel) { this.armorModel = armorModel; } @Override public void addInformation(ItemStack p_77624_1_, EntityPlayer p_77624_2_, List p_77624_3_, boolean p_77624_4_) { ItemLoreHelper.shiftLoreWithStat(p_77624_3_, "item." + textureName); } }
gpl-3.0
M66B/BackPackTrackII
app/src/main/java/eu/faircode/backpacktrack2/GPXFileWriter.java
8502
package eu.faircode.backpacktrack2; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import android.content.Context; import android.database.Cursor; import org.jdom2.Attribute; import org.jdom2.Namespace; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class GPXFileWriter { private static final String NS = "http://www.topografix.com/GPX/1/1"; private static final String XSI = "http://www.w3.org/2001/XMLSchema-instance"; private static final String BPT = "http://www.faircode.eu/backpacktrack2"; private static final String XSD = "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"; private static final String CREATOR = "BackPackTrackII"; private static final DecimalFormat DF = new DecimalFormat("0.##", new DecimalFormatSymbols(Locale.ROOT)); private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault()); public static void writeGeonames(List<Geonames.Geoname> names, File target, Context context) throws IOException { Document doc = new Document(); Element gpx = new Element("gpx", NS); Namespace xsi = Namespace.getNamespace("xsi", XSI); gpx.addNamespaceDeclaration(xsi); Namespace bpt2 = Namespace.getNamespace("bpt2", BPT); gpx.addNamespaceDeclaration(bpt2); gpx.setAttribute("schemaLocation", XSD, xsi); gpx.setAttribute(new Attribute("version", "1.1")); gpx.setAttribute(new Attribute("creator", CREATOR)); Collection<Element> wpts = new ArrayList<>(); for (Geonames.Geoname name : names) { Element wpt = new Element("wpt", NS); wpt.setAttribute(new Attribute("lat", Double.toString(name.location.getLatitude()))); wpt.setAttribute(new Attribute("lon", Double.toString(name.location.getLongitude()))); wpt.addContent(new Element("name", NS).addContent(name.name)); wpts.add(wpt); } gpx.addContent(wpts); doc.setRootElement(gpx); FileWriter fw = null; try { fw = new FileWriter(target); XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); xout.output(doc, fw); fw.flush(); } finally { if (fw != null) fw.close(); } } public static void writeWikiPages(List<Wikimedia.Page> pages, File target, Context context) throws IOException { Document doc = new Document(); Element gpx = new Element("gpx", NS); Namespace xsi = Namespace.getNamespace("xsi", XSI); gpx.addNamespaceDeclaration(xsi); Namespace bpt2 = Namespace.getNamespace("bpt2", BPT); gpx.addNamespaceDeclaration(bpt2); gpx.setAttribute("schemaLocation", XSD, xsi); gpx.setAttribute(new Attribute("version", "1.1")); gpx.setAttribute(new Attribute("creator", CREATOR)); Collection<Element> wpts = new ArrayList<>(); for (Wikimedia.Page page : pages) { Element wpt = new Element("wpt", NS); wpt.setAttribute(new Attribute("lat", Double.toString(page.location.getLatitude()))); wpt.setAttribute(new Attribute("lon", Double.toString(page.location.getLongitude()))); wpt.addContent(new Element("name", NS).addContent(page.title)); Element link = new Element("link", NS); link.setAttribute(new Attribute("href", page.getPageUrl())); wpt.addContent(link); wpts.add(wpt); } gpx.addContent(wpts); doc.setRootElement(gpx); FileWriter fw = null; try { fw = new FileWriter(target); XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); xout.output(doc, fw); fw.flush(); } finally { if (fw != null) fw.close(); } } public static void writeGPXFile(File target, String trackName, boolean extensions, Cursor cTrackPoints, Cursor cWayPoints, Context context) throws IOException { Document doc = new Document(); Element gpx = new Element("gpx", NS); Namespace xsi = Namespace.getNamespace("xsi", XSI); gpx.addNamespaceDeclaration(xsi); Namespace bpt2 = Namespace.getNamespace("bpt2", BPT); gpx.addNamespaceDeclaration(bpt2); gpx.setAttribute("schemaLocation", XSD, xsi); gpx.setAttribute(new Attribute("version", "1.1")); gpx.setAttribute(new Attribute("creator", CREATOR)); gpx.addContent(getWayPoints(extensions, cWayPoints, bpt2, context)); gpx.addContent(getTrackpoints(trackName, extensions, cTrackPoints, bpt2, context)); doc.setRootElement(gpx); FileWriter fw = null; try { fw = new FileWriter(target); XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); xout.output(doc, fw); fw.flush(); } finally { if (fw != null) fw.close(); } // http://www.topografix.com/gpx/1/1/gpx.xsd // xmllint --noout --schema gpx.xsd BackPackTrack.gpx } private static Collection<Element> getWayPoints(boolean extensions, Cursor c, Namespace bpt2, Context context) { Collection<Element> wpts = new ArrayList<>(); while (c.moveToNext()) wpts.add(getPoint(c, "wpt", extensions, bpt2, context)); return wpts; } private static Element getTrackpoints(String trackName, boolean extensions, Cursor c, Namespace bpt2, Context context) { Element trk = new Element("trk", NS); trk.addContent(new Element("name", NS).addContent(trackName)); Element trkseg = new Element("trkseg", NS); trk.addContent(trkseg); while (c.moveToNext()) trkseg.addContent(getPoint(c, "trkpt", extensions, bpt2, context)); return trk; } private static Element getPoint(Cursor c, String name, boolean extensions, Namespace bpt2, Context context) { int colLatitude = c.getColumnIndex("latitude"); int colLongitude = c.getColumnIndex("longitude"); int colAltitude = c.getColumnIndex("altitude"); int colTime = c.getColumnIndex("time"); int colName = c.getColumnIndex("name"); int colAccuracy = c.getColumnIndex("accuracy"); Element wpt = new Element(name, NS); wpt.setAttribute(new Attribute("lat", Double.toString(c.getDouble(colLatitude)))); wpt.setAttribute(new Attribute("lon", Double.toString(c.getDouble(colLongitude)))); if (!c.isNull(colAltitude)) wpt.addContent(new Element("ele", NS).addContent(DF.format(c.getDouble(colAltitude)))); wpt.addContent(new Element("time", NS).addContent(SDF.format(new Date(c.getLong(colTime))))); if (!c.isNull(colName)) wpt.addContent(new Element("name", NS).addContent(c.getString(colName))); if (extensions) wpt.addContent(new Element("hdop", NS).addContent(DF.format(c.getDouble(colAccuracy) / 4))); if (extensions) wpt.addContent(getExtensions(c, bpt2, context)); return wpt; } private static Element getExtensions(Cursor c, Namespace bpt2, Context context) { int colProvider = c.getColumnIndex("provider"); int colSpeed = c.getColumnIndex("speed"); int colBearing = c.getColumnIndex("bearing"); int colAccuracy = c.getColumnIndex("accuracy"); Element ext = new Element("extensions", NS); if (!c.isNull(colProvider)) ext.addContent(new Element("provider", bpt2).addContent(c.getString(colProvider))); if (!c.isNull(colSpeed)) ext.addContent(new Element("speed", bpt2).addContent(DF.format(c.getDouble(colSpeed)))); if (!c.isNull(colBearing)) ext.addContent(new Element("bearing", bpt2).addContent(DF.format(c.getDouble(colBearing)))); if (!c.isNull(colAccuracy)) ext.addContent(new Element("accuracy", bpt2).addContent(DF.format(c.getDouble(colAccuracy)))); return ext; } }
gpl-3.0
David-OConnor/plates
plates/about_gui.py
2183
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\Dave\Desktop\Programming\plates\resources\about.ui' # # Created: Tue Oct 22 11:28:19 2013 # by: PyQt5 UI code generator 5.0.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_About(object): def setupUi(self, About): About.setObjectName("About") About.resize(275, 106) self.label = QtWidgets.QLabel(About) self.label.setGeometry(QtCore.QRect(90, 0, 101, 20)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) self.label.setFont(font) self.label.setObjectName("label") self.textBrowser = QtWidgets.QTextBrowser(About) self.textBrowser.setGeometry(QtCore.QRect(20, 20, 241, 71)) self.textBrowser.setObjectName("textBrowser") self.retranslateUi(About) QtCore.QMetaObject.connectSlotsByName(About) def retranslateUi(self, About): _translate = QtCore.QCoreApplication.translate About.setWindowTitle(_translate("About", "About")) self.label.setText(_translate("About", "Plates v0.3")) self.textBrowser.setHtml(_translate("About", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Downloads FAA instrument procedures</span></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Licensed under the GPL</span></p></body></html>"))
gpl-3.0
HiSPARC/pysparc
pysparc/tests/test_hardware.py
11728
import unittest import weakref from mock import patch, Mock, MagicMock, sentinel, call from pysparc import hardware, ftdi_chip, messages class HiSPARCIIITest(unittest.TestCase): def test_description(self): self.assertEqual(hardware.HiSPARCIII.description, "HiSPARC III Master") @patch.object(hardware.BaseHardware, '__init__') @patch.object(hardware.HiSPARCIII, 'reset_hardware') def test_slave_description(self, mock_reset, mock_basehardware): slave = hardware.HiSPARCIII(slave=True) self.assertEqual(slave.description, "HiSPARC III Slave") @patch.object(hardware.HiSPARCIII, '__init__') @patch.object(hardware.HiSPARCIII, '_burn_firmware') @patch('time.sleep') @patch('pysparc.hardware.FtdiChip') def test_open(self, mock_Device, mock_sleep, mock_burn, mock_init): # Using a manager with child mocks allows us to test for the order of # calls (see below). The manager itself is not used. manager = Mock() manager.attach_mock(mock_burn, 'burn') manager.attach_mock(mock_sleep, 'sleep') manager.attach_mock(mock_Device, 'Device') mock_init.return_value = None hisparc = hardware.HiSPARCIII() hisparc.open() expected = [call.burn(), call.sleep(.5), call.Device(hardware.HiSPARCIII.description, interface_select=2)] self.assertEqual(manager.mock_calls, expected) class HiSPARCIITest(unittest.TestCase): @patch.object(hardware.BaseHardware, '__init__') @patch('pysparc.hardware.config.Config') @patch.object(hardware.HiSPARCII, 'reset_hardware') def setUp(self, mock_reset, mock_Config, mock_super): self.mock_super = mock_super self.mock_Config = mock_Config self.mock_config = mock_Config.return_value self.mock_reset = mock_reset self.mock_device = Mock() self.hisparc = hardware.HiSPARCII() self.hisparc._device = self.mock_device self.hisparc._buffer = MagicMock() def test_description(self): self.assertEqual(hardware.HiSPARCII.description, "HiSPARC II Master") @patch.object(hardware.BaseHardware, '__init__') @patch.object(hardware.HiSPARCII, 'reset_hardware') def test_slave_description(self, mock_reset, mock_basehardware): slave = hardware.HiSPARCII(slave=True) self.assertEqual(slave.description, "HiSPARC II Slave") def test_init_calls_super(self): # test that super *was* called during setUp() self.mock_super.assert_called_once_with() def test_init_creates_device_configuration(self): self.mock_Config.assert_called_once_with(self.hisparc) self.assertIs(self.hisparc.config, self.mock_config) def test_init_calls_reset(self): self.mock_reset.assert_called_once_with() @patch.object(hardware.HiSPARCII, 'send_message') @patch('pysparc.hardware.GetControlParameterList') @patch('pysparc.hardware.ResetMessage') @patch('pysparc.hardware.InitializeMessage') def test_reset_hardware(self, mock_Init_msg, mock_Reset_msg, mock_Parameter_msg, mock_send): self.hisparc.config = Mock() self.hisparc.reset_hardware() msg1 = mock_Reset_msg.return_value msg2 = mock_Init_msg.return_value msg3 = mock_Parameter_msg.return_value mock_send.assert_has_calls([call(msg1), call(msg2), call(msg3)]) self.hisparc.config.reset_hardware.assert_called_once_with() @patch.object(hardware.HiSPARCII, 'read_into_buffer') @patch('pysparc.hardware.HisparcMessageFactory') def test_read_message(self, mock_factory, mock_read_into_buffer): self.hisparc.read_message() mock_read_into_buffer.assert_called_once_with() @patch('pysparc.hardware.HisparcMessageFactory') def test_read_message_calls_message_factory(self, mock_factory): self.hisparc.read_message() mock_factory.assert_called_once_with(self.hisparc._buffer) @patch('pysparc.hardware.HisparcMessageFactory') def test_read_message_sets_config_parameters(self, mock_factory): mock_config_message = Mock(spec=messages.ControlParameterList) mock_other_message = Mock() mock_factory.return_value = mock_other_message self.hisparc.read_message() self.assertFalse(self.mock_config.update_from_config_message.called) mock_factory.return_value = mock_config_message self.hisparc.read_message() self.mock_config.update_from_config_message.assert_called_once_with( mock_config_message) @patch('pysparc.hardware.HisparcMessageFactory') def test_read_message_returns_message(self, mock_factory): mock_factory.return_value = sentinel.msg actual = self.hisparc.read_message() self.assertIs(actual, sentinel.msg) @patch('pysparc.hardware.HisparcMessageFactory') def test_read_message_returns_config_message(self, mock_factory): mock_config_message = Mock(spec=messages.ControlParameterList) mock_factory.return_value = mock_config_message actual = self.hisparc.read_message() self.assertIs(actual, mock_config_message) @patch.object(hardware.HiSPARCII, 'flush_device') @patch.object(hardware.HiSPARCII, 'read_message') def test_flush_and_get_measured_data_message_calls_flush(self, mock_read, mock_flush): self.hisparc.flush_and_get_measured_data_message(timeout=.01) mock_flush.assert_called_once_with() @patch.object(hardware.HiSPARCII, 'read_message') def test_flush_and_get_measured_data_message_calls_read_message(self, mock_read): self.hisparc.flush_and_get_measured_data_message(timeout=.01) self.assertTrue(mock_read.called) @patch.object(hardware.HiSPARCII, 'read_message') def test_flush_and_get_measured_data_message_returns_correct_type( self, mock_read): mock_msg = Mock(spec=messages.MeasuredDataMessage) mock_read.side_effect = [Mock(), Mock(), mock_msg, Mock()] msg = self.hisparc.flush_and_get_measured_data_message( timeout=.01) self.assertIs(msg, mock_msg) class BaseHardwareTest(unittest.TestCase): @patch.object(hardware.BaseHardware, 'open') def setUp(self, mock_open): self.mock_open = mock_open self.mock_device = Mock() self.hisparc = hardware.BaseHardware() self.hisparc._device = self.mock_device self.mock_device.closed = False def test_description(self): self.assertEqual(hardware.BaseHardware.description, "BaseHardware") def test_device_is_none_before_instantiation(self): self.assertIs(hardware.BaseHardware._device, None) def test_init_calls_open(self): self.mock_open.assert_called_once_with() @patch('pysparc.hardware.FtdiChip') def test_open_opens_and_saves_device(self, mock_Device): mock_device = Mock() mock_Device.return_value = mock_device self.hisparc.open() mock_Device.assert_called_once_with(self.hisparc.description) self.assertIs(self.hisparc._device, mock_device) @patch.object(hardware.BaseHardware, 'close') def test_destructor_calls_close(self, mock_close): del self.hisparc mock_close.assert_called_once_with() def test_close_closes_device(self): self.hisparc.close() self.mock_device.close.assert_called_once_with() def test_close_does_nothing_if_device_is_closed(self): self.mock_device.closed = True self.hisparc.close() self.assertFalse(self.mock_device.close.called) def test_close_does_nothing_if_device_is_none(self): self.hisparc._device = None self.hisparc.close() self.assertFalse(self.mock_device.close.called) def test_buffer_is_none_before_instantiation(self): self.assertIs(hardware.BaseHardware._buffer, None) def test_buffer_attribute_is_bytearray(self): self.assertIs(type(self.hisparc._buffer), bytearray) def test_flush_device_flushes_device(self): self.hisparc._buffer = MagicMock() self.hisparc.flush_device() self.mock_device.flush.assert_called_once_with() def test_flush_device_clears_buffer(self): self.hisparc._buffer = bytearray([0x1, 0x2, 0x3]) self.hisparc.flush_device() self.assertEqual(len(self.hisparc._buffer), 0) def test_send_message_calls_msg_encode(self): msg = Mock() self.hisparc.send_message(msg) msg.encode.assert_called_once_with() def test_send_message_writes_to_device(self): msg = Mock() msg.encode.return_value = sentinel.encoded_msg self.hisparc.send_message(msg) self.mock_device.write.assert_called_once_with( sentinel.encoded_msg) def test_read_into_buffer_reads_from_device(self): self.hisparc._buffer = MagicMock() self.mock_device.read.return_value = MagicMock() self.hisparc.read_into_buffer() self.mock_device.read.assert_called_once_with(hardware.READ_SIZE) def test_read_into_buffer_reads_into_buffer(self): mock_buffer = Mock() self.hisparc._buffer = mock_buffer read_data = self.mock_device.read.return_value self.hisparc.read_into_buffer() mock_buffer.extend.assert_called_once_with(read_data) @patch.object(hardware.BaseHardware, 'read_into_buffer') def test_read_message(self, mock_read_into_buffer): self.assertRaises(NotImplementedError, self.hisparc.read_message) mock_read_into_buffer.assert_called_once_with() class TrimbleGPSTest(unittest.TestCase): # mock __init__ of the parent class, so we do not depend on that # implementation @patch.object(hardware.TrimbleGPS, '__init__') def setUp(self, mock_init): mock_init.return_value = None self.gps = hardware.TrimbleGPS() self.gps._buffer = sentinel.buffer self.mock_device = Mock() self.gps._device = self.mock_device patcher1 = patch.object(hardware.TrimbleGPS, 'read_into_buffer') patcher2 = patch('pysparc.hardware.GPSMessageFactory') self.mock_read_into_buffer = patcher1.start() self.mock_factory = patcher2.start() self.addCleanup(patcher1.stop) self.addCleanup(patcher2.stop) def test_type_is_basehardware(self): self.assertIsInstance(self.gps, hardware.BaseHardware) @patch.object(hardware.BaseHardware, 'open') def test_open_calls_super(self, mock_super): self.gps.open() mock_super.assert_called_once_with() @patch.object(hardware.BaseHardware, 'open') def test_open_sets_line_settings(self, mock_super): self.gps.open() self.gps._device.set_line_settings.assert_called_once_with( ftdi_chip.BITS_8, ftdi_chip.PARITY_ODD, ftdi_chip.STOP_BIT_1) def test_description(self): self.assertEqual(hardware.TrimbleGPS.description, "FT232R USB UART") def test_read_message(self): self.gps.read_message() self.mock_read_into_buffer.assert_called_once_with() def test_read_message_calls_message_factory(self): self.gps.read_message() self.mock_factory.assert_called_once_with(sentinel.buffer) def test_read_message_returns_message(self): self.mock_factory.return_value = sentinel.msg actual = self.gps.read_message() self.assertIs(actual, sentinel.msg) if __name__ == '__main__': unittest.main()
gpl-3.0
vmindru/ansible
lib/ansible/modules/database/aerospike/aerospike_migrations.py
18758
#!/usr/bin/python """short_description: Check or wait for migrations between nodes""" # Copyright: (c) 2018, Albert Autin # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: aerospike_migrations short_description: Check or wait for migrations between nodes description: - This can be used to check for migrations in a cluster. This makes it easy to do a rolling upgrade/update on Aerospike nodes. - If waiting for migrations is not desired, simply just poll until port 3000 if available or asinfo -v status returns ok version_added: 2.8 author: "Albert Autin (@Alb0t)" options: host: description: - Which host do we use as seed for info connection required: False type: str default: localhost port: description: - Which port to connect to Aerospike on (service port) required: False type: int default: 3000 connect_timeout: description: - How long to try to connect before giving up (milliseconds) required: False type: int default: 1000 consecutive_good_checks: description: - How many times should the cluster report "no migrations" consecutively before returning OK back to ansible? required: False type: int default: 3 sleep_between_checks: description: - How long to sleep between each check (seconds). required: False type: int default: 60 tries_limit: description: - How many times do we poll before giving up and failing? default: 300 required: False type: int local_only: description: - Do you wish to only check for migrations on the local node before returning, or do you want all nodes in the cluster to finish before returning? required: True type: bool min_cluster_size: description: - Check will return bad until cluster size is met or until tries is exhausted required: False type: int default: 1 fail_on_cluster_change: description: - Fail if the cluster key changes if something else is changing the cluster, we may want to fail required: False type: bool default: True migrate_tx_key: description: - The metric key used to determine if we have tx migrations remaining. Changeable due to backwards compatibility. required: False type: str default: migrate_tx_partitions_remaining migrate_rx_key: description: - The metric key used to determine if we have rx migrations remaining. Changeable due to backwards compatibility. required: False type: str default: migrate_rx_partitions_remaining target_cluster_size: description: - When all aerospike builds in the cluster are greater than version 4.3, then the C(cluster-stable) info command will be used. Inside this command, you can optionally specify what the target cluster size is - but it is not necessary. You can still rely on min_cluster_size if you don't want to use this option. - If this option is specified on a cluster that has at least 1 host <4.3 then it will be ignored until the min version reaches 4.3. required: False type: int ''' EXAMPLES = ''' # check for migrations on local node - name: wait for migrations on local node before proceeding aerospike_migrations: host: "localhost" connect_timeout: 2000 consecutive_good_checks: 5 sleep_between_checks: 15 tries_limit: 600 local_only: False # example playbook: --- - name: upgrade aerospike hosts: all become: true serial: 1 tasks: - name: Install dependencies apt: name: - python - python-pip - python-setuptools state: latest - name: setup aerospike pip: name: aerospike # check for migrations every (sleep_between_checks) # If at least (consecutive_good_checks) checks come back OK in a row, then return OK. # Will exit if any exception, which can be caused by bad nodes, # nodes not returning data, or other reasons. # Maximum runtime before giving up in this case will be: # Tries Limit * Sleep Between Checks * delay * retries - name: wait for aerospike migrations aerospike_migrations: local_only: True sleep_between_checks: 1 tries_limit: 5 consecutive_good_checks: 3 fail_on_cluster_change: true min_cluster_size: 3 target_cluster_size: 4 register: migrations_check until: migrations_check is succeeded changed_when: false delay: 60 retries: 120 - name: another thing shell: | echo foo - name: reboot reboot: ''' RETURN = ''' # Returns only a success/failure result. Changed is always false. ''' import traceback from ansible.module_utils.basic import AnsibleModule, missing_required_lib LIB_FOUND_ERR = None try: import aerospike from time import sleep import re except ImportError as ie: LIB_FOUND = False LIB_FOUND_ERR = traceback.format_exc() else: LIB_FOUND = True def run_module(): """run ansible module""" module_args = dict( host=dict(type='str', required=False, default='localhost'), port=dict(type='int', required=False, default=3000), connect_timeout=dict(type='int', required=False, default=1000), consecutive_good_checks=dict(type='int', required=False, default=3), sleep_between_checks=dict(type='int', required=False, default=60), tries_limit=dict(type='int', requires=False, default=300), local_only=dict(type='bool', required=True), min_cluster_size=dict(type='int', required=False, default=1), target_cluster_size=dict(type='int', required=False, default=None), fail_on_cluster_change=dict(type='bool', required=False, default=True), migrate_tx_key=dict(type='str', required=False, default="migrate_tx_partitions_remaining"), migrate_rx_key=dict(type='str', required=False, default="migrate_rx_partitions_remaining") ) result = dict( changed=False, ) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) if not LIB_FOUND: module.fail_json(msg=missing_required_lib('aerospike'), exception=LIB_FOUND_ERR) try: if module.check_mode: has_migrations, skip_reason = False, None else: migrations = Migrations(module) has_migrations, skip_reason = migrations.has_migs( module.params['local_only'] ) if has_migrations: module.fail_json(msg="Failed.", skip_reason=skip_reason) except Exception as e: module.fail_json(msg="Error: {0}".format(e)) module.exit_json(**result) class Migrations: """ Check or wait for migrations between nodes """ def __init__(self, module): self.module = module self._client = self._create_client().connect() self._nodes = {} self._update_nodes_list() self._cluster_statistics = {} self._update_cluster_statistics() self._namespaces = set() self._update_cluster_namespace_list() self._build_list = set() self._update_build_list() self._start_cluster_key = \ self._cluster_statistics[self._nodes[0]]['cluster_key'] def _create_client(self): """ TODO: add support for auth, tls, and other special features I won't use those features, so I'll wait until somebody complains or does it for me (Cross fingers) create the client object""" config = { 'hosts': [ (self.module.params['host'], self.module.params['port']) ], 'policies': { 'timeout': self.module.params['connect_timeout'] } } return aerospike.client(config) def _info_cmd_helper(self, cmd, node=None, delimiter=';'): """delimiter is for seperate stats that come back, NOT for kv separation which is =""" if node is None: # If no node passed, use the first one (local) node = self._nodes[0] data = self._client.info_node(cmd, node) data = data.split("\t") if len(data) != 1 and len(data) != 2: self.module.fail_json( msg="Unexpected number of values returned in info command: " + str(len(data)) ) # data will be in format 'command\touput' data = data[-1] data = data.rstrip("\n\r") data_arr = data.split(delimiter) # some commands don't return in kv format # so we dont want a dict from those. if '=' in data: retval = dict( metric.split("=", 1) for metric in data_arr ) else: # if only 1 element found, and not kv, return just the value. if len(data_arr) == 1: retval = data_arr[0] else: retval = data_arr return retval def _update_build_list(self): """creates self._build_list which is a unique list of build versions.""" self._build_list = set() for node in self._nodes: build = self._info_cmd_helper('build', node) self._build_list.add(build) # just checks to see if the version is 4.3 or greater def _can_use_cluster_stable(self): # if version <4.3 we can't use cluster-stable info cmd # regex hack to check for versions beginning with 0-3 or # beginning with 4.0,4.1,4.2 if re.search(R'^([0-3]\.|4\.[0-2])', min(self._build_list)): return False return True def _update_cluster_namespace_list(self): """ make a unique list of namespaces TODO: does this work on a rolling namespace add/deletion? thankfully if it doesnt, we dont need this on builds >=4.3""" self._namespaces = set() for node in self._nodes: namespaces = self._info_cmd_helper('namespaces', node) for namespace in namespaces: self._namespaces.add(namespace) def _update_cluster_statistics(self): """create a dict of nodes with their related stats """ self._cluster_statistics = {} for node in self._nodes: self._cluster_statistics[node] = \ self._info_cmd_helper('statistics', node) def _update_nodes_list(self): """get a fresh list of all the nodes""" self._nodes = self._client.get_nodes() if not self._nodes: self.module.fail_json("Failed to retrieve at least 1 node.") def _namespace_has_migs(self, namespace, node=None): """returns a True or False. Does the namespace have migrations for the node passed? If no node passed, uses the local node or the first one in the list""" namespace_stats = self._info_cmd_helper("namespace/" + namespace, node) try: namespace_tx = \ int(namespace_stats[self.module.params['migrate_tx_key']]) namespace_rx = \ int(namespace_stats[self.module.params['migrate_tx_key']]) except KeyError: self.module.fail_json( msg="Did not find partition remaining key:" + self.module.params['migrate_tx_key'] + " or key:" + self.module.params['migrate_rx_key'] + " in 'namespace/" + namespace + "' output." ) except TypeError: self.module.fail_json( msg="namespace stat returned was not numerical" ) return namespace_tx != 0 or namespace_rx != 0 def _node_has_migs(self, node=None): """just calls namespace_has_migs and if any namespace has migs returns true""" migs = 0 self._update_cluster_namespace_list() for namespace in self._namespaces: if self._namespace_has_migs(namespace, node): migs += 1 return migs != 0 def _cluster_key_consistent(self): """create a dictionary to store what each node returns the cluster key as. we should end up with only 1 dict key, with the key being the cluster key.""" cluster_keys = {} for node in self._nodes: cluster_key = self._cluster_statistics[node][ 'cluster_key'] if cluster_key not in cluster_keys: cluster_keys[cluster_key] = 1 else: cluster_keys[cluster_key] += 1 if len(cluster_keys.keys()) is 1 and \ self._start_cluster_key in cluster_keys: return True return False def _cluster_migrates_allowed(self): """ensure all nodes have 'migrate_allowed' in their stats output""" for node in self._nodes: node_stats = self._info_cmd_helper('statistics', node) allowed = node_stats['migrate_allowed'] if allowed == "false": return False return True def _cluster_has_migs(self): """calls node_has_migs for each node""" migs = 0 for node in self._nodes: if self._node_has_migs(node): migs += 1 if migs == 0: return False return True def _has_migs(self, local): if local: return self._local_node_has_migs() return self._cluster_has_migs() def _local_node_has_migs(self): return self._node_has_migs(None) def _is_min_cluster_size(self): """checks that all nodes in the cluster are returning the mininimum cluster size specified in their statistics output""" sizes = set() for node in self._cluster_statistics: sizes.add(int(self._cluster_statistics[node]['cluster_size'])) if (len(sizes)) > 1: # if we are getting more than 1 size, lets say no return False if (min(sizes)) >= self.module.params['min_cluster_size']: return True return False def _cluster_stable(self): """Added 4.3: cluster-stable:size=<target-cluster-size>;ignore-migrations=<yes/no>;namespace=<namespace-name> Returns the current 'cluster_key' when the following are satisfied: If 'size' is specified then the target node's 'cluster-size' must match size. If 'ignore-migrations' is either unspecified or 'false' then the target node's migrations counts must be zero for the provided 'namespace' or all namespaces if 'namespace' is not provided.""" cluster_key = set() cluster_key.add(self._info_cmd_helper('statistics')['cluster_key']) cmd = "cluster-stable:" target_cluster_size = self.module.params['target_cluster_size'] if target_cluster_size is not None: cmd = cmd + "size=" + str(target_cluster_size) + ";" for node in self._nodes: cluster_key.add(self._info_cmd_helper(cmd, node)) if len(cluster_key) == 1: return True return False def _cluster_good_state(self): """checks a few things to make sure we're OK to say the cluster has no migs. It could be in a unhealthy condition that does not allow migs, or a split brain""" if self._cluster_key_consistent() is not True: return False, "Cluster key inconsistent." if self._is_min_cluster_size() is not True: return False, "Cluster min size not reached." if self._cluster_migrates_allowed() is not True: return False, "migrate_allowed is false somewhere." return True, "OK." def has_migs(self, local=True): """returns a boolean, False if no migrations otherwise True""" consecutive_good = 0 try_num = 0 skip_reason = list() while \ try_num < int(self.module.params['tries_limit']) and \ consecutive_good < \ int(self.module.params['consecutive_good_checks']): self._update_nodes_list() self._update_cluster_statistics() # These checks are outside of the while loop because # we probably want to skip & sleep instead of failing entirely stable, reason = self._cluster_good_state() if stable is not True: skip_reason.append( "Skipping on try#" + str(try_num) + " for reason:" + reason ) else: if self._can_use_cluster_stable(): if self._cluster_stable(): consecutive_good += 1 else: consecutive_good = 0 skip_reason.append( "Skipping on try#" + str(try_num) + " for reason:" + " cluster_stable" ) elif self._has_migs(local): # print("_has_migs") skip_reason.append( "Skipping on try#" + str(try_num) + " for reason:" + " migrations" ) consecutive_good = 0 else: consecutive_good += 1 if consecutive_good == self.module.params[ 'consecutive_good_checks']: break try_num += 1 sleep(self.module.params['sleep_between_checks']) # print(skip_reason) if consecutive_good == self.module.params['consecutive_good_checks']: return False, None return True, skip_reason def main(): """main method for ansible module""" run_module() if __name__ == '__main__': main()
gpl-3.0
will4wachter/Project1
scripts/commands/godmode.lua
3028
--------------------------------------------------------------------------------------------------- -- func: godmode -- auth: bluekirby0 :: Modded by atom0s. (Thanks to Mishima for more buff ideas.) -- desc: Toggles god mode on the player; granting them several special abilities. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 5, parameters = "" }; function onTrigger(player) if (player:getVar("GodMode") == 0) then -- Toggle GodMode on.. player:setVar("GodMode", 1); -- Add bonus effects to the player.. player:addStatusEffect(EFFECT_MAX_HP_BOOST,1000,0,0); player:addStatusEffect(EFFECT_MAX_MP_BOOST,1000,0,0); player:addStatusEffect(EFFECT_SENTINEL,100,0,0); player:addStatusEffect(EFFECT_MIGHTY_STRIKES,1,0,0); player:addStatusEffect(EFFECT_HUNDRED_FISTS,1,0,0); player:addStatusEffect(EFFECT_CHAINSPELL,1,0,0); player:addStatusEffect(EFFECT_PERFECT_DODGE,1,0,0); player:addStatusEffect(EFFECT_INVINCIBLE,1,0,0); player:addStatusEffect(EFFECT_MANAFONT,1,0,0); player:addStatusEffect(EFFECT_REGAIN,100,1,0); player:addStatusEffect(EFFECT_REFRESH,99,0,0); player:addStatusEffect(EFFECT_REGEN,99,0,0); -- Add bonus mods to the player.. player:addMod(MOD_RACC,5000); player:addMod(MOD_RATT,5000); player:addMod(MOD_ACC,5000); player:addMod(MOD_ATT,5000); player:addMod(MOD_MATT,5000); player:addMod(MOD_MACC,5000); player:addMod(MOD_RDEF,5000); player:addMod(MOD_DEF,5000); player:addMod(MOD_MDEF,5000); -- Heal the player from the new buffs.. player:addHP( 50000 ); player:setMP( 50000 ); else -- Toggle GodMode off.. player:setVar("GodMode", 0); -- Remove bonus effects.. player:delStatusEffect(EFFECT_MAX_HP_BOOST); player:delStatusEffect(EFFECT_MAX_MP_BOOST); player:delStatusEffect(EFFECT_SENTINEL); player:delStatusEffect(EFFECT_MIGHTY_STRIKES); player:delStatusEffect(EFFECT_HUNDRED_FISTS); player:delStatusEffect(EFFECT_CHAINSPELL); player:delStatusEffect(EFFECT_PERFECT_DODGE); player:delStatusEffect(EFFECT_INVINCIBLE); player:delStatusEffect(EFFECT_MANAFONT); player:delStatusEffect(EFFECT_REGAIN); player:delStatusEffect(EFFECT_REFRESH); player:delStatusEffect(EFFECT_REGEN); -- Remove bonus mods.. player:delMod(MOD_RACC,5000); player:delMod(MOD_RATT,5000); player:delMod(MOD_ACC,5000); player:delMod(MOD_ATT,5000); player:delMod(MOD_MATT,5000); player:delMod(MOD_MACC,5000); player:delMod(MOD_RDEF,5000); player:delMod(MOD_DEF,5000); player:delMod(MOD_MDEF,5000); end end
gpl-3.0
drjod/conePlusPlus
gui/data.cpp
8719
#include "data.h" CData::CData() { modificationCounter = 0; aquifer.storativity = 0.; aquifer.transmissivity = 0.; domain.length[0] = 0.; domain.length[1] = 0.; domain.resolution[0] = 0.; domain.resolution[1] = 0.; timing.end = 0.; timing.numberOfIntervals = 0; outputs.clear(); wells.clear(); pumpseries_vec.clear(); } CData::~CData() {} ////////////////////////////////////////////////////////////////////////////// /// \brief CData::readData /// \param inputFile: path and name /// /// !!!!! restriction on output instances generated by keyword #output: /// there is a convention in the output and view pages of the wizard /// exactly 2 output instances must be generated in this order: /// 1. snaphots: distributionType 0 /// 2. timeseries: distributionType 1 /// timingType must be 0 always (output for all time steps) /// the ConePlusPlus simulator itself supports more output types /// void CData::readData(QString inputFile, bool inputReadFlag) { QFile file(inputFile); if(!file.open(QIODevice::ReadOnly)) QMessageBox::information(0,"error","No file " + inputFile); else { int numberOfNodes; QTextStream in (&file); QString valueString ; QStringList fields; wells.clear(); outputs.clear(); for (;;) { valueString = in.readLine(); fields = valueString.split(" "); if(fields[0] == "#end") break; ////////// if(fields[0] == "#aquifer") { valueString = in.readLine(); fields = valueString.split(" "); aquifer.transmissivity = QString(fields[0]).toDouble(); aquifer.storativity = QString(fields[1]).toDouble(); } ////////// if(fields[0] == "#domain") { valueString = in.readLine(); fields = valueString.split(" "); domain.length[0] = QString(fields[0]).toDouble(); domain.length[1] = QString(fields[1]).toDouble(); domain.resolution[0] = QString(fields[2]).toDouble(); domain.resolution[1] = QString(fields[3]).toDouble(); } ////////// if(fields[0] == "#well") { valueString = in.readLine(); fields = valueString.split(" "); wellData well_inst; well_inst.location[0] = QString(fields[0]).toDouble(); well_inst.location[1] = QString(fields[1]).toDouble(); well_inst.pumpingRate = QString(fields[2]).toDouble(); well_inst.pumpseriesName = fields[3]; wells.push_back(well_inst); } ////////// if(fields[0] == "#timing") { if(fields[1] == "intervals") { valueString = in.readLine(); fields = valueString.split(" "); timing.numberOfIntervals = QString(fields[0]).toInt(); timing.end = QString(fields[1]).toDouble(); } } ////////// mind restriction mentioned above if(fields[0] == "#output") { outputData output_inst; valueString = in.readLine(); fields = valueString.split(" "); output_inst.outfileName = fields[0]; /// distribution type valueString = in.readLine(); // domain or selected fields = valueString.split(" "); if(fields[0] == "domain") { output_inst.outputDistributionType = 0; if (outputs.size() != 0) QMessageBox::information(0, "error", "Distribution type domain is" "for 1st output instance"); } else if(fields[0] == "selected") { output_inst.outputDistributionType = 1; if (outputs.size() != 1) QMessageBox::information(0, "error", "Distribution type selected is" "for 2nd output instance"); valueString = in.readLine(); fields = valueString.split(" "); numberOfNodes = QString(fields[0]).toInt(); for (int i = 0; i < numberOfNodes; i++) { outputNode node_inst; valueString = in.readLine(); fields = valueString.split(" "); node_inst.x = QString(fields[0]).toDouble(); node_inst.y = QString(fields[1]).toDouble(); output_inst.outputNodes.push_back(node_inst); } } else { QMessageBox::information(0, "error", "Output distribution type '" + fields[0] + "' not supported"); } /// timing type valueString = in.readLine(); // only timing type fields = valueString.split(" "); if(fields[0] == "times") { if(fields[1] == "all") { output_inst.outputTimingType = 0; } else { QMessageBox::information(0, "error", "Output timing type '" + fields[1] + "' not supported"); } } outputs.push_back(output_inst); } // end output ////////// if(fields[0] == "#table" && inputReadFlag == false // input has not been read yet - avoid duplication of tables ) { pumpseries pumpseries_inst; entry entry_inst; valueString = in.readLine(); fields = valueString.split(" "); pumpseries_inst.name = fields[0]; valueString = in.readLine(); fields = valueString.split(" "); pumpseries_inst.numberOfEntries = QString(fields[0]).toInt(); for (int i = 0; i < pumpseries_inst.numberOfEntries; i++) { valueString = in.readLine(); fields = valueString.split(" "); entry_inst.time = QString(fields[0]).toDouble(); entry_inst.value = QString(fields[1]).toDouble(); pumpseries_inst.entries.push_back(entry_inst); } pumpseries_vec.push_back(pumpseries_inst); } } // for file.close(); if (outputs.size() != 2) QMessageBox::information(0, "error", "You must provide exactly two output instances"); } // end file open } ////////////////////////////////////////////////////////////////////////////// /// \brief setOutputNodes - fill output[1] with nodes /// \param _outputNodes /// \param ndx: 1 must be taken (see restriction above) /// void CData::setOutputNodes( QVector<outputNode> _outputNodes, int ndx) { outputs[ndx].outputNodes.clear(); for(int i=0; i < (int)_outputNodes.size(); i++) outputs[ndx].outputNodes.push_back(_outputNodes[i]); } ////////////////////////////////////////////////////////////////////////////// /// \brief CData::writeData /// \param outputFile: path and name /// void CData::writeData(QString outputFile) { QFile file( outputFile ); if ( file.open(QIODevice::WriteOnly) ) { QTextStream stream( &file ); stream << endl << "#aquifer" << endl; stream << aquifer.transmissivity << " " << aquifer.storativity << endl; stream << endl << "#domain" << endl; stream << domain.length[0] << " " << domain.length[1] << " "; stream << domain.resolution[0] << " " << domain.resolution[1] << endl; for(int i = 0; i < (int)wells.size(); i++) { stream << endl << "#well" << endl; stream << wells[i].location[0] << " " << wells[i].location[1] << " "; stream << wells[i].pumpingRate << " " << wells[i].pumpseriesName << endl; } stream << endl << "#timing intervals" << endl; stream << timing.numberOfIntervals << " " << timing.end << endl; for(int i = 0; i < (int)outputs.size(); i++) { stream << endl << "#output" << endl; stream << outputs[i].outfileName << endl; if (outputs[i].outputDistributionType == 0) { stream << "domain" << endl; } else { stream << "selected nodes" << endl; stream << outputs[i].outputNodes.size() << endl; for(int j = 0; j < (int)outputs[i].outputNodes.size(); j++) { stream << outputs[i].outputNodes[j].x << " " << outputs[i].outputNodes[j].y << endl; } } stream << "times all" << endl; } // end for for(int i = 0; i < (int)pumpseries_vec.size(); i++) { stream << endl << "#table" << endl; stream << pumpseries_vec[i].name << endl; stream << pumpseries_vec[i].numberOfEntries << endl; for (int j=0 ; j < pumpseries_vec[i].numberOfEntries; j++) { stream << pumpseries_vec[i].entries[j].time << " " << pumpseries_vec[i].entries[j].value << endl; } } // end for stream << endl << "#end" << endl; } // end file open file.close(); }
gpl-3.0
gaojianyang/only
Only/app/src/main/java/com/personal/xiri/only/widgets/ChatView.java
33534
package com.personal.xiri.only.widgets; import android.content.Context; import android.graphics.Canvas; import android.os.Parcelable; import android.support.annotation.Nullable; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.VelocityTrackerCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import com.personal.xiri.only.chat.ChatAdapter; import com.personal.xiri.only.utils.DensityUtils; import java.util.ArrayList; import java.util.List; /** * Created by GJY on 2016/7/15. */ public class ChatView extends RecyclerView implements View.OnLayoutChangeListener { private static final String TAG = "ChatView"; public static final int DATA_NOTHING = 0; public static final int DATA_INSERT = 1; public static final int DATA_LOADING = 2; public static final int DATA_REMOVED = 3; public static final int SEND_CLICK = 4; private int dataChangeType = DATA_NOTHING; private int dataLoadingOrRemoveType = DATA_NOTHING; public static final int REFRESH_DURING = 1; public static final int REFRESH_OVER = 2; private static final int INVALID_POINTER = -1; private boolean loadingData = false; private int mScrollPointerId = INVALID_POINTER; private VelocityTracker mVelocityTracker; private int mLastTouchY; private boolean isFirstMove = true; private int refreshHeight; private int currentStatus = REFRESH_OVER; private int movedY; private int footViewHeight; private OnRefreshListener onRefreshListener; private OnDrawFinishListener onDrawFinishListener; private int height; private int contentHeight = 0; private int needComputeLoadItemHeightMaxNum = 0; private int needComputeInsertItemHeightMaxNum = 0; private boolean init; // private int originalHeight; // private int editTextChangeheight=0; private int loadingPositionsNum; private boolean dataInit=false; private int headOffset; private int bottomOffset; public ChatView(Context context) { this(context, null); } public ChatView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public ChatView(Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setFocusable(true); refreshHeight = DensityUtils.dip2px(context, 60); setItemAnimator(null); setOverScrollMode(OVER_SCROLL_NEVER); setVerticalFadingEdgeEnabled(false); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); addOnLayoutChangeListener(this); // if (getAdapter() != null) { // ((ChatAdapter) getAdapter()).setOnItemRemovelistener(new ChatAdapter // .OnItemRemoveListener() { // @Override // public void onItemRemove(int position) { // dataLoadingOrRemoveType = DATA_REMOVED; // } // }); // } } @Override public void onScrolled(int dx, int dy) { super.onScrolled(dx, dy); Log.d(TAG, "onScrolled: dy"+dy); if (needComputeLoadItemHeightMaxNum > 0) { int j = needComputeLoadItemHeightMaxNum; if (j >= 1) { for (int i = j; i >= 1; i--) { if (findViewByPosition(getItemCount() - i - 1) != null) { contentHeight += findViewByPosition(getItemCount() - i - 1) .getMeasuredHeight(); needComputeLoadItemHeightMaxNum--; } else { break; } } } setFootViewHeight(); Log.d(TAG, "onScrolled: contentHeight needComputeLoadItemHeightMaxNum" + contentHeight); } if (needComputeInsertItemHeightMaxNum > 0) { int j = needComputeInsertItemHeightMaxNum; if (j >= 1) { for (int i = j; i >= 1; i--) { if (findViewByPosition(j) != null) { contentHeight += findViewByPosition(j).getMeasuredHeight(); needComputeInsertItemHeightMaxNum--; } else { break; } } } setFootViewHeight(); Log.d(TAG, "onScrolled: contentHeight needComputeInsertItemHeightMaxNum" + contentHeight); } if (loadingData) { Log.d(TAG, "onScrolled: loadingdata"); Log.d(TAG, "onScrolled: getItemCount" + getItemCount()); // if (isOverScrolled() && isHeadViewVisible()) { if (Math.abs(getHeadViewOffset()) <= refreshHeight) { stopScroll(); if(onRefreshListener!=null){ onRefreshListener.onHeadRefresh(); }else{ Log.d(TAG, "onScrolled: resetHeadViewOffset"); resetHeadViewOffset(); loadingData = false; } } } return; } if (getScrollState() == SCROLL_STATE_DRAGGING || currentStatus == REFRESH_DURING||init) { return; } if (!isOverScrolled() && !isFootOverScrolled()) { return; } else if (isOverScrolled() &&isHeadViewVisible()&&dy <= 0) { headOffset=getHeadViewOffset(); if(headOffset>=refreshHeight/2) { stopScroll(); Log.d(TAG, "onScrolled:Math.abs(headOffset)>=refreshHeight"); } // Log.d(TAG, "onScroll: resetHeadViewOffset"); // stopScroll(); // resetHeadViewOffset(); return; } else if (!isOverScrolled() && isFootOverScrolled() && dy >= 0 && isFootViewVisible()) { Log.d(TAG, "onScroll: resetFootViewOffset"); bottomOffset=getBottomOffset(); if(bottomOffset>=refreshHeight/2){ stopScroll(); // resetFootViewOffset(); // bottomOffset=0; } // stopScroll(); // resetFootViewOffset(); return; } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); this.height = h; Log.d(TAG, "onSizeChanged: h" + h); } //// TODO: 2016/8/15 //onkeyup 时需还原bottomset 和head set //上拉和下拉时禁止其他组件的点击事件 @Override public synchronized void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { // if (onDrawFinishListener != null) onDrawFinishListener.onDrawfinish(false); // Log.d(TAG, "onLayoutChange: +oldBottom" + oldBottom); // Log.d(TAG, "onLayoutChange: +bottom" + bottom); int changeHeight = bottom - oldBottom; Log.d(TAG, "onLayoutChange: oldBottom"+oldBottom+" oldright :"+oldRight); Log.d(TAG, "onLayoutChange: changeheight"+changeHeight+" right :"+right); // if (oldRight != 0 && oldBottom != 0 && isOverScrolled() && isHeadViewVisible()) { // scrollBy(0, getHeadViewOffset()); // setFootViewHeight(); // return; // } // if (oldRight == 0 || oldBottom == 0 || dataInit) { Log.d(TAG, "onLayoutChange: datainit"+dataInit); if(dataInit) dataInit=false; init=true; // scrollToPosition(getItemCount()-1); Log.d(TAG, "onLayoutChange: oldRight == 0 || oldBottom == 0"+oldBottom+" oldright :"+oldRight); if (isOverScrolled() && isHeadViewVisible()) { Log.d(TAG, "onLayoutChange: bottom scrolled"); scrollBy(0, getHeadViewOffset()); } if(getItemCount()!=2&&isFootOverScrolled()&&isFootViewVisible()){ scrollBy(0, -getBottomOffset()); } if(getItemCount()!=2&&isOverScrolled() && isHeadViewVisible()){ scrollBy(0, getHeadViewOffset()); } contentHeight = 0; init=false; // if (getItemCount() != 2 && findFirstCompletelyVisibleItemPosition() != 1) { // Log.d(TAG, "onLayoutChange: scrollToPosition(1)"); // scrollToPosition(1); // } Log.d(TAG, "onLayoutChange: getItemCount" + getItemCount()); needComputeLoadItemHeightMaxNum = getItemCount() - 2; int j = needComputeLoadItemHeightMaxNum; if (j > 0) { for (int i = j; i >= 1; i--) { if (findViewByPosition(getItemCount() - i - 1) != null) { contentHeight += findViewByPosition(getItemCount() - i - 1) .getMeasuredHeight(); needComputeLoadItemHeightMaxNum--; } else { break; } } } setFootViewHeight(); Log.d(TAG, "onLayoutChange:footViewHeight " + footViewHeight); } if (dataLoadingOrRemoveType == DATA_LOADING) { Log.d(TAG, "onLayoutChange: needComputeLoadItemHeightMaxNum DATA_LOADING" + needComputeLoadItemHeightMaxNum); dataLoadingOrRemoveType=DATA_NOTHING; if (needComputeLoadItemHeightMaxNum == 0) { needComputeLoadItemHeightMaxNum += loadingPositionsNum; } int j = needComputeLoadItemHeightMaxNum; if (j > 0) { for (int i = j; i >= 1; i--) { if (findViewByPosition(getItemCount() - i - 1) != null) { needComputeLoadItemHeightMaxNum--; int viewTop = findViewByPosition((getItemCount() - i - 1)).getTop(); contentHeight += findViewByPosition(getItemCount() - i - 1) .getMeasuredHeight(); if (footViewHeight > 0) { if (viewTop <= 0) { if (needComputeLoadItemHeightMaxNum > 0) { //to make pre view show scrollBy(0, viewTop - 3); } else { scrollBy(0, viewTop); } } setFootViewHeight(); } } else { break; } } } } // // if (dataChangeType == DATA_INSERT) { dataChangeType = DATA_NOTHING; if (getItemCount() == 3) { scrollBy(0, -3); if (findViewByPosition(1) != null) { Log.d(TAG, "DATA_INSERT:DATA_INSERT item 3"); scrollBy(0, findViewByPosition(1).getTop()); contentHeight += findViewByPosition(1).getMeasuredHeight(); Log.d(TAG, "DATA_INSERT: height" + height); Log.d(TAG, "DATA_INSERT:onChildViewAdded: 3"); setFootViewHeight(); // if(isFootOverScrolled()&&isFootViewVisible()){ // if (footViewHeight > 0) { // scrollBy(0, footViewHeight - getBottomOffset()); // } else { // scrollBy(0, -getBottomOffset()); // } // } } return; } //if(changeHeight>0){ // int currentFootHeight; // if (height - contentHeight <= 0) { // currentFootHeight = 0; // } else { // currentFootHeight = height - contentHeight; // } // if (isFootOverScrolled() && isFootViewVisible()) { // if (currentFootHeight > 0) { // scrollBy(0, currentFootHeight - getBottomOffset()); // } else { // scrollBy(0, -getBottomOffset()); // } // } //} Log.d(TAG, "DATA_INSERT: footViewHeight:" + footViewHeight); if (findViewByPosition(1) != null) { Log.d(TAG, "DATA_INSERT:onChildViewAdded:1 "); int viewheight = findViewByPosition(1).getMeasuredHeight(); contentHeight += viewheight; setFootViewHeight(); Log.d(TAG, "DATA_INSERT: footViewHeight2:" + footViewHeight); Log.d(TAG, "DATA_INSERT:onChildViewAdded:1+findViewByPosition(1).getBottom() - footViewHeight "+(footViewHeight-(height-findViewByPosition(1).getBottom()))); stopScroll(); scrollBy(0,footViewHeight-(height-findViewByPosition(1).getBottom())); // if (isOverScrolled() && isHeadViewVisible()) { // Log.d(TAG, "resetHeadViewOffset: getHeadViewOffset"+getHeadViewOffset()); // scrollBy(0, getHeadViewOffset()); // // } // } } else if (findFirstVisibleItemPosition() == 1) { Log.d(TAG, "DATA_INSERT:onChildViewAdded:2 "); Log.d(TAG, "onLayoutChange: "); if (findViewByPosition(1) != null) { int viewheight = findViewByPosition(1).getMeasuredHeight(); smoothScrollBy(0, findViewByPosition(1).getBottom() - height); Log.d(TAG, "DATA_INSERT:onLayoutChange:smoothheight "+(findViewByPosition(1).getBottom() - height)); contentHeight += viewheight; setFootViewHeight(); } }else if (findFirstVisibleItemPosition() == 2) { Log.d(TAG, "DATA_INSERT:onChildViewAdded:3 "); scrollBy(0, findViewByPosition(2).getBottom() - height + 3); if (findViewByPosition(1) != null) { int viewheight = findViewByPosition(1).getMeasuredHeight(); smoothScrollBy(0, findViewByPosition(1).getBottom() - height); contentHeight += viewheight; setFootViewHeight(); } } else if (findViewByPosition(1) == null) { needComputeInsertItemHeightMaxNum++; } // if(isFootOverScrolled()&&isFootViewVisible()){ // Log.d(TAG, "DATA_INSERT: isFootOverScrolled()&&isFootViewVisible()"); // // if (footViewHeight > 0) { // scrollBy(0, footViewHeight - getBottomOffset()); // } else { // scrollBy(0, -getBottomOffset()); // } //// } return; } // //// if (oldBottom == bottom && dataLoadingOrRemoveType == DATA_LOADING && //// footViewHeight >= 0) { //// dataLoadingOrRemoveType = DATA_NOTHING; //// if (loadingPositions.size() != 0) { //// for (int j = 0; j < loadingPositions.size(); j++) { //// if (footViewHeight > 0 && findViewByPosition(loadingPositions.get(j)) //// != null) { //// int viewTop = findViewByPosition(loadingPositions.get(j)).getTop(); //// int viewheight = findViewByPosition(loadingPositions.get(j)) //// .getMeasuredHeight(); //// if (viewTop <= 0) { //// if (j < (loadingPositions.size() - 1)) { //// //to make pre view show //// scrollBy(0, viewTop - 3); //// } else { //// scrollBy(0, viewTop); //// } //// } //// if (footViewHeight > 0) { //// footViewHeight -= viewheight; //// setFootViewHeightZeroIfLessThanZero(); ////// originalHeight -= viewheight; //// setOrignalViewHeightZeroIfLessThanZero(); //// } ////// else if (originalHeight > 0) { ////// originalHeight -= viewheight; ////// setOrignalViewHeightZeroIfLessThanZero(); ////// } //// } //// } //// } //// return; //// } // //// if (oldBottom == bottom && dataLoadingOrRemoveType == DATA_REMOVED) { //// dataLoadingOrRemoveType = DATA_NOTHING; //// if (isOverScrolled() && isHeadViewVisible()) { //// scrollBy(0, getHeadViewOffset()); //// } //// if (isFootOverScrolled() && isFootViewVisible()) { //// footViewHeight = getBottomOffset(); ////// originalHeight=footViewHeight; //// } //// //// return; //// //// } // //>0 space add <0 space reduce ////if(changeHeight>0&&dataChangeType==SEND_CLICK){ //// dataLoadingOrRemoveType=DATA_NOTHING; //// footViewHeight=getBottomOffset(); //// if(onSendLayoutOver!=null){ //// onSendLayoutOver.onSendLayoutOver();} //// return; ////} if (changeHeight < 0) { Log.d(TAG, "onLayoutChange:changeHeight < 0 "+changeHeight); // if (Math.abs(changeHeight) > DensityUtils.dip2px(getContext(), 250)) { //// isKeyBoardShow = true; // }else{ //// editTextChangeheight-=changeHeight; // } if (footViewHeight > 0 && footViewHeight < Math.abs(changeHeight)) { scrollBy(0, -footViewHeight); } // if (isFootOverScrolled() && isFootViewVisible()) { // footViewHeight = getBottomOffset(); // } else { // footViewHeight = 0; // } setFootViewHeight(); } //// //// if (changeHeight > 0) { Log.d(TAG, "onLayoutChange:changeHeight > 0 "+changeHeight); // if (changeHeight > DensityUtils.dip2px(getContext(), 250)) { // isKeyBoardShow = false; // }else{ // editTextChangeheight-=changeHeight; // } if (isOverScrolled() && isHeadViewVisible()) { Log.d(TAG, "onLayoutChange: changeHeight > 0 footViewHeight = getHeadViewOffset()" + "" + getHeadViewOffset()); scrollBy(0, getHeadViewOffset()); } setFootViewHeight(); // if (isFootOverScrolled() && isFootViewVisible()) { // // resetFootViewOffset(); // } // if (isFootOverScrolled() && isFootViewVisible()) { // Log.d(TAG, "onLayoutChange: changeHeight > 0 footViewHeight = getBottomOffset()" // + getBottomOffset()); //// if (changeHeight > DensityUtils.dip2px(getContext(), 250)) { //// Log.d(TAG, "onLayoutChange: originalHeight"+originalHeight); //// Log.d(TAG, "onLayoutChange: editTextChangeheight"+editTextChangeheight); //// //// //// footViewHeight = originalHeight-editTextChangeheight; //// setFootViewHeightZeroIfLessThanZero(); //// } else { // footViewHeight = getBottomOffset(); // setFootViewHeightZeroIfLessThanZero(); //// } // } else { // footViewHeight = 0; // } } } @Override public boolean onTouchEvent(MotionEvent e) { final int action = MotionEventCompat.getActionMasked(e); Log.d(TAG, "onTouchEvent() called with: " + "action = [" + action + "]"); final int actionIndex = MotionEventCompat.getActionIndex(e); if (action == MotionEvent.ACTION_DOWN) { mScrollPointerId = MotionEventCompat.getPointerId(e, 0); Log.d(TAG, "onTouchEvent() called with: " + "ACTION_DOWN = [" + mScrollPointerId + "]"); } if (currentStatus == REFRESH_DURING) { if (action == MotionEvent.ACTION_POINTER_DOWN) { mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex); Log.d(TAG, "onTouchEvent() called with: " + "ACTION_POINTER_DOWN = [" + mScrollPointerId + "]"); mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f); } } if (isFootOverScrolled() || isOverScrolled() || currentStatus == REFRESH_DURING) { // Log.d(TAG, "onTouchEvent: jinlaile"); if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } final MotionEvent vtev = MotionEvent.obtain(e); boolean eventAddedToVelocityTracker = false; switch (action) { case MotionEvent.ACTION_MOVE: int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId); if (index < 0) { Log.e(TAG, "Error processing scroll; pointer index for id " + mScrollPointerId + " not found. Did any MotionEvents get skipped?"); mScrollPointerId = MotionEventCompat.getPointerId(e, 0); index = MotionEventCompat.findPointerIndex(e, mScrollPointerId); } final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f); if (isFirstMove) { mLastTouchY = y; isFirstMove = false; } currentStatus = REFRESH_DURING; int dy = mLastTouchY - y; Log.d(TAG, "onTouchEvent: dy" + dy); mLastTouchY = y; if(!isFootOverScrolled() &&!isOverScrolled()){ scrollBy(0,dy); }else{ scrollBy(0, dy / 3); Log.d(TAG, "onTouchEvent: scrollBy(0, dy / 3)"); movedY += dy / 3;} break; case MotionEventCompat.ACTION_POINTER_UP: { Log.d(TAG, "onTouchEvent: ACTION_POINTER_UP"); onPointerUp(e); } break; case MotionEvent.ACTION_UP: Log.d(TAG, "onTouchEvent:ACTION_UP "); Log.d(TAG, "onTouchEvent: ACTION_UP movedY"+movedY); Log.d(TAG, "onTouchEvent: ACTION_UP isOverScrolled"+isOverScrolled()); Log.d(TAG, "onTouchEvent: ACTION_UP findViewByPosition(getHeadViewPosition())"+(findViewByPosition(getHeadViewPosition())==null)); if (isOverScrolled() &&findViewByPosition(getHeadViewPosition())!=null&& movedY <= 0) { movedY = 0; if (getHeadViewOffset() > refreshHeight) { loadingData = true; stopScroll(); smoothScrollBy(0, getHeadViewOffset() - refreshHeight); Log.d(TAG, "onTouchEvent: refreshing"); } else { Log.d(TAG, "onTouchEvent:resetHeadViewOffset "); resetHeadViewOffset(); } } else if (isFootOverScrolled() &&findViewByPosition(0)!=null&& movedY >= 0) { movedY = 0; if (footViewHeight != 0) { stopScroll(); smoothScrollBy(0, footViewHeight - getBottomOffset()); } else { stopScroll(); smoothScrollBy(0, -getBottomOffset()); } } else { mVelocityTracker.addMovement(vtev); eventAddedToVelocityTracker = true; mVelocityTracker.computeCurrentVelocity(1000, getMaxFlingVelocity()); final float yvel = -VelocityTrackerCompat.getYVelocity(mVelocityTracker, mScrollPointerId); if (yvel != 0 && fling(0, (int) yvel)) { } resetTouchEvent(); } currentStatus = REFRESH_OVER; isFirstMove = true; movedY = 0; break; case MotionEvent.ACTION_CANCEL: Log.d(TAG, "onTouchEvent:ACTION_CANCEL "); resetTouchEvent(); if (isOverScrolled() && isHeadViewVisible() && movedY <= 0) { movedY = 0; if (getHeadViewOffset() > refreshHeight) { loadingData = true; stopScroll(); smoothScrollBy(0, getHeadViewOffset() - refreshHeight); Log.d(TAG, "onTouchEvent: refreshing"); } else { Log.d(TAG, "onTouchEvent:resetHeadViewOffset "); resetHeadViewOffset(); } } else if (isFootOverScrolled() && isFootViewVisible() && movedY >= 0) { movedY = 0; if (footViewHeight != 0) { stopScroll(); smoothScrollBy(0, footViewHeight - getBottomOffset()); } else { stopScroll(); smoothScrollBy(0, -getBottomOffset()); } } currentStatus = REFRESH_OVER; isFirstMove = true; movedY = 0; break; } if (!eventAddedToVelocityTracker) { mVelocityTracker.addMovement(vtev); } vtev.recycle(); return true; } return super.onTouchEvent(e); } private void resetTouchEvent() { if (mVelocityTracker != null) { mVelocityTracker.clear(); } } // @Override // public boolean fling(int velocityX, int velocityY) { // Log.d(TAG, "fling:velocityY "+velocityY); // if(velocityY>0){ // velocityY=Math.max(Math.min(height,velocityY),velocityY-height*2);}else{ // velocityY=Math.min(Math.max(-height,velocityY),velocityY+height*2); // } // return super.fling(velocityX, velocityY); // } private void onPointerUp(MotionEvent e) { final int actionIndex = MotionEventCompat.getActionIndex(e); if (MotionEventCompat.getPointerId(e, actionIndex) == mScrollPointerId) { // Pick a new pointer to pick up the slack. final int newIndex = actionIndex == 0 ? 1 : 0; mScrollPointerId = MotionEventCompat.getPointerId(e, newIndex); mLastTouchY = (int) (MotionEventCompat.getY(e, newIndex) + 0.5f); } } private boolean isOverScrolled() { return findLastCompletelyVisibleItemPosition() == getFirstContentViewPosition() || findLastVisibleItemPosition() == getHeadViewPosition(); } private boolean isFootOverScrolled() { return findFirstCompletelyVisibleItemPosition() == 1 || findFirstVisibleItemPosition() == 0; } private int findLastVisibleItemPosition() { return ((LinearLayoutManager) getLayoutManager()).findLastVisibleItemPosition(); } private int findFirstVisibleItemPosition() { return ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition(); } private int findLastCompletelyVisibleItemPosition() { return ((LinearLayoutManager) getLayoutManager()).findLastCompletelyVisibleItemPosition(); } private int findFirstCompletelyVisibleItemPosition() { return ((LinearLayoutManager) getLayoutManager()).findFirstCompletelyVisibleItemPosition(); } private View findViewByPosition(int position) { return getLayoutManager().findViewByPosition(position); } private int getItemCount() { return getLayoutManager().getItemCount(); } private int getHeadViewPosition() { Log.d(TAG, "getHeadViewPosition:getItemCount "+getItemCount()); return getItemCount() - 1; } private int getFirstContentViewPosition() { return getItemCount() - 2; } private int getHeadViewOffset() { Log.d(TAG, "getHeadViewOffset: "); return findViewByPosition(getHeadViewPosition()).getBottom(); } private int getBottomOffset() { return height - findViewByPosition(0).getTop(); } private boolean isHeadViewVisible() { Log.d(TAG, "isHeadViewVisible: "); return findViewByPosition(getHeadViewPosition()) != null; } private boolean isFootViewVisible() { return findViewByPosition(0) != null; } private void resetHeadViewOffset() { if (isOverScrolled() && isHeadViewVisible()) { Log.d(TAG, "resetHeadViewOffset: getHeadViewOffset"+getHeadViewOffset()); smoothScrollBy(0, getHeadViewOffset()); } } private void resetFootViewOffset() { if (isFootOverScrolled() && isFootViewVisible()) { if (footViewHeight > 0) { stopScroll(); Log.d(TAG, "resetFootViewOffset1: resetFootViewOffset"+getBottomOffset()); smoothScrollBy(0, footViewHeight - getBottomOffset()); } else { stopScroll(); Log.d(TAG, "resetFootViewOffset2: resetFootViewOffset"+getBottomOffset()); smoothScrollBy(0, -getBottomOffset()); } } } public interface OnRefreshListener { //如果有更多的数据返回true,没有返回false; void onHeadRefresh(); void onFooterRefresh(); } public interface OnDrawFinishListener { //如果有更多的数据返回true,没有返回false; void onDrawfinish(boolean isfinished); } public void setOnRefreshListener(OnRefreshListener onRefreshListener) { this.onRefreshListener = onRefreshListener; } // public void setOnSendLayoutOver(OnSendLayoutOver onSendLayoutOver) { // this.onSendLayoutOver = onSendLayoutOver; // } // // @Override // public int computeVerticalScrollOffset() { // if (findLastVisibleItemPosition() == getHeadViewPosition() || // findLastCompletelyVisibleItemPosition() == getFirstContentViewPosition()) { // return 0; // } // if (findFirstVisibleItemPosition() == 0 || findFirstCompletelyVisibleItemPosition() == 1) { // return super.computeVerticalScrollRange(); // // } // return super.computeVerticalScrollOffset(); // } private void setFootViewHeight() { Log.d(TAG, "setFootViewHeight:contentHeight " + contentHeight); Log.d(TAG, "setFootViewHeight:height " + height); if (height - contentHeight <= 0) { footViewHeight = 0; } else { footViewHeight = height - contentHeight; } } // private void setOrignalViewHeightZeroIfLessThanZero() { // if (originalHeight < 0) originalHeight = 0; // } public void setDataChangeInsert() { dataChangeType = DATA_INSERT; } public void setDataSendClick() { dataChangeType = SEND_CLICK; } public void setLoadingDataStatusAndCount(int loadingPositionsNum) { if (loadingPositionsNum == 0) { loadingData = false; resetHeadViewOffset(); } else { dataLoadingOrRemoveType = DATA_LOADING; this.needComputeLoadItemHeightMaxNum = loadingPositionsNum; } } public void setDataIsInit() { dataInit=true; } public void setRefreshFinished(boolean hasData){ if(loadingData)loadingData=false; if(!hasData) resetHeadViewOffset(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeOnLayoutChangeListener(this); } @Override public void onScrollStateChanged(int state) { Log.d(TAG, "onScrollStateChanged: state:"+state); super.onScrollStateChanged(state); if(state==SCROLL_STATE_IDLE){ if(isOverScrolled()&&!loadingData){ resetHeadViewOffset(); }else if(isFootOverScrolled() && isFootViewVisible()){ resetFootViewOffset(); } } } }
gpl-3.0
alexandervonkurtz/CP2406_Programming2
WEEK9(PRAC8)/cp2406_farrell8_ch12-master/CodeInFigures/DemoStackTrace2.java
870
public class DemoStackTrace2 { public static void main(String[] args) { methodA(); // line 5 } public static void methodA() { System.out.println("In methodA()"); try { methodB(); // line 12 } catch(ArrayIndexOutOfBoundsException error) { System.out.println("In methodA() - The stack trace:"); error.printStackTrace(); } System.out.println("methodA() ends normally."); System.out.println("Application could continue " + "from this point."); } public static void methodB() { System.out.println("In methodB()"); methodC(); // line 26 } public static void methodC() { System.out.println("In methodC()"); int[] array = {0, 1, 2}; System.out.println(array[3]); // line 32 } }
gpl-3.0
realopenit/bubble
bubble/commands/cmd_promote.py
5849
# -*- coding: utf-8 -*- # Part of bubble. See LICENSE file for full copyright and licensing details. import click import tablib from ..cli import pass_bubble from ..cli import STAGES from ..util.cli_misc import bubble_lod_load from ..util.cli_misc import get_pairs from ..util.generators import get_gen_slice from ..util.flat_dict import flat, get_flat_path from ..util.buts import buts # todo:move to magic definitions exportables = ['pulled', 'uniq_pull', 'uniq_push', 'push', 'pushed', 'store', 'stats'] @click.command('promote', short_help='Like Export, but promote from step stage to step stage(experimental)') @click.option('--amount', '-a', type=int, default=-1, help='set the amount to export') @click.option('--index', '-i', type=int, default=-1, help='set the starting index') @click.option('--stage', '-s', default='DEV', help='set the staging :' + ','.join(STAGES)) @click.option('--deststage', '-d', default='DEV', help='set the destination staging :' + ','.join(STAGES)) @click.option('--stepresult', '-r', default='pushed', help='the input stepresult for the export one of:' + ', '.join(exportables)) @click.option('--tostep', '-t', default='pushed', help='the selection of "export" of should be stored in this step, one of:' + ', '.join(exportables)) @click.option('--select', '-c', default='', help='keys to select keys for export key1,key2 or aliased key1:first,key2:second') @click.option('--where', '-w', default='', help='where key1:value1 [,key2:value2]') @click.option('--order', '-O', default='', help='order by key,ascending') @click.option('--position', '-p', is_flag=True, default=False, help='if position, also append the position (index for item in total list)') @pass_bubble def cli(ctx, amount, index, stage, deststage, stepresult, tostep, select, where, order, position): """Promote data from one stage to another(experimental) First collect the correct information with export, and promote result by adjusting command to promote and adding missing options. """ if not ctx.bubble: msg = 'There is no bubble present, will not promote' ctx.say_yellow(msg) raise click.Abort() if stage not in STAGES: ctx.say_yellow('There is no known stage:' + stage) raise click.Abort() if stepresult not in exportables: ctx.say_yellow('stepresult not one of: ' + ', '.join(exportables)) raise click.Abort() ctx.gbc.say('promote:args', stuff=(ctx, amount, index, stage, deststage, stepresult, tostep, select, where, order, position)) data_gen = bubble_lod_load(ctx, stepresult, stage) ctx.gbc.say('data_gen:', stuff=data_gen, verbosity=20) part = get_gen_slice(ctx.gbc, data_gen, amount, index) ctx.gbc.say('selected part:', stuff=part, verbosity=20) aliases = get_pairs(ctx.gbc, select, missing_colon=True) if position: ctx.gbc.say('adding position to selection of columns:', stuff=aliases, verbosity=20) aliases.insert(0, {'key': buts('index'), 'val': 'BUBBLE_IDX'}) ctx.gbc.say('added position to selection of columns:', stuff=aliases, verbosity=20) wheres = get_pairs(ctx.gbc, where) # TODO: use aliases as lookup for wheres data = tablib.Dataset() data.headers = [sel['val'] for sel in aliases] ctx.gbc.say('select wheres:' + str(wheres), verbosity=20) ctx.gbc.say('select aliases:' + str(aliases), verbosity=20) ctx.gbc.say('select data.headers:' + str(data.headers), verbosity=20) # TODO: get this selecting stuff into a shared function from export try: for ditem in part: row = [] ctx.gbc.say('curr dict', stuff=ditem, verbosity=101) flitem = flat(ctx, ditem) ctx.gbc.say('curr flat dict', stuff=flitem, verbosity=101) row_ok = True for wp in wheres: # TODO: negative selects: k:None, k:False,k:Zero,k:Null,k:0,k:-1,k:'',k:"", # TODO: negative selects: k:BUBBLE_NO_KEY,k:BUBBLE_NO_VAL if not wp['val'] in str(flitem[wp['key']]): row_ok = False if not row_ok: continue for sel in aliases: if sel['key'] in flitem: row.append(flitem[sel['key']]) else: # temporary to check, not use case for buts() bnp = '____BTS_NO_PATH_' tempv = get_flat_path(ctx, flitem, sel['key'] + '.*', bnp) if tempv != bnp: row.append(tempv) else: row.append('None') # TODO maybe 'NONE', or just '' or something like: # magic.export_format_none data.append(row) except Exception as excpt: ctx.say_red('Cannot promote data', stuff=excpt) raise click.Abort() if order: olast2 = order[-2:] ctx.gbc.say('order:' + order + ' last2:' + olast2, verbosity=100) if olast2 not in [':+', ':-']: data = data.sort(order, False) else: if olast2 == ':+': data = data.sort(order[:-2], False) if olast2 == ':-': data = data.sort(order[:-2], True)
gpl-3.0
tautcony/ChapterTool
Time_Shift/SharpDvdInfo/DvdInfoContainer.cs
15009
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SharpDvdInfo.cs" company="JT-Soft (https://github.com/UniqProject/SharpDvdInfo)"> // This file is part of the SharpDvdInfo source code - It may be used under the terms of the GNU General Public License. // </copyright> // <summary> // Main DVD info container // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace SharpDvdInfo { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using ChapterTool.Util; using SharpDvdInfo.DvdTypes; using SharpDvdInfo.Model; /// <summary> /// Container for DVD Specification /// </summary> public class DvdInfoContainer { /// <summary> /// Length of DVD Sector /// </summary> private const int SectorLength = 2048; /// <summary> /// DVD directory /// </summary> private readonly string _path; /// <summary> /// VMGM properties. /// </summary> public VmgmInfo Vmgm { get; set; } /// <summary> /// List of <see cref="TitleInfo"/> containing Title information. /// </summary> public List<TitleInfo> Titles { get; set; } /// <summary> /// Creates a <see cref="DvdInfoContainer"/> and reads stream infos /// </summary> /// <param name="path">DVD directory</param> public DvdInfoContainer(string path) { if (File.Exists(path)) { _path = Directory.GetParent(path).FullName; var rTitle = new Regex(@"VTS_(\d{2})_0.IFO"); var result = rTitle.Match(path); if (!result.Success) throw new Exception("Invalid file"); var titleSetNumber = byte.Parse(result.Groups[1].Value); var list = new TitleInfo { TitleNumber = titleSetNumber, TitleSetNumber = titleSetNumber, TitleNumberInSet = 1, }; GetTitleInfo(titleSetNumber, ref list); Titles = new List<TitleInfo> { list }; } else { if (path.IndexOf("VIDEO_TS", StringComparison.Ordinal) > 0) { _path = path; } else if (Directory.Exists(Path.Combine(path, "VIDEO_TS"))) { _path = Path.Combine(path, "VIDEO_TS"); } Vmgm = new VmgmInfo(); Titles = new List<TitleInfo>(); GetVmgmInfo(); } } /// <summary> /// fills the <see cref="TitleInfo"/> with informations /// </summary> private void GetTitleInfo(int titleSetNumber, ref TitleInfo item) { item.VideoStream = new VideoProperties(); item.AudioStreams = new List<AudioProperties>(); item.SubtitleStreams = new List<SubpictureProperties>(); item.Chapters = new List<TimeSpan>(); var buffer = new byte[192]; using (var fs = File.OpenRead(Path.Combine(_path, $"VTS_{titleSetNumber:00}_0.IFO"))) { fs.Seek(0x00C8, SeekOrigin.Begin); fs.Read(buffer, 0, 4); fs.Seek(0x0200, SeekOrigin.Begin); fs.Read(buffer, 0, 2); item.VideoStream.DisplayFormat = (DvdVideoPermittedDisplayFormat)GetBits(buffer, 2, 0); item.VideoStream.AspectRatio = (DvdVideoAspectRatio)GetBits(buffer, 2, 2); item.VideoStream.VideoStandard = (DvdVideoStandard)GetBits(buffer, 2, 4); switch (item.VideoStream.VideoStandard) { case DvdVideoStandard.NTSC: item.VideoStream.Framerate = 30000f / 1001f; item.VideoStream.FrameRateNumerator = 30000; item.VideoStream.FrameRateDenominator = 1001; break; case DvdVideoStandard.PAL: item.VideoStream.Framerate = 25f; item.VideoStream.FrameRateNumerator = 25; item.VideoStream.FrameRateDenominator = 1; break; } item.VideoStream.CodingMode = (DvdVideoMpegVersion)GetBits(buffer, 2, 6); item.VideoStream.VideoResolution = (DvdVideoResolution)GetBits(buffer, 3, 11) + ((int)item.VideoStream.VideoStandard * 8); fs.Read(buffer, 0, 2); var numAudio = GetBits(buffer, 16, 0); for (var audioNum = 0; audioNum < numAudio; audioNum++) { fs.Read(buffer, 0, 8); var langMode = GetBits(buffer, 2, 2); var codingMode = GetBits(buffer, 3, 5); var audioStream = new AudioProperties { CodingMode = (DvdAudioFormat)codingMode, Channels = GetBits(buffer, 3, 8) + 1, SampleRate = 48000, Quantization = (DvdAudioQuantization)GetBits(buffer, 2, 14), StreamId = DvdAudioId.ID[codingMode] + audioNum, StreamIndex = audioNum + 1, }; if (langMode == 1) { var langChar1 = (char)GetBits(buffer, 8, 16); var langChar2 = (char)GetBits(buffer, 8, 24); audioStream.Language = LanguageSelectionContainer.LookupISOCode($"{langChar1}{langChar2}"); } else { audioStream.Language = LanguageSelectionContainer.LookupISOCode(" "); } audioStream.Extension = (DvdAudioType)GetBits(buffer, 8, 40); item.AudioStreams.Add(audioStream); } fs.Seek(0x0254, SeekOrigin.Begin); fs.Read(buffer, 0, 2); var numSubs = GetBits(buffer, 16, 0); for (var subNum = 0; subNum < numSubs; subNum++) { fs.Read(buffer, 0, 6); var langMode = GetBits(buffer, 2, 0); var sub = new SubpictureProperties { Format = (DvdSubpictureFormat)GetBits(buffer, 3, 5), StreamId = 0x20 + subNum, StreamIndex = subNum + 1, }; if (langMode == 1) { var langChar1 = (char)GetBits(buffer, 8, 16); var langChar2 = (char)GetBits(buffer, 8, 24); var langCode = langChar1.ToString(CultureInfo.InvariantCulture) + langChar2.ToString(CultureInfo.InvariantCulture); sub.Language = LanguageSelectionContainer.LookupISOCode(langCode); } else { sub.Language = LanguageSelectionContainer.LookupISOCode(" "); } sub.Extension = (DvdSubpictureType)GetBits(buffer, 8, 40); item.SubtitleStreams.Add(sub); } fs.Seek(0xCC, SeekOrigin.Begin); fs.Read(buffer, 0, 4); var pgciSector = GetBits(buffer, 32, 0); var pgciAdress = pgciSector * SectorLength; fs.Seek(pgciAdress, SeekOrigin.Begin); fs.Read(buffer, 0, 8); fs.Seek(8 * (item.TitleNumberInSet - 1), SeekOrigin.Current); fs.Read(buffer, 0, 8); var offsetPgc = GetBits(buffer, 32, 32); fs.Seek(pgciAdress + offsetPgc + 2, SeekOrigin.Begin); fs.Read(buffer, 0, 6); var numCells = GetBits(buffer, 8, 8); var hour = GetBits(buffer, 8, 16); var minute = GetBits(buffer, 8, 24); var second = GetBits(buffer, 8, 32); var msec = GetBits(buffer, 8, 40); item.VideoStream.Runtime = DvdTime2TimeSpan(hour, minute, second, msec); fs.Seek(224, SeekOrigin.Current); fs.Read(buffer, 0, 2); var cellmapOffset = GetBits(buffer, 16, 0); fs.Seek(pgciAdress + cellmapOffset + offsetPgc, SeekOrigin.Begin); var chapter = default(TimeSpan); item.Chapters.Add(chapter); for (var i = 0; i < numCells; i++) { fs.Read(buffer, 0, 24); var chapHour = GetBits(buffer, 8, 4 * 8); var chapMinute = GetBits(buffer, 8, 5 * 8); var chapSecond = GetBits(buffer, 8, 6 * 8); var chapMsec = GetBits(buffer, 8, 7 * 8); chapter = chapter.Add(DvdTime2TimeSpan(chapHour, chapMinute, chapSecond, chapMsec)); item.Chapters.Add(chapter); } } } /// <summary> /// Gets VMGM info and initializes Title list /// </summary> private void GetVmgmInfo() { var buffer = new byte[12]; using (var fs = File.OpenRead(Path.Combine(_path, "VIDEO_TS.IFO"))) { fs.Seek(0x20, SeekOrigin.Begin); fs.Read(buffer, 0, 2); Vmgm.MinorVersion = GetBits(buffer, 4, 8); Vmgm.MajorVersion = GetBits(buffer, 4, 12); fs.Seek(0x3E, SeekOrigin.Begin); fs.Read(buffer, 0, 2); Vmgm.NumTitleSets = GetBits(buffer, 16, 0); fs.Seek(0xC4, SeekOrigin.Begin); fs.Read(buffer, 0, 4); var sector = GetBits(buffer, 32, 0); fs.Seek(sector * SectorLength, SeekOrigin.Begin); fs.Read(buffer, 0, 8); Vmgm.NumTitles = GetBits(buffer, 16, 0); for (var i = 0; i < Vmgm.NumTitles; i++) { fs.Read(buffer, 0, 12); var info = new TitleInfo { TitleNumber = (byte)(i + 1), TitleType = (byte)GetBits(buffer, 8, 0), NumAngles = (byte)GetBits(buffer, 8, 1 * 8), NumChapters = (short)GetBits(buffer, 16, 2 * 8), ParentalMask = (short)GetBits(buffer, 16, 4 * 8), TitleSetNumber = (byte)GetBits(buffer, 8, 6 * 8), TitleNumberInSet = (byte)GetBits(buffer, 8, 7 * 8), StartSector = GetBits(buffer, 32, 8 * 8), }; GetTitleInfo(info.TitleNumber, ref info); Titles.Add(info); } } } public List<ChapterInfo> GetChapterInfo() { var ret = new List<ChapterInfo>(); foreach (var titleInfo in Titles) { var chapterName = ChapterName.GetChapterName(); var index = 1; var tmp = new ChapterInfo { SourceName = $"VTS_{titleInfo.TitleSetNumber:D2}_1", SourceType = "DVD", }; foreach (var time in titleInfo.Chapters) { tmp.Chapters.Add(new Chapter(chapterName(), time, index++)); } ret.Add(tmp); } return ret; } /// <summary> /// Reads up to 32 bits from a byte array and outputs an integer /// </summary> /// <param name="buffer">bytearray to read from</param> /// <param name="length">count of bits to read from array</param> /// <param name="start">position to start from</param> /// <returns>resulting <see cref="int"/></returns> public static int GetBits(byte[] buffer, byte length, byte start) { var result = 0; // read bytes from left to right and every bit in byte from low to high var ba = new BitArray(buffer); short j = 0; var tempResult = 0; for (int i = start; i < start + length; i++) { if (ba.Get(i)) tempResult += (1 << j); j++; if (j % 8 == 0 || j == length) { j = 0; result <<= 8; result += tempResult; tempResult = 0; } } return result; } public static int GetBits_Effi(byte[] buffer, byte length, byte start) { if (length > 8) { length = (byte)(length / 8 * 8); } long temp = 0; long mask = 0xffffffffu >> (32 - length); // [b1] {s} [b2] {s+l} [b3] for (var i = 0; i < Math.Ceiling((start + length) / 8.0); ++i) { temp |= (uint)buffer[i] << (24 - (i * 8)); } return (int)((temp >> (32 - start - length)) & mask); } /// <summary> /// converts bcd formatted time to milliseconds /// </summary> /// <param name="hours">hours in bcd format</param> /// <param name="minutes">minutes in bcd format</param> /// <param name="seconds">seconds in bcd format</param> /// <param name="milliseconds">milliseconds in bcd format (2 high bits are the frame rate)</param> /// <returns>Converted time in milliseconds</returns> private static TimeSpan DvdTime2TimeSpan(int hours, int minutes, int seconds, int milliseconds) { var fpsMask = milliseconds >> 6; milliseconds &= 0x3f; var fps = fpsMask == 0x01 ? 25D : fpsMask == 0x03 ? (30D / 1.001D) : 0; hours = BcdToInt(hours); minutes = BcdToInt(minutes); seconds = BcdToInt(seconds); milliseconds = fps > 0 ? (int)Math.Round(BcdToInt(milliseconds) / fps * 1000) : 0; return new TimeSpan(0, hours, minutes, seconds, milliseconds); } private static int BcdToInt(int value) => ((0xFF & (value >> 4)) * 10) + (value & 0x0F); } }
gpl-3.0
manovotny/wp-array-util
tests/class-wp-array-util-Test.php
1893
<?php require_once 'vendor/autoload.php'; class WP_Array_Util_Test extends PHPUnit_Framework_TestCase { private $existing_array; private $items_to_add; private $wp_array_util; protected function setUp() { $this->existing_array = array( any_string(), any_string(), any_string() ); $this->items_to_add = array( any_string(), any_string(), any_string() ); $this->wp_array_util = WP_Array_Util::get_instance(); } public function test_empty_existing_array_returns_items_to_add() { $result = $this->wp_array_util->add_items_at_index( null, $this->items_to_add ); $this->assertEquals( $this->items_to_add, $result ); } public function test_empty_items_to_add_returns_existing_array() { $result = $this->wp_array_util->add_items_at_index( $this->existing_array, null ); $this->assertEquals( $this->existing_array, $result ); } public function test_index_higher_than_existing_array_appends_items_to_add() { $expected = array_merge( $this->existing_array, $this->items_to_add ); $result = $this->wp_array_util->add_items_at_index( $this->existing_array, $this->items_to_add, count( $this->existing_array ) + 10 ); $this->assertEquals( $expected, $result ); } public function test_items_to_add_are_inserted_at_the_specified_index() { $expected = array( $this->existing_array[0], $this->existing_array[1], $this->items_to_add[0], $this->items_to_add[1], $this->items_to_add[2], $this->existing_array[2], ); $result = $this->wp_array_util->add_items_at_index( $this->existing_array, $this->items_to_add, 2 ); $this->assertEquals( $expected, $result ); } }
gpl-3.0
forman/frex
src/main/java/z/core/PlaneRenderer.java
8705
/* * Created at 06.01.2004 14:39:17 * Copyright (c) 2004 by Norman Fomferra */ package z.core; import z.StringLiterals; import z.core.color.RGBA; import z.core.progress.ProgressMonitor; import z.core.progress.SubProgressMonitor; import z.util.Assert; import java.text.MessageFormat; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class PlaneRenderer { private final ImageInfo imageInfo; private final boolean colorizeOnly; public PlaneRenderer(ImageInfo imageInfo, boolean colorizeOnly) { Assert.notNull(imageInfo, "imageInfo"); // NON-NLS this.imageInfo = imageInfo; this.colorizeOnly = colorizeOnly; } /** * Renders multiple planes. * * @param planes the planes * @param pixelDataBuffers the pixel data buffers in ABGR order * @param pm a progress monitor */ public void renderPlanes(Plane[] planes, int[][] pixelDataBuffers, ProgressMonitor pm) { Assert.notNull(planes, "planes"); // NON-NLS Assert.notNull(pixelDataBuffers, "pixelDataBuffers"); // NON-NLS Assert.notNull(pm, "pm"); // NON-NLS int background = imageInfo.getBackground().getValue(); pm.beginTask(StringLiterals.getString("gui.msg.computingLayer"), planes.length); try { for (int i = 0; i < planes.length && !pm.isCanceled(); i++) { renderPlane(planes[i], pixelDataBuffers[i], background, new SubProgressMonitor(pm, 1)); background = RGBA.TRANSPARENT.getValue(); } } finally { pm.done(); } } private void renderPlane(Plane plane, int[] pixelDataBuffer, int background, ProgressMonitor pm) { int imageWidth = imageInfo.getImageWidth(); int imageHeight = imageInfo.getImageHeight(); pm.beginTask(MessageFormat.format(StringLiterals.getString("gui.msg.computingLayer0"), plane.getName()), imageHeight); try { renderPlane(plane, imageWidth, imageHeight, pixelDataBuffer, background, pm); } finally { pm.done(); } } private void renderPlane(final Plane plane, final int imageWidth, final int imageHeight, final int[] pixelDataBuffer, final int background, final ProgressMonitor pm) { PlaneRaster raster = plane.getRaster(); final boolean computeFractal; if (raster == null || raster.getWidth() != imageWidth || raster.getHeight() != imageHeight) { raster = new PlaneRaster(imageWidth, imageHeight, pixelDataBuffer); plane.setRaster(raster); computeFractal = true; } else { computeFractal = !this.colorizeOnly; } raster.clearStatistics(); int numProcessors = Runtime.getRuntime().availableProcessors(); if (numProcessors == 1) { renderPlane(plane, 0, imageHeight, imageWidth, imageHeight, pixelDataBuffer, background, computeFractal, pm); return; } ExecutorService executorService = Executors.newFixedThreadPool(numProcessors); final int numLines = imageHeight / numProcessors; final int rest = imageHeight % numProcessors; int iy = 0; for (int i = 0; i < numProcessors; i++) { final int n = numLines + (i == 0 ? rest : 0); final int iy0 = iy; executorService.submit(new Runnable() { @Override public void run() { renderPlane(plane, iy0, n, imageWidth, imageHeight, pixelDataBuffer, background, computeFractal, pm); } }); iy += n; } executorService.shutdown(); try { executorService.awaitTermination(7L, TimeUnit.DAYS); } catch (InterruptedException e) { // ok } } private void renderPlane(Plane plane, int iy0, int numLines, int imageWidth, int imageHeight, int[] pixelDataBuffer, int background, boolean computeFractal, ProgressMonitor pm) { final IFractal fractal = plane.getFractal(); final IAccumulator accumulator = plane.getAccumulator(); IIndexer indexer = plane.getIndexer(); final IColorizer innerColorizer; final IColorizer outerColorizer; if (plane.isInnerOuterDisjoined()) { innerColorizer = plane.getInnerColorizer(); outerColorizer = plane.getOuterColorizer(); } else { innerColorizer = plane.getColorizer(); outerColorizer = plane.getColorizer(); } final boolean trapMode = plane.getTrapMode(); final boolean decompositionMode = plane.getDecompositionMode(); final float[] rawData = plane.getRaster().getRawData(); final Region region = plane.getRegion(); final double pixelSize = 2.0 * region.getRadius() / (double) Math.min(imageWidth, imageHeight); final double zx1 = region.getCenterX() - 0.5 * pixelSize * (double) imageWidth; final double zy2 = region.getCenterY() + 0.5 * pixelSize * (double) imageHeight; fractal.prepare(); if (accumulator != null) { accumulator.prepare(); if (accumulator.computesIndex()) { indexer = null; } if (indexer != null) { indexer.prepare(); } } innerColorizer.prepare(); outerColorizer.prepare(); double zx, zy; int i, k, iy, ix, color, iter; float index; final int iterMax = fractal.getIterMax(); final double[] orbitX = new double[iterMax]; final double[] orbitY = new double[iterMax]; final double[] accuResult = new double[2]; final int iy1 = iy0 + numLines - 1; for (iy = iy0; iy <= iy1 && !pm.isCanceled(); iy++) { zy = zy2 - (double) iy * pixelSize; i = iy * imageWidth; k = iy * imageWidth; for (ix = 0; ix < imageWidth; ix++) { zx = zx1 + (double) ix * pixelSize; if (computeFractal) { iter = fractal.compute(zx, zy, orbitX, orbitY); if (accumulator != null) { accumulator.compute(orbitX, orbitY, iter, iterMax, trapMode, accuResult); if (indexer != null) { index = (float) indexer.computeIndex(accuResult[0], accuResult[1]); } else { index = (float) accuResult[0]; } } else if (iter < iterMax) { index = (float) iter; } else { index = 0.0F; } if (iter == iterMax) { index = -1.0F - index; } if (decompositionMode && iter > 0 && orbitY[iter - 1] < 0.0) { index *= 2.0F; } rawData[k++] = index; } else { index = rawData[k++]; } if (index < 0.0F) { color = innerColorizer.getRgba(-1.0F - index); } else { color = outerColorizer.getRgba(index); } pixelDataBuffer[i++] = color; } pm.worked(1); } } }
gpl-3.0
fabrimaciel/colosoft
Core/Colosoft.Core/TimeSpanSerializationSurrogate.cs
1586
/* * Colosoft Framework - generic framework to assist in development on the .NET platform * Copyright (C) 2013 <http://www.colosoft.com.br/framework> - support@colosoft.com.br * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Colosoft.Serialization.IO; namespace Colosoft.Serialization.Surrogates { /// <summary> /// Implementação do substituto de serialização para <see cref="TimeSpan"/>. /// </summary> internal sealed class TimeSpanSerializationSurrogate : SerializationSurrogate { public TimeSpanSerializationSurrogate() : base(typeof(TimeSpan)) { } public override object Read(CompactBinaryReader reader) { return reader.ReadTimeSpan(); } public override void Skip(CompactBinaryReader reader) { reader.SkipTimeSpan(); } public override void Write(CompactBinaryWriter writer, object graph) { writer.Write((TimeSpan)graph); } } }
gpl-3.0
Martin-Spamer/java-coaching
src/main/java/patterns/factory/package-info.java
148
/** * Package provides an example of the GOF Factory pattern. * <p> * Detailed description of package. * */ package patterns.factory;
gpl-3.0
webSPELL/webSPELL
admin/languages/it/squads.php
2939
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2011 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $language_array = Array( /* do not edit above this line */ 'access_denied'=>'Accesso negato', 'actions'=>'Azioni', 'add_squad'=>'Aggiungi Squadra', 'back'=>'indietro', 'current_icon'=>'actuello Simbolo', 'current_icon_small'=>'actuello Simbolo (piccolo)', 'delete'=>'cancellare', 'edit'=>'cambiare', 'edit_squad'=>'Squadra modificare', 'format_incorrect'=>'Il formato del banner è sbagliato. Si prega di caricare solo banner *.gif, *.jpg o *.png formato.', 'game'=>'Gioco', 'gaming_squad'=>'Team che gioca', 'icon'=>'Icona', 'icon_upload'=>'Carica icona', 'icon_upload_info'=>'per includere sc_squads', 'icon_upload_small'=>'Carica Icona (piccola)', 'information_incomplete'=>'Informazioni incomplete.', 'new_squad'=>'nuova squadra', 'no_icon'=>'Nessuna icona disponibile', 'non_gaming_squad'=>'squadra che non giocando', 'really_delete'=>'Questa squadra veramente cancellare?', 'sort'=>'assortire', 'squad_info'=>'Team Info', 'squad_name'=>'Team nome', 'squad_type'=>'Team typo', 'squads'=>'Squadre', 'transaction_invalid'=>'ID transazione non valido', 'to_sort'=>'assortire' ); ?>
gpl-3.0
cameoh/android-demo
app/src/main/java/com/github/cameoh/demo/preference/PreferenceFragment.java
360
package com.github.cameoh.demo.preference; import android.os.Bundle; import com.github.cameoh.demo.R; public class PreferenceFragment extends android.preference.PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } }
gpl-3.0
yujikato/DIRAC
docs/diracdoctools/cmd/concatcfg.py
5101
#!/usr/bin/env python """script to concatenate the dirac.cfg file's Systems sections with the content of the ConfigTemplate.cfg files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import OrderedDict import logging import os import re import textwrap import sys import shutil from diracdoctools.Config import Configuration from diracdoctools.Utilities import makeLogger from diraccfg import CFG # Try/except for python3 compatibility to ignore errors in ``import DIRAC`` while they last # ultimate protection against not having the symbols imported is also done in the ``run`` function try: from DIRAC import S_OK, S_ERROR except ImportError: pass LOG = makeLogger('ConcatCFG') class ConcatCFG(object): def __init__(self, configFile='docs.conf'): self.config = Configuration(configFile, sections=['CFG']) self.retVal = 0 def prepareDiracCFG(self): """Copy dirac.cfg file to source dir.""" LOG.info('Copy %r to source directory', self.config.cfg_baseFile) shutil.copy(self.config.cfg_baseFile, '/'.join([self.config.docsPath, 'source/'])) def updateCompleteDiracCFG(self): """Read the dirac.cfg and update the Systems sections from the ConfigTemplate.cfg files.""" compCfg = CFG() mainDiracCfgPath = self.config.cfg_baseFile if not os.path.exists(mainDiracCfgPath): LOG.error('Failed to find Main Dirac cfg at %r', mainDiracCfgPath) return 1 self.prepareDiracCFG() LOG.info('Extracting default configuration from %r', mainDiracCfgPath) loadCFG = CFG() loadCFG.loadFromFile(mainDiracCfgPath) compCfg = loadCFG.mergeWith(compCfg) cfg = self.getSystemsCFG() compCfg = compCfg.mergeWith(cfg) diracCfgOutput = self.config.cfg_targetFile LOG.info('Writing output to %r', diracCfgOutput) with open(diracCfgOutput, 'w') as rst: rst.write(textwrap.dedent(""" ========================== Full Configuration Example ========================== .. This file is created by docs/Tools/UpdateDiracCFG.py Below is a complete example configuration with anotations for some sections:: """)) # indent the cfg text cfgString = ''.join(' ' + line for line in str(compCfg).splitlines(True)) # fix the links, add back the # for targets # match .html with following character using positive look ahead htmlMatch = re.compile(r'\.html(?=[a-zA-Z0-9])') cfgString = re.sub(htmlMatch, '.html#', cfgString) rst.write(cfgString) return self.retVal def getSystemsCFG(self): """Find all the ConfigTemplates and collate them into one CFG object.""" cfg = CFG() cfg.createNewSection('/Systems') templateLocations = self.findConfigTemplates() for templatePath in templateLocations: cfgRes = self.parseConfigTemplate(templatePath, cfg) if cfgRes['OK']: cfg = cfgRes['Value'] return cfg def findConfigTemplates(self): """Traverse folders in DIRAC and find ConfigTemplate.cfg files.""" configTemplates = dict() for baseDirectory, _subdirectories, files in os.walk(self.config.sourcePath): LOG.debug('Looking in %r', baseDirectory) if 'ConfigTemplate.cfg' in files: system = baseDirectory.rsplit('/', 1)[1] LOG.info('Found Template for %r in %r', system, baseDirectory) configTemplates[system] = baseDirectory return OrderedDict(sorted(configTemplates.items(), key=lambda t: t[0])).values() def parseConfigTemplate(self, templatePath, cfg): """Parse the ConfigTemplate.cfg files. :param str templatePath: path to the folder containing a ConfigTemplate.cfg file :param CFG cfg: cfg to merge with the systems config :returns: CFG object """ system = os.path.split(templatePath.rstrip('/'))[1] if system.lower().endswith('system'): system = system[:-len('System')] templatePath = os.path.join(templatePath, 'ConfigTemplate.cfg') if not os.path.exists(templatePath): return S_ERROR('File not found: %s' % templatePath) loadCfg = CFG() try: loadCfg.loadFromFile(templatePath) except ValueError as err: LOG.error('Failed loading file %r: %r', templatePath, err) self.retVal = 1 return S_ERROR() cfg.createNewSection('/Systems/%s' % system, contents=loadCfg) return S_OK(cfg) def run(configFile='docs.conf', logLevel=logging.INFO, debug=False): """Add sections from System/ConfigTemplates to main dirac.cfg file :param str configFile: path to the configFile :param logLevel: logging level to use :param bool debug: unused :returns: return value 1 or 0 """ try: logging.getLogger().setLevel(logLevel) concat = ConcatCFG(configFile=configFile) return concat.updateCompleteDiracCFG() except (ImportError, NameError): return 1 if __name__ == '__main__': sys.exit(run())
gpl-3.0
fsinf/certificate-authority
ca/django_ca/apps.py
194
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class DjangoCAConfig(AppConfig): name = 'django_ca' verbose_name = _('Certificate Authority')
gpl-3.0
zbx/device
APDPlat_Core/src/main/java/org/apdplat/platform/criteria/OrderCriteria.java
1109
/** * * APDPlat - Application Product Development Platform * Copyright (c) 2013, 张炳祥, zbx13@163.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.apdplat.platform.criteria; import java.util.LinkedList; /** * 包含多个排序条件 * @author 张炳祥 */ public class OrderCriteria { private LinkedList<Order> orders=new LinkedList<>(); public LinkedList<Order> getOrders() { return orders; } public void addOrder(Order order) { this.orders.add(order); } }
gpl-3.0
KevinWG/OSS.Core
FrontEnds/Admin/ClientApp/src/pages/portal/login/index.tsx
2150
import React, { useState } from 'react'; import { Link, useModel } from 'umi'; import { Alert, Tabs } from 'antd'; import { RespData, Resp } from '@/utils/resp_d'; import { getPageQuery } from '@/utils/utils'; const { TabPane } = Tabs; import PasswordLoginForm from './compents/password_login_form'; import CodeLoginForm from './compents/code_login_form'; import styles from './style.less'; import { AdminIdentity } from './service'; export default (props: any) => { // const { initialState, setInitialState } = useModel('@@initialState'); const [errMsg, setErrMsg] = useState<Resp>(); function callBack(res: RespData<AdminIdentity>) { if (res.is_ok) { // setInitialState({ ...initialState, currentUser: res.data }); const query = getPageQuery(); let { rurl } = query as { rurl: string }; if (!rurl) { rurl = '/'; } window.location.href = rurl; // 因为使用history,ProLayout菜单没有刷新是空,需要改写,改写前使用浏览器直接跳转 } else { setErrMsg(res); } } return ( <div className={styles.container}> <div className={styles.content}> <div className={styles.top}> <div className={styles.header}> <Link to="/"> <span className={styles.title}>OSSCore</span> </Link> </div> {/* <div className={styles.desc}>.Net Core 开源框架</div> */} </div> <div className={styles.main}> {errMsg?.is_failed && ( <Alert style={{ marginBottom: 24, }} message={errMsg?.msg || '网络请求出现问题!'} type="error" showIcon /> )} <Tabs centered> <TabPane tab="账号密码登录" key="1"> <PasswordLoginForm call_back={callBack}></PasswordLoginForm> </TabPane> <TabPane tab="动态码登录" key="2"> <CodeLoginForm call_back={callBack}></CodeLoginForm> </TabPane> </Tabs> </div> </div> </div> ); };
gpl-3.0
VisualCrypt/VisualCrypt
Windows_Universal/VisualCrypt.UWP/Controls/EditorSupport/IEditor.cs
292
using Windows.UI.Xaml.Controls; namespace VisualCrypt.UWP.Controls.EditorSupport { public interface IEditor { TextBox TextBox1 { get; } TextBox TextBoxFind { get; } TextBox TextBoxFindReplace { get; } TextBox TextBoxGoTo { get; } UserControl EditorControl { get; } } }
gpl-3.0
cTn-dev/Phoenix-FlightController
extras/Configurator/background.js
820
chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('main.html', { frame: 'chrome', id: 'main-window', minWidth: 960, maxWidth: 960, minHeight: 550, maxHeight: 550 }, function(main_window) { main_window.onClosed.addListener(function() { // connectionId is passed from the script side through the chrome.runtime.getBackgroundPage refference // allowing us to automatically close the port when application shut down if (connectionId != -1) { chrome.serial.close(connectionId, function() { console.log('CLEANUP: Connection to serial port was opened after application closed, closing the connection.'); }); } }); }); });
gpl-3.0
redaaz/GrammarInduction
Inducer/src/spm/clasp2/Trie.java
12172
package spm.clasp2; import java.util.AbstractMap; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.List; import java.util.Map.Entry; /** * Class that implement a trie structure. A trie is composed of a list of * nodes children that are also the beginning of other trie structure. Those * nodes are composed of both a ItemAstractionPair object and a Trie, where the * children appear. * * The current trie is referring to a pattern that can be obtained from the root * until this one, passing by the different nodes in the way that are ancestors * of the current trie. We do not keep any trace of the parent nodes since the * whole trie will be run at the end of the algorithm, just before applying the * postprocessing step to remove the remaining non-closed frequent patterns. * * Besides, in a trie we keep some information relative to that pattern that is * referred, such as the sequences where the pattern appears, its support, and * some other information used in the key generation of the pruning methods. * * Copyright Antonio Gomariz Peñalver 2013 * * This file is part of the SPMF DATA MINING SOFTWARE * (http://www.philippe-fournier-viger.com/spmf). * * SPMF is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * SPMF is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * SPMF. If not, see <http://www.gnu.org/licenses/>. * * @author agomariz */ public class Trie implements Comparable<Trie> { /** * List of children of the current trie */ List<TrieNode> nodes; /** * IdList associated with the pattern to which the current trie is referring to */ private IDList idList; /** * List of sequences IDs where the pattern, to which the current trie is * referring to, appears */ private BitSet appearingIn = new BitSet(); /** * Support that the pattern, to which the current trie is referring to, has */ private int support = -1; /** * Counter that keeps the sum of all the sequence IDs that are in * appearingIn list */ private int sumSequencesIDs = -1; /** * Static field in order to generate a different identifier for all the * tries generated by the algorithm */ static int intId = 1; /** * Trie identifier */ private int id; /** * Constructor of a Trie by means of a list of NodeTrie and the * IdList of the pattern associated to the trie. * @param nodes List of nodes with which we want to initialize the Trie * @param idList IdList of the pattern associated to the trie */ public Trie(List<TrieNode> nodes, IDList idList) { this.nodes = nodes; this.idList = idList; id = intId++; } /** * Constructor of a Trie by means of a list of NodeTrie. * @param nodes List of nodes with which we want to initialize the Trie */ public Trie(List<TrieNode> nodes) { this.nodes = nodes; id = intId++; } /** * Standard constructor of a Trie. It sets the list of nodes to empty. */ public Trie() { nodes = new ArrayList<TrieNode>(); id = intId++; } /** * It obtain its ith trie child * @param index Child index in which we are interested * @return the trie */ public Trie getChild(int index) { return nodes.get(index).getChild(); } /** * It set a child to the Trie given as parameter * @param index Child index in which we are interested * @param child Trie that we want to insert */ public void setChild(int index, Trie child) { this.nodes.get(index).setChild(child); } /** * It gets the IdList of the pattern associated to the trie * @return the idlist */ public IDList getIdList() { return idList; } /** * It updates the value of the IdList of the pattern associated to * the trie * @param idList */ public void setIdList(IDList idList) { this.idList = idList; } /** * It gets the list of nodes associated with the Trie * @return the list of trie nodes */ public List<TrieNode> getNodes() { return nodes; } /** * It updates the list of nodes associated with the Trie * @param nodes */ public void setNodes(List<TrieNode> nodes) { this.nodes = nodes; } /** * It removes the ith child of the Trie. * @param index Child index in which we are interested * @return true if the item was removed, otherwise it means that the index is outside the bounds of the trie */ public boolean remove(int index) { //if there are some nodes and the index is within the range of nodes if (levelSize() == 0 || index >= levelSize()) { return false; } //We remove the child pointed out by index getChild(index).removeAll(); return true; } /** * It gets the pair of the ith child * @param index Child index in which we are interested * @return the pair */ public ItemAbstractionPair getPair(int index) { return nodes.get(index).getPair(); } /** * It gets the whole TrieNode of the ith child * @param index Child index in which we are interested * @return the trie node */ public TrieNode getNode(int index) { return nodes.get(index); } /** * It updates the whole TrieNode of the ith child * @param index Child index in which we are interested * @param node */ public void setNode(int index, TrieNode node) { nodes.set(index, node); } /** * It returns the number of children that a Trie has * @return the number of children */ public int levelSize() { if (nodes == null) { return 0; } return nodes.size(); } /** * It removes all its descendands tries and then the Trie itself. */ public void removeAll() { //If there are no nodes if (levelSize() == 0) { //We have already finish return; } //Otherwise, for each node of the Trie children for (TrieNode node : nodes) { Trie currentChild = node.getChild(); //We remove all the descendants appearing from its child if (currentChild != null) { currentChild.removeAll(); } //And we make null both its child and pair node.setChild(null); node.setPair(null); } setIdList(null); nodes.clear(); } /** * It merges a trie with another one, inserting the TrieNode given as * parameter in the list of node associated with the current Trie. * @param trie */ public void mergeWithTrie(TrieNode trie) { if (levelSize() == 0) { if (nodes == null) { nodes = new ArrayList<TrieNode>(1); } } nodes.add(trie); } /** * It sorts the children by lexicographic order (given by their pair values) */ public void sort() { Collections.sort(nodes); } /** * It returns the list of sequences Ids where the pattern referred by * the Trie appears. * @return the list of sequence IDs as a bitset */ public BitSet getAppearingIn(){ return this.appearingIn; } /** * It updates the list of sequences Ids where the pattern referred by * the Trie appears * @param appearingIn The list of sequence Ids to update */ public void setAppearingIn(BitSet appearingIn) { this.appearingIn = appearingIn; } /** * Get a string representation of this Trie * @return the string representation */ @Override public String toString() { if (nodes == null) { return ""; } StringBuilder result = new StringBuilder("ID=" + id + "["); if (!nodes.isEmpty()) { for (TrieNode node : nodes) { result.append(node.getPair()).append(','); } result.deleteCharAt(result.length() - 1); } else { result.append("NULL"); } result.append(']'); return result.toString(); } /** * It gets the support of the pattern referred by the Trie. * @return the support */ public int getSupport() { if (this.support < 0) { this.support = appearingIn.cardinality(); } return this.support; } /** * It updates the support of the pattern referred by the Trie * @param support */ public void setSupport(int support) { this.support = support; } /** * It gets the sum of the sequence identifiers of the sequences where * the pattern, referred by the Trie, appears * @return the sum */ public int getSumIdSequences() { if (sumSequencesIDs < 0) { sumSequencesIDs = calculateSumIdSequences(); } return sumSequencesIDs; } /** * It updates the sum of the sequence identifiers of the sequences where * the pattern, referred by the Trie, appears * @param sumIdSequences Value of the sum of sequence identifiers to update */ public void setSumIdSequences(int sumIdSequences) { this.sumSequencesIDs = sumIdSequences; } /** * It calculates the sum of the sequence identifiers * @return */ private int calculateSumIdSequences() { int acum = 0; for(int i=appearingIn.nextSetBit(0);i>=0;i=appearingIn.nextSetBit(i+1)) { acum += i; } return acum; } /** * It makes a pre-order traversal from the Trie. The result is concatenate * to the prefix pattern given as parameter * @param p Prefix pattern * @return a list of entries <Pattern, Trie> */ public List<Entry<Pattern, Trie>> preorderTraversal(Pattern p) { List<Entry<Pattern, Trie>> result = new ArrayList<Entry<Pattern, Trie>>(); //If there is any node if (nodes != null) { for (TrieNode node : nodes) { /* * We concatenate the pair component of this child with the * previous prefix pattern, we set its appearances and we add it * as a element in the result list */ Pattern newPattern = PatternCreator.getInstance().concatenate(p, node.getPair()); Trie child = node.getChild(); AbstractMap.SimpleEntry newEntry = new AbstractMap.SimpleEntry(newPattern, child); result.add(newEntry); if (child != null) { /* * If the child is not null we make a recursive call with the * new pattern */ // System.out.println(newPattern); List<Entry<Pattern, Trie>> patternsFromChild = child.preorderTraversal(newPattern); if (patternsFromChild != null) { result.addAll(patternsFromChild); } } } return result; } else { return null; } } /** * It compares this trie with another * @param t the other trie * @return 0 if equal, -1 if smaller, otherwise 1 */ @Override public int compareTo(Trie t) { return (new Integer(this.id)).compareTo(t.id); } }
gpl-3.0
abarch/expmodel
rbm.py
7325
from sklearn.neural_network import BernoulliRBM from sklearn import linear_model, metrics from sklearn.cross_validation import train_test_split from sklearn.pipeline import Pipeline from sklearn.preprocessing import MultiLabelBinarizer from sklearn.multiclass import OneVsRestClassifier from sklearn import svm from sklearn import preprocessing import sys import optparse import os import numpy as np from compiler.ast import flatten def checkBoard(annotation, boards): if (boards==[0,1] or boards==[1,0] or boards==[0,0]): return annotation == boards elif boards==[1,1] and not annotation==[0,0]: return True else: pass def parseFile (fn, fn_board_annotation, boards, features, sample_rate=1): all_features = [] f = open(fn, 'r') f_annotation = open(fn_board_annotation, 'r') # fixme take out this different format f_annotation.readline() def cutline(line, divchar, fr, num): line = line.rstrip() line = line.split(divchar) line = map(int, line[fr:fr+num]) return line for (line, annotation) in zip (f, f_annotation)[::sample_rate]: annotation = cutline(annotation, ' ', 2, 2) if checkBoard (annotation,boards): line = line.rstrip() line = line.split(',') frame = int (line[0]) featurevec = [line [features[i]] for i in range(len(features))] all_features.append((frame,featurevec)) f.close() f_annotation.close() return all_features #FIXME bug with 2 frames lag in distances def composeFeatures (): def empty(featurevec): if ('' in featurevec ) or (' ' in featurevec): return True def equal_ts(tss): tss= map (int, tss) return all(x==tss[0] for x in tss) def get_ts(vec): return vec[0] def get_feature(vec): return vec[1] def map_labels_spread_to_fingers(labels,maxlabel): labeli = map (lambda x,y: x+y, labels, [0,maxlabel,2*maxlabel,3*maxlabel,4*maxlabel]) return labeli #groups: 0(unclear), 1 (on),2 (off), 3 (slip), 4 (luft) def map_labels_4 (labels): newlabels=[] dic = {0:0, 1:1, 2:2, 3:3, 4:3, 5:3, 6:3, 7:3,8:3, 9:3, 10:3, 11:3, 12:3, 13:3, 14:3, 15:4 } for i in range(5): newlabels.append(dic[labels[i]]) return newlabels alldata=[] labeling=[] for i in range(len(distances)): di=distances[i] vfi=fingers[i] vhi=hand[i] labeli = labels[i] if equal_ts(map(get_ts, [vfi,vhi, labeli])): features= map (get_feature, [di, vfi,vhi]) if not (True in map (empty, features)): features= flatten (features) labeli= get_feature(labeli) labeli = map( int, labeli) #FIXME: dirty hack for multilabel classification labeli= map_labels_4(labeli) labeli = map_labels_spread_to_fingers(labeli, 5) labeling += [labeli] alldata +=[map(float, features)] X = np.array(alldata) Y = np.array(labeling) Y= MultiLabelBinarizer().fit_transform(Y) return X,Y # FIXME: assert the similarity of timestamps if __name__ == "__main__": parser = optparse.OptionParser(usage = 'usage: %prog [OPTIONS]') parser.add_option('--handv-file', dest = 'handv_file', default = 'handvelocity.txt') parser.add_option('--fingerv-file', dest = 'fingerv_file', default = 'fingervelocity.txt') parser.add_option('--distance-file', dest = 'distance_file', default = 'smootheddistances.txt') parser.add_option('--board-annotation-file', dest = 'board_annotation_file', default = 'annotation2D.txt') parser.add_option('--label-annotation-file', dest = 'label_annotation_file', default = 'labels_25ms.csv') parser.add_option('--input-dir', dest = 'input_dir', default = '/homes/abarch/hapticexp/code/expmodel/featuredata') (options, args) = parser.parse_args(sys.argv) # data extraction parameters board = [1,1] # reading data from files board_annotation_file=os.path.join(options.input_dir, options.board_annotation_file) distances= parseFile(os.path.join(options.input_dir, options.distance_file), board_annotation_file, board, range(2,12)) fingers= parseFile(os.path.join(options.input_dir, options.fingerv_file), board_annotation_file, board, range(1,11)) hand = parseFile(os.path.join(options.input_dir, options.handv_file), board_annotation_file, board, range(1,4)) labels = parseFile(os.path.join(options.input_dir, options.label_annotation_file), board_annotation_file, board, range(2, 7)) # put data togeather with its labels X,Y = composeFeatures() # data processing for rbms test_size = 0.2 #scaler to 1 variance scaler = preprocessing.StandardScaler(with_mean=False) X=scaler.fit_transform(X) # 0-1 scaling X = (X - np.min(X, 0)) / (np.max(X, 0) + 0.0001) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=test_size, random_state=0) #models rbm = BernoulliRBM(random_state=0, verbose=True) multilabel= OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=0)) classifier = Pipeline(steps=[('rbm', rbm), ('multilabel', multilabel)]) ############################################################################### # Training rbm.learning_rate = 0.06 rbm.n_iter = 20 # rbm components rbm.n_components = 20 # Training Pipeline classifier.fit(X_train, Y_train) multilabel_classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=0)) multilabel_classifier.fit(X_train,Y_train) ############################################################################### # Evaluation print() print("classification using RBM features:\n%s\n" % ( metrics.classification_report( Y_train, classifier.predict(X_train)))) print("classification on raw features:\n%s\n" % ( metrics.classification_report( Y_train, multilabel_classifier.predict(X_train))))
gpl-3.0
tima/ansible
lib/ansible/modules/network/aci/aci_domain_to_vlan_pool.py
7395
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Dag Wieers <dag@wieers.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: aci_domain_to_vlan_pool short_description: Bind Domain to VLAN Pools on Cisco ACI fabrics (infra:RsVlanNs) description: - Bind Domain to VLAN Pools on Cisco ACI fabrics. - More information from the internal APIC class I(infra:RsVlanNs) at U(https://developer.cisco.com/docs/apic-mim-ref/). author: - Dag Wieers (@dagwieers) version_added: '2.5' notes: - The C(domain) and C(vlan_pool) parameters should exist before using this module. The M(aci_domain) and M(aci_vlan_pool) can be used for these. options: domain: description: - Name of the domain being associated with the VLAN Pool. aliases: [ domain_name, domain_profile ] domain_type: description: - Determines if the Domain is physical (phys) or virtual (vmm). choices: [ fc, l2dom, l3dom, phys, vmm ] pool: description: - The name of the pool. aliases: [ pool_name, vlan_pool ] pool_allocation_mode: description: - The method used for allocating VLANs to resources. choices: [ dynamic, static] required: yes aliases: [ allocation_mode, mode ] state: description: - Use C(present) or C(absent) for adding or removing. - Use C(query) for listing an object or multiple objects. choices: [ absent, present, query ] default: present vm_provider: description: - The VM platform for VMM Domains. choices: [ cloudfoundry, kubernetes, microsoft, openshift, openstack, redhat, vmware ] extends_documentation_fragment: aci ''' EXAMPLES = r''' - name: Bind a VMM domain to VLAN pool aci_domain_to_vlan_pool: hostname: apic username: admin password: SomeSecretPassword domain: vmw_dom domain_type: vmm pool: vmw_pool pool_allocation_mode: dynamic vm_provider: vmware state: present - name: Remove a VMM domain to VLAN pool binding aci_domain_to_vlan_pool: hostname: apic username: admin password: SomeSecretPassword domain: vmw_dom domain_type: vmm pool: vmw_pool pool_allocation_mode: dynamic vm_provider: vmware state: absent - name: Bind a physical domain to VLAN pool aci_domain_to_vlan_pool: hostname: apic username: admin password: SomeSecretPassword domain: phys_dom domain_type: phys pool: phys_pool pool_allocation_mode: static state: present - name: Bind a physical domain to VLAN pool aci_domain_to_vlan_pool: hostname: apic username: admin password: SomeSecretPassword domain: phys_dom domain_type: phys pool: phys_pool pool_allocation_mode: static state: absent - name: Query an domain to VLAN pool binding aci_domain_to_vlan_pool: hostname: apic username: admin password: SomeSecretPassword domain: phys_dom domain_type: phys pool: phys_pool pool_allocation_mode: static state: query - name: Query all domain to VLAN pool bindings aci_domain_to_vlan_pool: hostname: apic username: admin password: SomeSecretPassword state: query ''' RETURN = ''' # ''' from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec from ansible.module_utils.basic import AnsibleModule VM_PROVIDER_MAPPING = dict( microsoft='Microsoft', openstack='OpenStack', redhat='Redhat', vmware='VMware', ) def main(): argument_spec = aci_argument_spec() argument_spec.update( domain=dict(type='str', aliases=['domain_name', 'domain_profile']), domain_type=dict(type='str', choices=['fc', 'l2dom', 'l3dom', 'phys', 'vmm']), pool=dict(type='str', aliases=['pool_name', 'vlan_pool']), pool_allocation_mode=dict(type='str', required=True, aliases=['allocation_mode', 'mode'], choices=['dynamic', 'static']), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), vm_provider=dict(type='str', choices=['cloudfoundry', 'kubernetes', 'microsoft', 'openshift', 'openstack', 'redhat', 'vmware']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['domain_type', 'vmm', ['vm_provider']], ['state', 'absent', ['domain', 'domain_type', 'pool']], ['state', 'present', ['domain', 'domain_type', 'pool']], ], ) domain = module.params['domain'] domain_type = module.params['domain_type'] pool = module.params['pool'] pool_allocation_mode = module.params['pool_allocation_mode'] vm_provider = module.params['vm_provider'] state = module.params['state'] # Report when vm_provider is set when type is not virtual if domain_type != 'vmm' and vm_provider is not None: module.fail_json(msg="Domain type '{0}' cannot have a 'vm_provider'".format(domain_type)) # ACI Pool URL requires the allocation mode for vlan and vsan pools (ex: uni/infra/vlanns-[poolname]-static) pool_name = pool if pool is not None: pool_name = '[{0}]-{1}'.format(pool, pool_allocation_mode) # Compile the full domain for URL building if domain_type == 'fc': domain_class = 'fcDomP' domain_mo = 'uni/fc-{0}'.format(domain) domain_rn = 'fc-{0}'.format(domain) elif domain_type == 'l2dom': domain_class = 'l2extDomP' domain_mo = 'uni/l2dom-{0}'.format(domain) domain_rn = 'l2dom-{0}'.format(domain) elif domain_type == 'l3dom': domain_class = 'l3extDomP' domain_mo = 'uni/l3dom-{0}'.format(domain) domain_rn = 'l3dom-{0}'.format(domain) elif domain_type == 'phys': domain_class = 'physDomP' domain_mo = 'uni/phys-{0}'.format(domain) domain_rn = 'phys-{0}'.format(domain) elif domain_type == 'vmm': domain_class = 'vmmDomP' domain_mo = 'uni/vmmp-{0}/dom-{1}'.format(VM_PROVIDER_MAPPING[vm_provider], domain) domain_rn = 'dom-{0}'.format(domain) aci_mo = 'uni/infra/vlanns-' + pool_name aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class=domain_class, aci_rn=domain_rn, filter_target='eq({0}.name, "{1}")'.format(domain_class, domain), module_object=domain_mo, ), child_classes=['infraRsVlanNs'], ) aci.get_existing() if state == 'present': # Filter out module params with null values aci.payload( aci_class=domain_class, class_config=dict(name=domain_mo), child_configs=[ {'infraRsVlanNs': {'attributes': {'tDn': aci_mo}}}, ] ) # Generate config diff which will be used as POST request body aci.get_diff(aci_class=domain_class) # Submit changes if module not in check_mode and the proposed is different than existing aci.post_config() elif state == 'absent': aci.delete_config() module.exit_json(**aci.result) if __name__ == "__main__": main()
gpl-3.0
zeatul/poc
e-commerce/e-commerce-mall-product-service/src/main/java/com/hawk/ecom/product/exception/AttrNameIsNotUsedByProductRuntimeException.java
510
package com.hawk.ecom.product.exception; import com.hawk.ecom.pub.exception.ErrorCodeAllocation; import com.hawk.framework.pub.exception.BasicRuntimeException; public class AttrNameIsNotUsedByProductRuntimeException extends BasicRuntimeException { /** * */ private static final long serialVersionUID = -2807413836191102335L; private final static int code = ErrorCodeAllocation.PRODUCT+28; public AttrNameIsNotUsedByProductRuntimeException() { super(code,ErrorCode.getErrMsg(code)); } }
gpl-3.0
cclerke/snozama
project/src/snozama/amazons/mechanics/algo/DummySearch.java
1928
package snozama.amazons.mechanics.algo; import snozama.amazons.mechanics.Board; import snozama.amazons.mechanics.MoveManager; /** * A randomized search algorithm. * * @author Graeme Douglas * */ public class DummySearch { /** * The time limit of the search as a system milliseconds time. */ long endTime; /** * The default constructor. * * @param end The end time of the search, a system milliseconds time. */ public DummySearch(long end) { endTime = end; } /** * Choose a move to make randomly. * * @param board The current board state. * @param colour The current player's colour, either {@code BLACK} or * {@code WHITE}. * @param turn Count of current turn (turn 1, turn 2, etc.) * @return An integer encoded move. */ public int chooseMove(Board board, int colour, int turn) { if (board.isTerminal()) { return -1; } // Choose your algorithm here. //return fastRandomMove(board, colour); return timedRandomMove(board, colour); } /** * Choose a move to make randomly, as fast as possible. * * @param board The current board state. * @param colour The current player's colour, either {@code BLACK} or * {@code WHITE}. * @return An integer encoded move. */ private int fastRandomMove(Board board, int colour) { MoveManager successors = board.getSuccessors(colour); successors.shuffle(); return successors.getMove(0); } /** * Choose a move to make randomly, but wait until search time is up. * * LOL Will. * * @param board The current board state. * @param colour The current player's colour, either {@code BLACK} or * {@code WHITE}. * @return An integer encoded move. */ private int timedRandomMove(Board board, int colour) { // Look like we are making good decisions while (System.currentTimeMillis() < endTime){} return fastRandomMove(board, colour); } }
gpl-3.0
ski7777/ftcommunity-apps
packages/brickly/custom_blocks.js
27004
// custom block definitions for brickly incl. python code generation // https://blockly-demo.appspot.com/static/demos/blockfactory/index.html CustomBlocksHUE = 180 InputBlocksHUE = 200 OutputBlocksHUE = 220 MobileBlocksHUE = 250 TextBlocksHUE = 350 // -------------------------------------------------------- var block_wait = { "message0": MSG['blockWaitMessage'], "args0": [ { "type": "input_value", "name": "seconds", "check": "Number" } ], "inputsInline": true, "previousStatement": null, "nextStatement": null, "colour": CustomBlocksHUE, "tooltip": MSG['blockWaitToolTip'] }; var block_repeat = { "message0": MSG['blockRepeatMessage'], "args0": [ { "type": "input_dummy" },{ "type": "input_statement", "name": "STATEMENTS" } ], "previousStatement": null, "colour": Blockly.Blocks.loops.HUE, "tooltip": MSG['blockRepeatToolTip'] }; // -------------------------------------------------------- // --------------------- Joystick ------------------------- // -------------------------------------------------------- var block_js_present = { "message0": MSG['blockJsPresentMessage'], "output": "Boolean", "colour": InputBlocksHUE, "tooltip": MSG['blockJsPresetToolTip'] }; Blockly.Python['js_present'] = function(block) { code = 'jsIsPresent()'; return [code, Blockly.Python.ORDER_NONE]; } var block_js_axis = { "message0": MSG['blockJsAxisMessage'], "args0": [ { "type": "field_dropdown", "name": "axis", "options": [ [ MSG["blockAxisX"], "x" ], [ MSG["blockAxisY"], "y" ], [ MSG["blockAxisZ"], "z" ], [ MSG["blockAxisRx"], "rx" ], [ MSG["blockAxisRy"], "ry" ], [ MSG["blockAxisRz"], "rz" ], [ MSG["blockAxisHx"], "hat0x" ], [ MSG["blockAxisHy"], "hat0y" ] ] } ], "output": "Number", "colour": InputBlocksHUE, "tooltip": MSG['blockJsAxisToolTip'] }; Blockly.Python['js_axis'] = function(block) { var axis = block.getFieldValue('axis'); code = 'jsGetAxis("%1")'.replace('%1', axis); return [code, Blockly.Python.ORDER_NONE]; } var block_js_button = { "message0": MSG['blockJsButtonMessage'], "args0": [ { "type": "field_dropdown", "name": "button", "options": [ [ MSG["blockButtonTrigger"], "trigger" ], [ MSG["blockButtonThumb"], "thumb" ], [ MSG["blockButtonThumb2"], "thumb2" ], [ MSG["blockButtonTop"], "top" ], [ MSG["blockButtonTop2"], "top2" ], [ MSG["blockButtonPinkieBtn"], "pinkie" ], [ MSG["blockButtonBaseBtn"], "base" ], [ MSG["blockButtonBaseBtn2"], "base2" ], [ MSG["blockButtonBaseBtn3"], "base3" ], [ MSG["blockButtonBaseBtn4"], "base4" ], [ MSG["blockButtonBaseBtn5"], "base5" ], [ MSG["blockButtonBaseBtn6"], "base6" ], [ MSG["blockButtonA"], "a" ], [ MSG["blockButtonB"], "b" ], [ MSG["blockButtonC"], "c" ], [ MSG["blockButtonX"], "x" ], [ MSG["blockButtonY"], "y" ], [ MSG["blockButtonZ"], "z" ], [ MSG["blockButtonTL"], "tl" ], [ MSG["blockButtonTR"], "tr" ], [ MSG["blockButtonTL2"], "tl2" ], [ MSG["blockButtonTR2"], "tr2" ], [ MSG["blockButtonSelect"], "select" ], [ MSG["blockButtonStart"], "start" ], [ MSG["blockButtonMode"], "mode" ], [ MSG["blockButtonThumbL"], "thumbl" ], [ MSG["blockButtonThimbR"], "thumbr" ], [ MSG["blockButtonDPadUp"], "dpad_up" ], [ MSG["blockButtonDPadDown"], "dpad_down" ], [ MSG["blockButtonDPadLeft"], "dpad_left" ], [ MSG["blockButtonDPadRight"], "dpad_right" ], [ MSG["blockButtonIrOn"], "ir_on" ], [ MSG["blockButtonIrOff"], "ir_off" ] ] } ], "output": "Boolean", "colour": InputBlocksHUE, "tooltip": MSG['blockJsButtonToolTip'] }; Blockly.Python['js_button'] = function(block) { var button = block.getFieldValue('button'); code = 'jsGetButton("%1")'.replace('%1', button); return [code, Blockly.Python.ORDER_NONE]; } // -------------------------------------------------------- var block_pwm_value = { "message0": MSG['blockPwmValueMessage'], "args0": [ { "type": "field_dropdown", "name": "state", "options": [ [ "100% ("+MSG['blockOn']+")", "100" ], [ "90%", "90" ], [ "80%", "80" ], [ "70%", "70" ], [ "60%", "60" ], [ "50%", "50" ], [ "40%", "40" ], [ "30%", "30" ], [ "20%", "20" ], [ "10%", "10" ], [ "0% ("+MSG['blockOff']+")", "0" ] ] } ], "output": "Number", "colour": OutputBlocksHUE, "tooltip": MSG['blockPwmValueToolTip'] }; var block_on_off = { "message0": MSG['blockOnOffMessage'], "args0": [ { "type": "field_dropdown", "name": "state", "options": [ [ MSG['blockOn'], "100" ], [ MSG['blockOff'], "0" ] ] } ], "output": "Number", "colour": OutputBlocksHUE, "tooltip": MSG['blockOnOffToolTip'] }; var block_output = { "message0": MSG['blockOutputMessage'], "args0": [ { "type": "field_dropdown", "name": "port", "options": [ [ "O1", "0" ], [ "O2", "1" ], [ "O3", "2" ], [ "O4", "3" ], [ "O5", "4" ], [ "O6", "5" ], [ "O7", "6" ], [ "O8", "7" ] ] }, { "type": "input_value", "name": "value", "check": "Number" } ], "previousStatement": null, "nextStatement": null, "colour": OutputBlocksHUE, "tooltip": MSG['blockOutputToolTip'] } var block_io_sync = { "message0": MSG['blockIOSyncMessage'], "args0": [ { "type": "input_dummy" },{ "type": "input_statement", "name": "STATEMENTS" } ], "previousStatement": null, "nextStatement": null, "colour": OutputBlocksHUE, "tooltip": MSG['blockIOSyncToolTip'] }; var block_mobile_config = { "message0": MSG['blockMobileConfigMessage'], "args0": [ { "type": "input_dummy" }, { "type": "field_dropdown", "name": "motor_left", "options": [ [ "M1", "0" ], [ "M2", "1" ], [ "M3", "2" ], [ "M4", "3" ] ] }, { "type": "field_dropdown", "name": "motor_right", "options": [ [ "M1", "0" ], [ "M2", "1" ], [ "M3", "2" ], [ "M4", "3" ] ] }, { "type": "input_value", "name": "motor_type", "check": "Number" }, { "type": "field_number", "name": "gear_ratio_1", "value": 10, "min": 1 }, { "type": "field_number", "name": "gear_ratio_2", "value": 20, "min": 1 }, { "type": "input_dummy" }, { "type": "field_number", "name": "wheel_diam", "value": 5.8, "min": 1 }, { "type": "input_dummy" }, { "type": "field_number", "name": "wheel_dist", "value": 15.4, "min": 1 } ], "previousStatement": null, "nextStatement": null, "colour": MobileBlocksHUE, "tooltip": MSG['blockMobileConfigToolTip'] } var block_mobile_drive = { "message0": MSG['blockMobileDriveMessage'], "args0": [ { "type": "field_dropdown", "name": "dir", "options": [ [ MSG['blockForward'], "1" ], [ MSG['blockBackward'], "-1" ] ] }, { "type": "input_value", "name": "dist", "check": "Number" } ], "previousStatement": null, "nextStatement": null, "colour": MobileBlocksHUE, "tooltip": MSG['blockMobileDriveToolTip'] } var block_mobile_drive_while = { "message0": MSG['blockMobileDriveWhileMessage'], "args0": [ { "type": "field_dropdown", "name": "dir", "options": [ [ MSG['blockForward'], "1" ], [ MSG['blockBackward'], "-1" ] ] }, { "type": "field_dropdown", "name": "while", "options": [ [ MSG['blockWhile'], "True" ], [ MSG['blockUntil'], "False" ] ] }, { "type": "input_value", "name": "value", "check": "Boolean" } ], "previousStatement": null, "nextStatement": null, "colour": MobileBlocksHUE, "tooltip": MSG['blockMobileDriveWhileToolTip'] } var block_mobile_turn = { "message0": MSG['blockMobileTurnMessage'], "args0": [ { "type": "field_dropdown", "name": "dir", "options": [ [ MSG['blockRight'], "1" ], [ MSG['blockLeft'], "-1" ] ] }, { "type": "input_value", "name": "angle", "check": "Number" } ], "previousStatement": null, "nextStatement": null, "colour": MobileBlocksHUE, "tooltip": MSG['blockMobileTurnToolTip'] } var block_simple_angle = { "message0": MSG['blockAngleMessage'], "args0": [ { "type": "field_dropdown", "name": "angle", "options": [ [ MSG['blockRot45'], "45" ], [ MSG['blockRot90'], "90" ], [ MSG['blockRot135'], "135" ], [ MSG['blockRot180'], "180" ] ] } ], "output": "Number", "colour": MobileBlocksHUE, "tooltip": MSG['blockAngleToolTip'] }; var block_angle = { "message0": MSG['blockAngleMessage']+"°", "args0": [ { "type": "field_angle", "name": "angle", "angle": 90 } ], "output": "Number", "colour": MobileBlocksHUE, "tooltip": MSG['blockAngleToolTip'] }; // old motor block var block_motor = { "message0": MSG['blockMotorMessage'], "args0": [ { "type": "field_dropdown", "name": "port", "options": [ [ "M1", "0" ], [ "M2", "1" ], [ "M3", "2" ], [ "M4", "3" ] ] }, { "type": "field_dropdown", "name": "dir", "options": [ [ MSG['blockLeft'] + ' \u21BA', "-1" ], [ MSG['blockRight'] + ' \u21BB', "1" ] ] }, { "type": "input_value", "name": "value", "check": "Number" } ], "previousStatement": null, "nextStatement": null, "colour": OutputBlocksHUE, "tooltip": MSG['blockMotorToolTip'] } // old motor block with distance var block_motor_steps = { "message0": MSG['blockMotorStepsMessage'], "args0": [ { "type": "field_dropdown", "name": "port", "options": [ [ "M1", "0" ], [ "M2", "1" ], [ "M3", "2" ], [ "M4", "3" ] ] }, { "type": "field_dropdown", "name": "dir", "options": [ [ MSG['blockLeft'] + ' \u21BA', "-1" ], [ MSG['blockRight'] + ' \u21BB', "1" ] ] }, { "type": "input_value", "name": "value", "check": "Number" }, { "type": "input_value", "name": "steps", "check": "Number" } ], "previousStatement": null, "nextStatement": null, "colour": OutputBlocksHUE, "tooltip": MSG['blockMotorStepsToolTip'] } var block_motor_set = { "message0": MSG['blockMotorSetMessage'], "args0": [ { "type": "field_dropdown", "name": "port", "options": [ [ "M1", "0" ], [ "M2", "1" ], [ "M3", "2" ], [ "M4", "3" ] ] }, { "type": "field_dropdown", "name": "name", "options": [ [ MSG['blockMotorSetSpeed'], "speed" ], [ MSG['blockMotorSetDir'], "dir" ], [ MSG['blockMotorSetDist'], "dist" ], [ MSG['blockMotorSetGear'], "gear" ] ] }, { "type": "input_value", "name": "value", "check": "Number" } ], "previousStatement": null, "nextStatement": null, "colour": OutputBlocksHUE, "tooltip": MSG['blockMotorSetToolTip'] } var block_motor_sync = { "message0": MSG['blockMotorSyncMessage'], "args0": [ { "type": "field_dropdown", "name": "port_a", "options": [ [ "M1", "0" ], [ "M2", "1" ], [ "M3", "2" ], [ "M4", "3" ] ] }, { "type": "field_dropdown", "name": "port_b", "options": [ [ "M1", "0" ], [ "M2", "1" ], [ "M3", "2" ], [ "M4", "3" ] ] }, ], "previousStatement": null, "nextStatement": null, "colour": OutputBlocksHUE, "tooltip": MSG['blockMotorSyncToolTip'] } var block_left_right = { "message0": MSG['blockLeftRightMessage'], "args0": [ { "type": "field_dropdown", "name": "dir", "options": [ [ MSG['blockLeft'] + ' \u21BA', "-1" ], [ MSG['blockRight'] + ' \u21BB', "1" ] ] } ], "output": "Number", "colour": OutputBlocksHUE, "tooltip": MSG['blockLeftRightToolTip'] }; var block_gear_ratio = { "message0": MSG['blockGearMessage'], "args0": [ { "type": "field_dropdown", "name": "gear_ratio", "options": [ [ MSG['blockGearTXT'], "63" ], [ MSG['blockGearTX'], "75" ] ] } ], "output": "Number", "colour": OutputBlocksHUE, "tooltip": MSG['blockGearToolTip'] }; var block_motor_has_stopped = { "message0": MSG['blockMotorHasStoppedMessage'] , "args0": [ { "type": "field_dropdown", "name": "port", "options": [ [ "M1", "0" ], [ "M2", "1" ], [ "M3", "2" ], [ "M4", "3" ] ] } ], "output": "Boolean", "colour": OutputBlocksHUE, "tooltip": MSG['blockMotorHasStoppedToolTip'] } var block_motor_off = { "message0": MSG['blockMotorOffMessage'], "args0": [ { "type": "field_dropdown", "name": "port", "options": [ [ "M1", "0" ], [ "M2", "1" ], [ "M3", "2" ], [ "M4", "3" ] ] }, { "type": "input_value", "name": "value", "check": "Number" } ], "previousStatement": null, "nextStatement": null, "colour": OutputBlocksHUE, "tooltip": MSG['blockMotorOffToolTip'] } var block_simple_input = { "message0": MSG['blockSimpleInputMessage'], "args0": [ { "type": "field_dropdown", "name": "input_port", "options": [ [ "I1", "0" ], [ "I2", "1" ], [ "I3", "2" ], [ "I4", "3" ], [ "I5", "4" ], [ "I6", "5" ], [ "I7", "6" ], [ "I8", "7" ] ] } ], "output": "Boolean", "colour": InputBlocksHUE, "tooltip": MSG['blockSimpleInputToolTip'] } var block_input = { "message0": MSG['blockInputMessage'], "args0": [ { "type": "field_dropdown", "name": "type", "options": [ [ MSG['blockInputModeVoltage'], '"voltage"' ], [ MSG['blockInputModeSwitch'], '"switch"' ], [ MSG['blockInputModeResistor'], '"resistor"' ], // [ MSG['blockInputModeResistor2'], '"resistor2"' ], [ MSG['blockInputModeUltrasonic'], '"ultrasonic"' ] ] }, { "type": "field_dropdown", "name": "input_port", "options": [ [ "I1", "0" ], [ "I2", "1" ], [ "I3", "2" ], [ "I4", "3" ], [ "I5", "4" ], [ "I6", "5" ], [ "I7", "6" ], [ "I8", "7" ] ] } ], "output": "Number", "colour": InputBlocksHUE, "tooltip": MSG['blockInputToolTip'] } var block_input_converter_r2t = { "message0": MSG['blockInputConvTempMessage'], "args0": [ { "type": "field_dropdown", "name": "system", "options": [ [ "°C", '"degCelsius"' ], [ "°F", '"degFahrenheit"' ], [ "K", '"kelvin"' ] ] }, { "type": "input_value", "name": "value", "check": "Number" } ], "output": "Number", "colour": InputBlocksHUE, "tooltip": MSG['blockInputConvTempToolTip'] } var block_play_snd = { "message0": MSG['blockPlaySndMessage'], "args0": [ { "type": "input_value", "name": "sound_index" } ], "previousStatement": null, "nextStatement": null, "colour": CustomBlocksHUE, "tooltip": MSG['blockPlaySndToolTip'] } var block_sound = { "message0": MSG['blockSoundMessage'], "args0": [ { "type": "field_dropdown", "name": "index", "options": [ [ MSG['blockSoundAirplane'], "1" ], [ MSG['blockSoundAlarm'], "2" ], [ MSG['blockSoundBell'], "3" ], [ MSG['blockSoundBraking'], "4" ], [ MSG['blockSoundCar_horn_long'], "5" ], [ MSG['blockSoundCar_horn_short'], "6" ], [ MSG['blockSoundCrackling_wood'], "7" ], [ MSG['blockSoundExcavator'], "8" ], [ MSG['blockSoundFantasy_1'], "9" ], [ MSG['blockSoundFantasy_2'], "10" ], [ MSG['blockSoundFantasy_3'], "11" ], [ MSG['blockSoundFantasy_4'], "12" ], [ MSG['blockSoundFarm'], "13" ], [ MSG['blockSoundFire_department'], "14" ], [ MSG['blockSoundFire_noises'], "15" ], [ MSG['blockSoundFormula1'], "16" ], [ MSG['blockSoundHelicopter'], "17" ], [ MSG['blockSoundHydraulic'], "18" ], [ MSG['blockSoundMotor_sound'], "19" ], [ MSG['blockSoundMotor_starting'], "20" ], [ MSG['blockSoundPropeller_airplane'], "21" ], [ MSG['blockSoundRoller_coaster'], "22" ], [ MSG['blockSoundShips_horn'], "23" ], [ MSG['blockSoundTractor'], "24" ], [ MSG['blockSoundTruck'], "25" ], [ MSG['blockSoundRobby_1'], "26" ], [ MSG['blockSoundRobby_2'], "27" ], [ MSG['blockSoundRobby_3'], "28" ], [ MSG['blockSoundRobby_4'], "29" ] ] } ], "output": "Number", "colour": CustomBlocksHUE, "tooltip": MSG['blockSoundToolTip'] }; // custom text related blocks var block_text_print_color = { "message0": MSG['blockTextPrintColorMessage'], "args0": [ { "type": "field_colour", "name": "color", "colour": "#ffff00" }, { "type": "input_value", "name": "str" } ], "previousStatement": null, "nextStatement": null, "colour": TextBlocksHUE, "tooltip": MSG['blockTextPrintColorToolTip'] } var block_text_clear = { "message0": MSG['blockTextEraseMessage'], "previousStatement": null, "nextStatement": null, "colour": TextBlocksHUE, "tooltip": MSG['blockTextEraseToolTip'] } // generate python code for custom blocks Blockly.Python['start'] = function(block) { var code = '# program start\n'; return code; }; Blockly.Python['wait'] = function(block) { var value_seconds = Blockly.Python.valueToCode(block, 'seconds', Blockly.Python.ORDER_ATOMIC); if(!value_seconds) value_seconds = 0; return 'wait(%1)\n'.replace('%1', value_seconds); }; Blockly.Python['repeat'] = function(block) { var statements = Blockly.Python.statementToCode(block, 'STATEMENTS'); var code = 'while True:\n' + statements; return code; } Blockly.Python['io_sync'] = function(block) { var statements = Blockly.Python.statementToCode(block, 'STATEMENTS'); var code = 'sync(True)\nif True:\n' + statements + "sync(False)\n"; return code; } Blockly.Python['mobile_config'] = function(block) { var motors = [ block.getFieldValue('motor_left'), block.getFieldValue('motor_right') ]; var motor_type = Blockly.Python.valueToCode(block, 'motor_type', Blockly.Python.ORDER_ATOMIC); var gear = block.getFieldValue('gear_ratio_1') / block.getFieldValue('gear_ratio_2'); var wheels = [ block.getFieldValue('wheel_diam'), block.getFieldValue('wheel_dist') ]; return 'mobileConfig([%1], %2, %3, [%4])\n'.replace('%1', motors).replace('%2', motor_type) .replace('%3', gear).replace('%4', wheels); } Blockly.Python['mobile_drive'] = function(block) { var dir = block.getFieldValue('dir'); var dist = Blockly.Python.valueToCode(block, 'dist', Blockly.Python.ORDER_ATOMIC); return 'mobileDrive(%1, %2)\n'.replace('%1', dir).replace('%2', dist); } Blockly.Python['mobile_drive_while'] = function(block) { var dir = block.getFieldValue('dir'); var w = block.getFieldValue('while'); var value = Blockly.Python.valueToCode(block, 'value', Blockly.Python.ORDER_ATOMIC) || 'False'; // todo: value is only evaluated once!! return 'mobileDriveWhile(%1, %2, \'%3\')\n'.replace('%1', dir).replace('%2', w).replace('%3', value); } Blockly.Python['mobile_turn'] = function(block) { var dir = block.getFieldValue('dir'); var angle = Blockly.Python.valueToCode(block, 'angle', Blockly.Python.ORDER_ATOMIC); return 'mobileTurn(%1, %2)\n'.replace('%1', dir).replace('%2', angle); } Blockly.Python['simple_angle'] = function(block) { var angle = block.getFieldValue('angle'); return [angle, Blockly.Python.ORDER_NONE]; }; Blockly.Python['angle'] = function(block) { var angle = block.getFieldValue('angle'); return [angle, Blockly.Python.ORDER_NONE]; }; Blockly.Python['pwm_value'] = function(block) { var state = block.getFieldValue('state'); return [state, Blockly.Python.ORDER_NONE]; }; Blockly.Python['on_off'] = function(block) { var state = block.getFieldValue('state'); return [state, Blockly.Python.ORDER_NONE]; }; Blockly.Python['left_right'] = function(block) { var dir = block.getFieldValue('dir'); return [dir, Blockly.Python.ORDER_NONE]; }; Blockly.Python['gear_ratio'] = function(block) { var impulses = block.getFieldValue('gear_ratio'); return [impulses, Blockly.Python.ORDER_NONE]; }; Blockly.Python['output'] = function(block) { var port = block.getFieldValue('port'); var value = Blockly.Python.valueToCode(block, 'value', Blockly.Python.ORDER_ATOMIC); return 'setOutput(%1, %2)\n'.replace('%1', port).replace('%2', value); } Blockly.Python['motor_set'] = function(block) { var port = block.getFieldValue('port'); var name = block.getFieldValue('name'); var value = Blockly.Python.valueToCode(block, 'value', Blockly.Python.ORDER_ATOMIC); return 'setMotor(%1, \'%2\', %3)\n'.replace('%1', port).replace('%2', name).replace('%3', value); } Blockly.Python['motor_sync'] = function(block) { var port_a = block.getFieldValue('port_a'); var port_b = block.getFieldValue('port_b'); return 'setMotorSync(%1, %2)\n'.replace('%1', port_a).replace('%2', port_b); } Blockly.Python['motor'] = function(block) { var port = block.getFieldValue('port'); var dir = block.getFieldValue('dir'); var value = Blockly.Python.valueToCode(block, 'value', Blockly.Python.ORDER_ATOMIC); return 'setMotorOld(%1, %2, %3)\n'.replace('%1', port).replace('%2', dir).replace('%3', value); } Blockly.Python['motor_steps'] = function(block) { var port = block.getFieldValue('port'); var dir = block.getFieldValue('dir'); var value = Blockly.Python.valueToCode(block, 'value', Blockly.Python.ORDER_ATOMIC); var steps = Blockly.Python.valueToCode(block, 'steps', Blockly.Python.ORDER_ATOMIC); return 'setMotorOld(%1, %2, %3, %4)\n'.replace('%1', port).replace('%2', dir).replace('%3', value).replace('%4', steps); }; Blockly.Python['motor_has_stopped'] = function(block) { var port = block.getFieldValue('port'); return ['motorHasStopped(%1)'.replace('%1', port), Blockly.Python.ORDER_NONE]; }; Blockly.Python['motor_off'] = function(block) { var port = block.getFieldValue('port'); return 'setMotorOff(%1)\n'.replace('%1', port); } Blockly.Python['simple_input'] = function(block) { var port = block.getFieldValue('input_port'); code = 'getInput("switch", %1)'.replace('%1', port); return [code, Blockly.Python.ORDER_NONE]; } Blockly.Python['input'] = function(block) { var type = block.getFieldValue('type'); var port = block.getFieldValue('input_port'); code = 'getInput(%1, %2)'.replace("%1", type).replace('%2', port); return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Python['input_converter_r2t'] = function(block) { var system = block.getFieldValue('system'); var value = Blockly.Python.valueToCode(block, 'value', Blockly.Python.ORDER_ATOMIC); var code = "inputConvR2T(%1, %2)".replace("%1", system).replace("%2", value); return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Python['play_snd'] = function(block) { var value = Blockly.Python.valueToCode(block, 'sound_index', Blockly.Python.ORDER_ATOMIC); return 'playSound(%1)\n'.replace('%1', value); } Blockly.Python['sound'] = function(block) { var index = block.getFieldValue('index'); return [index, Blockly.Python.ORDER_NONE]; } Blockly.Python['text_clear'] = function(block) { return 'textClear()\n'; } Blockly.Python['text_print_color'] = function(block) { var col = block.getFieldValue('color'); var str = Blockly.Python.valueToCode(block, 'str', Blockly.Python.ORDER_ATOMIC); return 'textPrintColor(\'%1\',%2)\n'.replace('%1', col).replace('%2', str); } function custom_blocks_init() { // make custom blocks known to blockly // the start block has some additional brickly specific magic and // is thus created programmatically Blockly.Blocks['start'] = { init: function() { // add icon and program name to block this.appendDummyInput() .appendField(new Blockly.FieldImage("icon_start.svg", 16, 16, "|>")) .appendField(new Blockly.FieldLabel(htmlDecode(Code.program_name[1]), 'program_name')) this.setNextStatement(true, null); this.setColour(225); this.setTooltip(MSG['blockStartToolTip']); } }; Blockly.Blocks['wait'] = { init: function() { this.jsonInit(block_wait); } }; Blockly.Blocks['repeat'] = { init: function() { this.jsonInit(block_repeat); } }; Blockly.Blocks['js_present'] = { init: function() { this.jsonInit(block_js_present); } }; Blockly.Blocks['js_axis'] = { init: function() { this.jsonInit(block_js_axis); } }; Blockly.Blocks['js_button'] = { init: function() { this.jsonInit(block_js_button); } }; Blockly.Blocks['output'] = { init: function() { this.jsonInit(block_output); } }; Blockly.Blocks['io_sync'] = { init: function() { this.jsonInit(block_io_sync); } }; Blockly.Blocks['mobile_config'] = { init: function() { this.jsonInit(block_mobile_config); } }; Blockly.Blocks['mobile_drive'] = { init: function() { this.jsonInit(block_mobile_drive); } }; Blockly.Blocks['mobile_drive_while'] = { init: function() { this.jsonInit(block_mobile_drive_while); } }; Blockly.Blocks['mobile_turn'] = { init: function() { this.jsonInit(block_mobile_turn); } }; Blockly.Blocks['simple_angle'] = { init: function() { this.jsonInit(block_simple_angle); } }; Blockly.Blocks['angle'] = { init: function() { this.jsonInit(block_angle); } }; Blockly.Blocks['motor_set'] = { init: function() { this.jsonInit(block_motor_set); } }; Blockly.Blocks['motor_sync'] = { init: function() { this.jsonInit(block_motor_sync); } }; Blockly.Blocks['motor'] = { init: function() { this.jsonInit(block_motor); } }; Blockly.Blocks['motor_steps'] = { init: function() { this.jsonInit(block_motor_steps); } }; Blockly.Blocks['motor_has_stopped'] = { init: function() { this.jsonInit(block_motor_has_stopped); } }; Blockly.Blocks['motor_off'] = { init: function() { this.jsonInit(block_motor_off); } }; Blockly.Blocks['simple_input'] = { init: function() { this.jsonInit(block_simple_input); } }; Blockly.Blocks['input'] = { init: function() { this.jsonInit(block_input); } }; Blockly.Blocks['input_converter_r2t'] = { init: function() { this.jsonInit(block_input_converter_r2t); } }; Blockly.Blocks['pwm_value'] = { init: function() { this.jsonInit(block_pwm_value); } }; Blockly.Blocks['on_off'] = { init: function() { this.jsonInit(block_on_off); } }; Blockly.Blocks['left_right'] = { init: function() { this.jsonInit(block_left_right); } }; Blockly.Blocks['gear_ratio'] = { init: function() { this.jsonInit(block_gear_ratio); } }; Blockly.Blocks['play_snd'] = { init: function() { this.jsonInit(block_play_snd); } }; Blockly.Blocks['sound'] = { init: function() { this.jsonInit(block_sound); } }; Blockly.Blocks['text_clear'] = { init: function() { this.jsonInit(block_text_clear); } }; Blockly.Blocks['text_print_color'] = { init: function() { this.jsonInit(block_text_print_color); } }; }
gpl-3.0
opencart-rewrite/opencart-rewrite
upload/admin/controller/payment/pp_pro.php
7751
<?php class ControllerPaymentPPPro extends Controller { private $error = array(); public function index() { $this->load->language('payment/pp_pro'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('setting/setting'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { $this->model_setting_setting->editSetting('pp_pro', $this->request->post); $this->session->data['success'] = $this->language->get('text_success'); $this->response->redirect($this->url->link('extension/payment', 'token=' . $this->session->data['token'], 'SSL')); } $data['heading_title'] = $this->language->get('heading_title'); $data['text_edit'] = $this->language->get('text_edit'); $data['text_enabled'] = $this->language->get('text_enabled'); $data['text_disabled'] = $this->language->get('text_disabled'); $data['text_all_zones'] = $this->language->get('text_all_zones'); $data['text_yes'] = $this->language->get('text_yes'); $data['text_no'] = $this->language->get('text_no'); $data['text_authorization'] = $this->language->get('text_authorization'); $data['text_sale'] = $this->language->get('text_sale'); $data['entry_username'] = $this->language->get('entry_username'); $data['entry_password'] = $this->language->get('entry_password'); $data['entry_signature'] = $this->language->get('entry_signature'); $data['entry_test'] = $this->language->get('entry_test'); $data['entry_transaction'] = $this->language->get('entry_transaction'); $data['entry_total'] = $this->language->get('entry_total'); $data['entry_order_status'] = $this->language->get('entry_order_status'); $data['entry_geo_zone'] = $this->language->get('entry_geo_zone'); $data['entry_status'] = $this->language->get('entry_status'); $data['entry_sort_order'] = $this->language->get('entry_sort_order'); $data['help_test'] = $this->language->get('help_test'); $data['help_total'] = $this->language->get('help_total'); $data['button_save'] = $this->language->get('button_save'); $data['button_cancel'] = $this->language->get('button_cancel'); if (isset($this->error['warning'])) { $data['error_warning'] = $this->error['warning']; } else { $data['error_warning'] = ''; } if (isset($this->error['username'])) { $data['error_username'] = $this->error['username']; } else { $data['error_username'] = ''; } if (isset($this->error['password'])) { $data['error_password'] = $this->error['password']; } else { $data['error_password'] = ''; } if (isset($this->error['signature'])) { $data['error_signature'] = $this->error['signature']; } else { $data['error_signature'] = ''; } $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL') ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_payment'), 'href' => $this->url->link('extension/payment', 'token=' . $this->session->data['token'], 'SSL') ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('payment/pp_pro', 'token=' . $this->session->data['token'], 'SSL') ); $data['action'] = $this->url->link('payment/pp_pro', 'token=' . $this->session->data['token'], 'SSL'); $data['cancel'] = $this->url->link('extension/payment', 'token=' . $this->session->data['token'], 'SSL'); if (isset($this->request->post['pp_pro_username'])) { $data['pp_pro_username'] = $this->request->post['pp_pro_username']; } else { $data['pp_pro_username'] = $this->config->get('pp_pro_username'); } if (isset($this->request->post['pp_pro_password'])) { $data['pp_pro_password'] = $this->request->post['pp_pro_password']; } else { $data['pp_pro_password'] = $this->config->get('pp_pro_password'); } if (isset($this->request->post['pp_pro_signature'])) { $data['pp_pro_signature'] = $this->request->post['pp_pro_signature']; } else { $data['pp_pro_signature'] = $this->config->get('pp_pro_signature'); } if (isset($this->request->post['pp_pro_test'])) { $data['pp_pro_test'] = $this->request->post['pp_pro_test']; } else { $data['pp_pro_test'] = $this->config->get('pp_pro_test'); } if (isset($this->request->post['pp_pro_method'])) { $data['pp_pro_transaction'] = $this->request->post['pp_pro_transaction']; } else { $data['pp_pro_transaction'] = $this->config->get('pp_pro_transaction'); } if (isset($this->request->post['pp_pro_total'])) { $data['pp_pro_total'] = $this->request->post['pp_pro_total']; } else { $data['pp_pro_total'] = $this->config->get('pp_pro_total'); } if (isset($this->request->post['pp_pro_order_status_id'])) { $data['pp_pro_order_status_id'] = $this->request->post['pp_pro_order_status_id']; } else { $data['pp_pro_order_status_id'] = $this->config->get('pp_pro_order_status_id'); } $this->load->model('localisation/order_status'); $data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses(); if (isset($this->request->post['pp_pro_geo_zone_id'])) { $data['pp_pro_geo_zone_id'] = $this->request->post['pp_pro_geo_zone_id']; } else { $data['pp_pro_geo_zone_id'] = $this->config->get('pp_pro_geo_zone_id'); } $this->load->model('localisation/geo_zone'); $data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones(); if (isset($this->request->post['pp_pro_status'])) { $data['pp_pro_status'] = $this->request->post['pp_pro_status']; } else { $data['pp_pro_status'] = $this->config->get('pp_pro_status'); } if (isset($this->request->post['pp_pro_sort_order'])) { $data['pp_pro_sort_order'] = $this->request->post['pp_pro_sort_order']; } else { $data['pp_pro_sort_order'] = $this->config->get('pp_pro_sort_order'); } $data['header'] = $this->load->controller('common/header'); $data['column_left'] = $this->load->controller('common/column_left'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view('payment/pp_pro.tpl', $data)); } protected function validate() { if (!$this->user->hasPermission('modify', 'payment/pp_pro')) { $this->error['warning'] = $this->language->get('error_permission'); } if (!$this->request->post['pp_pro_username']) { $this->error['username'] = $this->language->get('error_username'); } if (!$this->request->post['pp_pro_password']) { $this->error['password'] = $this->language->get('error_password'); } if (!$this->request->post['pp_pro_signature']) { $this->error['signature'] = $this->language->get('error_signature'); } return !$this->error; } }
gpl-3.0
RoyalVeterinaryCollege/Folium
src/Folium.Api/Services/SqlDbService.cs
1384
/** * Copyright 2017 The Royal Veterinary College, jbullock AT rvc.ac.uk * * This file is part of Folium. * * Folium is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Folium is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Folium. If not, see <http://www.gnu.org/licenses/>. */ using System.Data.Common; using System.Data.SqlClient; using Microsoft.Extensions.Options; namespace Folium.Api.Services { public class SqlDbService : IDbService { private readonly string _connectionString; public SqlDbService(IOptions<ConnectionStrings> connectionStrings) { _connectionString = connectionStrings.Value.SqlConnectionString; } public DbConnection GetConnection(string connectionString) { return new SqlConnection(connectionString); } public DbConnection GetConnection() { return GetConnection(_connectionString); } } }
gpl-3.0
CLAMP-IT/moodle
blocks/filtered_course_list/db/upgrade.php
5925
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file keeps track of upgrades to the filtered course list block * * @since 2.5 * @package block_filtered_course_list * @copyright 2016 CLAMP * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Upgrade code for the section links block. * * @param int $oldversion * @return bool */ function xmldb_block_filtered_course_list_upgrade($oldversion) { // Moodle v2.3.0 release upgrade line // Put any upgrade step following this. // Moodle v2.4.0 release upgrade line // Put any upgrade step following this. // Moodle v2.5.0 release upgrade line // Put any upgrade step following this. if ($oldversion < 2014010601) { $oldfiltertype = get_config('moodle', 'block_filtered_course_list/filtertype'); if ($oldfiltertype == 'term') { set_config('block_filtered_course_list/filtertype', 'shortname'); } $oldtermcurrent = get_config('moodle', 'block_filtered_course_list_termcurrent'); if (!empty($oldtermcurrent)) { set_config('block_filtered_course_list_currentshortname', $oldtermcurrent); unset_config('block_filtered_course_list_termcurrent'); } $oldtermfuture = get_config('moodle', 'block_filtered_course_list_termfuture'); if (!empty($oldtermfuture)) { set_config('block_filtered_course_list_futureshortname', $oldtermfuture); unset_config('block_filtered_course_list_termfuture'); } // Main savepoint reached. upgrade_block_savepoint(true, 2014010601, 'filtered_course_list'); } // Moodle v2.6.0 release upgrade line. // Put any upgrade step following this. if ($oldversion < 2015102002) { $fclsettings = array( 'filtertype', 'hideallcourseslink', 'hidefromguests', 'hideothercourses', 'useregex', 'currentshortname', 'currentexpanded', 'futureshortname', 'futureexpanded', 'labelscount', 'categories', 'adminview', 'maxallcourse', 'collapsible', ); $customrubrics = array( 'customlabel', 'customshortname', 'labelexpanded', ); foreach ($fclsettings as $name) { $value = get_config('moodle', 'block_filtered_course_list_' . $name); set_config($name, $value, 'block_filtered_course_list'); unset_config('block_filtered_course_list_' . $name); } for ($i = 1; $i <= 10; $i++) { foreach ($customrubrics as $setting) { $name = $setting . $i; $value = get_config('moodle', 'block_filtered_course_list_' . $name); if (!empty($value)) { set_config($name, $value, 'block_filtered_course_list'); unset_config('block_filtered_course_list_' . $name); } } } // Main savepoint reached. upgrade_block_savepoint(true, 2015102002, 'filtered_course_list'); } if ($oldversion < 2016080801) { $fclcnf = get_config('block_filtered_course_list'); $newcnf = ''; $disabled = ($fclcnf->filtertype == 'categories') ? '' : 'DISABLED '; $expanded = ($fclcnf->collapsible == 0) ? 'expanded' : 'collapsed'; $newcnf = "${disabled}category | $expanded | $fclcnf->categories (catID) | 0 (depth) \n"; $type = ($fclcnf->useregex) ? 'regex' : 'shortname'; $disabled = ($fclcnf->filtertype == 'shortname') ? '' : 'DISABLED '; if ($fclcnf->currentshortname != '') { $expanded = ($fclcnf->currentexpanded || $fclcnf->collapsible == 0) ? 'expanded' : 'collapsed'; $newcnf .= "${disabled}$type | $expanded | Current courses | $fclcnf->currentshortname \n"; } if ($fclcnf->futureshortname != '') { $expanded = ($fclcnf->futureexpanded || $fclcnf->collapsible == 0) ? 'expanded' : 'collapsed'; $newcnf .= "${disabled}$type | $expanded | Future courses | $fclcnf->futureshortname \n"; } for ($i = 1; $i <= 10; $i++) { $labelvarname = "customlabel$i"; $shortnamevarname = "customshortname$i"; $expandedvarname = "labelexpanded$i"; if (property_exists($fclcnf, $labelvarname) && $fclcnf->$labelvarname != '') { $label = $fclcnf->$labelvarname; $label = str_replace('|', '-', $label); $shortname = $fclcnf->$shortnamevarname; $expanded = ($fclcnf->$expandedvarname || $fclcnf->collapsible == 0) ? 'expanded' : 'collapsed'; $disabled = ($i > $fclcnf->labelscount) ? 'DISABLED ' : $disabled; $newcnf .= "${disabled}$type | $expanded | $label | $shortname \n"; } } set_config('filters', $newcnf, 'block_filtered_course_list'); set_config('managerview', $fclcnf->adminview, 'block_filtered_course_list'); upgrade_block_savepoint(true, 2016080801, 'filtered_course_list'); } return true; }
gpl-3.0
lgp171188/BuzzNotifier
src/in/lguruprasad/buzznotifier/MyNotificationManager.java
1932
package in.lguruprasad.buzznotifier; import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; public class MyNotificationManager { private MyNotificationManager() {} public static final int ALARM_NOT_SET = -1; private static AlarmManager getAlarmManager(Context context) { return (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); } private static PendingIntent getIntervalAlarmIntent(Context context) { return PendingIntent.getBroadcast(context, 0, new Intent(context, MyAlarmReceiver.class), 0); } @TargetApi(Build.VERSION_CODES.KITKAT) private static void setRepeatingAlarmKitkatAndAbove(Context context, int interval) { getAlarmManager(context).setExact(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + (interval*1000), getIntervalAlarmIntent(context)); } private static void setRepeatingAlarmDeprecated(Context context, int interval) { getAlarmManager(context).setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),interval*1000, getIntervalAlarmIntent(context)); } public static void setRepeatingAlarm(Context context, int interval) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) setRepeatingAlarmKitkatAndAbove(context, interval); else setRepeatingAlarmDeprecated(context, interval); } public static void setRepeatingAlarm(Context context, int interval, boolean skip_deprecated) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) setRepeatingAlarmKitkatAndAbove(context, interval); else if (skip_deprecated == false) setRepeatingAlarmDeprecated(context, interval); } public static void removeRepeatingAlarm(Context context) { getAlarmManager(context).cancel(getIntervalAlarmIntent(context)); } }
gpl-3.0
EntradaProject/entrada-1x
www-root/core/modules/admin/settings/manage/categories/add.inc.php
22977
<?php /** * Entrada [ http://www.entrada-project.org ] * * Entrada is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Entrada is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Entrada. If not, see <http://www.gnu.org/licenses/>. * * This file is used to add categories in the entrada_clerkship.categories table. * * @author Organisation: Queen's University * @author Unit: School of Medicine * @author Developer:James Ellis <james.ellis@queensu.ca> * @copyright Copyright 2010 Queen's University. All Rights Reserved. * */ if (!defined("PARENT_INCLUDED") || !defined("IN_CATEGORIES")) { exit; } elseif (!isset($_SESSION["isAuthorized"]) || !(bool) $_SESSION["isAuthorized"]) { header("Location: ".ENTRADA_URL); exit; } elseif (!$ENTRADA_ACL->amIAllowed("categories", "create", false)) { $ONLOAD[] = "setTimeout('window.location=\\'".ENTRADA_URL."/admin/settings/manage/".$MODULE."\\'', 15000)"; add_error("Your account does not have the permissions required to use this feature of this module.<br /><br />If you believe you are receiving this message in error please contact <a href=\"mailto:".html_encode($AGENT_CONTACTS["administrator"]["email"])."\">".html_encode($AGENT_CONTACTS["administrator"]["name"])."</a> for assistance."); echo display_error(); application_log("error", "Group [".$_SESSION["permissions"][$ENTRADA_USER->getAccessId()]["group"]."] and role [".$_SESSION["permissions"][$ENTRADA_USER->getAccessId()]["role"]."] does not have access to this module [".$MODULE."]"); } else { if (isset($_GET["mode"]) && $_GET["mode"] == "ajax") { $MODE = "ajax"; } if (isset($_GET["parent_id"]) && ($id = clean_input($_GET["parent_id"], array("notags", "trim")))) { $PARENT_ID = $id; } /** * Fetch a list of available evaluation targets that can be used as Form Types. */ $query = "SELECT * FROM `".CLERKSHIP_DATABASE."`.`category_type` ORDER BY `ctype_parent`, `ctype_id`"; $results = $db->GetAll($query); if ($results) { foreach ($results as $result) { $CATEGORY_TYPES[$result["ctype_id"]] = $result; } } if (isset($MODE) && $MODE == "ajax" && isset($PARENT_ID) && $PARENT_ID) { ob_clear_open_buffers(); $time = time(); switch ($STEP) { case "2" : /** * Required field "category_name" / Category Name */ if (isset($_POST["category_name"]) && ($category_name = clean_input($_POST["category_name"], array("notags", "trim")))) { $PROCESSED["category_name"] = $category_name; } else { $ERROR++; $ERRORSTR[] = "The <strong>Category Name</strong> is a required field."; } /** * Non-required field "category_code" / Category Code */ if (isset($_POST["category_code"]) && ($category_code = clean_input($_POST["category_code"], array("notags", "trim")))) { $PROCESSED["category_code"] = $category_code; } else { $PROCESSED["category_code"] = ""; } $category_dates = Entrada_Utilities::validate_calendars("sub_category", true, false, false); if ((isset($category_dates["start"])) && ((int) $category_dates["start"])) { $PROCESSED["category_start"] = (int) $category_dates["start"]; } else { $ERROR++; $ERRORSTR[] = "The <strong>Category Start</strong> field is required."; } if ((isset($category_dates["finish"])) && ((int) $category_dates["finish"])) { $PROCESSED["category_finish"] = (int) $category_dates["finish"]; } else { $ERROR++; $ERRORSTR[] = "The <strong>Category Finish</strong> field is required."; } /** * Required field "category_type" / Category Type. */ if (isset($_POST["category_type"]) && ($tmp_input = clean_input($_POST["category_type"], "int")) && array_key_exists($tmp_input, $CATEGORY_TYPES)) { $PROCESSED["category_type"] = $tmp_input; } else { $ERROR++; $ERRORSTR[] = "The <strong>Category Type</strong> field is a required field."; } /** * Non-required field "category_desc" / Category Description */ if (isset($_POST["category_desc"]) && ($category_desc = clean_input($_POST["category_desc"], array("notags", "trim")))) { $PROCESSED["category_desc"] = $category_desc; } else { $PROCESSED["category_desc"] = ""; } /** * Required field "category_order" / Category Order */ if (isset($_POST["category_order"]) && ($category_order = clean_input($_POST["category_order"], array("int"))) && $category_order != "-1") { $PROCESSED["category_order"] = clean_input($_POST["category_order"], array("int")) - 1; } else if($category_order == "-1") { $PROCESSED["category_order"] = $category_details["category_order"]; } else { $PROCESSED["category_order"] = 0; } if (!$ERROR) { $query = "SELECT MAX(`category_order`) FROM `".CLERKSHIP_DATABASE."`.`categories` WHERE `category_parent` = ".$db->qstr($PARENT_ID)." AND `category_status` != 'trash' AND (`organisation_id` = ".$db->qstr($ORGANISATION_ID)." OR `organisation_id` IS NULL)"; $count = $db->GetOne($query); if (($count + 1) != $PROCESSED["category_order"]) { $query = "SELECT `category_id` FROM `".CLERKSHIP_DATABASE."`.`categories` WHERE `category_parent` = ".$db->qstr($PARENT_ID)." AND (`organisation_id` = ".$db->qstr($ORGANISATION_ID)." OR `organisation_id` IS NULL) AND `category_status` != 'trash' ORDER BY `category_order` ASC"; $categories = $db->GetAll($query); if ($categories) { $count = 0; foreach ($categories as $category) { if($count === $PROCESSED["category_order"]) { $count++; } if (!$db->AutoExecute("`".CLERKSHIP_DATABASE."`.`categories`", array("category_order" => $count), "UPDATE", "`category_id` = ".$db->qstr($category["category_id"]))) { $ERROR++; $ERRORSTR[] = "There was a problem updating this category in the system. The system administrator was informed of this error; please try again later."; application_log("error", "There was an error updating an category. Database said: ".$db->ErrorMsg()); } $count++; } } } } if (!$ERROR) { $PROCESSED["category_parent"] = $PARENT_ID; $PROCESSED["organisation_id"] = $ORGANISATION_ID; $PROCESSED["updated_date"] = time(); $PROCESSED["updated_by"] = $ENTRADA_USER->getID(); if (!$db->AutoExecute("`".CLERKSHIP_DATABASE."`.`categories`", $PROCESSED, "INSERT") || !($category_id = $db->Insert_Id())) { echo json_encode(array("status" => "error", "msg" => "There was a problem updating this category in the system. The system administrator was informed of this error; please try again later.")); application_log("error", "There was an error updating an category. Database said: ".$db->ErrorMsg()); } else { $PROCESSED["category_id"] = $category_id; echo json_encode(array("status" => "success", "updates" => $PROCESSED)); } } else { echo json_encode(array("status" => "error", "msg" => implode("<br />", $ERRORSTR))); } break; case "1" : default : ?> <script type="text/javascript"> jQuery(function(){ selectCategory('#m_selectCategoryField_<?php echo $time; ?>', <?php echo (isset($PARENT_ID) && $PARENT_ID ? $PARENT_ID : "0"); ?>, 0, <?php echo $ORGANISATION_ID; ?>); selectOrder('#m_selectOrderField_<?php echo $time; ?>', 0, <?php echo (isset($PARENT_ID) && $PARENT_ID ? $PARENT_ID : "0"); ?>, <?php echo $ORGANISATION_ID; ?>); }); </script> <div class="row-fluid"> <form id="sub-category-form" action="<?php echo ENTRADA_URL."/admin/settings/manage/categories"."?".replace_query(array("action" => "add", "step" => 2, "mode" => "ajax")); ?>" method="post" class="form-horizontal"> <div class="display-error hide"></div> <div class="control-group"> <label for="sub_category_type" class="form-required control-label">Category Type</label> <div class="controls"> <select id="sub_category_type" name="category_type" value="<?php echo ((isset($PROCESSED["category_type"])) ? html_encode($PROCESSED["category_type"]) : ""); ?>" class="span5"> <?php foreach ($CATEGORY_TYPES as $type) { echo "<option value=\"".$type["ctype_id"]."\"".($PROCESSED["category_type"] == $type["ctype_id"] ? " selected=\"selected\"" : "").">".html_encode($type["ctype_name"])."</option>\n"; } ?> </select> </div> </div> <div class="control-group"> <label for="sub_category_code" class="form-nrequired control-label">Category Code</label> <div class="controls"> <input type="text" id="sub_category_code" name="category_code" value="<?php echo ((isset($PROCESSED["category_code"])) ? html_encode($PROCESSED["category_code"]) : ""); ?>" class="span5" /> </div> </div> <div class="control-group"> <label for="sub_category_name" class="form-required control-label">Category Name</label> <div class="controls"> <input type="text" id="sub_category_name" name="category_name" value="<?php echo ((isset($PROCESSED["category_name"])) ? html_encode($PROCESSED["category_name"]) : ""); ?>" class="span11" /> </div> </div> <div class="control-group"> <label for="sub_category_desc" class="form-nrequired control-label">Category Description</label> <div class="controls"> <textarea id="sub_category_desc" name="category_desc" class="span11 expandable"><?php echo ((isset($PROCESSED["category_desc"])) ? html_encode($PROCESSED["category_desc"]) : ""); ?></textarea> </div> </div> <!-- Add specific styling for the date input fields. Required because JQueryUI modal dialog styles override Bootstrap --> <style>#sub_category_start_date, #sub_category_finish_date {font-size: 12px;}</style> <?php echo Entrada_Utilities::generate_calendars("sub_category", "Category", true, true, ((isset($PROCESSED["category_start"])) ? $PROCESSED["category_start"] : 0), true, true, ((isset($PROCESSED["category_finish"])) ? $PROCESSED["category_finish"] : 0), false); ?> <div class="control-group"> <label for="category_id" class="form-required control-label">Category Order</label> <div class="controls"> <div id="m_selectOrderField_<?php echo $time; ?>"></div> </div> </div> </form> </div> <?php break; } exit; } else { $BREADCRUMB[] = array("url" => ENTRADA_URL."/admin/settings/manage/categories?".replace_query(array("section" => "add")), "title" => "Add Category"); // Error Checking if ($STEP == 2) { /** * Required field "category_name" / Category Name */ if (isset($_POST["category_name"]) && ($category_name = clean_input($_POST["category_name"], array("notags", "trim")))) { $PROCESSED["category_name"] = $category_name; } else { add_error("The <strong>Category".(isset($category_details["ctype_name"]) && $category_details["ctype_name"] ? " ".$category_details["ctype_name"] : "")." Name</strong> is a required field."); } /** * Non-required field "category_code" / Category Code */ if (isset($_POST["category_code"]) && ($category_code = clean_input($_POST["category_code"], array("notags", "trim")))) { $PROCESSED["category_code"] = $category_code; } else { $PROCESSED["category_code"] = ""; } /** * Required field "category_type" / Category Type. */ if (isset($_POST["category_type"]) && ($tmp_input = clean_input($_POST["category_type"], "int")) && array_key_exists($tmp_input, $CATEGORY_TYPES)) { $PROCESSED["category_type"] = $tmp_input; } else { add_error("The <strong>Category Type</strong> field is required."); } /** * Required field "category_order" / Category Order */ if (isset($_POST["category_order"]) && ($category_order = clean_input($_POST["category_order"], array("int"))) && $category_order != "-1") { $PROCESSED["category_order"] = clean_input($_POST["category_order"], array("int")) - 1; } else if($category_order == "-1") { $PROCESSED["category_order"] = $category_details["category_order"]; } else { $PROCESSED["category_order"] = 0; } /** * Non-required field "category_desc" / Category Description */ if (isset($_POST["category_desc"]) && ($category_desc = clean_input($_POST["category_desc"], array("notags", "trim")))) { $PROCESSED["category_desc"] = $category_desc; } else { $PROCESSED["category_desc"] = ""; } if (!has_error()) { if ($category_details["category_order"] != $PROCESSED["category_order"]) { $query = "SELECT `category_id` FROM `".CLERKSHIP_DATABASE."`.`categories` WHERE `category_parent` = ".$db->qstr($PARENT_ID)." AND (`organisation_id` = ".$db->qstr($ORGANISATION_ID)." OR `organisation_id` IS NULL) AND `category_status` != 'trash' ORDER BY `category_order` ASC"; $categories = $db->GetAll($query); if ($categories) { $count = 0; foreach ($categories as $category) { if ($count === $PROCESSED["category_order"]) { $count++; } if (!$db->AutoExecute("`".CLERKSHIP_DATABASE."`.`categories`", array("category_order" => $count), "UPDATE", "`category_id` = ".$db->qstr($category["category_id"]))) { add_error("There was a problem updating this category in the system. The system administrator was informed of this error; please try again later."); application_log("error", "There was an error updating a category. Database said: ".$db->ErrorMsg()); } $count++; } } } } if (!$ERROR) { $PROCESSED["category_parent"] = 0; $PROCESSED["organisation_id"] = $ORGANISATION_ID; $PROCESSED["updated_date"] = time(); $PROCESSED["updated_by"] = $ENTRADA_USER->getID(); if ($db->AutoExecute("`".CLERKSHIP_DATABASE."`.`categories`", $PROCESSED, "INSERT") || !($category_id = $db->Insert_Id())) { if (!$ERROR) { $url = ENTRADA_URL . "/admin/settings/manage/categories?org=".$ORGANISATION_ID; add_success("You have successfully added <strong>".html_encode($PROCESSED["category_name"])."</strong> to the system.<br /><br />You will now be redirected to the categories index; this will happen <strong>automatically</strong> in 5 seconds or <a href=\"".$url."\" style=\"font-weight: bold\">click here</a> to continue."); $ONLOAD[] = "setTimeout('window.location=\\'".$url."\\'', 5000)"; application_log("success", "New Category [".$category_id."] added to the system."); } } else { add_error("There was a problem updating this category in the system. The system administrator was informed of this error; please try again later."); application_log("error", "There was an error updating an category. Database said: ".$db->ErrorMsg()); } } if (has_error()) { $STEP = 1; } } //Display Content switch ($STEP) { case 2: if (has_success()) { echo display_success(); } if (has_notice()) { echo display_notice(); } if (has_error()) { echo display_error(); } break; case 1: if (has_error()) { echo display_error(); } $HEAD[] = "<script type=\"text/javascript\" src=\"".ENTRADA_RELATIVE."/javascript/clerkship_categories.js?release=".html_encode(APPLICATION_VERSION)."\"></script>"; $ONLOAD[] = "selectOrder('#selectOrderField', 0, ".(isset($PARENT_ID) && $PARENT_ID ? $PARENT_ID : "0").", ".$ORGANISATION_ID.")"; ?> <script type="text/javascript"> var SITE_URL = "<?php echo ENTRADA_URL;?>"; </script> <h1>Add Clinical Rotation Category</h1> <form id="category-form" action="<?php echo ENTRADA_URL."/admin/settings/manage/categories"."?".replace_query(array("action" => "add", "step" => 2)); ?>" method="post" class="form-horizontal"> <div class="control-group"> <label for="category_code" class="form-nrequired control-label">Category Code</label> <div class="controls"> <input type="text" id="category_code" name="category_code" value="<?php echo ((isset($PROCESSED["category_code"])) ? html_encode($PROCESSED["category_code"]) : ""); ?>" class="span5" /> </div> </div> <div class="control-group"> <label for="category_name" class="form-required control-label">Category Name</label> <div class="controls"> <input type="text" id="category_name" name="category_name" value="<?php echo ((isset($PROCESSED["category_name"])) ? html_encode($PROCESSED["category_name"]) : ""); ?>" class="span11" /> </div> </div> <div class="control-group"> <label for="category_desc" class="form-nrequired control-label">Category Description</label> <div class="controls"> <textarea id="category_desc" name="category_desc" class="span11 expandable"><?php echo ((isset($PROCESSED["category_desc"])) ? html_encode($PROCESSED["category_desc"]) : ""); ?></textarea> </div> </div> <input type="hidden" value="1" name="category_type" /> <div class="control-group"> <label for="category_id" class="form-required control-label">Category Order</label> <div class="controls"> <div id="selectOrderField"></div> </div> </div> <div class="control-group"> <a href="<?php echo ENTRADA_URL; ?>/admin/settings/manage/categories?org=<?php echo $ORGANISATION_ID; ?>" class="btn"><?php echo $translate->_("global_button_cancel"); ?></a> <input type="submit" class="btn btn-primary pull-right" value="<?php echo $translate->_("global_button_save"); ?>" /> </div> </form> <?php default: continue; break; } } }
gpl-3.0
ljonka/NFCDoorServer
app/Forms/DoorUserForm.php
1380
<?php namespace App\Forms; use Kris\LaravelFormBuilder\Form; use App\Door; use App\DoorUser; use App\DoorUserGrant; class DoorUserForm extends Form { public function buildForm() { $selected = []; if(isset($this->data['user'])){ $user = $this->data['user']; $grants = DoorUserGrant::where('door_user', '=', $user->id)->get(); foreach($grants as $grant){ $selected[] = $grant->door; } } $doors = Door::all(); $choices = []; foreach($doors as $door){ $choices[$door->id] = $door->name; } $this->add('permissions', 'choice', [ 'choices' => $choices, 'choice_options' => [ //'wrapper' => ['class' => 'choice-wrapper'], 'label_attr' => ['class' => 'label-class'], ], 'selected' => $selected, 'expanded' => true, 'multiple' => true ]); $this ->add('chip_uuid', 'text', ['rules' => 'required', 'attr' => ['readonly' => true]]) ->add('name', 'text', ['rules' => 'required']) ->add('phone', 'text', ['rules' => 'required']) ->add('email', 'email', ['rules' => 'required']) ->add('note', 'text', ['rules' => 'required']) ->add('submit', 'submit', ['label' => 'save']); } }
gpl-3.0
jake577/snaked
SnakeWar-android/gen/com/jesttek/snakeWar/R.java
33309
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.jesttek.snakeWar; public final class R { public static final class attr { /** The size of the ad. It must be one of BANNER, FULL_BANNER, LEADERBOARD, MEDIUM_RECTANGLE, SMART_BANNER, WIDE_SKYSCRAPER, or &lt;width&gt;x&lt;height&gt;. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int adSize=0x7f010000; /** A comma-separated list of the supported ad sizes. The sizes must be one of BANNER, FULL_BANNER, LEADERBOARD, MEDIUM_RECTANGLE, SMART_BANNER, WIDE_SKYSCRAPER, or &lt;width&gt;x&lt;height&gt;. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int adSizes=0x7f010001; /** The ad unit ID. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int adUnitId=0x7f010002; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int cameraBearing=0x7f010004; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int cameraTargetLat=0x7f010005; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int cameraTargetLng=0x7f010006; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int cameraTilt=0x7f010007; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int cameraZoom=0x7f010008; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>0</td><td></td></tr> <tr><td><code>normal</code></td><td>1</td><td></td></tr> <tr><td><code>satellite</code></td><td>2</td><td></td></tr> <tr><td><code>terrain</code></td><td>3</td><td></td></tr> <tr><td><code>hybrid</code></td><td>4</td><td></td></tr> </table> */ public static final int mapType=0x7f010003; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiCompass=0x7f010009; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiRotateGestures=0x7f01000a; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiScrollGestures=0x7f01000b; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiTiltGestures=0x7f01000c; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiZoomControls=0x7f01000d; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int uiZoomGestures=0x7f01000e; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int useViewLifecycle=0x7f01000f; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int zOrderOnTop=0x7f010010; } public static final class color { public static final int common_action_bar_splitter=0x7f040009; /** Sign-in Button Colors */ public static final int common_signin_btn_dark_text_default=0x7f040000; public static final int common_signin_btn_dark_text_disabled=0x7f040002; public static final int common_signin_btn_dark_text_focused=0x7f040003; public static final int common_signin_btn_dark_text_pressed=0x7f040001; public static final int common_signin_btn_default_background=0x7f040008; public static final int common_signin_btn_light_text_default=0x7f040004; public static final int common_signin_btn_light_text_disabled=0x7f040006; public static final int common_signin_btn_light_text_focused=0x7f040007; public static final int common_signin_btn_light_text_pressed=0x7f040005; public static final int common_signin_btn_text_dark=0x7f04000a; public static final int common_signin_btn_text_light=0x7f04000b; } public static final class drawable { public static final int common_signin_btn_icon_dark=0x7f020000; public static final int common_signin_btn_icon_disabled_dark=0x7f020001; public static final int common_signin_btn_icon_disabled_focus_dark=0x7f020002; public static final int common_signin_btn_icon_disabled_focus_light=0x7f020003; public static final int common_signin_btn_icon_disabled_light=0x7f020004; public static final int common_signin_btn_icon_focus_dark=0x7f020005; public static final int common_signin_btn_icon_focus_light=0x7f020006; public static final int common_signin_btn_icon_light=0x7f020007; public static final int common_signin_btn_icon_normal_dark=0x7f020008; public static final int common_signin_btn_icon_normal_light=0x7f020009; public static final int common_signin_btn_icon_pressed_dark=0x7f02000a; public static final int common_signin_btn_icon_pressed_light=0x7f02000b; public static final int common_signin_btn_text_dark=0x7f02000c; public static final int common_signin_btn_text_disabled_dark=0x7f02000d; public static final int common_signin_btn_text_disabled_focus_dark=0x7f02000e; public static final int common_signin_btn_text_disabled_focus_light=0x7f02000f; public static final int common_signin_btn_text_disabled_light=0x7f020010; public static final int common_signin_btn_text_focus_dark=0x7f020011; public static final int common_signin_btn_text_focus_light=0x7f020012; public static final int common_signin_btn_text_light=0x7f020013; public static final int common_signin_btn_text_normal_dark=0x7f020014; public static final int common_signin_btn_text_normal_light=0x7f020015; public static final int common_signin_btn_text_pressed_dark=0x7f020016; public static final int common_signin_btn_text_pressed_light=0x7f020017; public static final int ic_launcher=0x7f020018; public static final int ic_plusone_medium_off_client=0x7f020019; public static final int ic_plusone_small_off_client=0x7f02001a; public static final int ic_plusone_standard_off_client=0x7f02001b; public static final int ic_plusone_tall_off_client=0x7f02001c; } public static final class id { public static final int hybrid=0x7f050004; public static final int none=0x7f050000; public static final int normal=0x7f050001; public static final int satellite=0x7f050002; public static final int terrain=0x7f050003; } public static final class integer { public static final int google_play_services_version=0x7f070000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_id=0x7f06001f; public static final int app_name=0x7f060020; /** Title for notification shown when GooglePlayServices needs to be enabled for a application to work. [CHAR LIMIT=70] */ public static final int auth_client_needs_enabling_title=0x7f060015; /** Title for notification shown when GooglePlayServices needs to be installed for a application to work. [CHAR LIMIT=70] */ public static final int auth_client_needs_installation_title=0x7f060016; /** Title for notification shown when GooglePlayServices needs to be udpated for a application to work. [CHAR LIMIT=70] */ public static final int auth_client_needs_update_title=0x7f060017; /** Title for notification shown when GooglePlayServices is unavailable [CHAR LIMIT=42] */ public static final int auth_client_play_services_err_notification_msg=0x7f060018; /** Requested by string saying which app requested the notification. [CHAR LIMIT=42] */ public static final int auth_client_requested_by_msg=0x7f060019; /** Title for notification shown when a bad version of GooglePlayServices has been installed and needs correction for an application to work. [CHAR LIMIT=70] */ public static final int auth_client_using_bad_version_title=0x7f060014; /** Button in confirmation dialog to enable Google Play services. Clicking it will direct user to application settings of Google Play services where they can enable it [CHAR LIMIT=40] */ public static final int common_google_play_services_enable_button=0x7f060006; /** Message in confirmation dialog informing user they need to enable Google Play services in application settings [CHAR LIMIT=NONE] */ public static final int common_google_play_services_enable_text=0x7f060005; /** Title of confirmation dialog informing user they need to enable Google Play services in application settings [CHAR LIMIT=40] */ public static final int common_google_play_services_enable_title=0x7f060004; /** Button in confirmation dialog for installing Google Play services [CHAR LIMIT=40] */ public static final int common_google_play_services_install_button=0x7f060003; /** (For phones) Message in confirmation dialog informing user that they need to install Google Play services (from Play Store) [CHAR LIMIT=NONE] */ public static final int common_google_play_services_install_text_phone=0x7f060001; /** (For tablets) Message in confirmation dialog informing user that they need to install Google Play services (from Play Store) [CHAR LIMIT=NONE] */ public static final int common_google_play_services_install_text_tablet=0x7f060002; /** Title of confirmation dialog informing user that they need to install Google Play services (from Play Store) [CHAR LIMIT=40] */ public static final int common_google_play_services_install_title=0x7f060000; /** Message in confirmation dialog informing the user that they provided an invalid account. [CHAR LIMIT=NONE] */ public static final int common_google_play_services_invalid_account_text=0x7f06000c; /** Title of confirmation dialog informing the user that they provided an invalid account. [CHAR LIMIT=40] */ public static final int common_google_play_services_invalid_account_title=0x7f06000b; /** Message in confirmation dialog informing the user that a network error occurred. [CHAR LIMIT=NONE] */ public static final int common_google_play_services_network_error_text=0x7f06000a; /** Title of confirmation dialog informing the user that a network error occurred. [CHAR LIMIT=40] */ public static final int common_google_play_services_network_error_title=0x7f060009; /** Message in confirmation dialog informing user there is an unknown issue in Google Play services [CHAR LIMIT=NONE] */ public static final int common_google_play_services_unknown_issue=0x7f06000d; /** Message in confirmation dialog informing user that date on the device is not correct, causing certificate checks to fail. [CHAR LIMIT=NONE] */ public static final int common_google_play_services_unsupported_date_text=0x7f060010; /** Message in confirmation dialog informing user that Google Play services is not supported on their device [CHAR LIMIT=NONE] */ public static final int common_google_play_services_unsupported_text=0x7f06000f; /** Title of confirmation dialog informing user that Google Play services is not supported on their device [CHAR LIMIT=40] */ public static final int common_google_play_services_unsupported_title=0x7f06000e; /** Button in confirmation dialog for updating Google Play services [CHAR LIMIT=40] */ public static final int common_google_play_services_update_button=0x7f060011; /** Message in confirmation dialog informing user that they need to update Google Play services (from Play Store) [CHAR LIMIT=NONE] */ public static final int common_google_play_services_update_text=0x7f060008; /** Title of confirmation dialog informing user that they need to update Google Play services (from Play Store) [CHAR LIMIT=40] */ public static final int common_google_play_services_update_title=0x7f060007; /** Sign-in button text [CHAR LIMIT=15] */ public static final int common_signin_button_text=0x7f060012; /** Long form sign-in button text [CHAR LIMIT=30] */ public static final int common_signin_button_text_long=0x7f060013; public static final int game_problem=0x7f060021; public static final int gamehelper_app_misconfigured=0x7f06001c; public static final int gamehelper_license_failed=0x7f06001d; public static final int gamehelper_sign_in_failed=0x7f06001b; public static final int gamehelper_unknown_error=0x7f06001e; public static final int is_inviting_you=0x7f060023; /** Location client code resources (prefix with location_client) */ public static final int location_client_powered_by_google=0x7f06001a; public static final int network_problem=0x7f060022; } public static final class styleable { /** Attributes that can be used with a AdsAttrs. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #AdsAttrs_adSize com.jesttek.snakeWar:adSize}</code></td><td> The size of the ad.</td></tr> <tr><td><code>{@link #AdsAttrs_adSizes com.jesttek.snakeWar:adSizes}</code></td><td> A comma-separated list of the supported ad sizes.</td></tr> <tr><td><code>{@link #AdsAttrs_adUnitId com.jesttek.snakeWar:adUnitId}</code></td><td> The ad unit ID.</td></tr> </table> @see #AdsAttrs_adSize @see #AdsAttrs_adSizes @see #AdsAttrs_adUnitId */ public static final int[] AdsAttrs = { 0x7f010000, 0x7f010001, 0x7f010002 }; /** <p> @attr description The size of the ad. It must be one of BANNER, FULL_BANNER, LEADERBOARD, MEDIUM_RECTANGLE, SMART_BANNER, WIDE_SKYSCRAPER, or &lt;width&gt;x&lt;height&gt;. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.jesttek.snakeWar:adSize */ public static final int AdsAttrs_adSize = 0; /** <p> @attr description A comma-separated list of the supported ad sizes. The sizes must be one of BANNER, FULL_BANNER, LEADERBOARD, MEDIUM_RECTANGLE, SMART_BANNER, WIDE_SKYSCRAPER, or &lt;width&gt;x&lt;height&gt;. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.jesttek.snakeWar:adSizes */ public static final int AdsAttrs_adSizes = 1; /** <p> @attr description The ad unit ID. <p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. <p>This is a private symbol. @attr name com.jesttek.snakeWar:adUnitId */ public static final int AdsAttrs_adUnitId = 2; /** Attributes that can be used with a MapAttrs. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #MapAttrs_cameraBearing com.jesttek.snakeWar:cameraBearing}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_cameraTargetLat com.jesttek.snakeWar:cameraTargetLat}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_cameraTargetLng com.jesttek.snakeWar:cameraTargetLng}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_cameraTilt com.jesttek.snakeWar:cameraTilt}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_cameraZoom com.jesttek.snakeWar:cameraZoom}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_mapType com.jesttek.snakeWar:mapType}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiCompass com.jesttek.snakeWar:uiCompass}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiRotateGestures com.jesttek.snakeWar:uiRotateGestures}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiScrollGestures com.jesttek.snakeWar:uiScrollGestures}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiTiltGestures com.jesttek.snakeWar:uiTiltGestures}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiZoomControls com.jesttek.snakeWar:uiZoomControls}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_uiZoomGestures com.jesttek.snakeWar:uiZoomGestures}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_useViewLifecycle com.jesttek.snakeWar:useViewLifecycle}</code></td><td></td></tr> <tr><td><code>{@link #MapAttrs_zOrderOnTop com.jesttek.snakeWar:zOrderOnTop}</code></td><td></td></tr> </table> @see #MapAttrs_cameraBearing @see #MapAttrs_cameraTargetLat @see #MapAttrs_cameraTargetLng @see #MapAttrs_cameraTilt @see #MapAttrs_cameraZoom @see #MapAttrs_mapType @see #MapAttrs_uiCompass @see #MapAttrs_uiRotateGestures @see #MapAttrs_uiScrollGestures @see #MapAttrs_uiTiltGestures @see #MapAttrs_uiZoomControls @see #MapAttrs_uiZoomGestures @see #MapAttrs_useViewLifecycle @see #MapAttrs_zOrderOnTop */ public static final int[] MapAttrs = { 0x7f010003, 0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009, 0x7f01000a, 0x7f01000b, 0x7f01000c, 0x7f01000d, 0x7f01000e, 0x7f01000f, 0x7f010010 }; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#cameraBearing} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:cameraBearing */ public static final int MapAttrs_cameraBearing = 1; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#cameraTargetLat} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:cameraTargetLat */ public static final int MapAttrs_cameraTargetLat = 2; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#cameraTargetLng} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:cameraTargetLng */ public static final int MapAttrs_cameraTargetLng = 3; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#cameraTilt} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:cameraTilt */ public static final int MapAttrs_cameraTilt = 4; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#cameraZoom} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:cameraZoom */ public static final int MapAttrs_cameraZoom = 5; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#mapType} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>0</td><td></td></tr> <tr><td><code>normal</code></td><td>1</td><td></td></tr> <tr><td><code>satellite</code></td><td>2</td><td></td></tr> <tr><td><code>terrain</code></td><td>3</td><td></td></tr> <tr><td><code>hybrid</code></td><td>4</td><td></td></tr> </table> @attr name com.jesttek.snakeWar:mapType */ public static final int MapAttrs_mapType = 0; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#uiCompass} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:uiCompass */ public static final int MapAttrs_uiCompass = 6; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#uiRotateGestures} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:uiRotateGestures */ public static final int MapAttrs_uiRotateGestures = 7; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#uiScrollGestures} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:uiScrollGestures */ public static final int MapAttrs_uiScrollGestures = 8; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#uiTiltGestures} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:uiTiltGestures */ public static final int MapAttrs_uiTiltGestures = 9; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#uiZoomControls} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:uiZoomControls */ public static final int MapAttrs_uiZoomControls = 10; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#uiZoomGestures} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:uiZoomGestures */ public static final int MapAttrs_uiZoomGestures = 11; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#useViewLifecycle} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:useViewLifecycle */ public static final int MapAttrs_useViewLifecycle = 12; /** <p>This symbol is the offset where the {@link com.jesttek.snakeWar.R.attr#zOrderOnTop} attribute's value can be found in the {@link #MapAttrs} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.jesttek.snakeWar:zOrderOnTop */ public static final int MapAttrs_zOrderOnTop = 13; }; }
gpl-3.0
simoninireland/epydemic
epydemic/gf/continuous_gf.py
3791
# Continuous generating functions # # Copyright (C) 2021 Simon Dobson # # This file is part of epydemic, epidemic network simulations in Python. # # epydemic is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # epydemic is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with epydemic. If not, see <http://www.gnu.org/licenses/gpl.html>. from typing import Callable import numpy from mpmath import factorial from epydemic.gf import GF class ContinuousGF(GF): '''A continuous generating function. These generating functions are constructed from power series provided by functions, optionally differentiated some number of times. Note that computing the coefficients of a continuous generating function uses Cauchy's method, so the function needs to be able to handle complex numbers in its arguments. Typically this means using functions from ``numpy`` or ``cmath``, rather than simply from ``math``. These calculations also lead to large intermediate results, so functions from ``mpmath`` can also be useful. This approach is however able to extract coefficients of high degree. :param f: the function defining the power series :param order: (optional) the order of derivative represented (defaults to 0) ''' def __init__(self, f: Callable[[float], float], order: int = 0): super().__init__() self._f = f self._order = order # make sure the function vectorises if not isinstance(self._f, numpy.vectorize): self._f = numpy.vectorize(self._f) def _differentiate(self, z: float, n: int = 1, r: float = 1.0, dx: float = 1e-2) -> complex: '''Compute the n'th derivative of f at z using a Cauchy contour integral of radius r. :param z: point at which to find the derivative :param n: order of derivative (defaults to 1) :param r: radius of contour (defaults to 1.0) :param dx: step size (defaults to 1e-2)''' # increase the requested order of derivative by whatever we have intrinsically n += self._order # simple evaluation if we've got no derivatives to compute if n == 0: return self._f(z) # perform the Cauchy contour integral x = r * numpy.exp(2j * numpy.pi * numpy.arange(0, 1, dx)) return factorial(n) * numpy.mean(self._f(z + x) / x**n) def getCoefficient(self, i: int) -> float: '''Return the i'th coefficient. :param i: the index :returns: the coefficient of x^i''' # we need to adapt the step distance for the integration # so that it is smaller than 1 / i step = 1 / (numpy.ceil((i + 1) / 99) * 100) return float((self._differentiate(0.0, i, dx=step) / factorial(i)).real) def evaluate(self, x: float) -> float: '''Evaluate the generating function. :param x: the argument :returns: the value of the generating function''' return self._differentiate(x, 0).real def derivative(self, order: int = 1) -> GF: '''Return the requested derivative. This creates a new generating function over the same underlying series. :param order: (optional) order of derivative (defaults to 1) :returns: a generating function''' return ContinuousGF(self._f, self._order + order)
gpl-3.0
atilacamurca/guia-aberto-android-contatos
app/src/androidTest/java/exemplo/android/guia/contatos/ApplicationTest.java
360
package exemplo.android.guia.contatos; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
gpl-3.0
killbug2004/wdbgark
src/wdbgark.hpp
10709
/* * WinDBG Anti-RootKit extension * Copyright © 2013-2015 Vyacheslav Rusakoff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * This work is licensed under the terms of the GNU GPL, version 3. See * the COPYING file in the top-level directory. */ #if _MSC_VER > 1000 #pragma once #endif #ifndef WDBGARK_HPP_ #define WDBGARK_HPP_ #undef EXT_CLASS #define EXT_CLASS wa::WDbgArk #include <engextcpp.hpp> #if defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #endif // _DEBUG #include <string> #include <sstream> #include <map> #include <vector> #include <memory> #include <utility> #include <functional> #include "objhelper.hpp" #include "colorhack.hpp" #include "dummypdb.hpp" #include "systemver.hpp" #include "typedefs.hpp" #include "symcache.hpp" #include "ver.hpp" namespace wa { ////////////////////////////////////////////////////////////////////////// // main class ////////////////////////////////////////////////////////////////////////// class WDbgArk : public ExtExtension { public: ////////////////////////////////////////////////////////////////////////// using RemoteTypedCallback = std::function<HRESULT(WDbgArk* wdbg_ark_class, const ExtRemoteTyped &object, void* context)>; using RemoteDataCallback = std::function<HRESULT(WDbgArk* wdbg_ark_class, const ExtRemoteData &object, void* context)>; ////////////////////////////////////////////////////////////////////////// WDbgArk(); HRESULT __thiscall Initialize(void) { m_ExtMajorVersion = VER_MAJOR; m_ExtMinorVersion = VER_MINOR; return S_OK; } // this one is called _before_ main class destructor, but ExtExtension class is already dead // so, don't output any errors in these routines, don't call g_Ext->m_Something and so on void __thiscall Uninitialize(void) { if ( m_symbols3_iface.IsSet() ) { m_dummy_pdb->RemoveDummyPdbModule(m_symbols3_iface); // unload dummypdb fake module RemoveSyntheticSymbols(); // remove our symbols EXT_RELEASE(m_symbols3_iface); } } ////////////////////////////////////////////////////////////////////////// // main commands ////////////////////////////////////////////////////////////////////////// EXT_COMMAND_METHOD(wa_ver); EXT_COMMAND_METHOD(wa_scan); EXT_COMMAND_METHOD(wa_systemcb); EXT_COMMAND_METHOD(wa_objtype); EXT_COMMAND_METHOD(wa_objtypeidx); EXT_COMMAND_METHOD(wa_objtypecb); EXT_COMMAND_METHOD(wa_callouts); EXT_COMMAND_METHOD(wa_pnptable); EXT_COMMAND_METHOD(wa_ssdt); EXT_COMMAND_METHOD(wa_w32psdt); EXT_COMMAND_METHOD(wa_checkmsr); EXT_COMMAND_METHOD(wa_idt); EXT_COMMAND_METHOD(wa_gdt); EXT_COMMAND_METHOD(wa_colorize); EXT_COMMAND_METHOD(wa_crashdmpcall); EXT_COMMAND_METHOD(wa_haltables); EXT_COMMAND_METHOD(wa_drvmajor); EXT_COMMAND_METHOD(wa_cicallbacks); ////////////////////////////////////////////////////////////////////////// // init ////////////////////////////////////////////////////////////////////////// bool Init(void); bool IsInited(void) const { return m_inited; } bool IsLiveKernel(void) const { return ((m_DebuggeeClass == DEBUG_CLASS_KERNEL) && (m_DebuggeeQual == DEBUG_KERNEL_CONNECTION)); } void RequireLiveKernelMode(void) const throw(...) { if ( !IsLiveKernel() ) { throw ExtStatusException(S_OK, "live kernel-mode only"); } } ////////////////////////////////////////////////////////////////////////// // walk routines ////////////////////////////////////////////////////////////////////////// void WalkExCallbackList(const std::string &list_count_name, const unsigned __int64 offset_list_count, const unsigned __int32 routine_count, const std::string &list_head_name, const unsigned __int64 offset_list_head, const unsigned __int32 array_distance, const std::string &type, walkresType* output_list); void WalkAnyListWithOffsetToRoutine(const std::string &list_head_name, const unsigned __int64 offset_list_head, const unsigned __int32 link_offset, const bool is_double, const unsigned __int32 offset_to_routine, const std::string &type, const std::string &ext_info, walkresType* output_list); void WalkAnyListWithOffsetToObjectPointer(const std::string &list_head_name, const unsigned __int64 offset_list_head, const bool is_double, const unsigned __int32 offset_to_object_pointer, void* context, RemoteDataCallback callback); void WalkDeviceNode(const unsigned __int64 device_node_address, void* context, RemoteTypedCallback callback); void WalkShutdownList(const std::string &list_head_name, const std::string &type, walkresType* output_list); void WalkPnpLists(const std::string &type, walkresType* output_list); void WalkCallbackDirectory(const std::string &type, walkresType* output_list); void WalkAnyTable(const unsigned __int64 table_start, const unsigned __int32 offset_table_skip_start, const unsigned __int32 table_count, const std::string &type, walkresType* output_list, bool break_on_null = false, bool collect_null = false); void AddSymbolPointer(const std::string &symbol_name, const std::string &type, const std::string &additional_info, walkresType* output_list); void WalkDirectoryObject(const unsigned __int64 directory_address, void* context, RemoteTypedCallback callback); private: ////////////////////////////////////////////////////////////////////////// // callback routines ////////////////////////////////////////////////////////////////////////// static HRESULT DirectoryObjectCallback(WDbgArk* wdbg_ark_class, const ExtRemoteTyped &object, void* context); static HRESULT ShutdownListCallback(WDbgArk*, const ExtRemoteData &object_pointer, void* context); static HRESULT DirectoryObjectTypeCallback(WDbgArk*, const ExtRemoteTyped &object, void* context); static HRESULT DirectoryObjectTypeCallbackListCallback(WDbgArk* wdbg_ark_class, const ExtRemoteTyped &object, void* context); static HRESULT DeviceNodeCallback(WDbgArk* wdbg_ark_class, const ExtRemoteTyped &device_node, void* context); ////////////////////////////////////////////////////////////////////////// // helpers ////////////////////////////////////////////////////////////////////////// void CallCorrespondingWalkListRoutine(const callbacksInfo::const_iterator &citer, walkresType* output_list); ////////////////////////////////////////////////////////////////////////// // private inits ////////////////////////////////////////////////////////////////////////// bool FindDbgkLkmdCallbackArray(); void InitCallbackCommands(void); void InitCalloutNames(void); void InitGDTSelectors(void); void InitHalTables(void); WDbgArkAnalyzeWhiteList::WhiteListEntries GetObjectTypesWhiteList(void); WDbgArkAnalyzeWhiteList::WhiteListEntries GetDriversWhiteList(void); ////////////////////////////////////////////////////////////////////////// void RemoveSyntheticSymbols(void); private: ////////////////////////////////////////////////////////////////////////// // variables ////////////////////////////////////////////////////////////////////////// bool m_inited; bool m_is_cur_machine64; callbacksInfo m_system_cb_commands; std::vector<std::string> m_callout_names; std::vector<unsigned __int32> m_gdt_selectors; haltblInfo m_hal_tbl_info; std::vector<DEBUG_MODULE_AND_ID> m_synthetic_symbols; std::shared_ptr<WDbgArkSymCache> m_sym_cache; std::unique_ptr<WDbgArkObjHelper> m_obj_helper; std::unique_ptr<WDbgArkColorHack> m_color_hack; std::unique_ptr<WDbgArkDummyPdb> m_dummy_pdb; std::unique_ptr<WDbgArkSystemVer> m_system_ver; ExtCheckedPointer<IDebugSymbols3> m_symbols3_iface; ////////////////////////////////////////////////////////////////////////// // output streams ////////////////////////////////////////////////////////////////////////// std::stringstream out; std::stringstream warn; std::stringstream err; }; } // namespace wa #endif // WDBGARK_HPP_
gpl-3.0
Mrkwtkr/shinsei
src/main/java/com/megathirio/shinsei/item/powder/ItemOpalPowder.java
309
package com.megathirio.shinsei.item.powder; import com.megathirio.shinsei.item.PowderShinsei; import com.megathirio.shinsei.reference.Names; public class ItemOpalPowder extends PowderShinsei { public ItemOpalPowder(){ super(); this.setUnlocalizedName(Names.Powders.OPAL_POWDER); } }
gpl-3.0
NightsWatch/open-course
models/exams.php
5006
<?php include_once 'dbs.php'; class exams { private $id, $assnno, $deadline, $maxmarks, $extension, $path, $assn_name, $courseid; function __construct() { $db= New dbs(); $db->connect(); $this->id= NULL; $this->extension=NULL; $this->path=NULL; $this->courseid=NULL; } public function uploadQuestions($examtitle, $courseid, $maxmarks, $weightage) { echo "eneted"; if(!isset($_FILES["file"])) { echo 'File not chosen'; return -1; } $upFile = $_FILES["file"]; $allowedExts = array("pdf","docx","doc","ppt","zip","rar","xlsx","pptx","xls","txt","c","cpp","tar.gz","tar","java","py","sql"); $extension = end(explode(".", $_FILES["file"]["name"])); $extension = strtolower($extension); if(in_array($extension, $allowedExts)) { if($upFile["error"] > 0) { echo "Error Uploading"; return -1; } else { $this->examtitle= $examtitle; $this->weightage= $weightage; $this->maxmarks= $maxmarks; $this->courseid=$courseid; $this->extension=$extension; $this->add(); // move from servers temporary copy to the assignmets folder if(!move_uploaded_file ($upFile["tmp_name"], $this->path) ) return -1; else{ //$assignments= New assignments(); //$assignments->addAssignNotifs($this->id); return 1; } } } else { echo "Invalid extension"; return -2; } } public function uploadSolution($examid,$studid,$marks) { if(!isset($_FILES["file"])) { echo 'File not chosen'; return -1; } $upFile = $_FILES["file"]; $allowedExts = array("pdf","docx","doc","ppt","zip","rar","xlsx","pptx","xls","txt","c","cpp","tar.gz","tar","java","py","sql"); $extension = end(explode(".", $_FILES["file"]["name"])); $extension = strtolower($extension); if(in_array($extension, $allowedExts)) { if($upFile["error"] > 0) { echo "Error Uploading Submission"; return -1; } else { echo "uploading\n"; $this->extension=$extension; $this->id=$examid; $this->submit($examid,$studid,$marks); // move from servers temporary copy to the assignmets folder if(!move_uploaded_file ($upFile["tmp_name"], $this->path) ) return -1; else return 1; } } else { echo "Invalid extension"; return -2; } } public function getExamDetails($examid) { $query="select * from exams where examid='".$examid."';"; $result = mysql_query($query); return mysql_fetch_array($result); } public function getCourseidFromExamid($examid) { $query = "select courseid from exams where examid='".$examid."';"; $result = mysql_query($query); $row = mysql_fetch_array($result); return $row['courseid']; } public function add() { $query = "INSERT INTO ".DBNAME.".exams (examid, examtitle, courseid, maxmarks, weightage) values ( DEFAULT,'".$this->examtitle."','".$this->courseid."','".$this->maxmarks."','".$this->maxmarks."');"; echo "adding"; $result= mysql_query($query); if($result) { $this->id=intval(mysql_insert_id()); $this->path= "../exams/questions/".$this->id.'.'.$this->extension; $query= "UPDATE ".DBNAME.".exams SET FILEPATH='".$this->path."' where examid='".$this->id."';"; $result= mysql_query($query); if($result) return 1; echo "Error: ".mysql_error(); } echo "Error: ".mysql_error(); return 0; } public function submit($examid,$studid,$marks) { $details = $this->getExamDetails($examid); echo $details['maxmarks']; if($marks>$details['maxmarks']) return -1; $query = "INSERT INTO ".DBNAME.".examsolutions (solid, studentid, examid, marks) values ( DEFAULT,'".$studid."','".$this->id."','".$marks."');"; echo $query; //echo "Inserting"; $result= mysql_query($query); if($result) { $this->id=intval(mysql_insert_id()); //echo "updating ".$this->id; echo $this->id; $this->path= "../exams/solutions/".$this->id.'.'.$this->extension; echo $this->path; $query= "UPDATE examsolutions SET filepath='".$this->path."' where solid='".$this->id."';"; echo $query; $output= mysql_query($query); echo $output; if($output) { echo mysql_error(); return 1; } echo "Error: ".mysql_error(); } echo "Error: ".mysql_error(); return 0; } public function updateMarks($studid,$examid,$marks) { $query="update examsolutions set marks='".$marks."',reeval='no' where examid='".$examid."' and studentid='".$studid."';"; echo $query; $result = mysql_query($query); if($result) { return 1; } else { echo mysql_error(); return 0; } } public function updateReeval($studid,$examid,$comments) { $query="update examsolutions set reeval='yes',studcomments='".$comments."' where examid='".$examid."' and studentid='".$studid."';"; echo $query; $result = mysql_query($query); if($result) { return 1; } else { echo mysql_error(); return 0; } } } ?>
gpl-3.0
Yoon-jae/Algorithm_BOJ
problem/2954/2954.cpp
608
#include <iostream> #include <vector> #include <algorithm> using namespace std; char vowel[5] = {'a','e','i','o','u'}; int main() { vector<char> v; string in; getline(cin,in); for(int i=0; i<in.size(); i++) { char ch = in[i]; bool found = false; for(int j=0; j<5; j++) { if(vowel[j] == ch) { found = true; break; } } v.push_back(ch); if(found) i += 2; } for(int i=0; i<v.size(); i++) cout << v[i]; }
gpl-3.0
anadon/madlib
include/graph.hpp
15522
/*Copyright 2016-2018 Josh Marshall********************************************/ /******************************************************************************* This file is part of Madlib. Madlib is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version the GNU Affero Genral Public License version 1 of the License, or (at your option) any later version. Madlib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Madlib. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ /***************************************************************************//** @file @brief A graph implementation with the goal to be general enough and high quality enough to propose for inclusion to the C++ Standard Template Library. The structure to allow for such general usage of the most flexible and dynamic data structure incur some overhead, both in performance penalty in many applications and code complexity in how a graph is implemented. However, in the general case this should be preferable over trying to create a new graph for each application. Some pains have been taking in the design of this graph to allow for multiple simultaneous back end graph implementations with all their individual trade offs and complexities while still remaining fully interoperable and with a stable API. This graph file consists of three primary layers. Most broadly are the graph prototype classes, graph_prototype, vertex_prototype, and edge_prototype. The interface users see and use is the "graph" class, and the implemented vertexes and edges whose interface is defined by the prototypes. The middle layer is the implementation. The implementation included here is called "general_graph" and has theoretical best case performance for all operations. The graph_prototype, vertex_prototype, and edge_prototype define the interface which must be implemented by the graph implementation and the "graph" class proper as well as their respected edge and vertex implementations. The prototypes define interfaces to expand vertexes with their "other_vertex" function call if a expansion function is provided. Prototypes also define standard getters, setters, and iterators. The graph_prototype defines iterators over all edges and vertexes sperately. Vertexes befine iterators over incomming edges, outgoing edges, undirected edges, connected incomming vertexes, connected outgoing vertexes, and connected undirected vertexes. Edges may connect two vertexes, but must be attached to at least one; this is to allow for dynamic expansion. The "graph" class forwards inputs to a graph implementation which implements graph_prototype which it passed at a template paramater. It does not wrap edges or vertexes as that is effectely handled by these extending edge_prototype and vertex_prototpe respectively. For the structure, great flexability is afforded to the actual graph implementation, which is enabled to make calls to the overall graph structure and everything in it in a freeform way while also still enforcing interface correctness. The graph implementation must extend graph_prototype, be templated with the two template parameters T and U, and implement all functions in graph_prototype. The implementation has no restrictions on additional implemented functions, as some will be nessicary for all implementations except the incorrect and extremely suboptimal. The included implementation, general_graph, general_vertex, and general_edge use a hashmap based implementation, where single copies of all edges are help in general_graph, and edges and vertexes contain indexes into general_graph's internal store of vertexes and edges. Iterators in vertex are custom implemented in order to account for this unorthodox structure and still work. Future versions will include a matrix representation based off of valarray, which should come with an interesting set of tradeoffs making some operations significantly faster. Future work will also include support for special operations to make common algorithms faster once the logistics of these become known TODO: Tweak paramaterization to allow for transparent distributed computation and use of this data structure. That should help large scale operations, scalability, and hopefully compliance and features past the 2020 standard. TODO: Add a matrix backed implementation using sparse and dense upper diagonal matrixes. TODO: Add new tests to the test suite using RapidCheck. TODO: File save/open support. TODO: Peer review on IRC and standards forum. TODO: Add void edge value specialization. *******************************************************************************/ #pragma once //////////////////////////////////////////////////////////////////////////////// //INCLUDES////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #include <csignal> #include <general_graph.hpp> #include <graph_prototype.hpp> #include <iostream> #include <stdlib.h> #include <unistd.h> #include <unordered_map> #include <vector> #include <graph_prototype.hpp> #include <general_graph.hpp> //////////////////////////////////////////////////////////////////////////////// //GENERIC GRAPH INTERFACE/////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// template< typename T, typename U, typename T_A = std::allocator<T>, typename U_A = std::allocator<U>, typename Graph_Implementation = general_graph<T, U, T_A, U_A> > class graph : graph_prototype<T, U, T_A, U_A, typename Graph_Implementation::GRAPH_TYPES>{ Graph_Implementation wrapping_graph; public: typedef typename Graph_Implementation::GRAPH_TYPES GRAPH_TYPES; typedef typename GRAPH_TYPES::EDGE_ITERATOR_IN_GRAPH EDGE_ITERATOR_IN_GRAPH; typedef typename GRAPH_TYPES::VERTEX_ITERATOR_IN_GRAPH VERTEX_ITERATOR_IN_GRAPH; typedef vertex_prototype<T, U, T_A, U_A, typename Graph_Implementation::GRAPH_TYPES> VERTEX; typedef edge_prototype<T, U, T_A, U_A, typename Graph_Implementation::GRAPH_TYPES> EDGE; graph( size_t reserve_n_vertexes = 0, size_t reserve_n_edges = 0, vertex_prototype<T, U, T_A, U_A, GRAPH_TYPES>* (*dynamic_vertex_generator_function)( vertex_prototype<T, U, T_A, U_A, GRAPH_TYPES>*, edge_prototype<T, U, T_A, U_A, GRAPH_TYPES>*) = nullptr); graph( const graph_prototype<T, U, T_A, U_A, GRAPH_TYPES> *other); void add_vertex( T value); VERTEX_ITERATOR_IN_GRAPH begin_vertexes(); VERTEX_ITERATOR_IN_GRAPH end_vertexes(); VERTEX_ITERATOR_IN_GRAPH begin_vertexes() const; VERTEX_ITERATOR_IN_GRAPH end_vertexes() const; size_t vertex_count() const; T remove_vertex( VERTEX *vertex); void reserve_vertexes( size_t n); void shrink_to_fit_vertexes(); void add_undirected_edge( const VERTEX *vertex1, const VERTEX *vertex2, U weight); void add_directed_edge( const VERTEX *from_vertex, const VERTEX *to_vertex, U weight); EDGE* get_undirected_edge( const VERTEX *vertex1, const VERTEX *vertex2, U weight); EDGE* get_directed_edge( const VERTEX *from_vertex, const VERTEX *to_vertex); U remove_undirected_edge( const VERTEX *vertex1, const VERTEX *vertex2); U remove_directed_edge( const VERTEX *from_vertex, const VERTEX *to_vertex); void reserve_edges( size_t n); void shrink_to_fit_edges(); EDGE_ITERATOR_IN_GRAPH begin_edges(); EDGE_ITERATOR_IN_GRAPH end_edges(); EDGE_ITERATOR_IN_GRAPH begin_edges() const; EDGE_ITERATOR_IN_GRAPH end_edges() const; }; template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > graph<T, U, T_A, U_A, Graph_Implementation>:: graph( size_t reserve_n_vertexes, size_t reserve_n_edges, vertex_prototype<T, U, T_A, U_A, GRAPH_TYPES>* (*dynamic_vertex_generator_function)( vertex_prototype<T, U, T_A, U_A, GRAPH_TYPES>*, edge_prototype<T, U, T_A, U_A, GRAPH_TYPES>*) ) : wrapping_graph(Graph_Implementation( reserve_n_vertexes, reserve_n_edges, dynamic_vertex_generator_function)){ } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > graph<T, U, T_A, U_A, Graph_Implementation>:: graph( const graph_prototype<T, U, T_A, U_A, GRAPH_TYPES> *other ){ assert(other != nullptr); graph_implementation(other); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > void graph<T, U, T_A, U_A, Graph_Implementation>::add_vertex( T value ){ wrapping_graph.add_vertex(value); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > typename graph<T, U, T_A, U_A, Graph_Implementation>::VERTEX_ITERATOR_IN_GRAPH graph<T, U, T_A, U_A, Graph_Implementation>:: begin_vertexes( ){ return wrapping_graph.begin_vertexes(); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > typename graph<T, U, T_A, U_A, Graph_Implementation>::VERTEX_ITERATOR_IN_GRAPH graph<T, U, T_A, U_A, Graph_Implementation>:: end_vertexes( ){ return wrapping_graph.end_vertexes(); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > typename graph<T, U, T_A, U_A, Graph_Implementation>::VERTEX_ITERATOR_IN_GRAPH graph<T, U, T_A, U_A, Graph_Implementation>::begin_vertexes( ) const { return wrapping_graph.begin_vertexes(); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > typename graph<T, U, T_A, U_A, Graph_Implementation>::VERTEX_ITERATOR_IN_GRAPH graph<T, U, T_A, U_A, Graph_Implementation>:: end_vertexes( ) const { return wrapping_graph.begin_vertexes(); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > size_t graph<T, U, T_A, U_A, Graph_Implementation>:: vertex_count( ) const { return wrapping_graph.vertex_count(); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > T graph<T, U, T_A, U_A, Graph_Implementation>:: remove_vertex( typename graph<T, U, T_A, U_A, Graph_Implementation>::VERTEX *vertex ){ assert(vertex != nullptr); return wrapping_graph.remove_vertex(vertex); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > void graph<T, U, T_A, U_A, Graph_Implementation>:: reserve_vertexes( size_t n ){ return wrapping_graph.reserve_vertex(n); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > void graph<T, U, T_A, U_A, Graph_Implementation>:: shrink_to_fit_vertexes( ){ wrapping_graph.shrink_to_fit_vertexes(); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > void graph<T, U, T_A, U_A, Graph_Implementation>:: add_undirected_edge( const VERTEX *vertex1, const VERTEX *vertex2, U weight ){ assert(vertex1 != nullptr); assert(vertex2 != nullptr); wrapping_graph.add_undirected_edge(vertex1, vertex2, weight); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > void graph<T, U, T_A, U_A, Graph_Implementation>:: add_directed_edge( const VERTEX *from_vertex, const VERTEX *to_vertex, U weight ){ assert(from_vertex != nullptr); assert(to_vertex != nullptr); wrapping_graph.add_directed_edge(from_vertex, to_vertex, weight); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > typename graph<T, U, T_A, U_A, Graph_Implementation>::EDGE* graph<T, U, T_A, U_A, Graph_Implementation>:: get_undirected_edge( const VERTEX *vertex1, const VERTEX *vertex2, U weight ){ assert(vertex1 != nullptr); assert(vertex2 != nullptr); return wrapping_graph.get_undirected_edge(vertex1, vertex2, weight); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > typename graph<T, U, T_A, U_A, Graph_Implementation>::EDGE* graph<T, U, T_A, U_A, Graph_Implementation>:: get_directed_edge( const VERTEX *from_vertex, const VERTEX *to_vertex ){ assert(from_vertex != nullptr); assert(to_vertex != nullptr); return wrapping_graph.get_directed_edge(from_vertex, to_vertex); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > U graph<T, U, T_A, U_A, Graph_Implementation>:: remove_undirected_edge( const VERTEX *vertex1, const VERTEX *vertex2 ){ assert(vertex1 != nullptr); assert(vertex2 != nullptr); return wrapping_graph.remove_undirected_edge(vertex1, vertex2); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > U graph<T, U, T_A, U_A, Graph_Implementation>:: remove_directed_edge( const VERTEX *from_vertex, const VERTEX *to_vertex ){ assert(from_vertex != nullptr); assert(to_vertex != nullptr); return wrapping_graph.remove_directed_edge(from_vertex, to_vertex); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > void graph<T, U, T_A, U_A, Graph_Implementation>:: reserve_edges( size_t n ){ return wrapping_graph.reserve_edges(n); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > void graph<T, U, T_A, U_A, Graph_Implementation>:: shrink_to_fit_edges( ){ return wrapping_graph.shrink_to_fit_edges(); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > typename graph<T, U, T_A, U_A, Graph_Implementation>::EDGE_ITERATOR_IN_GRAPH graph<T, U, T_A, U_A, Graph_Implementation>:: begin_edges( ){ return wrapping_graph.begin_edges(); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > typename graph<T, U, T_A, U_A, Graph_Implementation>::EDGE_ITERATOR_IN_GRAPH graph<T, U, T_A, U_A, Graph_Implementation>:: end_edges( ){ return wrapping_graph.end_edges(); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > typename graph<T, U, T_A, U_A, Graph_Implementation>::EDGE_ITERATOR_IN_GRAPH graph<T, U, T_A, U_A, Graph_Implementation>:: begin_edges( ) const { return wrapping_graph.begin_edges(); } template< typename T, typename U, typename T_A, typename U_A, typename Graph_Implementation > typename graph<T, U, T_A, U_A, Graph_Implementation>::EDGE_ITERATOR_IN_GRAPH graph<T, U, T_A, U_A, Graph_Implementation>:: end_edges( ) const { return wrapping_graph.end_edges(); } //////////////////////////////////////////////////////////////////////// //END/////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
gpl-3.0
mnovits1/JavaStuff
ArrayLists.java
3730
/* Working with ArrayLists This program takes user entered integers and reads the values into an arraylist to be processed. The output is to the console showing totals and averages of values in the arraylist. Michael Novitsky Program #11, CS 1050, Section 1 jGRASP IDE, Winbook TW Series Windows 8. 32-bit operating system, x64-based processor. Knell: the sound of a bell rung slowly to announce a death. "If you can't make it good, at least make it look good" --- Bill Gates (b. 1955) */ import java.util.ArrayList; // Enable use of the arraylist import java.util.Scanner; // Access the Scanner class public class MichaelNovitsky_1_11 { static Toolkit tools = new Toolkit(); // Access the toolkit static Scanner scnr = new Scanner(System.in); // Keyboard input static final String NUMBER_MASK = "###,###,###.00"; public static void main (String[] args) throws Exception { int nextNum = 0; // Next integer to be processed int numOfNums = 0; // Number of integers in the arraylist double average = 0; // Calculate the average of the numbers double sum = 0; // Sum the values in the array // Main program executions ArrayList<Integer> arrayListOne = new ArrayList<>(); System.out.println("Please enter an array of integers." + "\nPress 0 to exit." ); System.out.println("Enter an integer:"); nextNum = scnr.nextInt(); arrayListOne.add(nextNum); // Loop through the arraylist until 0 is entered while (nextNum != 0) { if (arrayListOne.contains(0) && (arrayListOne.size() >= 2)) { arrayListOne.remove(arrayListOne.size() -1); numOfNums = arrayListOne.size(); System.out.println("A zero has been entered, input finished"); break; } // End if else { System.out.println("Enter an integer. Press 0 to exit."); arrayListOne.add(scnr.nextInt()); } // End else } // End while outputResults(arrayListOne, numOfNums); // Call method for summary } // End main //******************************************************************************* // Method details the summation and averaging of the integers entered by user public static void outputResults(ArrayList<Integer> arrayListOne, int numOfNums) { String lineStr1 = ""; // Prepare for a line of input double sum = 0; // Total up the integers double average = 0; // Get average of the integers for (int i = 0; i < numOfNums; i++) { sum += arrayListOne.get(i); } // End for if (numOfNums > 0) { average = (double) sum / numOfNums; // Typecast the sum lineStr1 = "\nNumber of integers entered: " + numOfNums + "\r\n" + "Sum of the integers: " + tools.leftPad(sum, 12, NUMBER_MASK, " ") + "\r\n" + "Average of the integers: " + tools.leftPad(average, 12, NUMBER_MASK, " "); System.out.println(lineStr1); // Output results to the console } // End if else { System.out.println("No Entries Processed."); } // End else } // outputResults } // End class //*******************************************************************************
gpl-3.0
brianhouse/txtml
src/modules/Module_subtract.php
1328
<?php class Module_subtract extends Module { protected function x ($user,$time,$input) { if ($user->getVar($this->param("var")) !== null) { $value = $user->getVar($this->param("var")); $value = $this->number($value); } if ($this->param("value") !== null) { $subtract = floatval($this->param("value")); if (!isset($value)) { $value = $subtract; } else { BH_util::log("--> $value - $subtract = ".($value - $subtract)); $value -= $subtract; } } foreach ($this->submods as $submod) { $c = $submod->execute($user,$time,$input); if ($c === false) return false; if ($c !== true) { $subtract = $this->number($c); if (!isset($value)) { $value = $subtract; } else { BH_util::log("--> $value - $subtract = ".($value - $subtract)); $value -= $subtract; } } } if ($this->param("float") && $this->param("float") == "false") { $value = floor($value); } else { $value = BH_util::shortdecimal($value); } if ($this->param("var")) { $user->setVar($this->param("var"),strval($value)); } return strval($value); } private function number ($value) { if (!is_numeric($value)) { $format = new Format_number(); $value = $format->process($value); } return $value; } } ?>
gpl-3.0
boggen/commerce_for_moodle
paygate/nochex/version.php
1243
<?php // short line of what this file is about // // commerce is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // commerce is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with commerce. If not, see <http://www.gnu.org/licenses/>. // // search and replace for notation for opencart /** * short line description * * @package package description * @copyright Ryan Sanders * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $plugin->version = 2014122100; $plugin->requires = 2015010800.00; //hopefully search for and replace required version $plugin->component = 'paygate_nochex'; $plugin->release = 'NEED TO CODE STILL'; $plugin->maturity = MATURITY_BETA; //$plugin->dependencies = array('commerce' => 2014122100);
gpl-3.0
sacloud/sackerel
job/worker/exchange/exchange_database.go
2357
package exchange import ( "fmt" mkr "github.com/mackerelio/mackerel-client-go" "github.com/sacloud/libsacloud/sacloud" "github.com/sacloud/sackerel/job/core" "strings" ) // DatabaseJob データベース変換用ジョブ func DatabaseJob(payload interface{}) core.JobAPI { return core.NewJob("ExchangeDatabase", exchangeDatabase, payload) } func exchangeDatabase(queue *core.Queue, option *core.Option, job core.JobAPI) { var payload = job.GetPayload() if payload == nil { queue.PushWarn(fmt.Errorf("'%s' => payload is nil", job.GetName())) return } if databasePayload, ok := payload.(*core.CreateHostPayload); ok { if database, ok := databasePayload.SacloudSource.(*sacloud.Database); ok { // exchange [sacloud.Database => mkr.CreateHostParam] databasePayload.MackerelHostParam = exchangeDatabaseToMackerelHost( databasePayload.GenerateMackerelName(), databasePayload.SacloudZone, database) // trigger next route queue.PushRequest("exchanged-database", databasePayload) } else { queue.PushWarn(fmt.Errorf("'%s' => payload.Source is invalid type. need [*sacloud.Database]", job.GetName())) return } } else { queue.PushWarn(fmt.Errorf("'%s' => payload is invalid type. need [*core.CreateHostPayload]", job.GetName())) return } } func exchangeDatabaseToMackerelHost(mackerelName string, zone string, database *sacloud.Database) *mkr.CreateHostParam { p := &mkr.CreateHostParam{ Name: mackerelName, DisplayName: database.Name, CustomIdentifier: mackerelName, RoleFullnames: []string{ "SakuraCloud:Database", fmt.Sprintf("SakuraCloud:Zone-%s", zone), }, } for _, tag := range database.Tags { if tag != "" && !strings.HasPrefix(tag, "@") { p.RoleFullnames = append(p.RoleFullnames, fmt.Sprintf("SakuraCloud:%s", tag)) } } if len(database.Interfaces) > 0 && database.Interfaces[0].Switch != nil { ip := database.Interfaces[0].IPAddress // 共有セグメントに接続されている場合 if database.Interfaces[0].Switch.Scope != sacloud.ESCopeShared { // スイッチに接続されている場合 ip = database.Remark.Servers[0].(map[string]interface{})["IPAddress"].(string) } p.Interfaces = append(p.Interfaces, mkr.Interface{ Name: fmt.Sprintf("eth%d", 0), IPAddress: ip, MacAddress: "", }) } return p }
gpl-3.0
samdroid-apps/bibliography-activity
browsewindow.py
6104
# Copyright 2016 Sam Parkinson # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import math import json import logging from datetime import date from gettext import gettext as _ from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GLib from gi.repository import GObject from gi.repository import WebKit2 from sugar3.graphics import style from sugar3.graphics.toolbutton import ToolButton from sugar3.graphics.style import GRID_CELL_SIZE from sugar3.activity.activity import launch_bundle from sugar3.datastore import datastore from popwindow import PopWindow from add_window import EntryWidget from bib_types import WEB_TYPES, ALL_TYPES HELP_TEXT = _( \ '''This Browse entry has no <i>bookmarks</i>. You need to bookmark the pages that you want to add to your bibliography. Bookmark these pages by opening the Browse journal entry, and clicking the <i>star</i> icon. Remember to close Browse before importing it into Bibliography activity, so that the bookmarks are saved!''') class BrowseImportWindow(PopWindow): ''' A window that let's users import items from a browse activity Args: data (dict): JSON decoded browse activity data toplevel (Gtk.Window): toplevel window jobject: jobject from object chooser ''' save_item = GObject.Signal('save-item', arg_types=[str, str, str]) try_again = GObject.Signal('try-again', arg_types=[object]) def __init__(self, data, toplevel, jobject): PopWindow.__init__(self, transient_for=toplevel) self.props.size = PopWindow.FULLSCREEN w, h = PopWindow.FULLSCREEN self._toplevel = toplevel self._jobject = jobject self._links = data.get('shared_links', []) if not self._links: self._show_howto_copy() return self._total_links = len(self._links) self._entry = None self._paned = Gtk.Paned() self.add_view(self._paned) self._paned.show() self._webview = WebKit2.WebView() self._paned.add1(self._webview) self._webview.set_size_request(w / 2, h) self._webview.show() self._2box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self._paned.add2(self._2box) self._2box.show() self._combo = Gtk.ComboBoxText() for t in WEB_TYPES: self._combo.append(t.type, t.name) self._combo.set_active(0) self._combo.connect('changed', self.__combo_changed_cb) self._2box.add(self._combo) self._combo.show() self.next_link() add = ToolButton(icon_name='dialog-ok') add.props.tooltip = \ _('Add This Bibliography Item and Continue to Next Bookmark') add.connect('clicked', self.__add_clicked_cb) self.props.title_box.insert(add, -2) add.show() def _show_howto_copy(self): self.get_title_box().props.title = _('Learn to Bookmark in Browse') l = Gtk.Label() l.set_markup('<big>{}</big>'.format(HELP_TEXT)) self.add_view(l) l.show() metadata = self._jobject.get_metadata() launch = Gtk.Button( label=_('Open "%s" in Browse and Add Bookmarks!') % metadata.get('title')) self.add_view(launch, fill=False) launch.connect('clicked', self.__launch_clicked_cb) launch.show() self._try_again = Gtk.Button( label=_('I added the bookmarks, let\'s try again')) self.add_view(self._try_again, fill=False) self._try_again.connect('clicked', self.__try_again_clicked_cb) def __launch_clicked_cb(self, button): launch_bundle(bundle_id='org.laptop.WebActivity', object_id=self._jobject.object_id) self._try_again.show() def __try_again_clicked_cb(self, button): # Need to refresh the jobject, as the file probably changed new_jobject = datastore.get(self._jobject.object_id) self.try_again.emit(new_jobject) def next_link(self): ''' Show the next link from the data to the user ''' if len(self._links) == 0: self.destroy() return self._link = self._links.pop(0) label = ('<span bgcolor="#fff" color="#282828" size="x-large"' '>{}/{}</span> {}').format( self._total_links - len(self._links), self._total_links, self._link.get('title', _('Untitled'))) self.get_title_box().props.title = label self._webview.load_uri(self._link.get('url')) id_ = self._combo.get_active_id() bib_type = ALL_TYPES[id_] self._set_entry(bib_type) def _set_entry(self, type_): if self._entry is not None: self._entry.hide() self._2box.remove(self._entry) self._entry.destroy() self._entry = EntryWidget( type_, self._toplevel, timestamp=self._link.get('timestamp'), title=self._link.get('title'), uri=self._link.get('url')) self._2box.pack_start(self._entry, True, True, 0) self._entry.show() def __add_clicked_cb(self, button): self.save_item.emit( *self._entry.get_data()) self.next_link() def __combo_changed_cb(self, combo): id_ = combo.get_active_id() bib_type = ALL_TYPES[id_] self._set_entry(bib_type)
gpl-3.0
lilith645/EulerChallenges
Problem14/Collatz.scala
749
import scala.annotation.tailrec object Collatz { @tailrec def getChainLength(testNum: Int, num: Int, chainLength: Int): Int = { if(num == 1) chainLength else if(num % 2 == 0) getChainLength(testNum, num/2, chainLength+1); else getChainLength(testNum, 3*num+1, chainLength+1); } @tailrec def Collatz(startNum: Int, highestStart: Int, chainLength: Int): Int = { val chain = getChainLength(startNum, startNum, 0) println(startNum) if(startNum > 1000000) highestStart else if(chain > chainLength) Collatz(startNum+1, startNum, chain) else Collatz(startNum+1, highestStart, chainLength) } def main(args: Array[String]) { println(Collatz(13, 0, 0)); } }
gpl-3.0
s0urc3d3v3l0pm3nt/qksms
QKSMS/src/main/java/com/moez/QKSMS/ui/base/QKActivity.java
6865
package com.moez.QKSMS.ui.base; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.PowerManager; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import com.moez.QKSMS.R; import com.moez.QKSMS.ui.ThemeManager; import com.moez.QKSMS.ui.view.QKTextView; import java.util.ArrayList; public class QKActivity extends ActionBarActivity { private final String TAG = "QKActivity"; private Toolbar mToolbar; private QKTextView mTitle; private ImageView mOverflowButton; private Menu mMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /** * Reloads the toolbar and it's view references. * <p/> * This is called every time the content view of the activity is set, since the * toolbar is now a part of the activity layout. * <p/> * TODO: If someone ever wants to manage the Toolbar dynamically instead of keeping it in their * TODO layout file, we can add an alternate way of setting the toolbar programmatically. */ private void reloadToolbar() { mToolbar = (Toolbar) findViewById(R.id.toolbar); if (mToolbar == null) { throw new RuntimeException("Toolbar not found in BaseActivity layout."); } else { mTitle = (QKTextView) mToolbar.findViewById(R.id.toolbar_title); setSupportActionBar(mToolbar); } ThemeManager.loadThemeProperties(this); } public void colorMenuIcons(Menu menu, int color) { // Toolbar navigation icon Drawable navigationIcon = getToolbar().getNavigationIcon(); if (navigationIcon != null) { navigationIcon.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); getToolbar().setNavigationIcon(navigationIcon); } // Customize actionbar overflow icon with color colorOverflowButtonWhenReady(color); // Settings expansion ArrayList<View> views = new ArrayList<>(); View decor = getWindow().getDecorView(); decor.findViewsWithText(views, getString(R.string.menu_show_all_prefs), View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); decor.findViewsWithText(views, getString(R.string.menu_show_fewer_prefs), View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); android.widget.TextView connected = !views.isEmpty() ? (android.widget.TextView) views.get(0) : null; if (connected != null) { connected.setTextColor(color); } // Apply color filter to other actionbar elements for (int i = 0; i < menu.size(); i++) { MenuItem menuItem = menu.getItem(i); Drawable newIcon = menuItem.getIcon(); if (newIcon != null) { newIcon.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); menuItem.setIcon(newIcon); } } } private void colorOverflowButtonWhenReady(final int color) { if (mOverflowButton != null) { // We already have the overflow button, so just color it. Drawable icon = mOverflowButton.getDrawable(); icon.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); // Have to clear the image drawable first or else it won't take effect mOverflowButton.setImageDrawable(null); mOverflowButton.setImageDrawable(icon); } else { // Otherwise, find the overflow button by searching for the content description. final String overflowDesc = getString(R.string.abc_action_menu_overflow_description); final ViewGroup decor = (ViewGroup) getWindow().getDecorView(); decor.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { decor.getViewTreeObserver().removeOnPreDrawListener(this); final ArrayList<View> views = new ArrayList<>(); decor.findViewsWithText(views, overflowDesc, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); if (views.isEmpty()) { Log.w(TAG, "no views"); } else { if (views.get(0) instanceof ImageView) { mOverflowButton = (ImageView) views.get(0); colorOverflowButtonWhenReady(color); } else { Log.w(TAG, "overflow button isn't an imageview"); } } return false; } }); } } public Menu getMenu() { return mMenu; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Save a reference to the menu so that we can quickly access menu icons later. mMenu = menu; colorMenuIcons(mMenu, ThemeManager.getTextOnColorPrimary()); return super.onCreateOptionsMenu(mMenu); } @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); reloadToolbar(); } @Override public void setContentView(View view) { super.setContentView(view); reloadToolbar(); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { super.setContentView(view, params); reloadToolbar(); } /** * Sets the title of the activity, displayed on the toolbar * <p/> * Make sure this is only called AFTER setContentView, or else the Toolbar * is likely not initialized yet and this method will do nothing * * @param title title of activity */ @Override public void setTitle(CharSequence title) { super.setTitle(title); if (mTitle != null) { mTitle.setText(title); } } /** * Returns the Toolbar for this activity. * * @return */ protected Toolbar getToolbar() { return mToolbar; } public boolean isScreenOn() { PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { return powerManager.isInteractive(); } else { return powerManager.isScreenOn(); } } }
gpl-3.0
Crash911/RaptoredSkyFire
src/server/game/Handlers/TaxiHandler.cpp
10787
/* * Copyright (C) 2011-2013 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2013 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "DatabaseEnv.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Opcodes.h" #include "Log.h" #include "ObjectMgr.h" #include "Player.h" #include "UpdateMask.h" #include "Path.h" #include "WaypointMovementGenerator.h" void WorldSession::HandleTaxiNodeStatusQueryOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_TAXINODE_STATUS_QUERY"); uint64 guid; recvData >> guid; SendTaxiStatus(guid); } void WorldSession::SendTaxiStatus(uint64 guid) { // cheating checks Creature* unit = GetPlayer()->GetMap()->GetCreature(guid); if (!unit) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WorldSession::SendTaxiStatus - Unit (GUID: %u) not found.", uint32(GUID_LOPART(guid))); return; } uint32 curloc = sObjectMgr->GetNearestTaxiNode(unit->GetPositionX(), unit->GetPositionY(), unit->GetPositionZ(), unit->GetMapId(), GetPlayer()->GetTeam()); // not found nearest if (curloc == 0) return; sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: current location %u ", curloc); WorldPacket data(SMSG_TAXINODE_STATUS, 9); data << guid; data << uint8(GetPlayer()->_taxi.IsTaximaskNodeKnown(curloc) ? 1 : 0); SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_TAXINODE_STATUS"); } void WorldSession::HandleTaxiQueryAvailableNodes(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_TAXIQUERYAVAILABLENODES"); uint64 guid; recvData >> guid; // cheating checks Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_FLIGHTMASTER); if (!unit) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: HandleTaxiQueryAvailableNodes - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); // unknown taxi node case if (SendLearnNewTaxiNode(unit)) SendTaxiMenu(unit); // known taxi node case SendTaxiMenu(unit); } void WorldSession::SendTaxiMenu(Creature* unit) { // find current node uint32 curloc = sObjectMgr->GetNearestTaxiNode(unit->GetPositionX(), unit->GetPositionY(), unit->GetPositionZ(), unit->GetMapId(), GetPlayer()->GetTeam()); if (curloc == 0) return; bool lastTaxiCheaterState = GetPlayer()->isTaxiCheater(); if (unit->GetEntry() == 29480) GetPlayer()->SetTaxiCheater(true); // Grimwing in Ebon Hold, special case. NOTE: Not perfect, Zul'Aman should not be included according to WoWhead, and I think taxicheat includes it. sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_TAXINODE_STATUS_QUERY %u ", curloc); WorldPacket data(SMSG_SHOWTAXINODES, (4 + 8 + 4 + 8 * 4)); // Checked for 406a data << uint32(1); data << uint64(unit->GetGUID()); data << uint32(curloc); data << uint8((sTaxiNodesStore.GetNumRows() >> 6) + 1); // This is 11 as of 4.0.6 13623 (count of following uint64's) GetPlayer()->_taxi.AppendTaximaskTo(data, GetPlayer()->isTaxiCheater()); SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_SHOWTAXINODES"); GetPlayer()->SetTaxiCheater(lastTaxiCheaterState); } void WorldSession::SendDoFlight(uint32 mountDisplayId, uint32 path, uint32 pathNode) { // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); while (GetPlayer()->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE) GetPlayer()->GetMotionMaster()->MovementExpired(false); if (mountDisplayId) GetPlayer()->Mount(mountDisplayId); GetPlayer()->GetMotionMaster()->MoveTaxiFlight(path, pathNode); } bool WorldSession::SendLearnNewTaxiNode(Creature* unit) { // find current node uint32 curloc = sObjectMgr->GetNearestTaxiNode(unit->GetPositionX(), unit->GetPositionY(), unit->GetPositionZ(), unit->GetMapId(), GetPlayer()->GetTeam()); if (curloc == 0) return true; // `true` send to avoid WorldSession::SendTaxiMenu call with one more curlock seartch with same false result. if (GetPlayer()->_taxi.SetTaximaskNode(curloc)) { WorldPacket msg(SMSG_NEW_TAXI_PATH, 0); SendPacket(&msg); WorldPacket update(SMSG_TAXINODE_STATUS, 9); update << uint64(unit->GetGUID()); update << uint8(1); SendPacket(&update); return true; } else return false; } void WorldSession::SendDiscoverNewTaxiNode(uint32 nodeid) { if (GetPlayer()->_taxi.SetTaximaskNode(nodeid)) { WorldPacket msg(SMSG_NEW_TAXI_PATH, 0); SendPacket(&msg); } } void WorldSession::HandleActivateTaxiExpressOpcode (WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ACTIVATETAXIEXPRESS"); uint64 guid; uint32 node_count; recvData >> guid >> node_count; Creature* npc = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_FLIGHTMASTER); if (!npc) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: HandleActivateTaxiExpressOpcode - Unit (GUID: %u) not found or you can't interact with it.", uint32(GUID_LOPART(guid))); return; } std::vector<uint32> nodes; for (uint32 i = 0; i < node_count; ++i) { uint32 node; recvData >> node; nodes.push_back(node); } if (nodes.empty()) return; sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ACTIVATETAXIEXPRESS from %d to %d", nodes.front(), nodes.back()); GetPlayer()->ActivateTaxiPathTo(nodes, npc); } void WorldSession::HandleMoveSplineDoneOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_MOVE_SPLINE_DONE"); uint64 guid; // used only for proper packet read recvData.readPackGUID(guid); MovementInfo movementInfo; // used only for proper packet read ReadMovementInfo(recvData, &movementInfo); recvData.read_skip<uint32>(); // unk // in taxi flight packet received in 2 case: // 1) end taxi path in far (multi-node) flight // 2) switch from one map to other in case multim-map taxi path // we need process only (1) uint32 curDest = GetPlayer()->_taxi.GetTaxiDestination(); if (!curDest) return; TaxiNodesEntry const* curDestNode = sTaxiNodesStore.LookupEntry(curDest); // far teleport case if (curDestNode && curDestNode->map_id != GetPlayer()->GetMapId()) { if (GetPlayer()->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE) { // short preparations to continue flight FlightPathMovementGenerator* flight = (FlightPathMovementGenerator*)(GetPlayer()->GetMotionMaster()->top()); flight->SetCurrentNodeAfterTeleport(); TaxiPathNodeEntry const& node = flight->GetPath()[flight->GetCurrentNode()]; flight->SkipCurrentNode(); GetPlayer()->TeleportTo(curDestNode->map_id, node.x, node.y, node.z, GetPlayer()->GetOrientation()); } return; } uint32 destinationnode = GetPlayer()->_taxi.NextTaxiDestination(); if (destinationnode > 0) // if more destinations to go { // current source node for next destination uint32 sourcenode = GetPlayer()->_taxi.GetTaxiSource(); // Add to taximask middle hubs in taxicheat mode (to prevent having player with disabled taxicheat and not having back flight path) if (GetPlayer()->isTaxiCheater()) { if (GetPlayer()->_taxi.SetTaximaskNode(sourcenode)) { WorldPacket data(SMSG_NEW_TAXI_PATH, 0); _player->GetSession()->SendPacket(&data); } } sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Taxi has to go from %u to %u", sourcenode, destinationnode); uint32 mountDisplayId = sObjectMgr->GetTaxiMountDisplayId(sourcenode, GetPlayer()->GetTeam()); uint32 path, cost; sObjectMgr->GetTaxiPath(sourcenode, destinationnode, path, cost); if (path && mountDisplayId) SendDoFlight(mountDisplayId, path, 1); // skip start fly node else GetPlayer()->_taxi.ClearTaxiDestinations(); // clear problematic path and next return; } else GetPlayer()->_taxi.ClearTaxiDestinations(); // not destinations, clear source node GetPlayer()->CleanupAfterTaxiFlight(); GetPlayer()->SetFallInformation(0, GetPlayer()->GetPositionZ()); if (GetPlayer()->pvpInfo.inHostileArea) GetPlayer()->CastSpell(GetPlayer(), 2479, true); } void WorldSession::HandleActivateTaxiOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ACTIVATETAXI"); uint64 guid; std::vector<uint32> nodes; nodes.resize(2); recvData >> guid >> nodes[0] >> nodes[1]; sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ACTIVATETAXI from %d to %d", nodes[0], nodes[1]); Creature* npc = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_FLIGHTMASTER); if (!npc) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: HandleActivateTaxiOpcode - Unit (GUID: %u) not found or you can't interact with it.", uint32(GUID_LOPART(guid))); return; } GetPlayer()->ActivateTaxiPathTo(nodes, npc); } void WorldSession::SendActivateTaxiReply(ActivateTaxiReply reply) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(reply); SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_ACTIVATETAXIREPLY"); }
gpl-3.0
LEPTON-project/LEPTON_2
upload/modules/tinymce/tinymce/plugins/pagelink/register_class_secure.php
580
<?php /** * @module pagelin-plugin for TinyMCE * @version see info.php of this module * @authors Ryan Djurovich, Chio Maisriml, Thomas Hornik, Dietrich Roland Pehlke * @copyright 2004-2017 Ryan Djurovich, Chio Maisriml, Thomas Hornik, Dietrich Roland Pehlke * @license GNU General Public License * @license terms see info.php of this module * @platform see info.php of this module * */ $files_to_register = array( 'pagelink.php' ); LEPTON_secure::getInstance()->accessFiles( $files_to_register ); ?>
gpl-3.0
googlecreativelab/creatability-seeing-music
src/visualization/SpectrogramPitchScroll.js
1371
/** * Copyright 2019 Google LLC * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ import { PitchScroll } from './PitchScroll' import { Spectrogram } from './Spectrogram' import { Grid } from './Grid' export class SpectrogramPitchScroll { constructor(source){ this._pitchScroll = new PitchScroll(source) this._pitchScroll.fullColor = true this._spectrogram = new Spectrogram(source) this._spectrogram.fullColor = false this._grid = new Grid(true) } resize(width, height){ this._pitchScroll.resize(width, height) this._spectrogram.resize(width, height) this._grid.resize(width, height) } clear(){ this._pitchScroll.clear() this._spectrogram.clear() } drawTo(context, width, height){ context.globalAlpha = 0.85 this._spectrogram.drawTo(context, width, height) context.globalAlpha = 1 this._pitchScroll.drawTo(context, width, height) if (this.showGrid){ this._grid.drawTo(context, 0, 0) this._pitchScroll.drawText(context) } } }
gpl-3.0
bitcoinbrisbane/BitPoker
BitPoker.Controllers.NTests/TablesControllerTests.cs
5414
using System; using NUnit.Framework; namespace BitPoker.Controllers.Tests { [TestFixture()] public class TablesControllerTests { //private BitPoker.Models.IRequest request; private const String REQUEST_ID = "a66a8eb4-ea1f-42bb-b5f2-03456094b1f6"; private const String TABLE_ID = "d6d9890d-0ca2-4b5d-ae98-fa4d45eb4363"; private const String BITCOIN_ADDRESS_1 = "n4HzHsTzz4kku4X21yaG1rjbqtVNDBsyKZ"; private const String PRIVATE_KEY = "93GnRYsUXD4FPCiV46n8vqKvwHSZQgjnyuBvhNtqRvq3Ac26kVc"; private BitPoker.Controllers.Rest.TablesController _controller; [SetUp] public void Setup() { _controller = new BitPoker.Controllers.Rest.TablesController(); } [Test()] public void Should_Join_Table_In_Seat_2() { Guid tableId = new Guid(TABLE_ID); _controller.TableRepo = new Repository.Mocks.TableRepository(); Models.Messages.JoinTableRequest request = new Models.Messages.JoinTableRequest() { Id = new Guid(REQUEST_ID), BitcoinAddress = BITCOIN_ADDRESS_1, TableId = tableId, TimeStamp = new DateTime(2016, 12, 12), Seat = 2, Version = 1 }; NBitcoin.BitcoinSecret secret = new NBitcoin.BitcoinSecret(PRIVATE_KEY, NBitcoin.Network.TestNet); request.Signature = secret.PrivateKey.SignMessage(request.ToString()); Models.Messages.JoinTableResponse response = null; //_controller.Post(request); Assert.IsNotNull(response); Assert.AreEqual(2, response.Seat); } [Test()] public void Should_Join_Table_In_First_Empty_Seat() { //private key 91xCHwaMdufE8fmxachVhU12wdTjY7nGbZeGgjx4JQSuSDNizhf Guid tableId = new Guid("be7514a3-e73c-4f95-ba26-c398641eea5c"); _controller.TableRepo = new Repository.Mocks.TableRepository(); NBitcoin.BitcoinSecret secret = new NBitcoin.BitcoinSecret("91xCHwaMdufE8fmxachVhU12wdTjY7nGbZeGgjx4JQSuSDNizhf", NBitcoin.Network.TestNet); NBitcoin.BitcoinAddress address = secret.GetAddress(); Models.Messages.JoinTableRequest request = new Models.Messages.JoinTableRequest() { Id = new Guid(REQUEST_ID), BitcoinAddress = address.ToString(), TableId = tableId, TimeStamp = new DateTime(2016, 12, 12), PublicKey = secret.PubKey.ToString(), Version = 1 }; Models.Messages.JoinTableResponse response = null; // = _controller.Join(request); Assert.IsNotNull(response); Assert.AreEqual(1, response.Seat); } [Test()] public void Should_Not_Join_Full_Table() { } [Test()] public void Should_Buy_In_To_Joined_Table() { //BitcoinSecret secret = new BitcoinSecret("91xCHwaMdufE8fmxachVhU12wdTjY7nGbZeGgjx4JQSuSDNizhf", Network.TestNet); //controller.TableRepo = new Repository.MockTableRepo(); ////"2NAxESoeuyA4KqudU3v9fh5idiBorgLpkUj"; //BitcoinScriptAddress tableAddress = new BitcoinScriptAddress("2NAxESoeuyA4KqudU3v9fh5idiBorgLpkUj", Network.TestNet); //BlockrTransactionRepository repo = new BlockrTransactionRepository(Network.TestNet); //BitcoinAddress myAddress = BitcoinAddress.Create("mypckwJUPVMi8z1kdSCU46hUY9qVQSrZWt", Network.TestNet); ////TODO: MAKE A JSON OBJECT ////var utxos = await repo.GetUnspentAsync(myAddress.ToString()); ////Coin[] coins = utxos.OrderByDescending(u => u.Amount).Select(u => new Coin(u.Outpoint, u.TxOut)).ToArray(); ////Money minersFee = new Money(50000); ////var txBuilder = new TransactionBuilder(); ////var tx = txBuilder //// //.AddCoins(coins) //// .AddCoins(utxos) //// .AddKeys(secret) //// .Send(tableAddress, new Money(100000)) //// .SendFees(minersFee) //// .SetChange(myAddress) //// .BuildTransaction(true); ////Debug.Assert(txBuilder.Verify(tx)); //check fully signed Models.Messages.BuyInRequest request = new Models.Messages.BuyInRequest() { BitcoinAddress = "mypckwJUPVMi8z1kdSCU46hUY9qVQSrZWt", TableId = new Guid(TABLE_ID), TimeStamp = new DateTime(2016, 12, 12) //, //TxID = "af651c3435b5a11a8d7792dbc1d20a20a23fce0beb0b6931bf0ce407bfd28a0a" }; //var response = _controller.BuyIn(request); //Assert.IsNotNull(response); //Assert.IsNull(response.Error); //Assert.AreEqual(response.Id.ToString(), REQUEST_ID); //Models.Messages.BuyInResponse buyInResponse = response.Result as Models.Messages.BuyInResponse; //Assert.IsNotNull(buyInResponse); } [Test()] public void Should_Not_Buy_In_Under_The_Min() { } [Test()] public void Should_Not_Buy_In_Over_The_Max() { } [Test()] public void Should_Not_Buy_In_With_Unconfirmed_UTXo() { } [Test()] public void Should_Not_Buy_In_With_Invalid_Tx() { } } }
gpl-3.0
ZOARDER-JR/Programming
Toph/Safe Zone.cpp
4556
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<sstream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cctype> #include<cstring> #include<climits> #include<iomanip> #include<string> #include<vector> #include<stack> #include<queue> #include<deque> #include<set> #include<map> #include<list> #include<algorithm> #include<utility> #include<functional> using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef vector<int> VI; typedef vector<double> VD; typedef vector<char> VC; typedef vector<string> VS; typedef list<int> LI; typedef map<int, int> MII; typedef map<string, int> MSI; typedef map<int, string> MIS; typedef pair<int,int> PII; #define psb(x) push_back(x) #define psf(x) push_front(x) #define ppb pop_back() #define ppf pop_front() #define pop pop() #define front front() #define back back() #define bgn begin() #define end end() #define emp empty() #define clr clear() #define sz size() #define sp setprecision #define fx fixed #define fst first #define snd second #define reset(a) memset(a,0,sizeof(a)) #define assign(a,b) memset(a,b,sizeof(a)) #define assignmx(a) memset(a,127,sizeof(a)) #define assignmn(a) memset(a,128,sizeof(a)) #define max3(x, y, z) max(x, max(y, z)) #define min3(x, y, z) min(x, min(y, z)) #define max4(w, x, y, z) max(w, max(x, max(y,z))) #define min4(w, x, y, z) min(w, min(x, min(y, z))) #define range(r,c) ((r >=0 && r <row) && (c >=0 && c <column)) #define getch char ch=getchar() #define gtl(str) getline(cin,str) #define loop(x,r,n) for(x = r ; x <= n ; x++) #define loopr(x, r, n) for (x = r; x >= n; x--) #define test(t) for(int o = 1 ; o <= t ; o++) #define printcs cout << "Case " << o << ": "; #define nl cout << "\n" //int X4[] = { 0, -1, 0, 1 }; //int Y4[] = { -1, 0, 1, 0 }; //int X8[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; //int Y8[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; //int X3D6[] = { 0, 0, -1, 1, 0, 0 }; //int Y3D6[] = { -1, 1, 0, 0, 0, 0 }; //int Z3D6[] = { 0, 0, 0, 0, -1, 1 }; bool flag, flag1, flag2, flag3; int row, column; int i, j, k, l; #define INFMX 2139062143 #define INFMN -2139062144 #define pi acos(-1.0) #define N 1000005 double calculate_area(double x1, double y1, double x2, double y2, double x3, double y3); double calculate_distance(double x1, double y1, double x2, double y2); double calculate_shortest_distance(double x1, double y1, double x2, double y2, double m, double n); int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); double x[3], y[3], area[3], m, n, total_area, d[3]; string str; int t; cin >> t; while (t--) { cin >> str; for (i = 1,j=0; i < 15; i+=5,j++) { x[j] = str[i] - '0'; y[j] = str[i + 2] - '0'; } m = str[16] - '0'; n = str[18] - '0'; total_area = calculate_area(x[0], y[0], x[1], y[1], x[2], y[2]); area[0] = calculate_area(x[0], y[0], x[1], y[1], m, n); area[1] = calculate_area(x[1], y[1], x[2], y[2], m, n); area[2] = calculate_area(x[0], y[0], x[2], y[2], m, n); if (total_area == (area[0] + area[1] + area[2])) { cout << "SUB IUPC!" << endl; } else { d[0] = calculate_shortest_distance(x[0], y[0], x[1], y[1], m, n); d[1] = calculate_shortest_distance(x[0], y[0], x[2], y[2], m, n); d[2] = calculate_shortest_distance(x[1], y[1], x[2], y[2], m, n); double temp = min3(d[0], d[1], d[2])*pow(10.0, 4.0); // this is bullshit.... int round = temp; cout << fixed << setprecision(4) << (round*1.0) / pow(10.0, 4.0) << endl; } } return 0; } double calculate_area(double x1, double y1, double x2, double y2, double x3, double y3) { double res; res = x1*(y2 - y3) - x2*(y1 - y3) + x3*(y1 - y2); res /= 2; return (res < 0 ? res*(-1) : res); } double calculate_distance(double x1, double y1, double x2, double y2) { double res; res = sqrt(((x1 - x2)*(x1 - x2)) + ((y1 - y2)*(y1 - y2))); return res; } double calculate_shortest_distance(double x1, double y1, double x2, double y2, double m, double n) { double x, y, m1, m2, c1, c2; m1 = (y1 - y2) / (x1 - x2); m2 = (x2 - x1) / (y1 - y2); c1 = (x1*y2 - x2*y1) / (x1 - x2); c2 = n - (m*m2); x = (c2 - c1) / (m1 - m2); y = (m1*x) + c1; if (x >= min(x1, x2) && x <= max(x1, x2) && y >= min(y1, y2) && y <= max(y1, y2)) { return calculate_distance(x, y, m, n); } else { return min(calculate_distance(x1, y1, m, n), calculate_distance(x2, y2, m, n)); } }
gpl-3.0
AleksNeStu/pytasks
EPAM/advanced_python/l1-8.py
551
"""Keyword Arguments in Dictionary.""" __author__ = 'AleksNeStu' __copyright__ = "The GNU General Public License v3.0" def printargs(arg, **kwargs): print arg, kwargs def test_var_args_call(arg1, arg2, arg3): print "arg1:", arg1 print "arg2:", arg2 print "arg3:", arg3 # normal call with separate arguments test_var_args_call(1, 2, 3) printargs('argument', rand_name=3, other_name=6) # call with arguments unpacked from a dictionary kwargs = {"arg3": 3, "arg2": "two"} test_var_args_call(1, **kwargs) printargs('argument:', **kwargs)
gpl-3.0
ifpb/projeto-estagio
sigtcc/spec/views/ata_defesas/create.html.erb_spec.rb
146
require 'rails_helper' RSpec.describe "ata_defesas/create.html.erb", type: :view do pending "add some examples to (or delete) #{__FILE__}" end
gpl-3.0
DoctorJew/Paragon-Discord-Bot
cogs/pick.py
5906
from discord.ext import commands from cogs.database import * class Pick: """Pick a random hero or set of heroes.""" def __init__(self, bot): self.bot = bot self.agora = self.bot.get_cog('Agora') # Requires the Agora extension be loaded @commands.command() async def pick(self, ctx): """Pick a random hero.""" embed = discord.Embed() hero = self.agora.random_hero() embed.title = hero.hero_name embed.url = 'https://agora.gg/hero/' + hero.agora_hero_id embed.set_thumbnail(url=hero.icon) embed.set_footer(text='Paragon', icon_url=self.agora.icon_url) await ctx.send(ctx.author.mention + ' Play:', embed=embed) @commands.command() async def pick5(self, ctx): """Pick 5 random heroes.""" embed = discord.Embed() picked = [] heroes = '' while len(picked) < 5: hero = self.agora.random_hero() if hero.id in picked: continue picked.append(hero.id) if len(picked) < 5: heroes = heroes + hero.hero_name + ", " if len(picked) < 4 else heroes + hero.hero_name + ", and " else: heroes += hero.hero_name embed.title = heroes embed.url = 'https://agora.gg/heroes' embed.set_footer(text='Paragon', icon_url=self.agora.icon_url) await ctx.send(embed=embed) @commands.command() async def pick10(self, ctx, mirror: bool = False): """Pick 10 random heroes.""" picked = [] heroes = '' embed = discord.Embed() while len(picked) < 5: hero = self.agora.random_hero() if hero.id in picked: continue picked.append(hero.id) if len(picked) < 5: heroes = heroes + hero.hero_name + ", " if len(picked) < 4 else heroes + hero.hero_name + ", and " else: heroes += hero.hero_name + '|' if mirror: picked.clear() size = len(picked) while len(picked) < size + 5: hero = self.agora.random_hero() if hero.id in picked: continue picked.append(hero.id) if len(picked) < size + 5: heroes = heroes + hero.hero_name + ", " if len( picked) < size + 4 else heroes + hero.hero_name + ", and " else: heroes += hero.hero_name + '|' embed.title = heroes.split('|')[0] embed.description = heroes.split('|')[1] embed.url = 'https://agora.gg/heroes' embed.set_footer(text='Paragon', icon_url=self.agora.icon_url) await ctx.send(embed=embed) @commands.command() async def pickteam(self, ctx): """Pick a team with proper roles for each lane.""" roles = {'ADC': 'ADC', 'SUPP': 'Support', 'MID': 'Midlane', 'OFF': 'Offlane', 'JUNG': 'Jungle'} picked = [] # Some heroes can be played in multiple roles, we need to keep track embed = discord.Embed() embed.title = 'Team Picks' for role, name in roles.items(): found = False while not found: hero = self.agora.role_hero(role) if hero.id in picked: continue found = True picked.append(hero.id) embed.add_field(name=name, value=hero.hero_name, inline=False) await ctx.send(embed=embed) @commands.command(aliases=['pickadc']) async def pickcarry(self, ctx): """Pick a random ADC.""" embed = discord.Embed() hero = self.agora.role_hero('ADC') embed.title = hero.hero_name embed.url = 'https://agora.gg/hero/' + hero.agora_hero_id embed.set_thumbnail(url=hero.icon) embed.set_footer(text='Paragon', icon_url=self.agora.icon_url) await ctx.send(ctx.message.author.mention + ' Play:', embed=embed) @commands.command() async def picksupport(self, ctx): """Pick a random Support.""" embed = discord.Embed() hero = self.agora.role_hero('SUPP') embed.title = hero.hero_name embed.url = 'https://agora.gg/hero/' + hero.agora_hero_id embed.set_thumbnail(url=hero.icon) embed.set_footer(text='Paragon', icon_url=self.agora.icon_url) await ctx.send(ctx.message.author.mention + ' Play:', embed=embed) @commands.command() async def pickmid(self, ctx): """Pick a random Midlaner.""" embed = discord.Embed() hero = self.agora.role_hero('MID') embed.title = hero.hero_name embed.url = 'https://agora.gg/hero/' + hero.agora_hero_id embed.set_thumbnail(url=hero.icon) embed.set_footer(text='Paragon', icon_url=self.agora.icon_url) await ctx.send(ctx.message.author.mention + ' Play:', embed=embed) @commands.command() async def pickoff(self, ctx): """Pick a random Offlaner.""" embed = discord.Embed() hero = self.agora.role_hero('OFF') embed.title = hero.hero_name embed.url = 'https://agora.gg/hero/' + hero.agora_hero_id embed.set_thumbnail(url=hero.icon) embed.set_footer(text='Paragon', icon_url=self.agora.icon_url) await ctx.send(ctx.message.author.mention + ' Play:', embed=embed) @commands.command() async def pickjungle(self, ctx): """Pick a random jungler.""" embed = discord.Embed() hero = self.agora.role_hero('JUNG') embed.title = hero.hero_name embed.url = 'https://agora.gg/hero/' + hero.agora_hero_id embed.set_thumbnail(url=hero.icon) embed.set_footer(text='Paragon', icon_url=self.agora.icon_url) await ctx.send(ctx.message.author.mention + ' Play:', embed=embed) def setup(bot): bot.add_cog(Pick(bot))
gpl-3.0