repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
smallsun912/ADC | Marksman/Tristana.cs | 13061 | #region
using System;
using System.Drawing;
using System.Linq;
using LeagueSharp;
using SharpDX.Direct3D9;
using Font = SharpDX.Direct3D9.Font;
using LeagueSharp.Common;
#endregion
namespace Marksman
{
internal class Tristana : Champion
{
public static Spell Q, W, E, R;
public static Font vText;
public static int xBuffCount;
public static int LastTickTime;
public Tristana()
{
Q = new Spell(SpellSlot.Q, 703);
W = new Spell(SpellSlot.W, 900);
W.SetSkillshot(.50f, 250f, 1400f, false, SkillshotType.SkillshotCircle);
E = new Spell(SpellSlot.E, 703);
R = new Spell(SpellSlot.R, 703);
Utility.HpBarDamageIndicator.DamageToUnit = GetComboDamage;
Utility.HpBarDamageIndicator.Enabled = true;
AntiGapcloser.OnEnemyGapcloser += AntiGapcloser_OnEnemyGapcloser;
Interrupter.OnPossibleToInterrupt += Interrupter_OnPossibleToInterrupt;
vText = new Font(
Drawing.Direct3DDevice,
new FontDescription
{
FaceName = "Courier new",
Height = 15,
OutputPrecision = FontPrecision.Default,
Quality = FontQuality.Default,
});
Utils.PrintMessage("Tristana loaded.");
}
public void AntiGapcloser_OnEnemyGapcloser(ActiveGapcloser gapcloser)
{
if (R.IsReady() && gapcloser.Sender.IsValidTarget(R.Range) && GetValue<bool>("UseRMG"))
R.CastOnUnit(gapcloser.Sender);
}
public void Interrupter_OnPossibleToInterrupt(Obj_AI_Base unit, InterruptableSpell spell)
{
if (R.IsReady() && unit.IsValidTarget(R.Range) && GetValue<bool>("UseRMI"))
R.CastOnUnit(unit);
}
public Obj_AI_Hero GetEMarkedEnemy
{
get
{
return
ObjectManager.Get<Obj_AI_Hero>()
.Where(
enemy =>
!enemy.IsDead &&
enemy.IsValidTarget(W.Range + Orbwalking.GetRealAutoAttackRange(ObjectManager.Player)))
.FirstOrDefault(enemy => enemy.Buffs.Any(buff => buff.DisplayName == "TristanaEChargeSound"));
}
}
public int GetEMarkedCount
{
get
{
return
GetEMarkedEnemy.Buffs.Where(buff => buff.DisplayName == "TristanaECharge")
.Select(xBuff => xBuff.Count)
.FirstOrDefault();
}
}
public override void Orbwalking_AfterAttack(AttackableUnit unit, AttackableUnit target)
{
var t = target as Obj_AI_Hero;
if (t != null && (ComboActive || HarassActive) && unit.IsMe)
{
var useQ = GetValue<bool>("UseQ" + (ComboActive ? "C" : "H"));
var useE = GetValue<bool>("UseE" + (ComboActive ? "C" : "H"));
if (useQ && Q.IsReady())
Q.CastOnUnit(ObjectManager.Player);
if (useE && canUseE(t) && E.IsReady())
E.CastOnUnit(t);
}
}
private static bool canUseE(Obj_AI_Hero t)
{
if (ObjectManager.Player.CountEnemiesInRange(W.Range + (E.Range / 2)) == 1)
return true;
return (Program.Config.Item("DontUseE" + t.ChampionName) != null &&
Program.Config.Item("DontUseE" + t.ChampionName).GetValue<bool>() == false);
}
public override void Game_OnGameUpdate(EventArgs args)
{
if (!Orbwalking.CanMove(100))
return;
var getEMarkedEnemy = GetEMarkedEnemy;
if (getEMarkedEnemy != null)
{
TargetSelector.SetTarget(getEMarkedEnemy);
}
else
{
var attackRange = Orbwalking.GetRealAutoAttackRange(ObjectManager.Player);
TargetSelector.SetTarget(TargetSelector.GetTarget(attackRange, TargetSelector.DamageType.Physical));
}
//Update Q range depending on level; 600 + 5 × ( Tristana's level - 1)/* dont waste your Q for only 1 or 2 hits. */
//Update E and R range depending on level; 630 + 9 × ( Tristana's level - 1)
Q.Range = 600 + 5 * (ObjectManager.Player.Level - 1);
E.Range = 630 + 9 * (ObjectManager.Player.Level - 1);
R.Range = 630 + 9 * (ObjectManager.Player.Level - 1);
if (GetValue<KeyBind>("UseETH").Active)
{
if (ObjectManager.Player.HasBuff("Recall"))
return;
var t = TargetSelector.GetTarget(E.Range, TargetSelector.DamageType.Physical);
if (E.IsReady() && canUseE(t) && t.IsValidTarget())
E.CastOnUnit(t);
}
if (ComboActive || HarassActive)
{
Obj_AI_Hero t;
if (GetEMarkedEnemy != null)
{
t = GetEMarkedEnemy;
TargetSelector.SetTarget(GetEMarkedEnemy);
}
else
{
t = TargetSelector.GetTarget(W.Range, TargetSelector.DamageType.Physical);
}
var useE = GetValue<bool>("UseE" + (ComboActive ? "C" : "H"));
if (useE && canUseE(t))
{
if (E.IsReady() && t.IsValidTarget(E.Range))
E.CastOnUnit(t);
}
var useW = GetValue<bool>("UseW" + (ComboActive ? "C" : "H"));
if (useW)
{
t = TargetSelector.GetTarget(W.Range, TargetSelector.DamageType.Physical);
if (t.IsValidTarget() && W.IsReady() && GetEMarkedCount == 4 && !t.UnderTurret() &&
ObjectManager.Player.Distance(t) > Orbwalking.GetRealAutoAttackRange(t))
{
W.Cast(t);
}
}
}
//Killsteal
if (!ComboActive)
return;
foreach (var hero in
ObjectManager.Get<Obj_AI_Hero>()
.Where(hero => hero.IsValidTarget(R.Range) || hero.IsValidTarget(W.Range)))
{
if (GetValue<bool>("UseWM") && W.IsReady() &&
ObjectManager.Player.GetSpellDamage(hero, SpellSlot.W) - 10 > hero.Health)
W.Cast(hero);
else if (GetValue<bool>("UseRM") && R.IsReady() &&
ObjectManager.Player.GetSpellDamage(hero, SpellSlot.R) - 30 > hero.Health)
R.CastOnUnit(hero);
}
}
private static float GetComboDamage(Obj_AI_Hero t)
{
var fComboDamage = 0f;
if (E.IsReady())
fComboDamage += (float) ObjectManager.Player.GetSpellDamage(t, SpellSlot.E);
if (R.IsReady())
fComboDamage += (float) ObjectManager.Player.GetSpellDamage(t, SpellSlot.R);
if (ObjectManager.Player.GetSpellSlot("summonerdot") != SpellSlot.Unknown &&
ObjectManager.Player.Spellbook.CanUseSpell(ObjectManager.Player.GetSpellSlot("summonerdot")) ==
SpellState.Ready && ObjectManager.Player.Distance(t) < 550)
fComboDamage += (float) ObjectManager.Player.GetSummonerSpellDamage(t, Damage.SummonerSpell.Ignite);
if (Items.CanUseItem(3144) && ObjectManager.Player.Distance(t) < 550)
fComboDamage += (float) ObjectManager.Player.GetItemDamage(t, Damage.DamageItems.Bilgewater);
if (Items.CanUseItem(3153) && ObjectManager.Player.Distance(t) < 550)
fComboDamage += (float) ObjectManager.Player.GetItemDamage(t, Damage.DamageItems.Botrk);
return fComboDamage;
}
public override void Drawing_OnDraw(EventArgs args)
{
// Draw marked enemy status
var drawEMarksStatus = Program.Config.SubMenu("Drawings").Item("DrawEMarkStatus").GetValue<bool>();
var drawEMarkEnemy = Program.Config.SubMenu("Drawings").Item("DrawEMarkEnemy").GetValue<Circle>();
if (drawEMarksStatus || drawEMarkEnemy.Active)
{
var getEMarkedEnemy = GetEMarkedEnemy;
if (getEMarkedEnemy != null)
{
if (drawEMarksStatus)
{
if (LastTickTime < Environment.TickCount)
LastTickTime = Environment.TickCount + 5000;
var xTime = LastTickTime - Environment.TickCount;
xBuffCount = GetEMarkedCount;
var timer = string.Format("0:{0:D2}", xTime / 1000);
Utils.DrawText(
vText, timer + " : 4 / " + xBuffCount, (int) getEMarkedEnemy.HPBarPosition.X + 145,
(int) getEMarkedEnemy.HPBarPosition.Y + 5, SharpDX.Color.White);
}
if (drawEMarkEnemy.Active)
{
Render.Circle.DrawCircle(GetEMarkedEnemy.Position, 140f, drawEMarkEnemy.Color, 1);
}
}
}
// draw W spell
Spell[] spellList = { W };
foreach (var spell in spellList)
{
var menuItem = GetValue<Circle>("Draw" + spell.Slot);
if (menuItem.Active)
Render.Circle.DrawCircle(ObjectManager.Player.Position, spell.Range, menuItem.Color, 1);
}
// draw E spell
var drawE = Program.Config.SubMenu("Drawings").Item("DrawE").GetValue<Circle>();
if (drawE.Active)
{
Render.Circle.DrawCircle(ObjectManager.Player.Position, E.Range, drawE.Color, 1);
}
}
public override bool ComboMenu(Menu config)
{
config.AddItem(new MenuItem("UseQC" + Id, "Use Q").SetValue(true));
config.AddItem(new MenuItem("UseWC" + Id, "Use W").SetValue(true));
config.AddItem(new MenuItem("UseEC" + Id, "Use E").SetValue(true));
config.AddSubMenu(new Menu("Don't Use E to", "DontUseE"));
{
foreach (var enemy in
ObjectManager.Get<Obj_AI_Hero>().Where(enemy => enemy.Team != ObjectManager.Player.Team))
{
config.SubMenu("DontUseE")
.AddItem(new MenuItem("DontUseE" + enemy.ChampionName, enemy.ChampionName).SetValue(false));
}
}
return true;
}
public override bool HarassMenu(Menu config)
{
config.AddItem(new MenuItem("UseQH" + Id, "Use Q").SetValue(false));
config.AddItem(new MenuItem("UseWH" + Id, "Use W").SetValue(true));
config.AddItem(new MenuItem("UseEH" + Id, "Use E").SetValue(true));
config.AddItem(
new MenuItem("UseETH" + Id, "Use E (Toggle)").SetValue(
new KeyBind("H".ToCharArray()[0], KeyBindType.Toggle)));
return true;
}
public override bool DrawingMenu(Menu config)
{
config.AddItem(new MenuItem("DrawW" + Id, "W range").SetValue(new Circle(true, Color.Beige)));
var drawE = new Menu("Draw E", "DrawE");
{
drawE.AddItem(new MenuItem("DrawE", "E range").SetValue(new Circle(true, Color.Beige)));
drawE.AddItem(
new MenuItem("DrawEMarkEnemy", "E Marked Enemy").SetValue(new Circle(true, Color.GreenYellow)));
drawE.AddItem(new MenuItem("DrawEMarkStatus", "E Marked Status").SetValue(true));
config.AddSubMenu(drawE);
}
var dmgAfterComboItem = new MenuItem("DamageAfterCombo", "Damage After Combo").SetValue(true);
Config.AddItem(dmgAfterComboItem);
return true;
}
public override bool MiscMenu(Menu config)
{
config.AddItem(new MenuItem("UseWM" + Id, "Use W KillSteal").SetValue(true));
config.AddItem(new MenuItem("UseRM" + Id, "Use R KillSteal").SetValue(true));
config.AddItem(new MenuItem("UseRMG" + Id, "Use R Gapclosers").SetValue(true));
config.AddItem(new MenuItem("UseRMI" + Id, "Use R Interrupt").SetValue(true));
return true;
}
public override bool ExtrasMenu(Menu config)
{
return true;
}
public override bool LaneClearMenu(Menu config)
{
return true;
}
}
}
| gpl-3.0 |
JulianH99/pygame2017 | Mundo/main_final.py | 6665 | from powerups.modules.powerup_generator import POWERUP_INTERVAL, PowerupGenerator
import sys as s
from Obstaculo import *
from Escenario import *
from pygame.locals import *
from Bolita.ClaseBolita import *
from Label import Label
from Menu.Menu import Menu
from pygame import *
# aumento de puntaje
SCORE_ADD_INTERVAL = 2000
SCREVENT = pygame.USEREVENT + 3
pygame.time.set_timer(SCREVENT, SCORE_ADD_INTERVAL)
global_score = 20
# POWERUPS
PWEVENT = pygame.USEREVENT + 1
pygame.time.set_timer(PWEVENT, POWERUP_INTERVAL)
powerup = None
sprite_group = pygame.sprite.Group()
pygame.font.init()
def generate():
return PowerupGenerator(ancho, alto - 150).generate()
def colisionBolita(power_up, ball, escen):
if power_up is not None:
power_up.check_collide(ball, escen)
if power_up.effect.triggered:
power_up.effect.start_reset_countdown(ball, 10)
# tamaño ventana
ancho = 800
alto = 600
def creditos():
credits_screen = pygame.display.set_mode((600, 400))
background = pygame.image.load('./credits.jpg').convert()
ext = False
while not ext:
for e in pygame.event.get():
if e.type == QUIT:
ext = True
if e.type == KEYDOWN:
if e.key == K_ESCAPE:
ext = True
main()
credits_screen.blit(background, (0, 0))
pygame.display.flip()
pygame.time.delay(10)
def salir():
exit()
def show_go_screen(final_score):
go_screen = pygame.display.set_mode((600, 400))
background = pygame.image.load("./img/go.jpg").convert()
ext = False
score_label = Label("Puntaje total: " + final_score, 180, 221)
while not ext:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
exit()
if event.key == K_RETURN:
ext = True
main()
go_screen.blit(background, (0, 0))
go_screen.blit(score_label.getLabel(), score_label.getPos())
pygame.display.flip()
def game():
imagenFondo = image.load("Imagenes/fondoEstatico1.png")
init()
ventana = display.set_mode([ancho, alto])
# escenario
escenario = Escenario(2, 1, Escenario.ORIENT_DER_IZQ, ventana, ancho, alto)
# bolita
bolita = Bolita(500, 0, escenario.alto - 40 - escenario.rectPlataforma[0].height, ancho, alto,
imagenFondo.get_height() + (escenario.rectPlataforma[0].height) / 2,
escenario.rectPlataformaA[0].height)
reloj = time.Clock()
cont = 0
cont2 = 0
score_label = Label("Puntage: " + str(bolita.obtenerPuntos()), 10, 5)
life_label = Label("Vida: " + str(bolita.obtenerVida()), 300, 5)
while True:
dt = reloj.tick() # provisional
reloj.tick(60) # frames
tiempo = int(time.get_ticks() / 100)
# bolita.invertirDireccion=True
# escenario.setOrientacion(escenario.ORIENT_IZQ_DER)
score_label.setText("Puntage: " + str(bolita.obtenerPuntos()))
life_label.setText("Vida: " + str(bolita.obtenerVida()))
"""
if tiempo == 50:
bolita.gravedad = False
escenario.setOrientacion(escenario.ORIENT_IZQ_DER)
print("Gravedad inver y sentido escenario izq der y bolita iz y der")
if tiempo == 100:
bolita.gravedad = True
escenario.setOrientacion(escenario.ORIENT_DER_IZQ)
bolita.invertirDireccion = True
print("Gravedad nor y sentido escenario der izq y bolita der iz")
if tiempo == 150:
bolita.gravedad = False
escenario.setOrientacion(escenario.ORIENT_IZQ_DER)
bolita.invertirDireccion = False
print("Gravedad inver y sentido escenario izq der y bolita iz der")
if tiempo == 200:
bolita.gravedad = True
escenario.setOrientacion(escenario.ORIENT_DER_IZQ)
print("Gravedad nor y sentido escenario der izq y bolita iz der")
if tiempo == 250:
bolita.gravedad = False
escenario.setOrientacion(escenario.ORIENT_IZQ_DER)
bolita.invertirDireccion = False
print("Gravedad inver y sentido escenario izq der y bolita iz der")
"""
escenario.moverFondo()
escenario.dibujarFondo(ventana)
for evento in event.get():
if evento.type == KEYDOWN:
if evento.key == K_LEFT or evento.key == K_RIGHT or evento.key == K_UP:
bolita.salto(escenario.velocidad + 10, evento.key,
bolita.modificarVida(escenario.colisionBolita(bolita.rectangulo), escenario))
if evento.type == QUIT:
quit()
s.exit()
if evento.type == PWEVENT:
global powerup
powerup = generate()
sprite_group.add(powerup)
if evento.type == SCREVENT:
bolita.acumularPuntos(global_score)
# bolita
bolita.salto(escenario.velocidad + 10, None,
bolita.modificarVida(escenario.colisionBolita(bolita.rectangulo), escenario))
bolita.dibujarBolita(ventana)
bolita.saltoDoble = False
if bolita.getVivoMuerto() == False:
show_go_screen(str(bolita.obtenerPuntos()))
# powerup
sprite_group.update()
# colisionBolita(powerup,bolita)
sprite_group.draw(ventana)
colisionBolita(powerup, bolita, escenario)
# escneario y obstcaulos
escenario.generarObstaculos(21, tiempo)
escenario.movimientoObstaculos()
escenario.removerObstaculo()
ventana.blit(imagenFondo, (0, 466))
ventana.blit(score_label.getLabel(), score_label.getPos())
ventana.blit(life_label.getLabel(), life_label.getPos())
display.update()
def main():
menu_screen = pygame.display.set_mode((600, 500))
opciones = [
("Jugar", game),
("Creditos", creditos),
("Salir", salir)
]
menu = Menu(opciones)
background = pygame.image.load("./Menu/fondo.jpg").convert()
ext = False
while not ext:
for e in pygame.event.get():
if e.type == QUIT:
exit()
ext = True
menu_screen.blit(background, (0, 0))
menu.actualizar()
menu.imprimir(menu_screen)
pygame.display.flip()
pygame.time.delay(10)
if __name__ == '__main__':
main() | gpl-3.0 |
derekberube/wildstar-foundation-architecture | src/main/java/com/wildstartech/wfa/propertymanagement/Payment.java | 2437 | /*
* Copyright (c) 2001 - 2017 Wildstar Technologies, LLC.
*
* This file is part of Wildstar Foundation Architecture.
*
* Wildstar Foundation Architecture 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.
*
* Wildstar Foundation Architecture 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
* Wildstar Foundation Architecture. If not, see
* <http://www.gnu.org/licenses/>.
*
* Linking this library statically or dynamically with other modules is making a
* combined work based on this library. Thus, the terms and conditions of the
* GNU General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module, the
* terms and conditions of the license of that module. An independent module is
* a module which is not derived from or based on this library. If you modify
* this library, you may extend this exception to your version of the library,
* but you are not obliged to do so. If you do not wish to do so, delete this
* exception statement from your version.
*
* If you need additional information or have any questions, please contact:
*
* Wildstar Technologies, LLC.
* Inlet Beach, FL 32461
* USA
*
* [email protected]
* www.wildstartech.com
*/
package com.wildstartech.wfa.propertymanagement;
import java.util.Date;
import javax.money.MonetaryAmount;
public interface Payment {
//***** amount
public MonetaryAmount getAmount();
public void setAmount(MonetaryAmount amount);
public void setAmount(float amount);
//***** dateReceived
public Date getDateReceived();
public void setDateReceived(Date dateReceived);
} | gpl-3.0 |
heartvalve/OpenFlipper | PluginCollection-Renderers/Plugin-Render-ShaderPipeline/Renderer.cc | 1758 |
#include "Renderer.hh"
#include <OpenFlipper/common/GlobalOptions.hh>
#include <OpenFlipper/BasePlugin/PluginFunctions.hh>
#include <ACG/GL/ShaderCache.hh>
#undef QT_NO_OPENGL
#include <QGLFormat>
#include <QMenu>
// =================================================
Renderer::Renderer()
{
}
Renderer::~Renderer()
{
}
void Renderer::initializePlugin()
{
ACG::ShaderProgGenerator::setShaderDir(OpenFlipper::Options::shaderDirStr());
}
void Renderer::render(ACG::GLState* _glState, Viewer::ViewerProperties& _properties)
{
// collect renderobjects + prepare OpenGL state
prepareRenderingPipeline(_glState, _properties.drawMode(), PluginFunctions::getSceneGraphRootNode());
// render every object
for (int i = 0; i < getNumRenderObjects(); ++i)
renderObject( getRenderObject(i) );
// restore common opengl state
// log window remains hidden otherwise
finishRenderingPipeline();
// dumpRenderObjectsToFile("../../dump_ro.txt", &sortedObjects_[0]);
}
QString Renderer::checkOpenGL()
{
// Get version and check
QGLFormat::OpenGLVersionFlags flags = QGLFormat::openGLVersionFlags();
if ( !flags.testFlag(QGLFormat::OpenGL_Version_3_2) )
return QString("Insufficient OpenGL Version! OpenGL 3.2 or higher required");
// Check extensions
QString glExtensions = QString((const char*)glGetString(GL_EXTENSIONS));
QString missing("");
if ( !glExtensions.contains("GL_ARB_vertex_buffer_object") )
missing += "GL_ARB_vertex_buffer_object extension missing\n";
#ifndef __APPLE__
if ( !glExtensions.contains("GL_ARB_vertex_program") )
missing += "GL_ARB_vertex_program extension missing\n";
#endif
return missing;
}
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2( shaderrenderer , Renderer );
#endif
| gpl-3.0 |
cneira/Taraxacum | include/beast/core/detail/type_traits.hpp | 1762 | //
// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BEAST_DETAIL_TYPE_TRAITS_HPP
#define BEAST_DETAIL_TYPE_TRAITS_HPP
#include <tuple>
#include <type_traits>
#include <stdexcept>
#include <string>
namespace beast {
namespace detail {
template<class... Ts>
struct make_void
{
using type = void;
};
template<class... Ts>
using void_t = typename make_void<Ts...>::type;
template<class... Ts>
inline
void
ignore_unused(Ts const& ...)
{
}
template<class... Ts>
inline
void
ignore_unused()
{}
template<class U>
std::size_t constexpr
max_sizeof()
{
return sizeof(U);
}
template<class U0, class U1, class... Us>
std::size_t constexpr
max_sizeof()
{
return
max_sizeof<U0>() > max_sizeof<U1, Us...>() ?
max_sizeof<U0>() : max_sizeof<U1, Us...>();
}
template<unsigned N, class T, class... Tn>
struct repeat_tuple_impl
{
using type = typename repeat_tuple_impl<
N - 1, T, T, Tn...>::type;
};
template<class T, class... Tn>
struct repeat_tuple_impl<0, T, Tn...>
{
using type = std::tuple<T, Tn...>;
};
template<unsigned N, class T>
struct repeat_tuple
{
using type =
typename repeat_tuple_impl<N-1, T>::type;
};
template<class T>
struct repeat_tuple<0, T>
{
using type = std::tuple<>;
};
template<class Exception>
Exception
make_exception(char const* reason, char const* file, int line)
{
char const* n = file;
for(auto p = file; *p; ++p)
if(*p == '\\' || *p == '/')
n = p + 1;
return Exception{std::string(reason) + " (" +
n + ":" + std::to_string(line) + ")"};
}
} // detail
} // beast
#endif
| gpl-3.0 |
sorab2142/sorabpithawala-magicgrove | source/Grove/Artifical/TargetingRules/GainReach.cs | 571 | namespace Grove.Artifical.TargetingRules
{
using System.Collections.Generic;
using System.Linq;
using Gameplay;
using Gameplay.Misc;
using Gameplay.Targeting;
public class GainReach : TargetingRule
{
protected override IEnumerable<Targets> SelectTargets(TargetingRuleParameters p)
{
var candidates = p.Candidates<Card>(ControlledBy.SpellOwner)
.Where(c => c.CanBlock())
.Where(c => !c.Has().Flying && !c.Has().Reach)
.OrderByDescending(x => x.Power);
return Group(candidates, p.MinTargetCount());
}
}
} | gpl-3.0 |
thEpisode/DevFest-IoT-Microsoft | Server/app/controllers/humidityController.js | 1619 | function HumidityController(dependencies) {
/// Dependencies
var _mongoose;
/// Properties
var _entity;
var constructor = function () {
_mongoose = dependencies.mongoose;
_entity = require('../Models/Humidity')(dependencies);
_entity.Initialize();
}
var createHumidity = function (data, callback) {
var humidity = new _entity.GetModel()(
{
Temperature: data.Temperature,
Humidity: data.Humidity
});
humidity.save().then(function (result) {
// When database return a result call the return
callback();
})
}
var deleteHumidity = function (data, callback) {
_entity.GetModel().findOneAndRemove(data, function (err, result) {
callback(result);
})
}
var getHumidityById = function (data, callback) {
_entity.GetModel().findOne({ "_id": data }, function (err, result) {
if (err) console.log(err);
callback(result);
})
}
var getAllHumidity = function (data, callback) {
_entity.GetModel().find({}, function (err, result) {
if (err) console.log(err);
callback(result);
})
}
var getEntity = function () {
return _entity;
}
return {
Initialize: constructor,
CreateHumidity: createHumidity,
DeleteHumidity: deleteHumidity,
GetHumidityById: getHumidityById,
GetAllHumidity: getAllHumidity,
Entity: getEntity
}
}
module.exports = HumidityController; | gpl-3.0 |
bioothod/apparat | middleware/cors.go | 180 | package middleware
import "github.com/gin-gonic/gin"
func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Next()
}
}
| gpl-3.0 |
risi-kondor/pMMF | utility/ThreadBank2.hpp | 3304 | /*
pMMF is an open source software library for efficiently computing
the MMF factorization of large matrices.
Copyright (C) 2015 Risi Kondor, Nedelina Teneva, Pramod Mudrakarta
This file is part of pMMF.
pMMF 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/>.
*/
#ifndef _ThreadBank2
#define _ThreadBank2
#include <thread>
#include "MMFbase.hpp"
#include "ThreadManager.hpp"
using namespace std;
extern mutex cout_mutex;
extern ThreadManager threadManager;
class ThreadBank2 {
public:
ThreadBank2() = delete;
ThreadBank2(const int _maxthreads = 1000, const int _maxprivileged = 1) :
maxthreads(_maxthreads), maxprivileged(_maxprivileged), nthreads(0), nprivileged(
0) {
gate.lock();
}
;
~ThreadBank2() {
for (auto& th : threads)
th.join();
}
public:
template<class FUNCTION, class OBJ>
void add(FUNCTION lambda, const OBJ x) {
lock_guard < mutex > lock(mx); // unnecessary if called from a single thread
threadManager.enqueue(this);
gate.lock(); // gate can only be unlocked by threadManager
nthreads++;
threads.push_back(
thread(
[this,lambda](OBJ _x) {lambda(_x); nthreads--; threadManager.release(this);},
x));
#ifdef _THREADBANKVERBOSE
printinfo();
#endif
}
template<class FUNCTION, class OBJ1, class OBJ2>
void add(FUNCTION lambda, const OBJ1 x1, const OBJ2 x2) {
lock_guard < mutex > lock(mx);
threadManager.enqueue(this);
gate.lock();
nthreads++;
threads.push_back(
thread([this,lambda](OBJ1 _x1, OBJ2 _x2) {
lambda(_x1,_x2); nthreads--; threadManager.release(this);},
x1, x2));
#ifdef _THREADBANKVERBOSE
printinfo();
#endif
}
template<class FUNCTION, class OBJ1, class OBJ2, class OBJ3>
void add(FUNCTION lambda, const OBJ1 x1, const OBJ2 x2, const OBJ3 x3) {
lock_guard < mutex > lock(mx);
threadManager.enqueue(this);
gate.lock();
nthreads++;
threads.push_back(
thread(
[this,lambda](OBJ1 _x1, OBJ2 _x2, OBJ3 _x3) {
lambda(_x1,_x2,_x3); nthreads--; threadManager.release(this);},
x1, x2, x3));
#ifdef _THREADBANKVERBOSE
printinfo();
#endif
}
bool is_ready() {
return nthreads < maxthreads;
}
void printinfo() {
lock_guard < mutex > lock(cout_mutex);
cout << " (threads: " << nthreads - nprivileged << "+" << nprivileged
<< " local, ";
cout << threadManager.get_nthreads() << " global)" << endl;
}
public:
mutex mx;
mutex gate;
atomic<int> nthreads;
int nprivileged = 0; // only to be touched by threadManager
int maxthreads = 4;
int maxprivileged = 1;
vector<thread> threads;
};
#endif
| gpl-3.0 |
cooked/NDT | sc.ndt.editor.fast.fst/src-gen/sc/ndt/editor/fast/fastfst/impl/nDTTorSprImpl.java | 5143 | /**
*/
package sc.ndt.editor.fast.fastfst.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import sc.ndt.editor.fast.fastfst.FastfstPackage;
import sc.ndt.editor.fast.fastfst.nDTTorSpr;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>nDT Tor Spr</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link sc.ndt.editor.fast.fastfst.impl.nDTTorSprImpl#getValue <em>Value</em>}</li>
* <li>{@link sc.ndt.editor.fast.fastfst.impl.nDTTorSprImpl#getName <em>Name</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class nDTTorSprImpl extends MinimalEObjectImpl.Container implements nDTTorSpr
{
/**
* The default value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected static final float VALUE_EDEFAULT = 0.0F;
/**
* The cached value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected float value = VALUE_EDEFAULT;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected nDTTorSprImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return FastfstPackage.eINSTANCE.getnDTTorSpr();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getValue()
{
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setValue(float newValue)
{
float oldValue = value;
value = newValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FastfstPackage.NDT_TOR_SPR__VALUE, oldValue, value));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName()
{
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName)
{
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FastfstPackage.NDT_TOR_SPR__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case FastfstPackage.NDT_TOR_SPR__VALUE:
return getValue();
case FastfstPackage.NDT_TOR_SPR__NAME:
return getName();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case FastfstPackage.NDT_TOR_SPR__VALUE:
setValue((Float)newValue);
return;
case FastfstPackage.NDT_TOR_SPR__NAME:
setName((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case FastfstPackage.NDT_TOR_SPR__VALUE:
setValue(VALUE_EDEFAULT);
return;
case FastfstPackage.NDT_TOR_SPR__NAME:
setName(NAME_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case FastfstPackage.NDT_TOR_SPR__VALUE:
return value != VALUE_EDEFAULT;
case FastfstPackage.NDT_TOR_SPR__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (value: ");
result.append(value);
result.append(", name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //nDTTorSprImpl
| gpl-3.0 |
martin-eden/workshop | concepts/date/is_valid_month.lua | 373 | --[[
Return whether given integer is valid month number.
If not, return false and string with error.
]]
return
function(month)
assert_integer(month)
local result, err_msg
result = (month >= 1) and (month <= 12)
if not result then
err_msg =
('Invalid value for month number: %d.'):format(month)
end
return result, err_msg
end
| gpl-3.0 |
COSMOGRAIL/COSMOULINE | pipe/2_skysub_scripts/123.py | 372 | import os
execfile("../config.py")
from variousfct import *
os.system("python 1_skysub_NU.py")
if defringed:
os.system("python 1b_compute_fringes.py")
if sample_only :
os.system("python 2_skypng_sample_NU.py")
else:
os.system("python 2_skypng_NU.py")
print "I can remove the electron images."
proquest(True)
os.system("python 3_facult_rm_electrons_NU.py")
| gpl-3.0 |
niksoc/srmconnect | app/js/pages/ListViewPage.js | 3722 | import React from 'react';
import {Col, Pagination, Nav, NavItem} from 'react-bootstrap';
import PageTitle from '../components/PageTitle';
import ListView from '../components/ModelViews/ListView';
import InfoPanel from '../components/InfoPanel';
import SearchBox from '../components/SearchBox';
import axios from 'axios';
import {BASE_URL} from '../constants';
class ListViewPage extends React.Component{
constructor(){
super();
this.state = {
page:1,
ordering:0,
num_pages:1,
tags:[],
q:null
};
}
resetState(){
this.state = {
page:1,
ordering:0,
num_pages:1,
tags:[],
q:null
};
this.state.page = 1;
}
construct_data_url(props = this.props){
const tags = this.state.tags.length>0? this.state.tags.join(','):'';
const ordering = props.route.orderings[this.state.ordering];
const q = this.state.q? this.state.q:'';
return `/api/list/${props.route.model}/?page=${this.state.page}&ordering=${ordering}&tags=${tags}&q=${q}`;
}
getPageCount(props = this.props){
const q = this.state.q? this.state.q:'';
axios.get(`/api/count/${props.route.model}/?tags=${this.state.tags}&q=${q}`)
.then(({data})=> {if(!this.ignoreLastFetch) this.setState({num_pages:Math.floor(data.count/15)+1});})
.catch((error)=> console.log(error));
}
updateListData(props = this.props){
this.getPageCount(props);
axios.get(this.construct_data_url(props))
.then(({data})=> {if(!this.ignoreLastFetch) this.setState({data});})
.catch((error)=> console.log(error));
}
componentWillUnmount(){
this.ignoreLastFetch = true;
}
componentDidMount(){
this.updateListData();
}
componentWillReceiveProps(newProps){
this.resetState();
this.updateListData(newProps);
}
handlePageSelect(eventKey){
if(!(eventKey>this.state.num_pages)){
this.setState({
page: eventKey
});
this.state.page = eventKey;
this.updateListData();
}
}
handleOrderingSelect(eventKey){
this.setState({
ordering: eventKey,
page: 1
});
this.state.ordering = eventKey;
this.state.page = 1;
this.updateListData();
}
setQuery(q){
this.resetState();
this.setState({q});
this.state.q=q;
this.updateListData();
}
render(){
const inlineBlock = {
'display':'inline-block'
};
const orderingButtons = this.props.route.orderings.map((name, i)=>
<NavItem eventKey={i} key={i}>
{this.props.route.orderings[i].slice(1,this.props.route.orderings[i].length)}
</NavItem>);
let search = null;
if(this.props.route.searchForm)
search = React.createElement(this.props.route.searchForm, {setQuery:this.setQuery.bind(this)});
else search = React.createElement(SearchBox, {setQuery:this.setQuery.bind(this)});
return (
<div>
<PageTitle model={this.props.route.model} title={this.props.route.title} src={`/api/create/${this.props.route.model}/`} />
<span style={{position:'relative', bottom:'20px'}}>sort by:</span> <Nav bsStyle="pills" style={{...inlineBlock, marginBottom:'10px'}} activeKey={this.state.ordering} onSelect={this.handleOrderingSelect.bind(this)}>
{orderingButtons}
</Nav>
{search}
<ListView itemsPerRow={this.props.route.itemsPerRow || 1} data={this.state.data} class={this.props.route.class} bsStyle={this.props.route.bsStyle} model={this.props.route.model} detail_url={`${BASE_URL}${this.props.route.model}/`} />
<Pagination
prev
next
first
last
ellipsis
boundaryLinks
items={this.state.num_pages}
maxButtons={3}
activePage={this.state.page}
onSelect={this.handlePageSelect.bind(this)} />
</div>
);
}
};
export default ListViewPage;
| gpl-3.0 |
eljost/pysisyphus | tests_staging/test_baker_irc/test_baker_irc.py | 2333 | #!/usr/bin/env python3
import itertools as it
from pathlib import Path
import shutil
from pysisyphus.helpers import get_baker_opt_ts_geoms
from pysisyphus.color import green, red
from pysisyphus.calculators import Gaussian16
from pysisyphus.irc import EulerPC
colors = {
True: green,
False: red,
}
geoms, meta_data = get_baker_opt_ts_geoms()
works = (
"01_hcn_opt_ts.xyz",
"03_h2co_opt_ts.xyz",
"04_ch3o_opt_ts.xyz",
"05_cyclopropyl_opt_ts.xyz",
"06_bicyclobutane_opt_ts.xyz",
"07_bicyclobutane_opt_ts.xyz",
"08_formyloxyethyl_opt_ts.xyz",
"13_hf_abstraction_opt_ts.xyz",
"14_vinyl_alcohol_opt_ts.xyz",
"16_h2po4_anion_opt_ts.xyz",
"18_silyene_insertion_opt_ts.xyz",
"19_hnccs_opt_ts.xyz",
"21_acrolein_rot_opt_ts.xyz",
"20_hconh3_cation_opt_ts.xyz",
"23_hcn_h2_opt_ts.xyz",
"24_h2cnh_opt_ts.xyz",
"25_hcnh2_opt_ts.xyz",
)
fails = (
# "05_cyclopropyl_opt_ts.xyz",
)
only = (
# "01_hcn_opt_ts.xyz",
# "16_h2po4_anion_opt_ts.xyz"
"08_formyloxyethyl_opt_ts.xyz",
)
use = (
# works,
#fails,
only,
)
use_meta_data = dict()
for key in it.chain(*use):
use_meta_data[key] = meta_data[key]
for i, (xyz_fn, (charge, mult)) in enumerate(use_meta_data.items()):
geom = geoms[xyz_fn]
print(f"@{i:02d}: {xyz_fn} ({charge},{mult})")
calc_kwargs = {
"route": "HF/3-21G",
"pal": 4,
"charge": charge,
"mult": mult,
}
# Otherwise SCF converges to wrong solution with no imaginary frequencies
if xyz_fn == "05_cyclopropyl_opt_ts.xyz":
calc_kwargs["route"] += " scf=qc"
geom.set_calculator(Gaussian16(**calc_kwargs))
irc_kwargs = {
"step_length": .1,
"hessian_recalc": 10,
# "displ_energy": 1e-3,
# "hessian_recalc": 10,
# "displ": "length",
# "backward": False,
# "forward": False,
}
irc = EulerPC(geom, **irc_kwargs)
irc.run()
forward_steps = irc.forward_cycle + 1
backward_steps = irc.backward_cycle + 1
col = colors[irc.converged]
print()
print(col(f"@Converged: {irc.converged}, (F {forward_steps}, B {backward_steps})"))
src = "finished_irc.trj"
dst = Path(xyz_fn).stem + "_finished_irc.trj"
shutil.copy(src, dst)
print(f"@Copied '{src}' to '{dst}'")
| gpl-3.0 |
informationsea/filereader | src/filereader_mmap.hpp | 776 | #ifndef _FILEREADER_MMAP_H_
#define _FILEREADER_MMAP_H_
#ifndef _WIN32
#include <sys/types.h>
#include "filereader_core.hpp"
class MmapReader : public FileReader
{
public:
MmapReader();
virtual ~MmapReader();
virtual bool open(int fd);
virtual const char* read(size_t length, size_t *readlen);
virtual bool seek(off_t offset);
virtual off_t tell(void) {return m_offset;}
virtual off_t length(void) {return m_filesize;}
virtual bool eof(void) {return m_offset == m_filesize;}
virtual int getc();
virtual const char* readblock(size_t *readlen, isdelimiter_func f, void* userobj);
private:
off_t m_filesize;
char *m_mapped_buffer;
size_t m_mapped_length;
off_t m_offset;
};
#endif
#endif /* _FILEREADER_MMAP_H_ */
| gpl-3.0 |
AuScope/VEGL-Portal | src/main/java/org/auscope/portal/server/vegl/VEGLJobManager.java | 4770 | package org.auscope.portal.server.vegl;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Class that talks to the data objects to retrieve or save data
*
* @author Cihan Altinay
* @author Josh Vote
* @author Richard Goh
*/
public class VEGLJobManager {
protected final Log logger = LogFactory.getLog(getClass());
private VEGLJobDao veglJobDao;
private VEGLSeriesDao veglSeriesDao;
private VGLJobAuditLogDao vglJobAuditLogDao;
private VGLSignatureDao vglSignatureDao;
public List<VEGLSeries> querySeries(String user, String name, String desc) {
return veglSeriesDao.query(user, name, desc);
}
public List<VEGLJob> getSeriesJobs(int seriesId) {
return veglJobDao.getJobsOfSeries(seriesId);
}
public List<VEGLJob> getPendingOrActiveJobs() {
return veglJobDao.getPendingOrActiveJobs();
}
public List<VEGLJob> getInQueueJobs() {
return veglJobDao.getInQueueJobs();
}
public VEGLJob getJobById(int jobId) {
return veglJobDao.get(jobId);
}
public void deleteJob(VEGLJob job) {
veglJobDao.deleteJob(job);
}
public VEGLSeries getSeriesById(int seriesId) {
return veglSeriesDao.get(seriesId);
}
public VGLSignature getSignatureByUser(String user) {
return vglSignatureDao.getSignatureOfUser(user);
}
public void saveJob(VEGLJob veglJob) {
veglJobDao.save(veglJob);
}
/**
* Create the job life cycle audit trail. If the creation is unsuccessful, it
* will silently fail and log the failure message to error log.
* @param oldJobStatus
* @param curJob
* @param message
*/
public void createJobAuditTrail(String oldJobStatus, VEGLJob curJob, String message) {
VGLJobAuditLog vglJobAuditLog = null;
try {
vglJobAuditLog = new VGLJobAuditLog();
vglJobAuditLog.setJobId(curJob.getId());
vglJobAuditLog.setFromStatus(oldJobStatus);
vglJobAuditLog.setToStatus(curJob.getStatus());
vglJobAuditLog.setTransitionDate(new Date());
vglJobAuditLog.setMessage(message);
// Failure in the creation of the job life cycle audit trail is
// not critical hence we allow it to fail silently and log it.
vglJobAuditLogDao.save(vglJobAuditLog);
} catch (Exception ex) {
logger.warn("Error creating audit trail for job: " + vglJobAuditLog, ex);
}
}
/**
* Create the job life cycle audit trail. If the creation is unsuccessful, it
* will silently fail and log the failure message to error log.
* @param oldJobStatus
* @param curJob
* @param message
*/
public void createJobAuditTrail(String oldJobStatus, VEGLJob curJob, Exception exception) {
String message = ExceptionUtils.getStackTrace(exception);
if(message.length() > 1000){
message = message.substring(0,1000);
}
VGLJobAuditLog vglJobAuditLog = null;
try {
vglJobAuditLog = new VGLJobAuditLog();
vglJobAuditLog.setJobId(curJob.getId());
vglJobAuditLog.setFromStatus(oldJobStatus);
vglJobAuditLog.setToStatus(curJob.getStatus());
vglJobAuditLog.setTransitionDate(new Date());
vglJobAuditLog.setMessage(message);
// Failure in the creation of the job life cycle audit trail is
// not critical hence we allow it to fail silently and log it.
vglJobAuditLogDao.save(vglJobAuditLog);
} catch (Exception ex) {
logger.warn("Error creating audit trail for job: " + vglJobAuditLog, ex);
}
}
public void deleteSeries(VEGLSeries series) {
veglSeriesDao.delete(series);
}
public void saveSeries(VEGLSeries series) {
veglSeriesDao.save(series);
}
public void saveSignature(VGLSignature vglSignature) {
vglSignatureDao.save(vglSignature);
}
public void setVeglJobDao(VEGLJobDao veglJobDao) {
this.veglJobDao = veglJobDao;
}
public void setVeglSeriesDao(VEGLSeriesDao veglSeriesDao) {
this.veglSeriesDao = veglSeriesDao;
}
public void setVglJobAuditLogDao(VGLJobAuditLogDao vglJobAuditLogDao) {
this.vglJobAuditLogDao = vglJobAuditLogDao;
}
public void setVglSignatureDao(VGLSignatureDao vglSignatureDao) {
this.vglSignatureDao = vglSignatureDao;
}
} | gpl-3.0 |
lawl-dev/Kiwi | src/Kiwi.Semantic/Binder/Nodes/BoundParameter.cs | 763 | using Kiwi.Parser.Nodes;
namespace Kiwi.Semantic.Binder.Nodes
{
public class BoundParameter : BoundNode, IBoundMember, IParameter
{
public BoundParameter(string name, IType type, ParameterSyntax parameterSyntax) : base(parameterSyntax)
{
Name = name;
Type = type;
}
public IType Type { get; }
public string Name { get; }
}
public interface IParameter
{
string Name { get; }
IType Type { get; }
}
public class SpecialParameter : IParameter
{
public SpecialParameter(string name, IType type)
{
Name = name;
Type = type;
}
public string Name { get; }
public IType Type { get; }
}
} | gpl-3.0 |
ngspipes/engine | src/main/java/ngspipesengine/core/configurator/engines/VMManager.java | 2552 | /*-
* Copyright (c) 2016, NGSPipes Team <[email protected]>
* All rights reserved.
*
* This file is part of NGSPipes <http://ngspipes.github.io/>.
*
* 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 ngspipesengine.core.configurator.engines;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class VMManager {
public static final String BASE_VM_NAME = "NGSPipesEngineExecutor";
protected static final List<String> REGISTERED_NAMES = new LinkedList<>();
protected static final Object LOCK = new Object();
public static String register(String vmName) {
synchronized (LOCK) {
if(REGISTERED_NAMES.contains(vmName) || vmName.equals(BASE_VM_NAME))
vmName = getName();
REGISTERED_NAMES.add(vmName);
return vmName;
}
}
public static void unregister(String vmName) {
synchronized (LOCK) {
if(REGISTERED_NAMES.contains(vmName))
REGISTERED_NAMES.remove(vmName);
}
}
private static String getName() {
if(REGISTERED_NAMES.size() == 0)
return BASE_VM_NAME + "0";
return BASE_VM_NAME + getNextNumber();
}
private static int getNextNumber() {
int[] usedNumbers = getRegisteredNumbers();
Arrays.sort(usedNumbers);
for(int idx = 0; idx < usedNumbers.length - 1; idx++) {
if (usedNumbers[idx] - usedNumbers[idx + 1] > -1)
return usedNumbers[idx] + 1;
}
return usedNumbers[usedNumbers.length - 1] + 1;
}
private static int[] getRegisteredNumbers() {
int[] registeredNumbers = new int[REGISTERED_NAMES.size()];
int idx = 0;
for (String name : REGISTERED_NAMES) {
name = name.replace(BASE_VM_NAME, "");
registeredNumbers[idx++] = Integer.parseInt(name);
}
return registeredNumbers;
}
}
| gpl-3.0 |
gsterjov/fusemc | Plugin.Theatre/Widgets/VideoWidget.cs | 3322 | /*
Copyright (c) Goran Sterjov
This file is part of the Fuse Project.
Fuse 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.
Fuse 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 Fuse; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Runtime.InteropServices;
using Gtk;
namespace Fuse.Plugin.Theatre
{
/// <summary>
/// The widget that actually shows the video.
/// </summary>
public class VideoWidget : EventBox
{
ulong drawable_xid = 0;
bool active = false;
// global widgets
public DrawingArea drawable = new DrawingArea ();
AspectFrame aspect = new AspectFrame (null, 0.5f, 0.5f, 1, false);
Gdk.Pixbuf logo = new Gdk.Pixbuf (null, "fuse-logo-theatre.png");
// create the widget
public VideoWidget (bool active) : base ()
{
this.active = active;
aspect.ShadowType = ShadowType.None;
aspect.Add (drawable);
this.Add (aspect);
this.Realized += box_realized;
drawable.Realized += drawable_realized;
drawable.ExposeEvent += drawable_exposed;
}
// make the media engine use this window
void drawable_realized (object o, EventArgs args)
{
drawable.ModifyBg (StateType.Normal, new Gdk.Color (0,0,0));
drawable_xid = gdk_x11_drawable_get_xid(drawable.GdkWindow.Handle);
if (active)
{
Global.Core.Fuse.MediaControls.MediaEngine.SetWindow (drawable_xid);
}
}
// make everything black
void box_realized (object o, EventArgs args)
{
this.ModifyBg (StateType.Normal, new Gdk.Color (0,0,0));
}
// make everything black
void drawable_exposed (object o, ExposeEventArgs args)
{
if (Global.Core.Fuse.MediaControls.MediaEngine.HasVideo) return;
int width, height;
this.GdkWindow.GetSize (out width, out height);
float ratio = (float)width / (float)height;
if (aspect.Ratio != ratio)
aspect.Ratio = ratio;
if (Global.Core.Fuse.MediaControls.MediaEngine.CurrentStatus == MediaStatus.Playing ||
Global.Core.Fuse.MediaControls.MediaEngine.CurrentStatus == MediaStatus.Paused)
return;
int x = 0; int y = 0;
if (width > logo.Width)
x = (width - logo.Width) / 2;
if (height > logo.Height)
y = (height - logo.Height) / 2;
drawable.GdkWindow.DrawPixbuf (drawable.Style.BlackGC, logo, 0,0,x,y, -1, -1, Gdk.RgbDither.None, 0,0);
}
/// <summary>
/// Changes the aspect ratio of the widget.
/// </summary>
public void ChangeAspect (float ratio)
{
aspect.Ratio = ratio;
}
/// <summary>
/// The window ID of the widget to draw on.
/// </summary>
public ulong Drawable {
get { return drawable_xid; }
}
[DllImport("gdk-x11-2.0")]
static extern ulong gdk_x11_drawable_get_xid(IntPtr window);
}
}
| gpl-3.0 |
soft4good/extension-release | lib/ObfuscatorIO/ObfuscatorIO/Api.php | 2761 | <?php
namespace ObfuscatorIO;
const BASE_URL = 'https://obfuscator.io';
class API
{
static function initRequest( $sUrl )
{
$iRequest = curl_init();
curl_setopt( $iRequest, CURLOPT_HEADER, 0 );
curl_setopt( $iRequest, CURLOPT_FOLLOWLOCATION, 1 );
curl_setopt( $iRequest, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $iRequest, CURLOPT_URL, $sUrl );
return $iRequest;
}
static function get( $sEndpoint, $aParams = null )
{
// not needed at this point...
}
static function post( $sEndpoint, $aParams = null )
{
// construct API URL
$sApiUrl = BASE_URL . "/$sEndpoint";
// construct request body
$jsonBody = json_encode($aParams);
// Do the request
$iRequest = self::initRequest( $sApiUrl );
curl_setopt( $iRequest, CURLOPT_VERBOSE, 1 );
curl_setopt( $iRequest, CURLOPT_HEADER, 1 );
// TODO: fix this !!!!!!! SECURITY !!!!!!!
curl_setopt($iRequest, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($iRequest, CURLOPT_SSL_VERIFYPEER, 0);
// ---------------------------------------
curl_setopt( $iRequest, CURLOPT_ENCODING, "");
curl_setopt( $iRequest, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $iRequest, CURLOPT_TIMEOUT, 30 );
curl_setopt( $iRequest, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
curl_setopt( $iRequest, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $iRequest, CURLOPT_POSTFIELDS, $jsonBody);
curl_setopt( $iRequest, CURLOPT_HTTPHEADER, array(
"Accept: */*",
"Accept-Encoding: gzip, deflate",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Host: obfuscator.io",
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36",
"cache-control: no-cache",
"Content-Type: application/json",
'Content-Length: ' . strlen($jsonBody)
)
);
$sResponse = curl_exec( $iRequest );
return $sResponse;
}
static function delete( $sEndpoint, $sSite = SITE_QUIBIDS, $aParams = null )
{
// not needed at this point...
}
static function put( $sEndpoint, $sSite = SITE_QUIBIDS, $aParams = null )
{
// not needed at this point...
}
static function patch( $sEndpoint, $sSite = SITE_QUIBIDS, $aParams = null )
{
// not needed at this point...
}
static function head( $sEndpoint, $sSite = SITE_QUIBIDS, $aParams = null )
{
// not needed at this point...
}
static function options( $sEndpoint, $sSite = SITE_QUIBIDS, $aParams = null )
{
// not needed at this point...
}
} | gpl-3.0 |
rendermani/ascio-ssl-whmcs-plugin | v3/service/GetMessagesResponse.php | 655 | <?php
namespace ascio\v3;
class GetMessagesResponse extends AbstractResponse
{
/**
* @var ArrayOfMessage $Messages
*/
protected $Messages = null;
/**
* @param int $ResultCode
*/
public function __construct($ResultCode = null)
{
parent::__construct($ResultCode);
}
/**
* @return ArrayOfMessage
*/
public function getMessages()
{
return $this->Messages;
}
/**
* @param ArrayOfMessage $Messages
* @return \ascio\v3\GetMessagesResponse
*/
public function setMessages($Messages)
{
$this->Messages = $Messages;
return $this;
}
}
| gpl-3.0 |
sipes23/Omeka | application/models/ElementSetTable.php | 1262 | <?php
/**
* @copyright Roy Rosenzweig Center for History and New Media, 2007-2010
* @license http://www.gnu.org/licenses/gpl-3.0.txt
* @package Omeka
*/
/**
* @package Omeka
* @subpackage Models
* @author CHNM
* @copyright Roy Rosenzweig Center for History and New Media, 2007-2010
*/
class ElementSetTable extends Omeka_Db_Table
{
public function getSelect() {
$select = parent::getSelect();
$select->order('id ASC');
return $select;
}
/**
* Find all the element sets that correspond to a particular record type.
* If the second param is set, this will include all element sets that belong
* to the 'All' record type.
*
* @param string
* @param boolean
* @return array
*/
public function findByRecordType($recordTypeName, $includeAll = true)
{
$select = $this->getSelect();
$select->where('record_type = ?', $recordTypeName);
if ($includeAll) {
$select->orWhere('record_type IS NULL');
}
return $this->fetchObjects($select);
}
public function findByName($name)
{
$select = $this->getSelect()->where('name = ?', $name);
return $this->fetchObject($select);
}
}
| gpl-3.0 |
Icemap/LineDesignManager | src/main/java/com/studio/tensor/ldm/controller/TestController.java | 986 | package com.studio.tensor.ldm.controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.studio.tensor.ldm.bean.FileSetting;
import com.studio.tensor.ldm.utils.FileUtils;
@Controller
@RequestMapping("/test")
public class TestController
{
@Autowired
FileSetting fileSetting;
@ResponseBody
@RequestMapping("/save")
public String saveFile(@RequestParam(value = "file",required = true)MultipartFile file)
{
String fileName = new Date().getTime() + file.getOriginalFilename();
FileUtils.saveFile(FileUtils.safeGetInputStream(file),
fileName, fileSetting.getSaveFilePath());
return fileSetting.getGetFilePath() + fileName;
}
}
| gpl-3.0 |
jrialland/parserjunior | old/lexer/src/test/java/net/jr/common/PositionTest.java | 1504 | package net.jr.common;
import net.jr.marshalling.MarshallingUtil;
import org.junit.Assert;
import org.junit.Test;
public class PositionTest {
@Test
public void test() {
Position p = new Position(12, 21);
Assert.assertEquals(12, p.getLine());
Assert.assertEquals(21, p.getColumn());
Assert.assertEquals(22, p.nextColumn().getColumn());
Assert.assertEquals(13, p.nextLine().getLine());
Assert.assertEquals(1, p.nextLine().getColumn());
Assert.assertEquals("12:21", p.toString());
Position p2 = new Position(12, 21);
Assert.assertEquals(p.hashCode(), p2.hashCode());
Assert.assertFalse(p.equals(new Position(13, 21)));
Assert.assertFalse(p.equals(new Position(12, 20)));
Assert.assertFalse(p.equals(null));
Assert.assertFalse(p.equals(new Object()));
Assert.assertTrue(p.equals(p2));
}
@Test
public void testUpdate() {
Position p = Position.start();
p = p.updated('c');
Assert.assertEquals(1, p.getLine());
Assert.assertEquals(2, p.getColumn());
p = p.updated('\n');
Assert.assertEquals(2, p.getLine());
Assert.assertEquals(1, p.getColumn());
}
@Test
public void testMarshall() {
Position p = new Position(54, 151);
byte[] bytes = MarshallingUtil.toByteArray(p, false);
Position p2 = MarshallingUtil.fromByteArray(bytes, false);
Assert.assertEquals(p, p2);
}
}
| gpl-3.0 |
PlamenHP/Softuni | Programing Basics/Programming Basics Exam - 17 January 2016/MasterHerbalist/MasterHerbalist.cs | 1429 |
namespace Namespace
{
using System;
using System.Collections.Generic;
using System.Linq;
class MasterHerbalist
{
static void Main()
{
int expense = int.Parse(Console.ReadLine());
int days = 0;
int totalEarn = 0;
string command;
while ((command = Console.ReadLine()) != "Season Over")
{
days++;
int dailyEarn = 0;
string[] parameter = command.Split();
int hours = int.Parse(parameter[0]);
string path = parameter[1];
int price = int.Parse(parameter[2]);
int herbs = 0;
for (int i = 0; i < hours; i++)
{
if (path[i % (path.Length)] == 'H')
{
herbs++;
}
}
dailyEarn = herbs * price;
totalEarn += dailyEarn;
}
double avgEarn = (double)totalEarn / days;
double profit = avgEarn - expense;
if (profit >= 0)
{
Console.WriteLine("Times are good. Extra money per day: {0:f2}.", profit);
}
else
{
Console.WriteLine("We are in the red. Money needed: {0}.", expense * days - totalEarn);
}
}
}
}
| gpl-3.0 |
neeasade/qutebrowser | tests/unit/browser/webkit/test_history.py | 13078 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2016 Florian Bruhin (The Compiler) <[email protected]>
#
# This file is part of qutebrowser.
#
# qutebrowser 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.
#
# qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Tests for the global page history."""
import base64
import logging
import pytest
import hypothesis
from hypothesis import strategies
from PyQt5.QtCore import QUrl
from PyQt5.QtWebKit import QWebHistoryInterface
from qutebrowser.browser.webkit import history
from qutebrowser.utils import objreg
class FakeWebHistory:
"""A fake WebHistory object."""
def __init__(self, history_dict):
self.history_dict = history_dict
@pytest.fixture(autouse=True)
def prerequisites(config_stub, fake_save_manager):
"""Make sure everything is ready to initialize a WebHistory."""
config_stub.data = {'general': {'private-browsing': False}}
@pytest.fixture()
def hist(tmpdir):
return history.WebHistory(hist_dir=str(tmpdir), hist_name='history')
def test_async_read_twice(monkeypatch, qtbot, tmpdir, caplog):
(tmpdir / 'filled-history').write('\n'.join([
'12345 http://example.com/ title',
'67890 http://example.com/',
'12345 http://qutebrowser.org/ blah',
]))
hist = history.WebHistory(hist_dir=str(tmpdir), hist_name='filled-history')
next(hist.async_read())
with pytest.raises(StopIteration):
next(hist.async_read())
expected = "Ignoring async_read() because reading is started."
assert len(caplog.records) == 1
assert caplog.records[0].msg == expected
def test_async_read_no_datadir(qtbot, config_stub, fake_save_manager):
config_stub.data = {'general': {'private-browsing': False}}
hist = history.WebHistory(hist_dir=None, hist_name='history')
with qtbot.waitSignal(hist.async_read_done):
list(hist.async_read())
@pytest.mark.parametrize('redirect', [True, False])
def test_adding_item_during_async_read(qtbot, hist, redirect):
"""Check what happens when adding URL while reading the history."""
url = QUrl('http://www.example.com/')
with qtbot.assertNotEmitted(hist.add_completion_item), \
qtbot.assertNotEmitted(hist.item_added):
hist.add_url(url, redirect=redirect, atime=12345)
if redirect:
with qtbot.assertNotEmitted(hist.add_completion_item):
with qtbot.waitSignal(hist.async_read_done):
list(hist.async_read())
else:
with qtbot.waitSignals([hist.add_completion_item,
hist.async_read_done]):
list(hist.async_read())
assert not hist._temp_history
expected = history.Entry(url=url, atime=12345, redirect=redirect, title="")
assert list(hist.history_dict.values()) == [expected]
def test_private_browsing(qtbot, tmpdir, fake_save_manager, config_stub):
"""Make sure no data is saved at all with private browsing."""
config_stub.data = {'general': {'private-browsing': True}}
private_hist = history.WebHistory(hist_dir=str(tmpdir),
hist_name='history')
# Before initial read
with qtbot.assertNotEmitted(private_hist.add_completion_item), \
qtbot.assertNotEmitted(private_hist.item_added):
private_hist.add_url(QUrl('http://www.example.com/'))
assert not private_hist._temp_history
# read
with qtbot.assertNotEmitted(private_hist.add_completion_item), \
qtbot.assertNotEmitted(private_hist.item_added):
with qtbot.waitSignals([private_hist.async_read_done]):
list(private_hist.async_read())
# after read
with qtbot.assertNotEmitted(private_hist.add_completion_item), \
qtbot.assertNotEmitted(private_hist.item_added):
private_hist.add_url(QUrl('http://www.example.com/'))
assert not private_hist._temp_history
assert not private_hist._new_history
assert not private_hist.history_dict
def test_iter(hist):
list(hist.async_read())
url = QUrl('http://www.example.com/')
hist.add_url(url, atime=12345)
entry = history.Entry(url=url, atime=12345, redirect=False, title="")
assert list(hist) == [entry]
def test_len(hist):
assert len(hist) == 0
list(hist.async_read())
url = QUrl('http://www.example.com/')
hist.add_url(url)
assert len(hist) == 1
@pytest.mark.parametrize('line', [
'12345 http://example.com/ title', # with title
'67890 http://example.com/', # no title
'12345 http://qutebrowser.org/ ', # trailing space
' ',
'',
])
def test_read(hist, tmpdir, line):
(tmpdir / 'filled-history').write(line + '\n')
hist = history.WebHistory(hist_dir=str(tmpdir), hist_name='filled-history')
list(hist.async_read())
def test_updated_entries(hist, tmpdir):
(tmpdir / 'filled-history').write('12345 http://example.com/\n'
'67890 http://example.com/\n')
hist = history.WebHistory(hist_dir=str(tmpdir), hist_name='filled-history')
list(hist.async_read())
assert hist.history_dict['http://example.com/'].atime == 67890
hist.add_url(QUrl('http://example.com/'), atime=99999)
assert hist.history_dict['http://example.com/'].atime == 99999
def test_invalid_read(hist, tmpdir, caplog):
(tmpdir / 'filled-history').write('foobar\n12345 http://example.com/')
hist = history.WebHistory(hist_dir=str(tmpdir), hist_name='filled-history')
with caplog.at_level(logging.WARNING):
list(hist.async_read())
entries = list(hist.history_dict.values())
assert len(entries) == 1
assert len(caplog.records) == 1
msg = "Invalid history entry 'foobar': 2 or 3 fields expected!"
assert caplog.records[0].msg == msg
def test_get_recent(hist, tmpdir):
(tmpdir / 'filled-history').write('12345 http://example.com/')
hist = history.WebHistory(hist_dir=str(tmpdir), hist_name='filled-history')
list(hist.async_read())
hist.add_url(QUrl('http://www.qutebrowser.org/'), atime=67890)
lines = hist.get_recent()
expected = ['12345 http://example.com/',
'67890 http://www.qutebrowser.org/']
assert lines == expected
def test_save(hist, tmpdir):
hist_file = tmpdir / 'filled-history'
hist_file.write('12345 http://example.com/\n')
hist = history.WebHistory(hist_dir=str(tmpdir), hist_name='filled-history')
list(hist.async_read())
hist.add_url(QUrl('http://www.qutebrowser.org/'), atime=67890)
hist.save()
lines = hist_file.read().splitlines()
expected = ['12345 http://example.com/',
'67890 http://www.qutebrowser.org/']
assert lines == expected
hist.add_url(QUrl('http://www.the-compiler.org/'), atime=99999)
hist.save()
expected.append('99999 http://www.the-compiler.org/')
lines = hist_file.read().splitlines()
assert lines == expected
def test_clear(qtbot, hist, tmpdir):
hist_file = tmpdir / 'filled-history'
hist_file.write('12345 http://example.com/\n')
hist = history.WebHistory(hist_dir=str(tmpdir), hist_name='filled-history')
list(hist.async_read())
hist.add_url(QUrl('http://www.qutebrowser.org/'))
with qtbot.waitSignal(hist.cleared):
hist.clear()
assert not hist_file.read()
assert not hist.history_dict
assert not hist._new_history
hist.add_url(QUrl('http://www.the-compiler.org/'), atime=67890)
hist.save()
lines = hist_file.read().splitlines()
assert lines == ['67890 http://www.the-compiler.org/']
def test_add_item(qtbot, hist):
list(hist.async_read())
url = 'http://www.example.com/'
with qtbot.waitSignals([hist.add_completion_item, hist.item_added]):
hist.add_url(QUrl(url), atime=12345, title="the title")
entry = history.Entry(url=QUrl(url), redirect=False, atime=12345,
title="the title")
assert hist.history_dict[url] == entry
def test_add_item_redirect(qtbot, hist):
list(hist.async_read())
url = 'http://www.example.com/'
with qtbot.assertNotEmitted(hist.add_completion_item):
with qtbot.waitSignal(hist.item_added):
hist.add_url(QUrl(url), redirect=True, atime=12345)
entry = history.Entry(url=QUrl(url), redirect=True, atime=12345, title="")
assert hist.history_dict[url] == entry
def test_add_item_redirect_update(qtbot, tmpdir):
"""A redirect update added should override a non-redirect one."""
url = 'http://www.example.com/'
hist_file = tmpdir / 'filled-history'
hist_file.write('12345 {}\n'.format(url))
hist = history.WebHistory(hist_dir=str(tmpdir), hist_name='filled-history')
list(hist.async_read())
with qtbot.assertNotEmitted(hist.add_completion_item):
with qtbot.waitSignal(hist.item_added):
hist.add_url(QUrl(url), redirect=True, atime=67890)
entry = history.Entry(url=QUrl(url), redirect=True, atime=67890, title="")
assert hist.history_dict[url] == entry
@pytest.mark.parametrize('line, expected', [
(
# old format without title
'12345 http://example.com/',
history.Entry(atime=12345, url=QUrl('http://example.com/'), title='',)
),
(
# trailing space without title
'12345 http://example.com/ ',
history.Entry(atime=12345, url=QUrl('http://example.com/'), title='',)
),
(
# new format with title
'12345 http://example.com/ this is a title',
history.Entry(atime=12345, url=QUrl('http://example.com/'),
title='this is a title')
),
(
# weird NUL bytes
'\x0012345 http://example.com/',
history.Entry(atime=12345, url=QUrl('http://example.com/'), title=''),
),
(
# redirect flag
'12345-r http://example.com/ this is a title',
history.Entry(atime=12345, url=QUrl('http://example.com/'),
title='this is a title', redirect=True)
),
])
def test_entry_parse_valid(line, expected):
entry = history.Entry.from_str(line)
assert entry == expected
@pytest.mark.parametrize('line', [
'12345', # one field
'12345 ::', # invalid URL
'xyz http://www.example.com/', # invalid timestamp
'12345-x http://www.example.com/', # invalid flags
'12345-r-r http://www.example.com/', # double flags
])
def test_entry_parse_invalid(line):
with pytest.raises(ValueError):
history.Entry.from_str(line)
@hypothesis.given(strategies.text())
def test_entry_parse_hypothesis(text):
"""Make sure parsing works or gives us ValueError."""
try:
history.Entry.from_str(text)
except ValueError:
pass
@pytest.mark.parametrize('entry, expected', [
# simple
(
history.Entry(12345, QUrl('http://example.com/'), "the title"),
"12345 http://example.com/ the title",
),
# timestamp as float
(
history.Entry(12345.678, QUrl('http://example.com/'), "the title"),
"12345 http://example.com/ the title",
),
# no title
(
history.Entry(12345.678, QUrl('http://example.com/'), ""),
"12345 http://example.com/",
),
# redirect flag
(
history.Entry(12345.678, QUrl('http://example.com/'), "",
redirect=True),
"12345-r http://example.com/",
),
])
def test_entry_str(entry, expected):
assert str(entry) == expected
@pytest.yield_fixture
def hist_interface():
entry = history.Entry(atime=0, url=QUrl('http://www.example.com/'),
title='example')
history_dict = {'http://www.example.com/': entry}
fake_hist = FakeWebHistory(history_dict)
interface = history.WebHistoryInterface(fake_hist)
QWebHistoryInterface.setDefaultInterface(interface)
yield
QWebHistoryInterface.setDefaultInterface(None)
def test_history_interface(qtbot, webview, hist_interface):
html = "<a href='about:blank'>foo</a>"
data = base64.b64encode(html.encode('utf-8')).decode('ascii')
url = QUrl("data:text/html;charset=utf-8;base64,{}".format(data))
with qtbot.waitSignal(webview.loadFinished):
webview.load(url)
def test_init(qapp, tmpdir, monkeypatch, fake_save_manager):
monkeypatch.setattr(history.standarddir, 'data', lambda: str(tmpdir))
history.init(qapp)
hist = objreg.get('web-history')
assert hist.parent() is qapp
assert QWebHistoryInterface.defaultInterface()._history is hist
assert fake_save_manager.add_saveable.called
objreg.delete('web-history')
| gpl-3.0 |
gruessung/gFramework | styles/style.gvisions.bootstrap_blue/header.php | 3190 | <!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title><?=sitetitle?> - <?=$sitename?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<?=$header?>
<!-- Le styles -->
<link href="<?=web_root?>/styles/style.gvisions.bootstrap_blue/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 60px;
padding-bottom: 40px;
}
.sidebar-nav {
padding: 9px 0;
}
@media (max-width: 980px) {
/* Enable use of floated navbar text */
.navbar-text.pull-right {
float: none;
padding-left: 5px;
padding-right: 5px;
}
}
</style>
<link href="<?=web_root?>/styles/style.gvisions.bootstrap_blue/css/bootstrap-responsive.css" rel="stylesheet">
<!-- <style>
/* Override Bootstrap Responsive CSS fixed navbar */
@media (max-width: 979px) {
.navbar-fixed-top,
.navbar-fixed-bottom {
position: fixed;
margin-left: 0px;
margin-right: 0px;
}
}
</style>-->
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="brand" href="index.php"><img src="<?=web_root?>/styles/style.gvisions.bootstrap_blue/img/logo.png" border="0" style="height:20px;" /></a>
<?php
$user = new gUserManagement();
if ($user->ifLogin())
{
?>
<div class="nav-collapse collapse">
<p class="navbar-text pull-right">
Hallo <a href="#" class="navbar-link"><?=$user->getUsername()?></a>!
</p>
<?php
}
//http://code.google.com/p/phpwcms/source/browse/branches/dev-2.0/include/js/?r=481
$nav = new Nav();
$nav->showHoricontal("nav", "", "", $menuid);
if ($user->ifLogin())
{
$nav->showHoricontal("nav", "", "", menuLoginUser);
}
else
{
$nav->showHoricontal("nav", "", "", menuLogoutUser);
}
?>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container-fluid">
<div class="row-fluid">
<?php //Schauen ob der aktuellen Seite eine Sidebar zugeordnet ist, diese dann in span3 anzeigen, sonst span1 ?>
<div class="span1">
<!-- Platz für Sidebar mit 100px -->
</div>
<!-- Content Span -->
<div class="span9">
| gpl-3.0 |
jypeitao/NFC2 | nfctools/nfctools-core/src/main/java/org/nfctools/spi/tama/TamaReader.java | 5418 | /**
* Copyright 2011-2012 Adrian Stabiszewski, [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nfctools.spi.tama;
import java.io.IOException;
import org.nfctools.NfcTimeoutException;
import org.nfctools.io.ByteArrayReader;
import org.nfctools.utils.NfcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Reader for the TAMA message format. This reader reads messages in the TAMA format and returns only the payload of a
* message (packet data) including the 0xD5 response byte. All ACK frames are silently ignored, but the first ACK frame
* must arrive within a timeout of 2 seconds. Any ERROR frames will be thrown as TamaExceptions containing the error
* code.
*
* If no data is available from the underlying ByteArrayReader this reader sleeps for 1ms.
*
* TODO check the checksum and throw a checksum exception
*
* TODO make the timeout configurable
*
* @see TamaException
*
*/
public class TamaReader implements ByteArrayReader {
protected Logger log = LoggerFactory.getLogger(getClass());
private final ByteArrayReader reader;
private byte[] buffer = new byte[1024];
private int bufPos = 0;
private boolean useDataFrameTimeout = false;
private long dataFrameTimeout = 0;
public TamaReader(ByteArrayReader reader) {
this.reader = reader;
}
@Override
public void setTimeout(long millis) {
dataFrameTimeout = millis;
useDataFrameTimeout = millis >= 0;
reader.setTimeout(millis);
}
@Override
public int read(byte[] data, int offset, int length) throws IOException {
byte[] response = readResponse();
if (response.length > length - offset)
throw new IllegalArgumentException("buffer too small for response, needed " + response.length + " bytes");
System.arraycopy(response, 0, data, offset, response.length);
return response.length;
}
public byte[] readResponse() throws IOException {
long timeoutTillFirstAckFrame = 2000;
boolean useAckFrameTimeout = true;
long timeoutCounter = System.currentTimeMillis();
long timeoutCounterForDataFrame = System.currentTimeMillis();
while (true) {
if (log.isTraceEnabled())
log.trace("reading... @" + bufPos);
int read = reader.read(buffer, bufPos, buffer.length - bufPos);
if (read <= 0) {
try {
Thread.sleep(1);
}
catch (InterruptedException e) {
}
}
if (read >= 0) {
bufPos += read;
if (log.isTraceEnabled())
log.trace("data read: " + read + " " + NfcUtils.convertBinToASCII(buffer, 0, bufPos) + "/"
+ bufPos);
if (bufPos >= 6) // we need at least 6 bytes to identify a message
{
for (int x = 0; x < bufPos; x++) {
if (x + 6 <= bufPos) // Check for ACK frame
{
if (TamaUtils.isACKFrame(buffer, x)) {
byte[] resp = new byte[6];
System.arraycopy(buffer, x, resp, 0, resp.length); // Copy data into response array
if (log.isDebugEnabled())
log.debug("Ack frame:" + NfcUtils.convertBinToASCII(resp));
removeFrameFromBuffer(x, resp);
useAckFrameTimeout = false;
timeoutCounterForDataFrame = System.currentTimeMillis();
// Ignore ACK Frames
}
}
if (x + 8 <= bufPos) // Check for ERROR frame
{
if (TamaUtils.isErrorFrame(buffer, x)) {
byte[] resp = new byte[8];
System.arraycopy(buffer, x, resp, 0, resp.length); // Copy data into response array
removeFrameFromBuffer(x, resp);
int status = TamaUtils.getErrorCodeFromStatus(resp[5]);
throw new TamaException(status);
}
}
if (x + 5 <= bufPos) // Check for DATA frame
{
int msgLength = (buffer[x + 3] & 0xFF) + 7;
if ((buffer[x] == 0x00) && (buffer[x + 1] == 0x00) && (buffer[x + 2] == (byte)0xFF)
&& (msgLength + x <= bufPos) && buffer[x + 3] == (byte)-buffer[x + 4]) {
byte[] resp = new byte[msgLength];
System.arraycopy(buffer, x, resp, 0, msgLength);
if (log.isDebugEnabled())
log.debug("Data frame:" + NfcUtils.convertBinToASCII(resp));
removeFrameFromBuffer(x, resp);
return TamaUtils.unpackPayload(resp);
}
}
}
}
}
if (useDataFrameTimeout && System.currentTimeMillis() - timeoutCounterForDataFrame > dataFrameTimeout) {
resetBuffer();
throw new NfcTimeoutException();
}
if ((useAckFrameTimeout) && (System.currentTimeMillis() - timeoutCounter > timeoutTillFirstAckFrame)) {
resetBuffer();
throw new NfcTimeoutException("No complete message within timeout. Msg: ["
+ NfcUtils.convertBinToASCII(buffer, 0, bufPos) + "] Length: " + bufPos);
}
}
}
private void resetBuffer() {
bufPos = 0;
}
private void removeFrameFromBuffer(int x, byte[] resp) {
System.arraycopy(buffer, x + resp.length, buffer, 0, bufPos - (resp.length + x)); // Move data in the buffer
bufPos -= (resp.length + x);
}
}
| gpl-3.0 |
BlastarIndia/roslyn | Src/Diagnostics/Core/FxCopRulesResources.Designer.cs | 26291 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.CodeAnalysis.FxCopAnalyzers {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class FxCopRulesResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal FxCopRulesResources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.CodeAnalysis.FxCopAnalyzers.FxCopRulesResources", typeof(FxCopRulesResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Abstract classes should not have public constructors.
/// </summary>
internal static string AbstractTypesShouldNotHavePublicConstructors {
get {
return ResourceManager.GetString("AbstractTypesShouldNotHavePublicConstructors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change the accessibility of all public contructors in this class to protected..
/// </summary>
internal static string AbstractTypesShouldNotHavePublicConstructorsCodeFix {
get {
return ResourceManager.GetString("AbstractTypesShouldNotHavePublicConstructorsCodeFix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add [Serializable] to {0} as this type implements ISerializable.
/// </summary>
internal static string AddSerializableAttributeToType {
get {
return ResourceManager.GetString("AddSerializableAttributeToType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Assemblies should be marked with AssemblyVersionAttribute.
/// </summary>
internal static string AssembliesShouldBeMarkedWithAssemblyVersionAttribute {
get {
return ResourceManager.GetString("AssembliesShouldBeMarkedWithAssemblyVersionAttribute", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Avoid unsealed attributes..
/// </summary>
internal static string AvoidUnsealedAttributes {
get {
return ResourceManager.GetString("AvoidUnsealedAttributes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Consider changing the ComVisible attribute on {0} to false, and opting in at the type level..
/// </summary>
internal static string CA1017_AttributeTrue {
get {
return ResourceManager.GetString("CA1017_AttributeTrue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Because {0} exposes externally visible types, mark it with ComVisible(false) at the assembly level and then mark all types within the assembly that should be exposed to COM clients with ComVisible(true)..
/// </summary>
internal static string CA1017_NoAttribute {
get {
return ResourceManager.GetString("CA1017_NoAttribute", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change '{0}' to a property if appropriate..
/// </summary>
internal static string ChangeToAPropertyIfAppropriate {
get {
return ResourceManager.GetString("ChangeToAPropertyIfAppropriate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Custom attributes should have AttributeUsage attribute defined..
/// </summary>
internal static string CustomAttrShouldHaveAttributeUsage {
get {
return ResourceManager.GetString("CustomAttrShouldHaveAttributeUsage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Define accessors for attribute arguments..
/// </summary>
internal static string DefineAccessorsForAttributeArguments {
get {
return ResourceManager.GetString("DefineAccessorsForAttributeArguments", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'..
/// </summary>
internal static string DefineAccessorsForAttributeArgumentsDefault {
get {
return ResourceManager.GetString("DefineAccessorsForAttributeArgumentsDefault", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to If '{0}' is the property accessor for positional argument '{1}', ensure that property getter is public..
/// </summary>
internal static string DefineAccessorsForAttributeArgumentsIncreaseVisibility {
get {
return ResourceManager.GetString("DefineAccessorsForAttributeArgumentsIncreaseVisibility", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove the property setter from '{0}' or reduce its accessibility because it corresponds to positional argument '{1}'..
/// </summary>
internal static string DefineAccessorsForAttributeArgumentsRemoveSetter {
get {
return ResourceManager.GetString("DefineAccessorsForAttributeArgumentsRemoveSetter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Disposable fields should be disposed.
/// </summary>
internal static string DisposableFieldsShouldBeDisposed {
get {
return ResourceManager.GetString("DisposableFieldsShouldBeDisposed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do not call overridable methods in constructors.
/// </summary>
internal static string DoNotCallOverridableMethodsInConstructors {
get {
return ResourceManager.GetString("DoNotCallOverridableMethodsInConstructors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do not lock on objects with weak identity..
/// </summary>
internal static string DoNotLockOnObjectsWithWeakIdentity {
get {
return ResourceManager.GetString("DoNotLockOnObjectsWithWeakIdentity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do not lock on a reference of type '{0}' as it has weak identity. Replace that with a lock against an object with strong identity..
/// </summary>
internal static string DoNotLockOnWeakIdentity {
get {
return ResourceManager.GetString("DoNotLockOnWeakIdentity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do not mark Enum with FlagsAttribute.
/// </summary>
internal static string DoNotMarkEnumsWithFlags {
get {
return ResourceManager.GetString("DoNotMarkEnumsWithFlags", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' is marked with FlagsAttribute but a discrete member cannot be found for every settable bit that is used across the range of enum values. Remove FlagsAttribute from the type or define new members for the following (currently missing) values: '{1}'..
/// </summary>
internal static string DoNotMarkEnumsWithFlagsMessage {
get {
return ResourceManager.GetString("DoNotMarkEnumsWithFlagsMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enums should have zero value..
/// </summary>
internal static string EnumsShouldHaveZeroValue {
get {
return ResourceManager.GetString("EnumsShouldHaveZeroValue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove all members that have the value zero from '{0}' except for one member that is named 'None'..
/// </summary>
internal static string EnumsShouldZeroValueFlagsMultipleZero {
get {
return ResourceManager.GetString("EnumsShouldZeroValueFlagsMultipleZero", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to In enum '{0}', change the name of '{1}' to 'None'..
/// </summary>
internal static string EnumsShouldZeroValueFlagsRename {
get {
return ResourceManager.GetString("EnumsShouldZeroValueFlagsRename", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add a member to '{0}' that has a value of zero with a suggested name of 'None'..
/// </summary>
internal static string EnumsShouldZeroValueNotFlagsNoZeroValue {
get {
return ResourceManager.GetString("EnumsShouldZeroValueNotFlagsNoZeroValue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Field {0} is a member of type {1} which is serializable but is of type {2} which is not serializable.
/// </summary>
internal static string FieldIsOfNonSerializableType {
get {
return ResourceManager.GetString("FieldIsOfNonSerializableType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} '{1}' have identical names in a case-insensitive manner..
/// </summary>
internal static string IdentifierNamesShouldDifferMoreThanCase {
get {
return ResourceManager.GetString("IdentifierNamesShouldDifferMoreThanCase", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Identifier names should differ by more than case.
/// </summary>
internal static string IdentifiersShouldDifferByMoreThanCase {
get {
return ResourceManager.GetString("IdentifiersShouldDifferByMoreThanCase", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Implement Serialization constructor.
/// </summary>
internal static string ImplementSerializationConstructor {
get {
return ResourceManager.GetString("ImplementSerializationConstructor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Interface names should be prefixed with 'I'.
/// </summary>
internal static string InterfaceNamesShouldStartWithI {
get {
return ResourceManager.GetString("InterfaceNamesShouldStartWithI", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mark all assemblies with ComVisible.
/// </summary>
internal static string MarkAllAssembliesWithComVisible {
get {
return ResourceManager.GetString("MarkAllAssembliesWithComVisible", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mark all non-serializable fields..
/// </summary>
internal static string MarkAllNonSerializableFields {
get {
return ResourceManager.GetString("MarkAllNonSerializableFields", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mark assemblies with CLSCompliantAttribute.
/// </summary>
internal static string MarkAssembliesWithCLSCompliantAttribute {
get {
return ResourceManager.GetString("MarkAssembliesWithCLSCompliantAttribute", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Specify AttributeUsage attribute on '{0}' attribute class..
/// </summary>
internal static string MarkAttributesWithAttributeUsage {
get {
return ResourceManager.GetString("MarkAttributesWithAttributeUsage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mark Enum with FlagsAttribute.
/// </summary>
internal static string MarkEnumsWithFlags {
get {
return ResourceManager.GetString("MarkEnumsWithFlags", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The constituent members of '{0}' appear to represent flags that can be combined rather than discrete values. If this is correct, mark the enumeration with FlagsAttribute..
/// </summary>
internal static string MarkEnumsWithFlagsMessage {
get {
return ResourceManager.GetString("MarkEnumsWithFlagsMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mark ISerializable types with SerializableAttribute..
/// </summary>
internal static string MarkISerializableTypesWithAttribute {
get {
return ResourceManager.GetString("MarkISerializableTypesWithAttribute", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Move P/Invokes to native methods class.
/// </summary>
internal static string MovePInvokesToNativeMethodsClass {
get {
return ResourceManager.GetString("MovePInvokesToNativeMethodsClass", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overload operator Equals and comparison operators when implementing System.IComparable.
/// </summary>
internal static string OverloadOperatorEqualsOnIComparableInterface {
get {
return ResourceManager.GetString("OverloadOperatorEqualsOnIComparableInterface", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overload operator equals on overriding ValueType.Equals.
/// </summary>
internal static string OverloadOperatorEqualsOnOverridingValueTypeEquals {
get {
return ResourceManager.GetString("OverloadOperatorEqualsOnOverridingValueTypeEquals", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to P/Invoke method '{0}' should not be visible.
/// </summary>
internal static string PInvokeMethodShouldNotBeVisible {
get {
return ResourceManager.GetString("PInvokeMethodShouldNotBeVisible", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to P/Invokes should not be visible..
/// </summary>
internal static string PInvokesShouldNotBeVisible {
get {
return ResourceManager.GetString("PInvokesShouldNotBeVisible", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove empty finalizers.
/// </summary>
internal static string RemoveEmptyFinalizers {
get {
return ResourceManager.GetString("RemoveEmptyFinalizers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Re-throwing caught exception changes stack information..
/// </summary>
internal static string RethrowException {
get {
return ResourceManager.GetString("RethrowException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rethrow to preserve stack details..
/// </summary>
internal static string RethrowToPreserveStackDetails {
get {
return ResourceManager.GetString("RethrowToPreserveStackDetails", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Seal attribute types for improved performance. Sealing attribute types speeds up performance during reflection on custom attributes..
/// </summary>
internal static string SealAttributeTypesForImprovedPerf {
get {
return ResourceManager.GetString("SealAttributeTypesForImprovedPerf", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Serializable type {0} doesn't have a serialization constructor.
/// </summary>
internal static string SerializableTypeDoesntHaveCtor {
get {
return ResourceManager.GetString("SerializableTypeDoesntHaveCtor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Declare serialization constructor for sealed type {0} as private.
/// </summary>
internal static string SerializationCtorAccessibilityForSealedType {
get {
return ResourceManager.GetString("SerializationCtorAccessibilityForSealedType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Declare serialization constructor for unsealed type {0} as protected.
/// </summary>
internal static string SerializationCtorAccessibilityForUnSealedType {
get {
return ResourceManager.GetString("SerializationCtorAccessibilityForUnSealedType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Specify marshaling for P/Invoke string arguments.
/// </summary>
internal static string SpecifyMarshalingForPInvokeStringArguments {
get {
return ResourceManager.GetString("SpecifyMarshalingForPInvokeStringArguments", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Type '{0}' is a static holder type but is neither static nor NotInheritable.
/// </summary>
internal static string StaticHolderTypeIsNotStatic {
get {
return ResourceManager.GetString("StaticHolderTypeIsNotStatic", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Static holder types should be Static or NotInheritable.
/// </summary>
internal static string StaticHolderTypesShouldBeStaticOrNotInheritable {
get {
return ResourceManager.GetString("StaticHolderTypesShouldBeStaticOrNotInheritable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Static holder types should not have instance constructors.
/// </summary>
internal static string StaticHolderTypesShouldNotHaveConstructors {
get {
return ResourceManager.GetString("StaticHolderTypesShouldNotHaveConstructors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Type '{0}' is a static holder type and should not contain Instance Constructors.
/// </summary>
internal static string StaticHolderTypesShouldNotHaveConstructorsMessage {
get {
return ResourceManager.GetString("StaticHolderTypesShouldNotHaveConstructorsMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to String comparison should use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase.
/// </summary>
internal static string StringComparisonShouldBeOrdinalOrOrdinalIgnoreCase {
get {
return ResourceManager.GetString("StringComparisonShouldBeOrdinalOrOrdinalIgnoreCase", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Type '{0}' is abstract but has public constructors.
/// </summary>
internal static string TypeIsAbstractButHasPublicConstructors {
get {
return ResourceManager.GetString("TypeIsAbstractButHasPublicConstructors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Type '{0}' owns disposable fields but is not disposable.
/// </summary>
internal static string TypeOwnsDisposableFieldButIsNotDisposable {
get {
return ResourceManager.GetString("TypeOwnsDisposableFieldButIsNotDisposable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Type parameter names should be prefixed with 'T'.
/// </summary>
internal static string TypeParameterNamesShouldStartWithT {
get {
return ResourceManager.GetString("TypeParameterNamesShouldStartWithT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Types that own disposable fields should be disposable.
/// </summary>
internal static string TypesThatOwnDisposableFieldsShouldBeDisposable {
get {
return ResourceManager.GetString("TypesThatOwnDisposableFieldsShouldBeDisposable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use System.EventHandler<T> where T inherits System.EventArgs or use System.EventHandler.
/// </summary>
internal static string UseGenericEventHandlerInstances {
get {
return ResourceManager.GetString("UseGenericEventHandlerInstances", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use properties where appropriate..
/// </summary>
internal static string UsePropertiesWhereAppropriate {
get {
return ResourceManager.GetString("UsePropertiesWhereAppropriate", resourceCulture);
}
}
}
}
| gpl-3.0 |
Giorox/AngelionOT-Repo | data/movements/scripts/premium.lua | 677 | function onStepIn(cid, item, pos)
local notPremium = {x=32060, y=32192, z=7}
local notPremium2 = {x=32060, y=32193, z=7}
if isPremium(cid) then
doTransformItem(item.uid, 447)
elseif (item.uid == 8800) then
doTeleportThing(cid, notPremium)
doSendMagicEffect(getCreaturePosition(cid), 14)
doPlayerSendTextMessage(cid,22,"Sorry, you don't have premium account.")
elseif (item.uid == 8801) then
doTeleportThing(cid, notPremium2)
doSendMagicEffect(getCreaturePosition(cid), 14)
doPlayerSendTextMessage(cid,22,"Sorry, you don't have premium account.")
end
end
function onStepOut(cid, item, pos)
if item.itemid == 447 then
doTransformItem(item.uid, 446)
end
end | gpl-3.0 |
EPSZ-DAW2/daw2-2016-actividades-y-eventos | basic/views/actividadetiquetas/view.php | 702 | <?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use app\models\Etiquetas;
use app\models\Actividades;
/* @var $this yii\web\View */
/* @var $model app\models\ActividadEtiquetas */
$this->title = "";
$this->params['breadcrumbs'][] = ['label' => 'Actividad Etiquetas', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="actividad-etiquetas-view">
<?= $this->render('_form', [
'model' => $model,
'disabled'=>'true',
]) ?>
<?= '<td>'.Html::a('Desetiquetar', ['delete', 'id' => $model->id], [
'data' => [
'confirm' => '¿está seguro?',
'method' => 'post',
],
]).'</td>' ?>
</div>
| gpl-3.0 |
djbdjb00djb/fog-client | PipeClient/PipeClient.cs | 3034 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Threading;
using System.IO;
namespace FOG {
/// <summary>
/// Inter-proccess communication client
/// </summary>
public class PipeClient
{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern SafeFileHandle CreateFile(String pipeName, uint dwDesiredAccess, uint dwShareMode,IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplate);
//Define variables
private const uint GENERIC_READ = (0x80000000);
private const uint GENERIC_WRITE = (0x40000000);
private const uint OPEN_EXISTING = 3;
private const uint FILE_FLAG_OVERLAPPED = (0x40000000);
public delegate void MessageReceivedHandler(string message);
public event MessageReceivedHandler MessageReceived;
private const int BUFFER_SIZE = 4096;
private Boolean connected;
private string pipeName;
private FileStream stream;
private SafeFileHandle handle;
private Thread readThread;
public PipeClient(String pipeName) {
this.connected = false;
this.pipeName = pipeName;
}
public Boolean isConnected() { return this.connected; }
public String getPipeName() { return this.pipeName; }
//Connect to a server using the same pipe
public Boolean connect() {
try {
this.handle = CreateFile(@"\\.\pipe\" + this.pipeName, GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);
if (this.handle == null)
return false;
if (this.handle.IsInvalid) {
this.connected = false;
return false;
}
this.connected = true;
this.readThread = new Thread(new ThreadStart(readFromPipe));
this.readThread.Start();
return true;
} catch {
return false;
}
}
//Stop the pipe client
public void kill() {
try {
if (this.stream != null)
this.stream.Close();
if (this.handle != null)
this.handle.Close();
this.readThread.Abort();
} catch { }
}
//Read a message sent over from the pipe server
public void readFromPipe() {
this.stream = new FileStream(handle, FileAccess.ReadWrite, BUFFER_SIZE, true);
byte[] readBuffer = new byte[BUFFER_SIZE];
ASCIIEncoding encoder = new ASCIIEncoding();
while (true) {
int bytesRead = 0;
try {
bytesRead = stream.Read(readBuffer, 0, BUFFER_SIZE);
} catch {
break;
}
if (bytesRead == 0) break;
if (MessageReceived != null) MessageReceived(encoder.GetString(readBuffer, 0, bytesRead));
}
this.stream.Close();
this.handle.Close();
}
//Send a message across the pipe
public void sendMessage(String message) {
try {
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] messageBuffer = encoder.GetBytes(message);
this.stream.Write(messageBuffer, 0, messageBuffer.Length);
this.stream.Flush();
} catch { }
}
}
} | gpl-3.0 |
SonamYeshe/AStarPathPlanning | docs/html/search/typedefs_e.js | 1390 | var searchData=
[
['uint',['UInt',['../classtesting_1_1internal_1_1TypeWithSize.html#a3898640d9f6c1e18110eef90f47a5d7b',1,'testing::internal::TypeWithSize::UInt()'],['../classtesting_1_1internal_1_1TypeWithSize_3_014_01_4.html#a7d559570f830bf35d095eeb94d98de58',1,'testing::internal::TypeWithSize< 4 >::UInt()'],['../classtesting_1_1internal_1_1TypeWithSize_3_018_01_4.html#a747e21c5aee8faf07ec65cd4c3d1ca62',1,'testing::internal::TypeWithSize< 8 >::UInt()']]],
['uint32',['UInt32',['../namespacetesting_1_1internal.html#a40d4fffcd2bf56f18b1c380615aa85e3',1,'testing::internal']]],
['uint64',['UInt64',['../namespacetesting_1_1internal.html#aa6a1ac454e6d7e550fa4925c62c35caa',1,'testing::internal']]],
['untypedactions',['UntypedActions',['../classtesting_1_1internal_1_1ExpectationBase.html#a9b21e82059961b9f1198d3f5d518254f',1,'testing::internal::ExpectationBase']]],
['untypedexpectations',['UntypedExpectations',['../classtesting_1_1internal_1_1UntypedFunctionMockerBase.html#a36480bd395e110b4eae5b0d0402de966',1,'testing::internal::UntypedFunctionMockerBase']]],
['untypedoncallspecs',['UntypedOnCallSpecs',['../classtesting_1_1internal_1_1UntypedFunctionMockerBase.html#a29cc87ed60ad0218432aa777abba7dbb',1,'testing::internal::UntypedFunctionMockerBase']]],
['unused',['Unused',['../namespacetesting.html#a603e329ec0263ebfcf16f712810bd511',1,'testing']]]
];
| gpl-3.0 |
BamBam0077/TorrentTrader-2.07 | blocks/latestuploads_block.php | 1055 | <?php
if (!$site_config["MEMBERSONLY"] || $CURUSER) {
begin_block(T_("LATEST_TORRENTS"));
$expire = 900; // time in seconds
if (($latestuploadsrecords = $GLOBALS["TTCache"]->Get("latestuploadsblock", $expire)) === false) {
$latestuploadsquery = mysql_query("SELECT id, name, size, seeders, leechers FROM torrents WHERE banned='no' ORDER BY id DESC LIMIT 5");
$latestuploadsrecords = array();
while ($latestuploadsrecord = mysql_fetch_array($latestuploadsquery))
$latestuploadsrecords[] = $latestuploadsrecord;
$GLOBALS["TTCache"]->set("latestuploadsblock", $latestuploadsrecords, $expire);
}
if ($latestuploadsrecords) {
foreach ($latestuploadsrecords as $row) {
$char1 = 18; //cut length
$smallname = htmlspecialchars(CutName($row["name"], $char1));
echo "<a href='torrents-details.php?id=$row[id]' title='".htmlspecialchars($row["name"])."'>$smallname</a><BR>\n";
echo "- [".T_("SIZE").": ".mksize($row["size"])."]<BR><BR>\n";
}
} else {
print("<CENTER>".T_("NOTHING_FOUND")."</CENTER>\n");
}
end_block();
}
?> | gpl-3.0 |
ThoNill/DRUCK | DRUCK/src/toni/druck/xml/EditorXMLWalker.java | 11271 | package toni.druck.xml;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.jdom2.Element;
import toni.druck.elements.Add;
import toni.druck.elements.Haken;
import toni.druck.elements.Hbox;
import toni.druck.elements.Image;
import toni.druck.elements.Label;
import toni.druck.elements.PositionBox;
import toni.druck.elements.Sum;
import toni.druck.elements.TextField;
import toni.druck.elements.Vbox;
import toni.druck.helper.DirectoryHelper;
import toni.druck.page.Action;
import toni.druck.page.Verteiler;
/*****
*
* @author Thomas Nill
*
* Läd ein XML Layout und erzeugt daraus eine andere XML Datei, deren
* Format speziell für die Bearbeitung in einem Editor geeignet ist.
*
*/
public class EditorXMLWalker extends DruckWalker {
private PrintWriter out;
private List<Verteiler> verteiler = new ArrayList<Verteiler>();
private List<toni.druck.page.Element> sections = new ArrayList<toni.druck.page.Element>();
private HashMap<String, String> clasnnames = new HashMap<String, String>();
public EditorXMLWalker() {
super();
clasnnames.put("toni.druck.elements.Sum", "druck.Summierer");
clasnnames.put("toni.druck.elements.Add", "druck.Addierer");
clasnnames.put("toni.druck.elements.TextField",
"druck.TextFieldComponent");
clasnnames.put("toni.druck.elements.Label", "druck.LabelComponent");
clasnnames
.put("toni.druck.elements.Image", "components.ImageComponent");
clasnnames.put("toni.druck.elements.Hbox", "druck.BoxComponent");
clasnnames.put("toni.druck.elements.Vbox", "druck.BoxComponent");
clasnnames.put("toni.druck.elements.Line", "druck.SectionComponent");
clasnnames.put("toni.druck.elements.Haken", "druck.SectionComponent");
clasnnames.put("toni.druck.elements.QRCode", "druck.SectionComponent");
clasnnames.put("toni.druck.elements.PositionBox", "druck.BoxComponent");
clasnnames.put("toni.druck.elements.MultiLine",
"druck.SectionComponent");
clasnnames.put("toni.druck.elements.OmrStriche",
"druck.SectionComponent");
}
@Override
protected void bearbeiteVerteiler(Element elem, Verteiler reference) {
super.bearbeiteVerteiler(elem, reference);
verteiler.add(reference);
}
@Override
public void bearbeiteDruckElement(Element elem,
toni.druck.page.Element reference) {
super.bearbeiteDruckElement(elem, reference);
if ((!hasParent()) && reference.getName() != null) {
sections.add(reference);
}
}
private void setDescendents(toni.druck.page.Element e,
List<toni.druck.page.Element> descendents) {
if (e.getChilds() != null) {
for (toni.druck.page.Element c : e.getChilds()) {
descendents.add(c);
setDescendents(c, descendents);
}
}
}
public void printParameterOfElement(toni.druck.page.Element e) {
if (e instanceof TextField) {
field(((TextField) e).getVariable());
}
if (e instanceof Label) {
stringProperty("text", e.getText());
}
if (e instanceof Image) {
stringProperty("image", ((Image) e).getImage());
}
booleanProperty("bordered", e.isBordered());
booleanProperty("filled", e.isFilled());
intProperty("grayscale", e.getGrayscale());
intProperty("linewidth", e.getLinewidth());
doubleProperty("width", e.getWidth());
doubleProperty("height", e.getHeight());
relXY(e);
font(e);
}
private void stringProperty(String propertyName, String value) {
property(propertyName, value, "string");
}
private void booleanProperty(String propertyName, boolean value) {
property(propertyName, (value) ? "true" : "false", "boolean");
}
private void intProperty(String propertyName, int value) {
property(propertyName, Integer.toString(value), "int");
}
private void doubleProperty(String propertyName, int value) {
property(propertyName, Integer.toString(value) + ".0", "double");
}
private void field(String name) {
out.println("<void id=\"FieldName0\" property=\"field\"> ");
out.println("<void property=\"name\"> ");
out.print("<string>");
out.print(name);
out.println("</string> ");
out.println("</void> ");
out.println("</void> ");
out.println("<void property=\"field\"> ");
out.println("<object idref=\"FieldName0\"/> ");
out.println("</void> ");
}
private void relXY(toni.druck.page.Element e) {
out.println("<void property=\"trans\"> ");
out.println("<void property=\"translateX\"> ");
out.println("<double>" + (e.shiftX() + (e.getWidth() / 2))
+ "</double> ");
out.println("</void> ");
out.println("<void property=\"translateY\"> ");
out.println("<double>" + (e.shiftY() + (e.getHeight() / 2))
+ "</double> ");
out.println("</void> ");
out.println("</void> ");
}
private void font(toni.druck.page.Element e) {
out.println("<void property=\"font\"> ");
out.println("<object class=\"java.awt.Font\"> ");
out.println("<string>Dialog</string> ");
out.println("<int>0</int> ");
out.println("<int>" + 4 + "</int> ");
out.println("</object> ");
out.println("</void> ");
}
public void printXML(String filename) throws IOException {
DirectoryHelper.createDirsForFile(filename);
printXML(new FileOutputStream(filename));
}
public void printXML(OutputStream ostream) throws IOException {
printXML(new PrintWriter(new OutputStreamWriter(ostream, "UTF-8")));
}
public void printXML(PrintWriter out) throws IOException {
this.out = out;
getPage().layout();
int nr = 1;
startPage();
startComponents();
for (toni.druck.page.Element e : sections) {
startSection();
startChilds();
List<toni.druck.page.Element> descendents = new ArrayList<toni.druck.page.Element>();
setDescendents(e, descendents);
e.layout();
for (toni.druck.page.Element c : descendents) {
if (erlaubt(c)) {
startClass(c.getClass());
printParameterOfElement(c);
endClass();
}
}
endChilds();
printParameterOfElement(e);
stringProperty("name", e.getName());
intProperty("nr", nr);
nr++;
endSection();
}
endComponents();
startKomponentenOhneGrafik();
for (Verteiler v : verteiler) {
startClass("druck.Verteiler");
stringProperty("name", v.getName());
stringProperty("fields", v.getFields());
endClass();
if (v.getActions() != null) {
for (Action a : v.getActions()) {
startClass(a.getClass());
stringProperty("verteiler", v.getName());
if (a instanceof Sum) {
Sum s = (Sum) a;
stringProperty("clearAt", s.getClearAt());
stringProperty("item", s.getItem());
stringProperty("sum", s.getSum());
}
if (a instanceof Add) {
Add s = (Add) a;
stringProperty("fields", s.getFields());
stringProperty("result", s.getResult());
}
endClass();
}
}
}
endKomponentenOhneGrafik();
endPage();
out.close();
}
private boolean erlaubt(toni.druck.page.Element e) {
if (e instanceof TextField)
return true;
if (e instanceof Image)
return true;
if (e instanceof Label) {
Label l = (Label) e;
if (l.getText() == null && (!e.isBordered()) && (!e.isFilled())) {
return false;
}
return true;
}
if (e instanceof Haken)
return false;
if ((e instanceof Vbox) && (!e.isBordered()) && (!e.isFilled()))
return false;
if ((e instanceof Hbox) && (!e.isBordered()) && (!e.isFilled()))
return false;
if ((e instanceof PositionBox) && (!e.isBordered()) && (!e.isFilled()))
return false;
return true;
}
public void startPage() {
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<java version=\"1.6.0_21\" class=\"java.beans.XMLDecoder\">\n<object class=\"druck.DruckDataInStore\"> ");
};
public void startClass(Class c) {
startClass(changeClassName(c));
}
private String changeClassName(Class c) {
String s = clasnnames.get(c.getCanonicalName());
if (s == null) {
s = c.getCanonicalName();
System.out.println(s);
}
return s;
}
public void startComponents() {
out.println("<void property=\"components\">\n<object class=\"java.util.ArrayList\">");
}
public void startSection() {
out.println("<void method=\"add\"> ");
out.println("<object class=\"druck.SectionComponent\"> ");
}
public void startChilds() {
out.println("<void property=\"childs\"> ");
}
public void endChilds() {
out.println("</void>");
}
public void endSection() {
out.println("</object></void> ");
}
public void endComponents() {
out.println("</object> </void> ");
}
public void startKomponentenOhneGrafik() {
out.println("<void property=\"komponentenOhneGrafik\"> <object class=\"java.util.ArrayList\"> ");
}
public void startClass(String classname) {
out.println("<void method=\"add\">");
out.println("<object class=\"" + classname + "\">");
};
public void property(String propertyName, String propertyValue, String type) {
out.println("<void property=\"" + propertyName + "\">");
out.println("<" + type + ">" + propertyValue + "</" + type
+ "></void> ");
}
public void endClass() {
out.println("</object></void> ");
}
public void endKomponentenOhneGrafik() {
out.println("</object></void> ");
}
void endPage() {
out.print(" </object></java> ");
}
}
| gpl-3.0 |
urashima9616/Leetcode_Python | Leet76_MinimumWindowSubstring2.py | 1676 | import collections
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
#opt represents the minimal length of the window that contains T
left, right = [0]*2
need_dict = collections.Counter(t)
symbol_dict = collections.Counter(t)
min_len = len(s)+1
min_i, min_j = 0,0
while 1:
while right < len(s):
if s[right] in need_dict:
if s[right] in symbol_dict:
symbol_dict[s[right]] -= 1
if symbol_dict[s[right]] == 0:
symbol_dict.pop(s[right])
need_dict[s[right]] -= 1
if len(symbol_dict) == 0:
break
right += 1
if right == len(s) and len(symbol_dict) > 0:
return s[min_i:min_j]
while left < right:
if s[left] in need_dict and need_dict[s[left]] < 0:
need_dict[s[left]] += 1
left += 1
elif s[left] not in need_dict:
left += 1
elif s[left] in need_dict and need_dict[s[left]] == 0:
break
if right - left < min_len:
min_len = right-left
min_i, min_j = left, right
symbol_dict[s[left]] = 1
need_dict[s[left]] += 1
left += 1
if right == len(s) -1:
break
return s[min_i:min_j]
Solve = Solution()
Solve.minWindow("ADOBECODEBANC", "ABC") | gpl-3.0 |
Scille/parsec-gui | src/components/App.js | 4560 | import React, { Component } from 'react'
import {
HashRouter as Router,
Route,
Redirect,
Switch,
} from 'react-router-dom'
import PersonalFilesContainer from '../containers/PersonalFilesContainer'
import DeletedFilesContainer from '../containers/DeletedFilesContainer'
import ManifestHistoryContainer from '../containers/ManifestHistoryContainer'
import LoginContainer from '../containers/LoginContainer'
import SignupContainer from '../containers/SignupContainer'
import ToolsContainer from '../containers/ToolsContainer'
import './App.css'
export class App extends Component {
constructor(props) {
super(props)
this.handleLogout = this.handleLogout.bind(this)
}
componentDidMount() {
this.props.dispatch.init()
const logged = this.props.dispatch.logged
logged()
// this.interval = setInterval(this.props.dispatch.listenEvents, 3000, true)
}
componentWillUnmount() {
this.props.dispatch.end()
}
handleLogout() {
const logout = this.props.dispatch.logout
const umount = this.props.dispatch.umount
if(this.props.state.socket.mounpoint !== null)
umount()
logout()
}
render() {
const showModal = this.props.dispatch.showModal
const hideModal = this.props.dispatch.hideModal
const inviteUser = this.props.dispatch.inviteUser
const declareDevice = this.props.dispatch.declareDevice
const endDeclareDevice = this.props.dispatch.endDeclareDevice
const listenEvents = this.props.dispatch.listenEvents
const acceptDevice = this.props.dispatch.acceptDevice
const inviteUserModal = () => {return { inviteUser, hideModal, user_invitation: this.props.state.authentication.user_invitation }}
const declareDeviceModal = () => {return { declareDevice, endDeclareDevice, listenEvents, acceptDevice, hideModal, event_device_try_claim_subscribed: this.props.state.modalReducer }}
const settingsModal = () => {return { hideModal }}
const connected = this.props.state.socket.connected
if(!connected) return (<div id="loader-wrapper"><div id="loader"></div></div>)
const authenticated = this.props.state.authentication.authenticated
if(!authenticated) {
return (
<Switch>
<Route path='/signup' component={SignupContainer}/>
<Route path='/login' component={LoginContainer}/>
<Redirect from='/' to='/login'/>
</Switch>
)
}
return (
<Router>
<div className="app">
<div className="sidebar">
<nav>
<ul className="header">
<li><i className="parsec-logo"/></li>
</ul>
<ToolsContainer/>
<ul className="footer">
<li><a onClick={() => showModal('inviteUserModal', inviteUserModal())} href="#"><i className="fa fa-user-plus fa-2x" title="Invite user"/></a></li>
<li><a onClick={() => showModal('declareDeviceModal', declareDeviceModal())} href="#"><i className="fa fa-plus-square fa-2x" title="Declare device"/></a></li>
<li><a onClick={() => showModal('settingsModal', settingsModal())} href="#"><i className="fa fa-cog fa-2x" title="Settings"/></a></li>
<li><a onClick={() => this.handleLogout()} href="#"><i className="fa fa-power-off fa-2x" title="Logout"/></a></li>
</ul>
</nav>
</div>
<div className="content">
<Switch>
{/* PersonalFiles component */}
<Route exact path='/login' component={PersonalFilesContainer}/>
<Route exact path='/' component={PersonalFilesContainer}/>
<Redirect from='/personal-files' to='/'/>
{/* DeletedFiles component */}
<Route path='/deleted-files' component={DeletedFilesContainer}/>
{/* History component */}
<Route path='/history' component={ManifestHistoryContainer}/>
{/* Errors component */}
<Redirect to='/404'/>
</Switch>
</div>
</div>
</Router>
)
}
}
export default App
// <ul className="navbar">
// <li><Link to="/personal-files"><i className="fa fa-home fa-2x" title="Personal Files"/></Link></li>
// <li><Link to="/deleted-files"><i className="fa fa-trash-o fa-2x" title="Deleted Files"/></Link></li>
// <li><Link to="/history"><i className="fa fa-history fa-2x" title="History"/></Link></li>
// </ul>
// <hr/>
// <hr/> | gpl-3.0 |
InfamousProductions/Infamous_Performance | src/com/infamous/performance/activities/VMSettings.java | 12261 | package com.infamous.performance.activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.infamous.performance.R;
import com.infamous.performance.util.ActivityThemeChangeInterface;
import com.infamous.performance.util.CMDProcessor;
import com.infamous.performance.util.Constants;
import com.infamous.performance.util.Helpers;
import com.infamous.performance.util.Prop;
import com.infamous.performance.util.PropAdapter;
import com.infamous.performance.util.PropUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by h0rn3t on 29.12.2013.
* http://forum.xda-developers.com/member.php?u=4674443
*/
public class VMSettings extends Activity implements Constants, AdapterView.OnItemClickListener, ActivityThemeChangeInterface {
private boolean mIsLightTheme;
SharedPreferences mPreferences;
private final Context context=this;
private ListView packList;
private LinearLayout linlaHeaderProgress;
private LinearLayout nofiles,search;
private RelativeLayout tools;
private PropAdapter adapter=null;
private EditText filterText = null;
private List<Prop> props = new ArrayList<Prop>();
private Boolean isdyn=false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setTheme();
setContentView(R.layout.prop_view);
if (new File(DYNAMIC_DIRTY_WRITEBACK_PATH).exists()){
isdyn=Helpers.readOneLine(DYNAMIC_DIRTY_WRITEBACK_PATH).equals("1");
}
packList = (ListView) findViewById(R.id.applist);
packList.setOnItemClickListener(this);
linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
nofiles = (LinearLayout) findViewById(R.id.nofiles);
tools = (RelativeLayout) findViewById(R.id.tools);
search = (LinearLayout) findViewById(R.id.search);
filterText = (EditText) findViewById(R.id.filtru);
filterText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(adapter!=null)
adapter.getFilter().filter(filterText.getText().toString());
}
});
Button applyBtn = (Button) findViewById(R.id.applyBtn);
applyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
final StringBuilder sb = new StringBuilder();
final String s=mPreferences.getString(PREF_VM,"");
if(!s.equals("")){
String p[]=s.split(";");
for (String aP : p) {
if(aP.contains(":")){
final String pn[]=aP.split(":");
sb.append("busybox echo ").append(pn[1]).append(" > ").append(VM_PATH).append(pn[0]).append(";\n");
}
}
Helpers.shExec(sb,context,true);
Toast.makeText(context, getString(R.string.applied_ok), Toast.LENGTH_SHORT).show();
}
}
});
final Switch setOnBoot = (Switch) findViewById(R.id.applyAtBoot);
setOnBoot.setChecked(mPreferences.getBoolean(VM_SOB, false));
setOnBoot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mPreferences.edit().putBoolean(VM_SOB, isChecked).apply();
}
});
tools.setVisibility(RelativeLayout.GONE);
search.setVisibility(LinearLayout.GONE);
isdyn= (new File(DYNAMIC_DIRTY_WRITEBACK_PATH).exists() && Helpers.readOneLine(DYNAMIC_DIRTY_WRITEBACK_PATH).equals("1"));
new GetPropOperation().execute();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.vm_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.reset_vm) {
new AlertDialog.Builder(this)
.setTitle(getString(R.string.mt_reset))
.setMessage(getString(R.string.reset_msg))
.setNegativeButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(getString(R.string.yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mPreferences.edit().remove(PREF_VM).apply();
}
}).create().show();
}
return true;
}
private class GetPropOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
Helpers.get_assetsScript("utils",context,"","");
new CMDProcessor().sh.runWaitFor("busybox chmod 750 "+getFilesDir()+"/utils" );
CMDProcessor.CommandResult cr =null;
cr = new CMDProcessor().su.runWaitFor(getFilesDir()+"/utils -getprop \""+VM_PATH+"/*\" \"1\"");
if(cr.success()){
load_prop(cr.stdout);
return "ok";
}
else{
Log.d(TAG, "VMSettings error: " + cr.stderr);
return "nok";
}
}
@Override
protected void onPostExecute(String result) {
if(result.equals("nok")) {
linlaHeaderProgress.setVisibility(LinearLayout.GONE);
nofiles.setVisibility(LinearLayout.VISIBLE);
}
else{
linlaHeaderProgress.setVisibility(LinearLayout.GONE);
if(props.isEmpty()){
nofiles.setVisibility(LinearLayout.VISIBLE);
}
else{
Collections.sort(props);
nofiles.setVisibility(LinearLayout.GONE);
tools.setVisibility(RelativeLayout.VISIBLE);
adapter = new PropAdapter(VMSettings.this, R.layout.prop_item, props);
packList.setAdapter(adapter);
}
}
}
@Override
protected void onPreExecute() {
linlaHeaderProgress.setVisibility(LinearLayout.VISIBLE);
nofiles.setVisibility(LinearLayout.GONE);
tools.setVisibility(RelativeLayout.GONE);
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long row) {
final Prop p = adapter.getItem(position);
editPropDialog(p);
}
@Override
public boolean isThemeChanged() {
final boolean is_light_theme = mPreferences.getBoolean(PREF_USE_LIGHT_THEME, false);
return is_light_theme != mIsLightTheme;
}
@Override
public void setTheme() {
final boolean is_light_theme = mPreferences.getBoolean(PREF_USE_LIGHT_THEME, false);
mIsLightTheme = is_light_theme;
setTheme(is_light_theme ? R.style.Theme_Light : R.style.Theme_Dark);
}
@Override
public void onResume() {
super.onResume();
}
private void editPropDialog(Prop p) {
final Prop pp = p;
String titlu="";
LayoutInflater factory = LayoutInflater.from(this);
final View editDialog = factory.inflate(R.layout.prop_edit_dialog, null);
final EditText tv = (EditText) editDialog.findViewById(R.id.vprop);
final TextView tn = (TextView) editDialog.findViewById(R.id.nprop);
if(pp!=null){
tv.setText(pp.getVal());
tn.setText(pp.getName());
titlu=getString(R.string.edit_prop_title);
}
else{//add
titlu=getString(R.string.add_prop_title);
}
new AlertDialog.Builder(this)
.setTitle(titlu)
.setView(editDialog)
.setNegativeButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(getString(R.string.ps_volt_save), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (pp!=null) {
if ((tv.getText().toString()!= null)&&(tv.getText().toString().length() > 0)){
pp.setVal(tv.getText().toString().trim());
PropUtil.set_pref(tn.getText().toString().trim(),tv.getText().toString().trim(),PREF_VM,mPreferences);
}
}
else {
if (tv.getText().toString() != null && tn.getText().toString() != null && tn.getText().toString().trim().length() > 0){
props.add(new Prop(tn.getText().toString().trim(),tv.getText().toString().trim()));
PropUtil.set_pref(tn.getText().toString().trim(),tv.getText().toString().trim(),PREF_VM,mPreferences);
}
}
Collections.sort(props);
adapter.notifyDataSetChanged();
}
}).create().show();
}
public boolean testprop(String s){
if (s.contains("dirty_writeback_active_centisecs") || s.contains("dynamic_dirty_writeback") || s.contains("dirty_writeback_suspend_centisecs") || isdyn && s.contains("dirty_writeback_centisecs")) {
return false;
}
return true;
}
public void load_prop(String s){
props.clear();
if(s==null) return;
final String p[]=s.split("\0");
for (String aP : p) {
try{
if(aP!=null){
String pn=aP;
pn=pn.substring(pn.lastIndexOf("/") + 1, pn.length()).trim();
if(testprop(pn)) props.add(new Prop(pn,Helpers.readOneLine(aP).trim()));
}
}
catch (Exception e){
}
}
}
}
| gpl-3.0 |
forgodsake/TowerPlus | ClientLib/src/main/java/com/o3dr/services/android/lib/drone/mission/item/command/Takeoff.java | 2382 | package com.o3dr.services.android.lib.drone.mission.item.command;
import android.os.Parcel;
import com.o3dr.services.android.lib.drone.mission.item.MissionItem;
import com.o3dr.services.android.lib.drone.mission.MissionItemType;
/**
* The vehicle will climb straight up from it’s current location to the altitude specified (in meters).
* This should be the first command of nearly all missions.
* If the mission is begun while the copter is already flying, the vehicle will climb straight up to the specified altitude.
* If the vehicle is already above the specified altitude the takeoff command will be ignored and the mission will move onto the next command immediately.
*
* Created by fhuya on 11/6/14.
*/
public class Takeoff extends MissionItem implements MissionItem.Command, android.os.Parcelable {
private double takeoffAltitude;
private double takeoffPitch;
public Takeoff(){
super(MissionItemType.TAKEOFF);
}
public Takeoff(Takeoff copy){
this();
takeoffAltitude = copy.takeoffAltitude;
takeoffPitch = copy.takeoffPitch;
}
/**
* @return take off altitude in meters
*/
public double getTakeoffAltitude() {
return takeoffAltitude;
}
/**
* Sets the take off altitude
* @param takeoffAltitude Altitude value in meters
*/
public void setTakeoffAltitude(double takeoffAltitude) {
this.takeoffAltitude = takeoffAltitude;
}
public double getTakeoffPitch() {
return takeoffPitch;
}
public void setTakeoffPitch(double takeoffPitch) {
this.takeoffPitch = takeoffPitch;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeDouble(this.takeoffAltitude);
dest.writeDouble(this.takeoffPitch);
}
private Takeoff(Parcel in) {
super(in);
this.takeoffAltitude = in.readDouble();
this.takeoffPitch = in.readDouble();
}
@Override
public MissionItem clone() {
return new Takeoff(this);
}
public static final Creator<Takeoff> CREATOR = new Creator<Takeoff>() {
public Takeoff createFromParcel(Parcel source) {
return new Takeoff(source);
}
public Takeoff[] newArray(int size) {
return new Takeoff[size];
}
};
}
| gpl-3.0 |
maestroanth/SkillzInDemand-1---DotNet-MVC-Practice | WebApplication4/Models/ManageViewModels/ManageLoginsViewModel.cs | 430 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Identity;
namespace WebApplication4.Models.ManageViewModels
{
public class ManageLoginsViewModel
{
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationDescription> OtherLogins { get; set; }
}
}
| gpl-3.0 |
TRPGEngine/Client | src/shared/model/chat-emotion.ts | 520 | import memoizeOne from 'memoize-one';
import { request } from '@shared/utils/request';
import _isString from 'lodash/isString';
export interface ChatEmotionItem {
name?: string;
url: string;
}
/**
* 搜索表情包
*/
export const searchEmotionWithKeyword = memoizeOne(async (keyword: string) => {
if (!_isString(keyword) || keyword === '') {
return [];
}
const { data } = await request.get<{
list: ChatEmotionItem[];
}>('/chatemotion/search', { params: { keyword } });
return data.list;
});
| gpl-3.0 |
variar/klogg | src/ui/src/iconloader.cpp | 3623 | /*
Sonic Visualiser
An audio file viewer and annotation editor.
Centre for Digital Music, Queen Mary, University of London.
This file copyright 2007 QMUL.
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. See the file
COPYING included with this distribution for more information.
*/
#include <QApplication>
#include <QFile>
#include <QPainter>
#include <QPalette>
#include <QPixmap>
#include <QStyleOption>
#include <QWidget>
#include "iconloader.h"
#include "log.h"
#include <array>
constexpr std::array<int, 8> IconSizes{ 0, 16 };
IconLoader::IconLoader( QWidget* widget )
: widget_{ widget }
{
}
QIcon IconLoader::load( QString name )
{
QIcon icon;
for ( int sz : IconSizes ) {
QPixmap pmap( loadPixmap( name, sz ) );
if ( !pmap.isNull() )
icon.addPixmap( pmap );
}
return icon;
}
bool IconLoader::shouldInvert() const
{
QStyleOption style;
style.initFrom( widget_ );
auto bg = style.palette.window().color();
bool darkBackground = ( bg.red() + bg.green() + bg.blue() <= 384 );
return darkBackground;
}
bool IconLoader::shouldAutoInvert( QString /*name*/ ) const
{
return true;
}
QPixmap IconLoader::loadPixmap( QString name, int size ) const
{
bool invert = shouldInvert();
QString scalableName, nonScalableName;
QPixmap pmap;
// attempt to load a pixmap with the right size and inversion
nonScalableName = makeNonScalableFilename( name, size, invert );
pmap = QPixmap( nonScalableName );
if ( pmap.isNull() && invert ) {
// if that failed, and we were asking for an inverted pixmap,
// that may mean we don't have an inverted version of it. We
// could either auto-invert or use the uninverted version
nonScalableName = makeNonScalableFilename( name, size, false );
pmap = QPixmap( nonScalableName );
if ( !pmap.isNull() && shouldAutoInvert( name ) ) {
pmap = invertPixmap( pmap );
}
}
return pmap;
}
QString IconLoader::makeNonScalableFilename( QString name, int size, bool invert ) const
{
if ( invert ) {
if ( size == 0 ) {
return QString( ":/images/%1_inverse.png" ).arg( name );
}
else {
return QString( ":/images/%1-%2_inverse.png" ).arg( name ).arg( size );
}
}
else {
if ( size == 0 ) {
return QString( ":/images/%1.png" ).arg( name );
}
else {
return QString( ":/images/%1-%2.png" ).arg( name ).arg( size );
}
}
}
QPixmap IconLoader::invertPixmap( QPixmap pmap ) const
{
// No suitable inverted icon found for black background; try to
// auto-invert the default one
QImage img = pmap.toImage().convertToFormat( QImage::Format_ARGB32 );
for ( int y = 0; y < img.height(); ++y ) {
for ( int x = 0; x < img.width(); ++x ) {
QRgb rgba = img.pixel( x, y );
QColor colour = QColor( qRed( rgba ), qGreen( rgba ), qBlue( rgba ), qAlpha( rgba ) );
int alpha = colour.alpha();
if ( colour.saturation() < 5 && colour.alpha() > 10 ) {
colour.setHsv( colour.hue(), colour.saturation(), 255 - colour.value() );
colour.setAlpha( alpha );
img.setPixel( x, y, colour.rgba() );
}
}
}
pmap = QPixmap::fromImage( img );
return pmap;
} | gpl-3.0 |
ArmandDelessert/WarTanks | NavalBattle/src/navalbattle/client/ClientGrid.java | 7785 | package navalbattle.client;
import java.awt.Dimension;
import java.util.ArrayList;
import navalbattle.boats.Boat;
import navalbattle.boats.BoatIsOutsideGridException;
import navalbattle.boats.BoatPosition;
import navalbattle.boats.BoatUtils;
import navalbattle.boats.PositionNotSetException;
import navalbattle.protocol.common.CoordinateWithType;
import navalbattle.protocol.common.MapSizeEnum;
import navalbattle.protocol.common.NavalBattleProtocol;
import navalbattle.server.BoatsAreOverlapping;
public class ClientGrid {
private final MapSizeEnum mapSize;
private ArrayList<Boat> allBoats = null;
private NavalBattleProtocol.COORDINATE_TYPE[][] grid = null;
private NavalBattleProtocol.COORDINATE_TYPE[][] previousGrid = null;
// TO-DO: return a copy
public NavalBattleProtocol.COORDINATE_TYPE[][] getGridForDrawing() {
return this.grid;
}
public NavalBattleProtocol.COORDINATE_TYPE[][] getGridForDrawinPreviousGrid() {
return this.previousGrid;
}
public ClientGrid(MapSizeEnum mapSize) {
this.mapSize = mapSize;
int cells = this.mapSize.getSize();
grid = new NavalBattleProtocol.COORDINATE_TYPE[cells][cells];
for (int i = 0; i < cells; ++i) {
for (int j = 0; j < cells; ++j) {
grid[i][j] = NavalBattleProtocol.COORDINATE_TYPE.NOTHING;
}
}
}
public void receivedFireFromOpponentSimpleDesign(ArrayList<CoordinateWithType> allCoordinates) {
previousGrid = new NavalBattleProtocol.COORDINATE_TYPE[grid.length][grid.length];
for (int i = 0; i < grid.length; ++i) {
for (int j = 0; j < grid[i].length; ++j) {
previousGrid[i][j] = grid[i][j];
}
}
for (CoordinateWithType cwt : allCoordinates) {
NavalBattleProtocol.COORDINATE_TYPE t = cwt.getType();
switch (cwt.getType()) {
case NOTHING:
// Your opponent (or a mine) fired here but there was no effect at all
t = NavalBattleProtocol.COORDINATE_TYPE.FIRED_BUT_DID_NOT_DAMAGE_ANYTHING;
break;
}
this.grid[cwt.getX()][cwt.getY()] = t;
}
}
public void receivedFireFromOpponent(ArrayList<CoordinateWithType> allCoordinates) throws InconsistentGameStateBetweenServerAndClientException, BoatNotPlacedException {
previousGrid = new NavalBattleProtocol.COORDINATE_TYPE[grid.length][grid.length];
for (int i = 0; i < grid.length; ++i) {
for (int j = 0; j < grid[i].length; ++j) {
previousGrid[i][j] = grid[i][j];
}
}
if (allBoats == null) {
throw new BoatNotPlacedException();
}
for (CoordinateWithType cwt : allCoordinates) {
int x = cwt.getX();
int y = cwt.getY();
switch (cwt.getType()) {
case DAMAGED:
case SINKED:
try {
for (Boat boat : this.allBoats) {
if (boat.isPositionOnShip(x, y)) {
NavalBattleProtocol.HIT_ON_BOAT hitResult = boat.fire(x, y);
if (cwt.getType() == NavalBattleProtocol.COORDINATE_TYPE.DAMAGED) {
if (hitResult != NavalBattleProtocol.HIT_ON_BOAT.HIT) {
throw new InconsistentGameStateBetweenServerAndClientException();
}
this.grid[x][y] = NavalBattleProtocol.COORDINATE_TYPE.DAMAGED;
} else if (cwt.getType() == NavalBattleProtocol.COORDINATE_TYPE.SINKED) {
if (hitResult != NavalBattleProtocol.HIT_ON_BOAT.SINKED) {
throw new InconsistentGameStateBetweenServerAndClientException();
}
BoatPosition position = boat.getPosition();
int boatLength = position.getLength();
int posX = position.getX();
int posY = position.getY();
switch (boat.getPosition().getOrientation()) {
case HORIZONTAL:
for (int i = 0; i < boatLength; ++i) {
grid[posX + i][posY] = NavalBattleProtocol.COORDINATE_TYPE.SINKED;
}
break;
case VERTICAL:
for (int i = 0; i < boatLength; ++i) {
grid[posX][posY + i] = NavalBattleProtocol.COORDINATE_TYPE.SINKED;
}
break;
}
}
}
}
} catch (PositionNotSetException ex) {
// will never happen (game has started)
}
break;
case SATELLITE:
grid[x][y] = NavalBattleProtocol.COORDINATE_TYPE.SATELLITE;
break;
case MINE:
grid[x][y] = NavalBattleProtocol.COORDINATE_TYPE.MINE;
break;
case NOTHING:
// Your opponent (or a mine) fired here but there was no effect at all
grid[x][y] = NavalBattleProtocol.COORDINATE_TYPE.FIRED_BUT_DID_NOT_DAMAGE_ANYTHING;
break;
case REAVEALED_HAS_SHIP:
grid[x][y] = NavalBattleProtocol.COORDINATE_TYPE.REAVEALED_HAS_SHIP;
break;
case REAVEALED_HAS_NO_SHIP:
grid[x][y] = NavalBattleProtocol.COORDINATE_TYPE.REAVEALED_HAS_NO_SHIP;
break;
}
}
}
public void positionBoats(ArrayList<Boat> boats) throws BoatsAreOverlapping, BoatIsOutsideGridException {
ArrayList<BoatPosition> positions = new ArrayList<>(boats.size());
for (Boat boat : boats) {
positions.add(boat.getPosition());
}
int cells = this.mapSize.getSize();
if (BoatUtils.areBoatsOverlapping(new Dimension(cells, cells), positions)) {
throw new BoatsAreOverlapping();
}
for (BoatPosition bp : positions) {
if (bp.getX() < 0 || bp.getX() >= cells
|| bp.getY() < 0 || bp.getY() >= cells) {
throw new BoatIsOutsideGridException();
}
}
for (BoatPosition bp : positions) {
int boatLength = bp.getLength();
int posX = bp.getX();
int posY = bp.getY();
switch (bp.getOrientation()) {
case HORIZONTAL:
for (int i = 0; i < boatLength; ++i) {
grid[posX + i][posY] = NavalBattleProtocol.COORDINATE_TYPE.BOAT;
}
break;
case VERTICAL:
for (int i = 0; i < boatLength; ++i) {
grid[posX][posY + i] = NavalBattleProtocol.COORDINATE_TYPE.BOAT;
}
break;
}
}
this.allBoats = boats;
}
public MapSizeEnum getMapSize() {
return this.mapSize;
}
}
| gpl-3.0 |
waikato-datamining/adams-base | adams-core/src/main/java/adams/gui/event/DataChangeListener.java | 1189 | /*
* 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/>.
*/
/*
* DataChangeListener.java
* Copyright (C) 2008 University of Waikato, Hamilton, New Zealand
*/
package adams.gui.event;
/**
* Inteface for classes that listen to data changes in a SpectrumPanel.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public interface DataChangeListener {
/**
* Gets called if the data of the spectrum panel has changed.
*
* @param e the event that the spectrum panel sent
*/
public void dataChanged(DataChangeEvent e);
}
| gpl-3.0 |
PprMkr/Opencart2.0_Dutch | upload/admin/language/dutch/catalog/profile.php | 2289 | <?php
// Heading
$_['heading_title'] = 'Betalingsprofiel(en)';
// Buttons
$_['button_insert'] = 'Toevoegen';
$_['button_copy'] = 'Kopieren';
$_['button_delete'] = 'Verwijderen';
$_['button_remove'] = 'Verwijderen';
// Text
$_['text_confirm'] = 'Weet u het zeker?';
$_['text_no_results'] = 'Geen resultaten';
$_['text_remove'] = 'Verwijderen';
$_['text_edit'] = 'Bewerken';
$_['text_enabled'] = 'Actief';
$_['text_disabled'] = 'Inactief';
$_['text_success'] = 'Betalingsprofiel succesvol toegevoegd';
$_['text_removed'] = 'Betalingsprofiel(en) verwijderd';
$_['text_copied'] = 'Betalingsprofiel(en) gekopieerd';
$_['text_day'] = 'Dag';
$_['text_week'] = 'Week';
$_['text_semi_month'] = 'Halve maand';
$_['text_month'] = 'Maand';
$_['text_year'] = 'Jaar';
$_['text_recurring_help'] = 'Terugkerende bedragen worden berekend aan de hand van frequentie and cyclus. <br />Kies bijvoorbeeld frequentie "week" en cyclus "2", dan zal de klant elke 2 weken een rekening ontvangen. <br />De "duur" is het aantal keer dat een betaling gedaan dient te worden. Zet dit op "0" als u betalingen wilt ontvangen totdat er geannuleerd wordt.';
// Entry
$_['entry_name'] = 'Naam:';
$_['entry_sort_order'] = 'Sorteervolgorde:';
$_['entry_price'] = 'Prijs:';
$_['entry_duration'] = 'Duur:<br /><span class="help">Zie: Help.<span class="help">';
$_['entry_status'] = 'Status:';
$_['entry_cycle'] = 'Cyclus:<br /><span class="help">Zie: Help.</span>';
$_['entry_frequency'] = 'Frequentie:<br /><span class="help">Zie: Help.</span>';
$_['entry_trial_price'] = 'Test prijs:';
$_['entry_trial_duration'] = 'Test duur:';
$_['entry_trial_status'] = 'Test status:';
$_['entry_trial_cycle'] = 'Test cyclus:';
$_['entry_trial_frequency'] = 'Test frequentie:';
// Column
$_['column_name'] = 'Naam';
$_['column_sort_order'] = 'Sorteervolgorde';
$_['column_action'] = 'Aktie';
// Error
$_['error_warning'] = 'Waarschuwing: Controlleer of alle verplichte velden volledig zijn ingevuld!';
$_['error_permission'] = 'Waarschuwing: U heeft geen rechten deze instellingen te wijzigen!';
$_['error_name'] = 'Waarschuwing: Betalingsprofielnaam dient tussen de 3 en 255 tekens lang te zijn!'; | gpl-3.0 |
gadonj18/ballsofsteel | Assets/Scripts/ApplicationLogic.cs | 2614 | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//This class handles interactions between the scenes and stores data to persist across scenes
public class ApplicationLogic : MonoBehaviour {
private string playerName; //Not sure why I even need this, I guess for high scores?
private long currentScore; //Will carry through to the scoreboard
private int currentLevel; //Level being played
private int unlockedLevel; //Highest level user has unlocked (Default = 1)
public Dictionary<int, long> highScores;
public int numLevels; //Stores the number of levels in the game
void Start() {
//Used to persist object across scenes
DontDestroyOnLoad(this.gameObject);
//Initialize the settings we want to save/persist across scenes
#if UNITY_WEBPLAYER
this.PlayerName = PlayerPrefs.GetString("PlayerName", "Player1");
#else
this.PlayerName = PlayerPrefs.GetString("PlayerName", System.Environment.UserName);
#endif
this.CurrentScore = 0;
this.CurrentLevel = 0;
this.UnlockedLevel = (int)PlayerPrefs.GetInt("UnlockedLevel", 1);
this.highScores = new Dictionary<int, long>();
//Grab any saved high scores
for(int i = 1; i <= this.numLevels; i++) {
this.highScores[i] = (long)PlayerPrefs.GetInt("HighScoreLevel" + i, 0);
}
}
//On button click from start screen
public void ShowLevelSelect() {
Application.LoadLevel("LevelSelectScene");
}
//On button click from start screen
public void StartGame(int levelNum = 0) {
if(levelNum > 0) this.CurrentLevel = levelNum;
this.CurrentScore = 0;
Application.LoadLevel("MainGameScene");
}
private void NextLevel() {
this.CurrentLevel++;
this.StartGame();
}
private void ReplayLevel() {
this.StartGame(this.CurrentLevel);
}
public void WinGame() {
if(this.currentScore > this.highScores[this.currentLevel]) {
this.highScores[this.currentLevel] = this.currentScore;
PlayerPrefs.SetInt("HighScoreLevel" + this.currentLevel, (int)this.currentScore);
}
Invoke("NextLevel", 3.0f);
}
public void LoseGame() {
Invoke("ReplayLevel", 3.0f);
}
//--------------- GETTERS/SETTERS BELOW --------------------------
public string PlayerName {
get { return this.playerName; }
private set { this.playerName = value; }
}
public long CurrentScore {
get { return this.currentScore; }
private set { this.currentScore = value; }
}
public int CurrentLevel {
get { return this.currentLevel; }
private set { this.currentLevel = value; }
}
public int UnlockedLevel {
get { return this.unlockedLevel; }
private set { this.unlockedLevel = value; }
}
} | gpl-3.0 |
deathman92/gibdd-web-services | register-vehicle-web-service/src/main/java/ru/vlsu/gibdd/webservice/register/endpoint/RegisterVehicleEndpoint.java | 2184 | package ru.vlsu.gibdd.webservice.register.endpoint;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import ru.vlsu.gibdd.webservice.register.config.WebServiceConfig;
import ru.vlsu.gibdd.webservice.register.io.FindRegistrationCertificateRequestIo;
import ru.vlsu.gibdd.webservice.register.io.FindRegistrationCertificateResponseIo;
import ru.vlsu.gibdd.webservice.register.io.RegisterVehicleRequestIo;
import ru.vlsu.gibdd.webservice.register.io.RegisterVehicleResponseIo;
import ru.vlsu.gibdd.webservice.register.service.api.RegistrationCertificateService;
/**
* @author Victor Zhivotikov
* @since 01.04.2016
*/
@Endpoint
@Slf4j
public class RegisterVehicleEndpoint {
@Autowired
private RegistrationCertificateService certificateService;
@PayloadRoot(namespace = WebServiceConfig.NAMESPACE_URI, localPart = "RegisterVehicleRequest")
@ResponsePayload
public RegisterVehicleResponseIo handle(@RequestPayload RegisterVehicleRequestIo request) {
log.info("Handle registerVehicle request: " + request);
RegisterVehicleResponseIo response = certificateService.createRegistrationCertificate(request);
log.info("Send back registerVehicle response: " + response);
return response;
}
@PayloadRoot(namespace = WebServiceConfig.NAMESPACE_URI, localPart = "FindRegistrationCertificateRequest")
@ResponsePayload
public FindRegistrationCertificateResponseIo handle(@RequestPayload FindRegistrationCertificateRequestIo request) {
log.info("Handle findRegistrationCertificate request: " + request);
FindRegistrationCertificateResponseIo response = certificateService.findRegistrationCertificate(request);
log.info("Send back findRegistrationCertificate response: " + response);
return response;
}
}
| gpl-3.0 |
nickapos/myBill | src/main/java/gr/oncrete/nick/mybill/BusinessLogic/InsertCompany.java | 4922 | /*
myBill, bills tracking program
Copyright (C) 2010 Nick Apostolakis
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/>.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gr.oncrete.nick.mybill.BusinessLogic;
import gr.oncrete.nick.mybill.RDBMS.InsertIntoTable;
import gr.oncrete.nick.mybill.BusinessLogic.SelectInfo.SelectCompanyDetails;
/**
*
* @author nickapos
*
* This class is used to insert new company entries into the database
*/
public class InsertCompany {
InsertIntoTable in;
int AFMSIZE=9;
/**
*
*/
public InsertCompany() {
}
/**
* method without an id
*
* @param cName
* @param afm
* @param catID
*/
public void insertCompany(String cName, String afm, String catID) {
if (cName.length() > 0 && afm.length() > 0 && catID.length() > 0) {
String sql = "insert into companies (companyname,afm,catid) values ('" + cName + "','" + this.truncateAfmString(afm,AFMSIZE) + "'," + catID + ")";
in = new InsertIntoTable(sql);
if (!in.hasCompletedSucesfully()) {
System.out.println("insertion has not completed sucesfully conficting company details are: ");
this.printConflictingCompany(afm);
}
//System.out.println(sql);
} else {
in = new InsertIntoTable();
in.warningPopUp(java.util.ResourceBundle.getBundle("i18n/myBillUIBundle").getString("ERROR IN COMPANY INSERTION"));
}
}
/**
* Constructor insert company with a specific id
* used in restoring the database from csv file format
*
* @param id
* @param cName
* @param afm
*/
public InsertCompany(String id, String cName, String afm) {
if (id.length() > 0 && cName.length() > 0 && afm.length() > 0) {
String sql = "insert into companies (cid, companyname,afm) values (" + id + ",'" + this.truncateAfmString(afm,AFMSIZE) + "','" + afm + "')";
in = new InsertIntoTable(sql);
if (!in.hasCompletedSucesfully()) {
System.out.println("insertion has not completed sucesfully conficting company details are: ");
this.printConflictingCompany(afm);
}
//System.out.println(sql);
} else {
in = new InsertIntoTable();
in.warningPopUp(java.util.ResourceBundle.getBundle("i18n/myBillUIBundle").getString("ERROR IN COMPANY INSERTION"));
}
}
/**
*
* @param id
* @param cName
* @param afm
* @param catid
*/
public InsertCompany(String id, String cName, String afm, String catid) {
if (id.length() > 0 && cName.length() > 0 && afm.length() > 0 && catid.length() > 0) {
String sql = "insert into companies (cid, companyname,afm,catid) values (" + id + ",'" + cName + "','" + this.truncateAfmString(afm,AFMSIZE) + "'," + catid + ")";
in = new InsertIntoTable(sql);
if (!in.hasCompletedSucesfully()) {
System.out.println("insertion has not completed sucesfully conficting company details are: ");
this.printConflictingCompany(afm);
}
//System.out.println(sql);
} else {
in = new InsertIntoTable();
in.warningPopUp(java.util.ResourceBundle.getBundle("i18n/myBillUIBundle").getString("ERROR IN COMPANY INSERTION"));
}
}
/**
* this private method will return the conflicting company in case of a unique constraint conflict in afm (the only possible constraint conflict with the specific table)
* @param afm
*/
private void printConflictingCompany(String afm) {
SelectCompanyDetails conflictingCompany = new SelectCompanyDetails();
conflictingCompany.SelectCompanyDetailsWithAfm(afm);
System.out.println(conflictingCompany.companyToString());
}
/**
* This method will check if the incoming afm string is more than AFMSIZE characters and if that is true, truncate it to the max size
*/
public String truncateAfmString(String afm, int AFMSIZE){
String truncAfm=afm;
if(afm.length()>AFMSIZE ){
truncAfm=afm.substring(0, AFMSIZE);
}
return truncAfm;
}
}
| gpl-3.0 |
Atvaark/x64dbg | src/gui/Src/Tracer/TraceBrowser.cpp | 54202 | #include "TraceBrowser.h"
#include "TraceFileReader.h"
#include "TraceFileSearch.h"
#include "RichTextPainter.h"
#include "main.h"
#include "BrowseDialog.h"
#include "QBeaEngine.h"
#include "GotoDialog.h"
#include "LineEditDialog.h"
#include "WordEditDialog.h"
#include "CachedFontMetrics.h"
#include "BreakpointMenu.h"
#include "MRUList.h"
#include <QFileDialog>
TraceBrowser::TraceBrowser(QWidget* parent) : AbstractTableView(parent)
{
mTraceFile = nullptr;
addColumnAt(getCharWidth() * 2 * 8 + 8, "", false); //index
addColumnAt(getCharWidth() * 2 * sizeof(dsint) + 8, "", false); //address
addColumnAt(getCharWidth() * 2 * 12 + 8, "", false); //bytes
addColumnAt(getCharWidth() * 40, "", false); //disassembly
addColumnAt(1000, "", false); //comments
setShowHeader(false); //hide header
mSelection.firstSelectedIndex = 0;
mSelection.fromIndex = 0;
mSelection.toIndex = 0;
setRowCount(0);
mRvaDisplayBase = 0;
mRvaDisplayEnabled = false;
mAutoDisassemblyFollowSelection = false;
int maxModuleSize = (int)ConfigUint("Disassembler", "MaxModuleSize");
mDisasm = new QBeaEngine(maxModuleSize);
mHighlightingMode = false;
mPermanentHighlightingMode = false;
mMRUList = new MRUList(this, "Recent Trace Files");
connect(mMRUList, SIGNAL(openFile(QString)), this, SLOT(openSlot(QString)));
mMRUList->load();
setupRightClickContextMenu();
Initialize();
connect(Bridge::getBridge(), SIGNAL(updateTraceBrowser()), this, SLOT(updateSlot()));
connect(Bridge::getBridge(), SIGNAL(openTraceFile(const QString &)), this, SLOT(openSlot(const QString &)));
}
TraceBrowser::~TraceBrowser()
{
delete mDisasm;
}
QString TraceBrowser::getAddrText(dsint cur_addr, char label[MAX_LABEL_SIZE], bool getLabel)
{
QString addrText = "";
if(mRvaDisplayEnabled) //RVA display
{
dsint rva = cur_addr - mRvaDisplayBase;
if(rva == 0)
{
#ifdef _WIN64
addrText = "$ ==> ";
#else
addrText = "$ ==> ";
#endif //_WIN64
}
else if(rva > 0)
{
#ifdef _WIN64
addrText = "$+" + QString("%1").arg(rva, -15, 16, QChar(' ')).toUpper();
#else
addrText = "$+" + QString("%1").arg(rva, -7, 16, QChar(' ')).toUpper();
#endif //_WIN64
}
else if(rva < 0)
{
#ifdef _WIN64
addrText = "$-" + QString("%1").arg(-rva, -15, 16, QChar(' ')).toUpper();
#else
addrText = "$-" + QString("%1").arg(-rva, -7, 16, QChar(' ')).toUpper();
#endif //_WIN64
}
}
addrText += ToPtrString(cur_addr);
char label_[MAX_LABEL_SIZE] = "";
if(getLabel && DbgGetLabelAt(cur_addr, SEG_DEFAULT, label_)) //has label
{
char module[MAX_MODULE_SIZE] = "";
if(DbgGetModuleAt(cur_addr, module) && !QString(label_).startsWith("JMP.&"))
addrText += " <" + QString(module) + "." + QString(label_) + ">";
else
addrText += " <" + QString(label_) + ">";
}
else
*label_ = 0;
if(label)
strcpy_s(label, MAX_LABEL_SIZE, label_);
return addrText;
}
QString TraceBrowser::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
if(!mTraceFile || mTraceFile->Progress() != 100)
{
return "";
}
if(mTraceFile->isError())
{
GuiAddLogMessage(tr("An error occured when reading trace file.\r\n").toUtf8().constData());
mTraceFile->Close();
delete mTraceFile;
mTraceFile = nullptr;
setRowCount(0);
return "";
}
if(mHighlightingMode)
{
QPen pen(mInstructionHighlightColor);
pen.setWidth(2);
painter->setPen(pen);
QRect rect = viewport()->rect();
rect.adjust(1, 1, -1, -1);
painter->drawRect(rect);
}
int index = rowBase + rowOffset;
duint cur_addr;
cur_addr = mTraceFile->Registers(index).regcontext.cip;
bool wIsSelected = (index >= mSelection.fromIndex && index <= mSelection.toIndex);
if(wIsSelected)
{
painter->fillRect(QRect(x, y, w, h), QBrush(mSelectionColor));
}
if(index >= mTraceFile->Length())
return "";
switch(col)
{
case 0: //index
{
return getIndexText(index);
}
case 1: //address
{
QString addrText;
char label[MAX_LABEL_SIZE] = "";
if(!DbgIsDebugging())
{
addrText = ToPtrString(cur_addr);
goto NotDebuggingLabel;
}
else
addrText = getAddrText(cur_addr, label, true);
BPXTYPE bpxtype = DbgGetBpxTypeAt(cur_addr);
bool isbookmark = DbgGetBookmarkAt(cur_addr);
//todo: cip
{
if(!isbookmark) //no bookmark
{
if(*label) //label
{
if(bpxtype == bp_none) //label only : fill label background
{
painter->setPen(mLabelColor); //red -> address + label text
painter->fillRect(QRect(x, y, w, h), QBrush(mLabelBackgroundColor)); //fill label background
}
else //label + breakpoint
{
if(bpxtype & bp_normal) //label + normal breakpoint
{
painter->setPen(mBreakpointColor);
painter->fillRect(QRect(x, y, w, h), QBrush(mBreakpointBackgroundColor)); //fill red
}
else if(bpxtype & bp_hardware) //label + hardware breakpoint only
{
painter->setPen(mHardwareBreakpointColor);
painter->fillRect(QRect(x, y, w, h), QBrush(mHardwareBreakpointBackgroundColor)); //fill ?
}
else //other cases -> do as normal
{
painter->setPen(mLabelColor); //red -> address + label text
painter->fillRect(QRect(x, y, w, h), QBrush(mLabelBackgroundColor)); //fill label background
}
}
}
else //no label
{
if(bpxtype == bp_none) //no label, no breakpoint
{
NotDebuggingLabel:
QColor background;
if(wIsSelected)
{
background = mSelectedAddressBackgroundColor;
painter->setPen(mSelectedAddressColor); //black address (DisassemblySelectedAddressColor)
}
else
{
background = mAddressBackgroundColor;
painter->setPen(mAddressColor); //DisassemblyAddressColor
}
if(background.alpha())
painter->fillRect(QRect(x, y, w, h), QBrush(background)); //fill background
}
else //breakpoint only
{
if(bpxtype & bp_normal) //normal breakpoint
{
painter->setPen(mBreakpointColor);
painter->fillRect(QRect(x, y, w, h), QBrush(mBreakpointBackgroundColor)); //fill red
}
else if(bpxtype & bp_hardware) //hardware breakpoint only
{
painter->setPen(mHardwareBreakpointColor);
painter->fillRect(QRect(x, y, w, h), QBrush(mHardwareBreakpointBackgroundColor)); //fill red
}
else //other cases (memory breakpoint in disassembly) -> do as normal
{
QColor background;
if(wIsSelected)
{
background = mSelectedAddressBackgroundColor;
painter->setPen(mSelectedAddressColor); //black address (DisassemblySelectedAddressColor)
}
else
{
background = mAddressBackgroundColor;
painter->setPen(mAddressColor);
}
if(background.alpha())
painter->fillRect(QRect(x, y, w, h), QBrush(background)); //fill background
}
}
}
}
else //bookmark
{
if(*label) //label + bookmark
{
if(bpxtype == bp_none) //label + bookmark
{
painter->setPen(mLabelColor); //red -> address + label text
painter->fillRect(QRect(x, y, w, h), QBrush(mBookmarkBackgroundColor)); //fill label background
}
else //label + breakpoint + bookmark
{
QColor color = mBookmarkBackgroundColor;
if(!color.alpha()) //we don't want transparent text
color = mAddressColor;
painter->setPen(color);
if(bpxtype & bp_normal) //label + bookmark + normal breakpoint
{
painter->fillRect(QRect(x, y, w, h), QBrush(mBreakpointBackgroundColor)); //fill red
}
else if(bpxtype & bp_hardware) //label + bookmark + hardware breakpoint only
{
painter->fillRect(QRect(x, y, w, h), QBrush(mHardwareBreakpointBackgroundColor)); //fill ?
}
}
}
else //bookmark, no label
{
if(bpxtype == bp_none) //bookmark only
{
painter->setPen(mBookmarkColor); //black address
painter->fillRect(QRect(x, y, w, h), QBrush(mBookmarkBackgroundColor)); //fill bookmark color
}
else //bookmark + breakpoint
{
QColor color = mBookmarkBackgroundColor;
if(!color.alpha()) //we don't want transparent text
color = mAddressColor;
painter->setPen(color);
if(bpxtype & bp_normal) //bookmark + normal breakpoint
{
painter->fillRect(QRect(x, y, w, h), QBrush(mBreakpointBackgroundColor)); //fill red
}
else if(bpxtype & bp_hardware) //bookmark + hardware breakpoint only
{
painter->fillRect(QRect(x, y, w, h), QBrush(mHardwareBreakpointBackgroundColor)); //fill red
}
else //other cases (bookmark + memory breakpoint in disassembly) -> do as normal
{
painter->setPen(mBookmarkColor); //black address
painter->fillRect(QRect(x, y, w, h), QBrush(mBookmarkBackgroundColor)); //fill bookmark color
}
}
}
}
}
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, addrText);
}
return "";
case 2: //opcode
{
RichTextPainter::List richBytes;
RichTextPainter::CustomRichText_t curByte;
RichTextPainter::CustomRichText_t space;
unsigned char opcodes[16];
int opcodeSize = 0;
mTraceFile->OpCode(index, opcodes, &opcodeSize);
space.text = " ";
space.flags = RichTextPainter::FlagNone;
space.highlightWidth = 1;
space.highlightConnectPrev = true;
curByte.flags = RichTextPainter::FlagAll;
curByte.highlightWidth = 1;
space.highlight = false;
curByte.highlight = false;
for(int i = 0; i < opcodeSize; i++)
{
if(i)
richBytes.push_back(space);
curByte.text = ToByteString(opcodes[i]);
curByte.textColor = mBytesColor;
curByte.textBackground = mBytesBackgroundColor;
richBytes.push_back(curByte);
}
RichTextPainter::paintRichText(painter, x, y, getColumnWidth(col), getRowHeight(), 4, richBytes, mFontMetrics);
return "";
}
case 3: //disassembly
{
RichTextPainter::List richText;
unsigned char opcodes[16];
int opcodeSize = 0;
mTraceFile->OpCode(index, opcodes, &opcodeSize);
Instruction_t inst = mDisasm->DisassembleAt(opcodes, opcodeSize, 0, mTraceFile->Registers(index).regcontext.cip, false);
if(mHighlightToken.text.length())
CapstoneTokenizer::TokenToRichText(inst.tokens, richText, &mHighlightToken);
else
CapstoneTokenizer::TokenToRichText(inst.tokens, richText, 0);
RichTextPainter::paintRichText(painter, x + 0, y, getColumnWidth(col) - 0, getRowHeight(), 4, richText, mFontMetrics);
return "";
}
case 4: //comments
{
if(DbgIsDebugging())
{
//TODO: draw arguments
QString comment;
bool autoComment = false;
char label[MAX_LABEL_SIZE] = "";
if(GetCommentFormat(cur_addr, comment, &autoComment))
{
QColor backgroundColor;
if(autoComment)
{
painter->setPen(mAutoCommentColor);
backgroundColor = mAutoCommentBackgroundColor;
}
else //user comment
{
painter->setPen(mCommentColor);
backgroundColor = mCommentBackgroundColor;
}
int width = mFontMetrics->width(comment);
if(width > w)
width = w;
if(width)
painter->fillRect(QRect(x, y, width, h), QBrush(backgroundColor)); //fill comment color
painter->drawText(QRect(x, y, width, h), Qt::AlignVCenter | Qt::AlignLeft, comment);
}
else if(DbgGetLabelAt(cur_addr, SEG_DEFAULT, label)) // label but no comment
{
QString labelText(label);
QColor backgroundColor;
painter->setPen(mLabelColor);
backgroundColor = mLabelBackgroundColor;
int width = mFontMetrics->width(labelText);
if(width > w)
width = w;
if(width)
painter->fillRect(QRect(x, y, width, h), QBrush(backgroundColor)); //fill comment color
painter->drawText(QRect(x, y, width, h), Qt::AlignVCenter | Qt::AlignLeft, labelText);
}
}
return "";
}
default:
return "";
}
}
void TraceBrowser::prepareData()
{
auto viewables = getViewableRowsCount();
int lines = 0;
if(mTraceFile != nullptr)
{
if(mTraceFile->Progress() == 100)
{
if(mTraceFile->Length() < getTableOffset() + viewables)
lines = mTraceFile->Length() - getTableOffset();
else
lines = viewables;
}
}
setNbrOfLineToPrint(lines);
}
void TraceBrowser::setupRightClickContextMenu()
{
mMenuBuilder = new MenuBuilder(this);
QAction* toggleRunTrace = makeShortcutAction(DIcon("trace.png"), tr("Start Run Trace"), SLOT(toggleRunTraceSlot()), "ActionToggleRunTrace");
mMenuBuilder->addAction(toggleRunTrace, [toggleRunTrace](QMenu*)
{
if(!DbgIsDebugging())
return false;
if(DbgValFromString("tr.runtraceenabled()") == 1)
toggleRunTrace->setText(tr("Stop Run Trace"));
else
toggleRunTrace->setText(tr("Start Run Trace"));
return true;
});
auto mTraceFileIsNull = [this](QMenu*)
{
return mTraceFile == nullptr;
};
mMenuBuilder->addAction(makeAction(DIcon("folder-horizontal-open.png"), tr("Open"), SLOT(openFileSlot())), mTraceFileIsNull);
mMenuBuilder->addMenu(makeMenu(DIcon("recentfiles.png"), tr("Recent Files")), [this](QMenu * menu)
{
if(mTraceFile == nullptr)
{
mMRUList->appendMenu(menu);
return true;
}
else
return false;
});
mMenuBuilder->addAction(makeAction(DIcon("fatal-error.png"), tr("Close"), SLOT(closeFileSlot())), [this](QMenu*)
{
return mTraceFile != nullptr;
});
mMenuBuilder->addAction(makeAction(DIcon("fatal-error.png"), tr("Close and delete"), SLOT(closeDeleteSlot())), [this](QMenu*)
{
return mTraceFile != nullptr;
});
mMenuBuilder->addSeparator();
auto isValid = [this](QMenu*)
{
return mTraceFile != nullptr && mTraceFile->Progress() == 100 && mTraceFile->Length() > 0;
};
auto isDebugging = [this](QMenu*)
{
return mTraceFile != nullptr && mTraceFile->Progress() == 100 && mTraceFile->Length() > 0 && DbgIsDebugging();
};
MenuBuilder* copyMenu = new MenuBuilder(this, isValid);
copyMenu->addAction(makeShortcutAction(DIcon("copy_selection.png"), tr("&Selection"), SLOT(copySelectionSlot()), "ActionCopy"));
copyMenu->addAction(makeAction(DIcon("copy_selection.png"), tr("Selection to &File"), SLOT(copySelectionToFileSlot())));
copyMenu->addAction(makeAction(DIcon("copy_selection_no_bytes.png"), tr("Selection (&No Bytes)"), SLOT(copySelectionNoBytesSlot())));
copyMenu->addAction(makeAction(DIcon("copy_selection_no_bytes.png"), tr("Selection to File (No Bytes)"), SLOT(copySelectionToFileNoBytesSlot())));
copyMenu->addAction(makeShortcutAction(DIcon("copy_address.png"), tr("Address"), SLOT(copyCipSlot()), "ActionCopyAddress"));
copyMenu->addAction(makeShortcutAction(DIcon("copy_address.png"), tr("&RVA"), SLOT(copyRvaSlot()), "ActionCopyRva"), isDebugging);
copyMenu->addAction(makeAction(DIcon("fileoffset.png"), tr("&File Offset"), SLOT(copyFileOffsetSlot())), isDebugging);
copyMenu->addAction(makeAction(DIcon("copy_disassembly.png"), tr("Disassembly"), SLOT(copyDisassemblySlot())));
copyMenu->addAction(makeAction(DIcon("copy_address.png"), tr("Index"), SLOT(copyIndexSlot())));
mMenuBuilder->addMenu(makeMenu(DIcon("copy.png"), tr("&Copy")), copyMenu);
mMenuBuilder->addAction(makeShortcutAction(DIcon(ArchValue("processor32.png", "processor64.png")), tr("&Follow in Disassembler"), SLOT(followDisassemblySlot()), "ActionFollowDisasm"), isValid);
mBreakpointMenu = new BreakpointMenu(this, getActionHelperFuncs(), [this, isValid]()
{
if(isValid(nullptr))
return mTraceFile->Registers(getInitialSelection()).regcontext.cip;
else
return (duint)0;
});
mBreakpointMenu->build(mMenuBuilder);
mMenuBuilder->addAction(makeShortcutAction(DIcon("label.png"), tr("Label Current Address"), SLOT(setLabelSlot()), "ActionSetLabel"), isDebugging);
mMenuBuilder->addAction(makeShortcutAction(DIcon("comment.png"), tr("&Comment"), SLOT(setCommentSlot()), "ActionSetComment"), isDebugging);
mMenuBuilder->addAction(makeShortcutAction(DIcon("highlight.png"), tr("&Highlighting mode"), SLOT(enableHighlightingModeSlot()), "ActionHighlightingMode"), isValid);
MenuBuilder* gotoMenu = new MenuBuilder(this, isValid);
gotoMenu->addAction(makeShortcutAction(DIcon("goto.png"), tr("Expression"), SLOT(gotoSlot()), "ActionGotoExpression"), isValid);
gotoMenu->addAction(makeShortcutAction(DIcon("previous.png"), tr("Previous"), SLOT(gotoPreviousSlot()), "ActionGotoPrevious"), [this](QMenu*)
{
return mHistory.historyHasPrev();
});
gotoMenu->addAction(makeShortcutAction(DIcon("next.png"), tr("Next"), SLOT(gotoNextSlot()), "ActionGotoNext"), [this](QMenu*)
{
return mHistory.historyHasNext();
});
mMenuBuilder->addMenu(makeMenu(DIcon("goto.png"), tr("Go to")), gotoMenu);
MenuBuilder* searchMenu = new MenuBuilder(this, isValid);
searchMenu->addAction(makeAction(DIcon("search_for_constant.png"), tr("Constant"), SLOT(searchConstantSlot())));
searchMenu->addAction(makeAction(DIcon("memory-map.png"), tr("Memory Reference"), SLOT(searchMemRefSlot())));
mMenuBuilder->addMenu(makeMenu(DIcon("search.png"), tr("&Search")), searchMenu);
// The following code adds a menu to view the information about currently selected instruction. When info box is completed, remove me.
MenuBuilder* infoMenu = new MenuBuilder(this, [this, isValid](QMenu * menu)
{
duint MemoryAddress[MAX_MEMORY_OPERANDS];
duint MemoryOldContent[MAX_MEMORY_OPERANDS];
duint MemoryNewContent[MAX_MEMORY_OPERANDS];
bool MemoryIsValid[MAX_MEMORY_OPERANDS];
int MemoryOperandsCount;
unsigned long long index;
if(!isValid(nullptr))
return false;
index = getInitialSelection();
MemoryOperandsCount = mTraceFile->MemoryAccessCount(index);
if(MemoryOperandsCount > 0)
{
mTraceFile->MemoryAccessInfo(index, MemoryAddress, MemoryOldContent, MemoryNewContent, MemoryIsValid);
bool RvaDisplayEnabled = mRvaDisplayEnabled;
char nolabel[MAX_LABEL_SIZE];
mRvaDisplayEnabled = false;
for(int i = 0; i < MemoryOperandsCount; i++)
{
menu->addAction(QString("%1: %2 -> %3").arg(getAddrText(MemoryAddress[i], nolabel, false)).arg(ToPtrString(MemoryOldContent[i])).arg(ToPtrString(MemoryNewContent[i])));
}
mRvaDisplayEnabled = RvaDisplayEnabled;
menu->addSeparator();
}
#define addReg(str, reg) if(index + 1 < mTraceFile->Length()){menu->addAction(QString(str ":%1 -> %2").arg(ToPtrString(mTraceFile->Registers(index).regcontext.##reg)) \
.arg(ToPtrString(mTraceFile->Registers(index + 1).regcontext.##reg))); }else{ menu->addAction(QString(str ":%1").arg(ToPtrString(mTraceFile->Registers(index).regcontext.##reg))); }
addReg(ArchValue("EAX", "RAX"), cax)
addReg(ArchValue("EBX", "RBX"), cbx)
addReg(ArchValue("ECX", "RCX"), ccx)
addReg(ArchValue("EDX", "RDX"), cdx)
addReg(ArchValue("ESP", "RSP"), csp)
addReg(ArchValue("EBP", "RBP"), cbp)
addReg(ArchValue("ESI", "RSI"), csi)
addReg(ArchValue("EDI", "RDI"), cdi)
#ifdef _WIN64
addReg("R8", r8)
addReg("R9", r9)
addReg("R10", r10)
addReg("R11", r11)
addReg("R12", r12)
addReg("R13", r13)
addReg("R14", r14)
addReg("R15", r15)
#endif //_WIN64
addReg(ArchValue("EIP", "RIP"), cip)
addReg(ArchValue("EFLAGS", "RFLAGS"), eflags)
menu->addSeparator();
menu->addAction(QString("ThreadID: %1").arg(mTraceFile->ThreadId(index)));
if(index + 1 < mTraceFile->Length())
{
menu->addAction(QString("LastError: %1 -> %2").arg(ToPtrString(mTraceFile->Registers(index).lastError.code)).arg(ToPtrString(mTraceFile->Registers(index + 1).lastError.code)));
}
else
{
menu->addAction(QString("LastError: %1").arg(ToPtrString(mTraceFile->Registers(index).lastError.code)));
}
return true;
});
mMenuBuilder->addMenu(makeMenu(tr("Information")), infoMenu);
QAction* toggleAutoDisassemblyFollowSelection = makeAction(tr("Toggle Auto Disassembly Scroll (off)"), SLOT(toggleAutoDisassemblyFollowSelectionSlot()));
mMenuBuilder->addAction(toggleAutoDisassemblyFollowSelection, [this, toggleAutoDisassemblyFollowSelection](QMenu*)
{
if(!DbgIsDebugging())
return false;
if(mAutoDisassemblyFollowSelection)
toggleAutoDisassemblyFollowSelection->setText(tr("Toggle Auto Disassembly Scroll (on)"));
else
toggleAutoDisassemblyFollowSelection->setText(tr("Toggle Auto Disassembly Scroll (off)"));
return true;
});
}
void TraceBrowser::contextMenuEvent(QContextMenuEvent* event)
{
QMenu menu(this);
mMenuBuilder->build(&menu);
menu.exec(event->globalPos());
}
void TraceBrowser::mousePressEvent(QMouseEvent* event)
{
duint index = getIndexOffsetFromY(transY(event->y())) + getTableOffset();
if(getGuiState() == AbstractTableView::NoState && mTraceFile != nullptr && mTraceFile->Progress() == 100)
{
switch(event->button())
{
case Qt::LeftButton:
if(index < getRowCount())
{
if(mHighlightingMode || mPermanentHighlightingMode)
{
if(getColumnIndexFromX(event->x()) == 3) //click in instruction column
{
Instruction_t inst;
unsigned char opcode[16];
int opcodeSize;
mTraceFile->OpCode(index, opcode, &opcodeSize);
inst = mDisasm->DisassembleAt(opcode, opcodeSize, mTraceFile->Registers(index).regcontext.cip, 0);
CapstoneTokenizer::SingleToken token;
if(CapstoneTokenizer::TokenFromX(inst.tokens, token, event->x() - getColumnPosition(3), mFontMetrics))
{
if(CapstoneTokenizer::IsHighlightableToken(token))
{
if(!CapstoneTokenizer::TokenEquals(&token, &mHighlightToken) || event->button() == Qt::RightButton)
mHighlightToken = token;
else
mHighlightToken = CapstoneTokenizer::SingleToken();
}
else if(!mPermanentHighlightingMode)
{
mHighlightToken = CapstoneTokenizer::SingleToken();
}
}
else if(!mPermanentHighlightingMode)
{
mHighlightToken = CapstoneTokenizer::SingleToken();
}
}
else if(!mPermanentHighlightingMode)
{
mHighlightToken = CapstoneTokenizer::SingleToken();
}
if(mHighlightingMode) //disable highlighting mode after clicked
{
mHighlightingMode = false;
reloadData();
}
}
if(event->modifiers() & Qt::ShiftModifier)
expandSelectionUpTo(index);
else
setSingleSelection(index);
mHistory.addVaToHistory(index);
updateViewport();
if(mAutoDisassemblyFollowSelection)
followDisassemblySlot();
return;
}
break;
case Qt::MiddleButton:
copyCipSlot();
MessageBeep(MB_OK);
break;
case Qt::BackButton:
gotoPreviousSlot();
break;
case Qt::ForwardButton:
gotoNextSlot();
break;
}
}
AbstractTableView::mousePressEvent(event);
}
void TraceBrowser::mouseDoubleClickEvent(QMouseEvent* event)
{
if(event->button() == Qt::LeftButton && mTraceFile != nullptr && mTraceFile->Progress() == 100)
{
switch(getColumnIndexFromX(event->x()))
{
case 0://Index: ???
break;
case 1://Address: set RVA
if(mRvaDisplayEnabled && mTraceFile->Registers(getInitialSelection()).regcontext.cip == mRvaDisplayBase)
mRvaDisplayEnabled = false;
else
{
mRvaDisplayEnabled = true;
mRvaDisplayBase = mTraceFile->Registers(getInitialSelection()).regcontext.cip;
}
reloadData();
break;
case 2: //Opcode: Breakpoint
mBreakpointMenu->toggleInt3BPActionSlot();
break;
case 3: //Instructions: ???
break;
case 4: //Comment
setCommentSlot();
break;
}
}
AbstractTableView::mouseDoubleClickEvent(event);
}
void TraceBrowser::mouseMoveEvent(QMouseEvent* event)
{
dsint index = getIndexOffsetFromY(transY(event->y())) + getTableOffset();
if((event->buttons() & Qt::LeftButton) != 0 && getGuiState() == AbstractTableView::NoState && mTraceFile != nullptr && mTraceFile->Progress() == 100)
{
if(index < getRowCount())
{
setSingleSelection(getInitialSelection());
expandSelectionUpTo(index);
}
if(transY(event->y()) > this->height())
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
}
else if(transY(event->y()) < 0)
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
}
updateViewport();
}
AbstractTableView::mouseMoveEvent(event);
}
void TraceBrowser::keyPressEvent(QKeyEvent* event)
{
int key = event->key();
int curindex = getInitialSelection();
int visibleindex = curindex;
if((key == Qt::Key_Up || key == Qt::Key_Down) && mTraceFile && mTraceFile->Progress() == 100)
{
if(key == Qt::Key_Up)
{
if(event->modifiers() == Qt::ShiftModifier)
{
if(curindex == getSelectionStart())
{
if(getSelectionEnd() > 0)
{
visibleindex = getSelectionEnd() - 1;
expandSelectionUpTo(visibleindex);
}
}
else
{
if(getSelectionStart() > 0)
{
visibleindex = getSelectionStart() - 1;
expandSelectionUpTo(visibleindex);
}
}
}
else
{
if(curindex > 0)
{
visibleindex = curindex - 1;
setSingleSelection(visibleindex);
}
}
}
else
{
if(getSelectionEnd() + 1 < mTraceFile->Length())
{
if(event->modifiers() == Qt::ShiftModifier)
{
visibleindex = getSelectionEnd() + 1;
expandSelectionUpTo(visibleindex);
}
else
{
visibleindex = getSelectionEnd() + 1;
setSingleSelection(visibleindex);
}
}
}
makeVisible(visibleindex);
mHistory.addVaToHistory(visibleindex);
updateViewport();
if(mAutoDisassemblyFollowSelection)
followDisassemblySlot();
}
else
AbstractTableView::keyPressEvent(event);
}
void TraceBrowser::tokenizerConfigUpdatedSlot()
{
mDisasm->UpdateConfig();
mPermanentHighlightingMode = ConfigBool("Disassembler", "PermanentHighlightingMode");
}
void TraceBrowser::expandSelectionUpTo(duint to)
{
if(to < mSelection.firstSelectedIndex)
{
mSelection.fromIndex = to;
}
else if(to > mSelection.firstSelectedIndex)
{
mSelection.toIndex = to;
}
else if(to == mSelection.firstSelectedIndex)
{
setSingleSelection(to);
}
}
void TraceBrowser::setSingleSelection(duint index)
{
mSelection.firstSelectedIndex = index;
mSelection.fromIndex = index;
mSelection.toIndex = index;
}
duint TraceBrowser::getInitialSelection()
{
return mSelection.firstSelectedIndex;
}
duint TraceBrowser::getSelectionSize()
{
return mSelection.toIndex - mSelection.fromIndex + 1;
}
duint TraceBrowser::getSelectionStart()
{
return mSelection.fromIndex;
}
duint TraceBrowser::getSelectionEnd()
{
return mSelection.toIndex;
}
void TraceBrowser::makeVisible(duint index)
{
if(index < getTableOffset())
setTableOffset(index);
else if(index + 2 > getTableOffset() + getViewableRowsCount())
setTableOffset(index - getViewableRowsCount() + 2);
}
QString TraceBrowser::getIndexText(duint index)
{
QString indexString;
indexString = QString::number(index, 16).toUpper();
if(mTraceFile->Length() < 16)
return indexString;
int digits;
digits = floor(log2(mTraceFile->Length() - 1) / 4) + 1;
digits -= indexString.size();
while(digits > 0)
{
indexString = '0' + indexString;
digits = digits - 1;
}
return indexString;
}
void TraceBrowser::updateColors()
{
AbstractTableView::updateColors();
//CapstoneTokenizer::UpdateColors(); //Already called in disassembly
mDisasm->UpdateConfig();
mBackgroundColor = ConfigColor("DisassemblyBackgroundColor");
mInstructionHighlightColor = ConfigColor("InstructionHighlightColor");
mSelectionColor = ConfigColor("DisassemblySelectionColor");
mCipBackgroundColor = ConfigColor("DisassemblyCipBackgroundColor");
mCipColor = ConfigColor("DisassemblyCipColor");
mBreakpointBackgroundColor = ConfigColor("DisassemblyBreakpointBackgroundColor");
mBreakpointColor = ConfigColor("DisassemblyBreakpointColor");
mHardwareBreakpointBackgroundColor = ConfigColor("DisassemblyHardwareBreakpointBackgroundColor");
mHardwareBreakpointColor = ConfigColor("DisassemblyHardwareBreakpointColor");
mBookmarkBackgroundColor = ConfigColor("DisassemblyBookmarkBackgroundColor");
mBookmarkColor = ConfigColor("DisassemblyBookmarkColor");
mLabelColor = ConfigColor("DisassemblyLabelColor");
mLabelBackgroundColor = ConfigColor("DisassemblyLabelBackgroundColor");
mSelectedAddressBackgroundColor = ConfigColor("DisassemblySelectedAddressBackgroundColor");
mTracedAddressBackgroundColor = ConfigColor("DisassemblyTracedBackgroundColor");
mSelectedAddressColor = ConfigColor("DisassemblySelectedAddressColor");
mAddressBackgroundColor = ConfigColor("DisassemblyAddressBackgroundColor");
mAddressColor = ConfigColor("DisassemblyAddressColor");
mBytesColor = ConfigColor("DisassemblyBytesColor");
mBytesBackgroundColor = ConfigColor("DisassemblyBytesBackgroundColor");
mAutoCommentColor = ConfigColor("DisassemblyAutoCommentColor");
mAutoCommentBackgroundColor = ConfigColor("DisassemblyAutoCommentBackgroundColor");
mCommentColor = ConfigColor("DisassemblyCommentColor");
mCommentBackgroundColor = ConfigColor("DisassemblyCommentBackgroundColor");
}
void TraceBrowser::openFileSlot()
{
BrowseDialog browse(this, tr("Open run trace file"), tr("Open trace file"), tr("Run trace files (*.%1);;All files (*.*)").arg(ArchValue("trace32", "trace64")), QApplication::applicationDirPath() + QDir::separator() + "db", false);
if(browse.exec() != QDialog::Accepted)
return;
emit openSlot(browse.path);
}
void TraceBrowser::openSlot(const QString & fileName)
{
if(mTraceFile != nullptr)
{
mTraceFile->Close();
delete mTraceFile;
}
mTraceFile = new TraceFileReader(this);
connect(mTraceFile, SIGNAL(parseFinished()), this, SLOT(parseFinishedSlot()));
mFileName = fileName;
mTraceFile->Open(fileName);
}
void TraceBrowser::toggleRunTraceSlot()
{
if(!DbgIsDebugging())
return;
if(DbgValFromString("tr.runtraceenabled()") == 1)
DbgCmdExec("StopRunTrace");
else
{
QString defaultFileName;
char moduleName[MAX_MODULE_SIZE];
QDateTime currentTime = QDateTime::currentDateTime();
duint defaultModule = DbgValFromString("mod.main()");
if(DbgFunctions()->ModNameFromAddr(defaultModule, moduleName, false))
{
defaultFileName = QString::fromUtf8(moduleName);
}
defaultFileName += "-" + QLocale(QString(currentLocale)).toString(currentTime.date()) + " " + currentTime.time().toString("hh-mm-ss") + ArchValue(".trace32", ".trace64");
BrowseDialog browse(this, tr("Select stored file"), tr("Store run trace to the following file"),
tr("Run trace files (*.%1);;All files (*.*)").arg(ArchValue("trace32", "trace64")), QCoreApplication::applicationDirPath() + QDir::separator() + "db" + QDir::separator() + defaultFileName, true);
if(browse.exec() == QDialog::Accepted)
{
if(browse.path.contains(QChar('"')) || browse.path.contains(QChar('\'')))
SimpleErrorBox(this, tr("Error"), tr("File name contains invalid character."));
else
DbgCmdExec(QString("StartRunTrace \"%1\"").arg(browse.path).toUtf8().constData());
}
}
}
void TraceBrowser::closeFileSlot()
{
if(DbgValFromString("tr.runtraceenabled()") == 1)
DbgCmdExec("StopRunTrace");
mTraceFile->Close();
delete mTraceFile;
mTraceFile = nullptr;
reloadData();
}
void TraceBrowser::closeDeleteSlot()
{
QMessageBox msgbox(QMessageBox::Critical, tr("Close and delete"), tr("Are you really going to delete this file?"), QMessageBox::Yes | QMessageBox::Cancel, this);
if(msgbox.exec() == QMessageBox::Yes)
{
if(DbgValFromString("tr.runtraceenabled()") == 1)
DbgCmdExecDirect("StopRunTrace");
mTraceFile->Delete();
delete mTraceFile;
mTraceFile = nullptr;
reloadData();
}
}
void TraceBrowser::parseFinishedSlot()
{
if(mTraceFile->isError())
{
SimpleErrorBox(this, tr("Error"), "Error when opening run trace file");
delete mTraceFile;
mTraceFile = nullptr;
setRowCount(0);
}
else
{
if(mTraceFile->HashValue() && DbgIsDebugging())
if(DbgFunctions()->DbGetHash() != mTraceFile->HashValue())
{
SimpleWarningBox(this, tr("Trace file is recorded for another debuggee"),
tr("Checksum is different for current trace file and the debugee. This probably means you have opened a wrong trace file. This trace file is recorded for \"%1\"").arg(mTraceFile->ExePath()));
}
setRowCount(mTraceFile->Length());
mMRUList->addEntry(mFileName);
mMRUList->save();
}
reloadData();
}
void TraceBrowser::gotoSlot()
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
GotoDialog gotoDlg(this, false, true); // TODO: Cannot use when not debugging
if(gotoDlg.exec() == QDialog::Accepted)
{
auto val = DbgValFromString(gotoDlg.expressionText.toUtf8().constData());
if(val > 0 && val < mTraceFile->Length())
{
setSingleSelection(val);
makeVisible(val);
mHistory.addVaToHistory(val);
updateViewport();
}
}
}
void TraceBrowser::gotoNextSlot()
{
if(mHistory.historyHasNext())
{
auto index = mHistory.historyNext();
setSingleSelection(index);
makeVisible(index);
updateViewport();
}
}
void TraceBrowser::gotoPreviousSlot()
{
if(mHistory.historyHasPrev())
{
auto index = mHistory.historyPrev();
setSingleSelection(index);
makeVisible(index);
updateViewport();
}
}
void TraceBrowser::copyCipSlot()
{
QString clipboard;
for(auto i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
if(i != getSelectionStart())
clipboard += "\r\n";
clipboard += ToPtrString(mTraceFile->Registers(i).regcontext.cip);
}
Bridge::CopyToClipboard(clipboard);
}
void TraceBrowser::copyIndexSlot()
{
QString clipboard;
for(auto i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
if(i != getSelectionStart())
clipboard += "\r\n";
clipboard += getIndexText(i);
}
Bridge::CopyToClipboard(clipboard);
}
void TraceBrowser::pushSelectionInto(bool copyBytes, QTextStream & stream, QTextStream* htmlStream)
{
const int addressLen = getColumnWidth(1) / getCharWidth() - 1;
const int bytesLen = getColumnWidth(2) / getCharWidth() - 1;
const int disassemblyLen = getColumnWidth(3) / getCharWidth() - 1;
if(htmlStream)
*htmlStream << QString("<table style=\"border-width:0px;border-color:#000000;font-family:%1;font-size:%2px;\">").arg(font().family()).arg(getRowHeight());
for(unsigned long long i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
if(i != getSelectionStart())
stream << "\r\n";
duint cur_addr = mTraceFile->Registers(i).regcontext.cip;
unsigned char opcode[16];
int opcodeSize;
mTraceFile->OpCode(i, opcode, &opcodeSize);
Instruction_t inst;
inst = mDisasm->DisassembleAt(opcode, opcodeSize, cur_addr, 0);
QString address = getAddrText(cur_addr, 0, addressLen > sizeof(duint) * 2 + 1);
QString bytes;
if(copyBytes)
{
for(int j = 0; j < opcodeSize; j++)
{
if(j)
bytes += " ";
bytes += ToByteString((unsigned char)(opcode[j]));
}
}
QString disassembly;
QString htmlDisassembly;
if(htmlStream)
{
RichTextPainter::List richText;
if(mHighlightToken.text.length())
CapstoneTokenizer::TokenToRichText(inst.tokens, richText, &mHighlightToken);
else
CapstoneTokenizer::TokenToRichText(inst.tokens, richText, 0);
RichTextPainter::htmlRichText(richText, htmlDisassembly, disassembly);
}
else
{
for(const auto & token : inst.tokens.tokens)
disassembly += token.text;
}
QString fullComment;
QString comment;
bool autocomment;
if(GetCommentFormat(cur_addr, comment, &autocomment))
fullComment = " " + comment;
stream << address.leftJustified(addressLen, QChar(' '), true);
if(copyBytes)
stream << " | " + bytes.leftJustified(bytesLen, QChar(' '), true);
stream << " | " + disassembly.leftJustified(disassemblyLen, QChar(' '), true) + " |" + fullComment;
if(htmlStream)
{
*htmlStream << QString("<tr><td>%1</td><td>%2</td><td>").arg(address.toHtmlEscaped(), htmlDisassembly);
if(!comment.isEmpty())
{
if(autocomment)
{
*htmlStream << QString("<span style=\"color:%1").arg(mAutoCommentColor.name());
if(mAutoCommentBackgroundColor != Qt::transparent)
*htmlStream << QString(";background-color:%2").arg(mAutoCommentBackgroundColor.name());
}
else
{
*htmlStream << QString("<span style=\"color:%1").arg(mCommentColor.name());
if(mCommentBackgroundColor != Qt::transparent)
*htmlStream << QString(";background-color:%2").arg(mCommentBackgroundColor.name());
}
*htmlStream << "\">" << comment.toHtmlEscaped() << "</span></td></tr>";
}
else
{
char label[MAX_LABEL_SIZE];
if(DbgGetLabelAt(cur_addr, SEG_DEFAULT, label))
{
comment = QString::fromUtf8(label);
*htmlStream << QString("<span style=\"color:%1").arg(mLabelColor.name());
if(mLabelBackgroundColor != Qt::transparent)
*htmlStream << QString(";background-color:%2").arg(mLabelBackgroundColor.name());
*htmlStream << "\">" << comment.toHtmlEscaped() << "</span></td></tr>";
}
else
*htmlStream << "</td></tr>";
}
}
}
if(htmlStream)
*htmlStream << "</table>";
}
void TraceBrowser::copySelectionSlot(bool copyBytes)
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
QString selectionString = "";
QString selectionHtmlString = "";
QTextStream stream(&selectionString);
QTextStream htmlStream(&selectionHtmlString);
pushSelectionInto(copyBytes, stream, &htmlStream);
Bridge::CopyToClipboard(selectionString, selectionHtmlString);
}
void TraceBrowser::copySelectionToFileSlot(bool copyBytes)
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
QString fileName = QFileDialog::getSaveFileName(this, tr("Open File"), "", tr("Text Files (*.txt)"));
if(fileName != "")
{
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly))
{
QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
return;
}
QTextStream stream(&file);
pushSelectionInto(copyBytes, stream);
file.close();
}
}
void TraceBrowser::copySelectionSlot()
{
copySelectionSlot(true);
}
void TraceBrowser::copySelectionToFileSlot()
{
copySelectionToFileSlot(true);
}
void TraceBrowser::copySelectionNoBytesSlot()
{
copySelectionSlot(false);
}
void TraceBrowser::copySelectionToFileNoBytesSlot()
{
copySelectionToFileSlot(false);
}
void TraceBrowser::copyDisassemblySlot()
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
QString clipboardHtml = QString("<div style=\"font-family: %1; font-size: %2px\">").arg(font().family()).arg(getRowHeight());
QString clipboard = "";
for(auto i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
if(i != getSelectionStart())
{
clipboard += "\r\n";
clipboardHtml += "<br/>";
}
RichTextPainter::List richText;
unsigned char opcode[16];
int opcodeSize;
mTraceFile->OpCode(i, opcode, &opcodeSize);
Instruction_t inst = mDisasm->DisassembleAt(opcode, opcodeSize, mTraceFile->Registers(i).regcontext.cip, 0);
CapstoneTokenizer::TokenToRichText(inst.tokens, richText, 0);
RichTextPainter::htmlRichText(richText, clipboardHtml, clipboard);
}
clipboardHtml += QString("</div>");
Bridge::CopyToClipboard(clipboard, clipboardHtml);
}
void TraceBrowser::copyRvaSlot()
{
QString text;
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
for(unsigned long long i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
duint cip = mTraceFile->Registers(i).regcontext.cip;
duint base = DbgFunctions()->ModBaseFromAddr(cip);
if(base)
{
if(i != getSelectionStart())
text += "\r\n";
text += ToHexString(cip - base);
}
else
{
SimpleWarningBox(this, tr("Error!"), tr("Selection not in a module..."));
return;
}
}
Bridge::CopyToClipboard(text);
}
void TraceBrowser::copyFileOffsetSlot()
{
QString text;
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
for(unsigned long long i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
duint cip = mTraceFile->Registers(i).regcontext.cip;
cip = DbgFunctions()->VaToFileOffset(cip);
if(cip)
{
if(i != getSelectionStart())
text += "\r\n";
text += ToHexString(cip);
}
else
{
SimpleErrorBox(this, tr("Error!"), tr("Selection not in a file..."));
return;
}
}
Bridge::CopyToClipboard(text);
}
void TraceBrowser::setCommentSlot()
{
if(!DbgIsDebugging() || mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
duint wVA = mTraceFile->Registers(getInitialSelection()).regcontext.cip;
LineEditDialog mLineEdit(this);
mLineEdit.setTextMaxLength(MAX_COMMENT_SIZE - 2);
QString addr_text = ToPtrString(wVA);
char comment_text[MAX_COMMENT_SIZE] = "";
if(DbgGetCommentAt((duint)wVA, comment_text))
{
if(comment_text[0] == '\1') //automatic comment
mLineEdit.setText(QString(comment_text + 1));
else
mLineEdit.setText(QString(comment_text));
}
mLineEdit.setWindowTitle(tr("Add comment at ") + addr_text);
if(mLineEdit.exec() != QDialog::Accepted)
return;
QString comment = mLineEdit.editText.replace('\r', "").replace('\n', "");
if(!DbgSetCommentAt(wVA, comment.toUtf8().constData()))
SimpleErrorBox(this, tr("Error!"), tr("DbgSetCommentAt failed!"));
static bool easter = isEaster();
if(easter && comment.toLower() == "oep")
{
QFile file(":/icons/images/egg.wav");
if(file.open(QIODevice::ReadOnly))
{
QByteArray egg = file.readAll();
PlaySoundA(egg.data(), 0, SND_MEMORY | SND_ASYNC | SND_NODEFAULT);
}
}
GuiUpdateAllViews();
}
void TraceBrowser::setLabelSlot()
{
if(!DbgIsDebugging() || mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
duint wVA = mTraceFile->Registers(getInitialSelection()).regcontext.cip;
LineEditDialog mLineEdit(this);
mLineEdit.setTextMaxLength(MAX_LABEL_SIZE - 2);
QString addr_text = ToPtrString(wVA);
char label_text[MAX_COMMENT_SIZE] = "";
if(DbgGetLabelAt((duint)wVA, SEG_DEFAULT, label_text))
mLineEdit.setText(QString(label_text));
mLineEdit.setWindowTitle(tr("Add label at ") + addr_text);
restart:
if(mLineEdit.exec() != QDialog::Accepted)
return;
QByteArray utf8data = mLineEdit.editText.toUtf8();
if(!utf8data.isEmpty() && DbgIsValidExpression(utf8data.constData()) && DbgValFromString(utf8data.constData()) != wVA)
{
QMessageBox msg(QMessageBox::Warning, tr("The label may be in use"),
tr("The label \"%1\" may be an existing label or a valid expression. Using such label might have undesired effects. Do you still want to continue?").arg(mLineEdit.editText),
QMessageBox::Yes | QMessageBox::No, this);
msg.setWindowIcon(DIcon("compile-warning.png"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::No)
goto restart;
}
if(!DbgSetLabelAt(wVA, utf8data.constData()))
SimpleErrorBox(this, tr("Error!"), tr("DbgSetLabelAt failed!"));
GuiUpdateAllViews();
}
void TraceBrowser::enableHighlightingModeSlot()
{
if(mHighlightingMode)
mHighlightingMode = false;
else
mHighlightingMode = true;
reloadData();
}
void TraceBrowser::followDisassemblySlot()
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
duint cip = mTraceFile->Registers(getInitialSelection()).regcontext.cip;
if(DbgMemIsValidReadPtr(cip))
DbgCmdExec(QString("dis ").append(ToPtrString(cip)).toUtf8().constData());
else
GuiAddStatusBarMessage(tr("Cannot follow %1. Address is invalid.\n").arg(ToPtrString(cip)).toUtf8().constData());
}
void TraceBrowser::searchConstantSlot()
{
WordEditDialog constantDlg(this);
constantDlg.setup(tr("Constant"), 0, sizeof(duint));
if(constantDlg.exec() == QDialog::Accepted)
{
TraceFileSearchConstantRange(mTraceFile, constantDlg.getVal(), constantDlg.getVal());
emit displayReferencesWidget();
}
}
void TraceBrowser::searchMemRefSlot()
{
WordEditDialog memRefDlg(this);
memRefDlg.setup(tr("References"), 0, sizeof(duint));
if(memRefDlg.exec() == QDialog::Accepted)
{
TraceFileSearchMemReference(mTraceFile, memRefDlg.getVal());
emit displayReferencesWidget();
}
}
void TraceBrowser::updateSlot()
{
if(mTraceFile && mTraceFile->Progress() == 100) // && this->isVisible()
{
mTraceFile->purgeLastPage();
setRowCount(mTraceFile->Length());
reloadData();
}
}
void TraceBrowser::toggleAutoDisassemblyFollowSelectionSlot()
{
mAutoDisassemblyFollowSelection = !mAutoDisassemblyFollowSelection;
}
| gpl-3.0 |
eduarmreyes/fel | catalog/language/es-es/account/address.php | 1956 | <?php
// Heading
$_['heading_title'] = 'Lista de Direcciones';
// Text
$_['text_account'] = 'Cuenta';
$_['text_address_book'] = 'Lista de Direcciones';
$_['text_edit_address'] = 'Modificar Direcciones';
$_['text_add'] = 'Su dirección se ha introducido con éxito';
$_['text_edit'] = 'Su dirección ha sido actualizado con éxito';
$_['text_delete'] = 'Su dirección se ha eliminado correctamente';
$_['text_empty'] = 'No tiene direcciones en su cuenta.';
// Entry
$_['entry_firstname'] = 'Nombre';
$_['entry_lastname'] = 'Apellidos';
$_['entry_company'] = 'Compañía';
$_['entry_address_1'] = 'Dirección 1';
$_['entry_address_2'] = 'Dirección 2';
$_['entry_postcode'] = 'Código Postal';
$_['entry_city'] = 'Ciudad';
$_['entry_country'] = 'País';
$_['entry_zone'] = 'Región / Estado';
$_['entry_default'] = 'Dirección por Defecto';
// Error
$_['error_delete'] = 'Advertencia: Debe tener al menos una dirección!';
$_['error_default'] = 'Advertencia: No se puede eliminar su dirección por defecto!';
$_['error_firstname'] = 'El nombre debe tener entre 1 y 32 caracteres!';
$_['error_lastname'] = 'Apellido debe tener entre 1 y 32 caracteres!';
$_['error_vat'] = 'Número de IVA no es válido!';
$_['error_address_1'] = 'Dirección debe estar entre 3 y 128 caracteres!';
$_['error_postcode'] = 'Código Postal debe tener entre 2 y 10 caracteres!';
$_['error_city'] = 'Ciudad debe tener entre 2 y 128 caracteres!';
$_['error_country'] = 'Por favor, seleccione un país!';
$_['error_zone'] = 'Por favor, seleccione una región / estado!';
$_['error_custom_field'] = '%s se requiere!';
| gpl-3.0 |
Traderain/Wolven-kit | WolvenKit.CR2W/Types/W3/RTTIConvert/CSSPPL.cs | 890 | using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CSSPPL : CObject
{
[Ordinal(1)] [RED("inGameConfigWrapper")] public CHandle<CInGameConfigWrapper> InGameConfigWrapper { get; set;}
[Ordinal(2)] [RED("isModOn")] public CBool IsModOn { get; set;}
[Ordinal(3)] [RED("SPperLevel")] public CInt32 SPperLevel { get; set;}
public CSSPPL(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CSSPPL(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | gpl-3.0 |
yangweijun213/Ruby | RubyTest/watir-classic/TimeOut.rb | 1481 | #-------------------------------------------------------------#
# 超时和元素等待.
# install watir-classic (deprecated),不需要 browser driver
# http://www.cnblogs.com/fithon/p/6689495.html
#-------------------------------------------------------------#
require 'rubygems'
require 'watir-classic' #watir-classic已经废弃,已经整合在watir,所有两者不能同时存在
# set a variable
test_site = "http://www.baidu.com/" #search URL baidu.com
Search_name = "test" #search name
Content = "test" #search results
#ie = Watir::Browser.new
##ie = Watir::Browser.new :ie #方式2, use Watir::Browser instead
browser = Watir::IE.new #方式3 IE constant is deprecated
# open page
#browser.goto("http://www.baidu.com/")
browser.goto test_site
# Setting a text field
#browser.text_field(:name=> "wd").set("test")
# 等待test输完,再进行下一步
break while browser.text_field(:name=> "wd").set Search_name
# 设置超时,等待10秒,如果10秒未出现就超时
#browser.button(:id=> "su").wait_until_present(10)
# 设置超时,等待10秒,然后点击click。如果10秒未出现就超时
browser.button(:id=> "su").when_present(10).click
# Checking for text in a page
#if browser.text.include?("test")
if browser.text.include? Content
puts " Test Passed. Found the test string: '#{Content} '.Actual Results match Expected Results."
else
puts " Test Failed! Could not find: '#{Content} '."
end
#close ie
#browser.close | gpl-3.0 |
JhonPolitecnico/Proyectos-2014 | MIDIPlayer/src/playlist/PlayList.java | 509 | package playlist;
/**
* MIDIPlayer
*
* @author Jhon Jairo Eslava
* @code 1310012946
*
*/
import midi.MIDITableModel;
/**
* Single playlist
*
*/
public class PlayList {
private String name;
private MIDITableModel list;
public PlayList(String name, MIDITableModel list) {
super();
this.name = name;
this.list = list;
}
public String getName() {
return name;
}
public MIDITableModel getList() {
return list;
}
@Override
public String toString() {
return this.name;
}
}
| gpl-3.0 |
murilotimo/moodle | lib/horde/framework/Horde/Crypt/Blowfish/Mcrypt.php | 2334 | <?php
/**
* Copyright 2005-2008 Matthew Fonda <[email protected]>
* Copyright 2008 Philippe Jausions <[email protected]>
* Copyright 2012-2014 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @category Horde
* @copyright 2005-2008 Matthew Fonda
* @copyright 2012-2014 Horde LLC
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Crypt_Blowfish
*/
/**
* Mcrypt driver for blowfish encryption.
*
* @author Matthew Fonda <[email protected]>
* @author Philippe Jausions <[email protected]>
* @author Michael Slusarz <[email protected]>
* @category Horde
* @copyright 2005-2008 Matthew Fonda
* @copyright 2012-2014 Horde LLC
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Crypt_Blowfish
*/
class Horde_Crypt_Blowfish_Mcrypt extends Horde_Crypt_Blowfish_Base
{
/**
* Mcrypt resource.
*
* @var resource
*/
private $_mcrypt;
/**
*/
static public function supported()
{
return extension_loaded('mcrypt');
}
/**
*/
public function __construct($cipher)
{
parent::__construct($cipher);
$this->_mcrypt = mcrypt_module_open(MCRYPT_BLOWFISH, '', $cipher, '');
}
/**
*/
public function encrypt($text)
{
mcrypt_generic_init($this->_mcrypt, $this->key, empty($this->iv) ? str_repeat('0', Horde_Crypt_Blowfish::IV_LENGTH) : $this->iv);
$out = mcrypt_generic($this->_mcrypt, $this->_pad($text));
mcrypt_generic_deinit($this->_mcrypt);
return $out;
}
/**
*/
public function decrypt($text)
{
mcrypt_generic_init($this->_mcrypt, $this->key, empty($this->iv) ? str_repeat('0', Horde_Crypt_Blowfish::IV_LENGTH) : $this->iv);
$out = mdecrypt_generic($this->_mcrypt, $this->_pad($text, true));
mcrypt_generic_deinit($this->_mcrypt);
return $this->_unpad($out);
}
/**
*/
public function setIv($iv = null)
{
$this->iv = is_null($iv)
? mcrypt_create_iv(Horde_Crypt_Blowfish::IV_LENGTH, MCRYPT_RAND)
: $iv;
}
}
| gpl-3.0 |
danielrothmann/Roth-AIR | JuceLibraryCode/modules/juce_audio_formats/codecs/juce_WavAudioFormat.cpp | 86162 | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
static const char* const wavFormatName = "WAV file";
//==============================================================================
const char* const WavAudioFormat::bwavDescription = "bwav description";
const char* const WavAudioFormat::bwavOriginator = "bwav originator";
const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
const String& originator,
const String& originatorRef,
Time date,
int64 timeReferenceSamples,
const String& codingHistory)
{
StringPairArray m;
m.set (bwavDescription, description);
m.set (bwavOriginator, originator);
m.set (bwavOriginatorRef, originatorRef);
m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
m.set (bwavTimeReference, String (timeReferenceSamples));
m.set (bwavCodingHistory, codingHistory);
return m;
}
const char* const WavAudioFormat::acidOneShot = "acid one shot";
const char* const WavAudioFormat::acidRootSet = "acid root set";
const char* const WavAudioFormat::acidStretch = "acid stretch";
const char* const WavAudioFormat::acidDiskBased = "acid disk based";
const char* const WavAudioFormat::acidizerFlag = "acidizer flag";
const char* const WavAudioFormat::acidRootNote = "acid root note";
const char* const WavAudioFormat::acidBeats = "acid beats";
const char* const WavAudioFormat::acidDenominator = "acid denominator";
const char* const WavAudioFormat::acidNumerator = "acid numerator";
const char* const WavAudioFormat::acidTempo = "acid tempo";
const char* const WavAudioFormat::riffInfoArchivalLocation = "IARL";
const char* const WavAudioFormat::riffInfoArtist = "IART";
const char* const WavAudioFormat::riffInfoBaseURL = "IBSU";
const char* const WavAudioFormat::riffInfoCinematographer = "ICNM";
const char* const WavAudioFormat::riffInfoComment = "CMNT";
const char* const WavAudioFormat::riffInfoComment2 = "ICMT";
const char* const WavAudioFormat::riffInfoComments = "COMM";
const char* const WavAudioFormat::riffInfoCommissioned = "ICMS";
const char* const WavAudioFormat::riffInfoCopyright = "ICOP";
const char* const WavAudioFormat::riffInfoCostumeDesigner = "ICDS";
const char* const WavAudioFormat::riffInfoCountry = "ICNT";
const char* const WavAudioFormat::riffInfoCropped = "ICRP";
const char* const WavAudioFormat::riffInfoDateCreated = "ICRD";
const char* const WavAudioFormat::riffInfoDateTimeOriginal = "IDIT";
const char* const WavAudioFormat::riffInfoDefaultAudioStream = "ICAS";
const char* const WavAudioFormat::riffInfoDimension = "IDIM";
const char* const WavAudioFormat::riffInfoDirectory = "DIRC";
const char* const WavAudioFormat::riffInfoDistributedBy = "IDST";
const char* const WavAudioFormat::riffInfoDotsPerInch = "IDPI";
const char* const WavAudioFormat::riffInfoEditedBy = "IEDT";
const char* const WavAudioFormat::riffInfoEighthLanguage = "IAS8";
const char* const WavAudioFormat::riffInfoEncodedBy = "CODE";
const char* const WavAudioFormat::riffInfoEndTimecode = "TCDO";
const char* const WavAudioFormat::riffInfoEngineer = "IENG";
const char* const WavAudioFormat::riffInfoFifthLanguage = "IAS5";
const char* const WavAudioFormat::riffInfoFirstLanguage = "IAS1";
const char* const WavAudioFormat::riffInfoFourthLanguage = "IAS4";
const char* const WavAudioFormat::riffInfoGenre = "GENR";
const char* const WavAudioFormat::riffInfoKeywords = "IKEY";
const char* const WavAudioFormat::riffInfoLanguage = "LANG";
const char* const WavAudioFormat::riffInfoLength = "TLEN";
const char* const WavAudioFormat::riffInfoLightness = "ILGT";
const char* const WavAudioFormat::riffInfoLocation = "LOCA";
const char* const WavAudioFormat::riffInfoLogoIconURL = "ILIU";
const char* const WavAudioFormat::riffInfoLogoURL = "ILGU";
const char* const WavAudioFormat::riffInfoMedium = "IMED";
const char* const WavAudioFormat::riffInfoMoreInfoBannerImage = "IMBI";
const char* const WavAudioFormat::riffInfoMoreInfoBannerURL = "IMBU";
const char* const WavAudioFormat::riffInfoMoreInfoText = "IMIT";
const char* const WavAudioFormat::riffInfoMoreInfoURL = "IMIU";
const char* const WavAudioFormat::riffInfoMusicBy = "IMUS";
const char* const WavAudioFormat::riffInfoNinthLanguage = "IAS9";
const char* const WavAudioFormat::riffInfoNumberOfParts = "PRT2";
const char* const WavAudioFormat::riffInfoOrganisation = "TORG";
const char* const WavAudioFormat::riffInfoPart = "PRT1";
const char* const WavAudioFormat::riffInfoProducedBy = "IPRO";
const char* const WavAudioFormat::riffInfoProductName = "IPRD";
const char* const WavAudioFormat::riffInfoProductionDesigner = "IPDS";
const char* const WavAudioFormat::riffInfoProductionStudio = "ISDT";
const char* const WavAudioFormat::riffInfoRate = "RATE";
const char* const WavAudioFormat::riffInfoRated = "AGES";
const char* const WavAudioFormat::riffInfoRating = "IRTD";
const char* const WavAudioFormat::riffInfoRippedBy = "IRIP";
const char* const WavAudioFormat::riffInfoSecondaryGenre = "ISGN";
const char* const WavAudioFormat::riffInfoSecondLanguage = "IAS2";
const char* const WavAudioFormat::riffInfoSeventhLanguage = "IAS7";
const char* const WavAudioFormat::riffInfoSharpness = "ISHP";
const char* const WavAudioFormat::riffInfoSixthLanguage = "IAS6";
const char* const WavAudioFormat::riffInfoSoftware = "ISFT";
const char* const WavAudioFormat::riffInfoSoundSchemeTitle = "DISP";
const char* const WavAudioFormat::riffInfoSource = "ISRC";
const char* const WavAudioFormat::riffInfoSourceFrom = "ISRF";
const char* const WavAudioFormat::riffInfoStarring_ISTR = "ISTR";
const char* const WavAudioFormat::riffInfoStarring_STAR = "STAR";
const char* const WavAudioFormat::riffInfoStartTimecode = "TCOD";
const char* const WavAudioFormat::riffInfoStatistics = "STAT";
const char* const WavAudioFormat::riffInfoSubject = "ISBJ";
const char* const WavAudioFormat::riffInfoTapeName = "TAPE";
const char* const WavAudioFormat::riffInfoTechnician = "ITCH";
const char* const WavAudioFormat::riffInfoThirdLanguage = "IAS3";
const char* const WavAudioFormat::riffInfoTimeCode = "ISMP";
const char* const WavAudioFormat::riffInfoTitle = "INAM";
const char* const WavAudioFormat::riffInfoTrackNo = "IPRT";
const char* const WavAudioFormat::riffInfoTrackNumber = "TRCK";
const char* const WavAudioFormat::riffInfoURL = "TURL";
const char* const WavAudioFormat::riffInfoVegasVersionMajor = "VMAJ";
const char* const WavAudioFormat::riffInfoVegasVersionMinor = "VMIN";
const char* const WavAudioFormat::riffInfoVersion = "TVER";
const char* const WavAudioFormat::riffInfoWatermarkURL = "IWMU";
const char* const WavAudioFormat::riffInfoWrittenBy = "IWRI";
const char* const WavAudioFormat::riffInfoYear = "YEAR";
const char* const WavAudioFormat::ISRC = "ISRC";
const char* const WavAudioFormat::tracktionLoopInfo = "tracktion loop info";
//==============================================================================
namespace WavFileHelpers
{
constexpr inline int chunkName (const char* name) noexcept { return (int) ByteOrder::littleEndianInt (name); }
constexpr inline size_t roundUpSize (size_t sz) noexcept { return (sz + 3) & ~3u; }
#if JUCE_MSVC
#pragma pack (push, 1)
#endif
struct BWAVChunk
{
char description[256];
char originator[32];
char originatorRef[32];
char originationDate[10];
char originationTime[8];
uint32 timeRefLow;
uint32 timeRefHigh;
uint16 version;
uint8 umid[64];
uint8 reserved[190];
char codingHistory[1];
void copyTo (StringPairArray& values, const int totalSize) const
{
values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, sizeof (description)));
values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, sizeof (originator)));
values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, sizeof (originatorRef)));
values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, sizeof (originationDate)));
values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, sizeof (originationTime)));
auto timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
auto timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
auto time = (((int64) timeHigh) << 32) + timeLow;
values.set (WavAudioFormat::bwavTimeReference, String (time));
values.set (WavAudioFormat::bwavCodingHistory,
String::fromUTF8 (codingHistory, totalSize - (int) offsetof (BWAVChunk, codingHistory)));
}
static MemoryBlock createFrom (const StringPairArray& values)
{
MemoryBlock data (roundUpSize (sizeof (BWAVChunk) + values[WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8()));
data.fillWith (0);
auto* b = (BWAVChunk*) data.getData();
// Allow these calls to overwrite an extra byte at the end, which is fine as long
// as they get called in the right order..
values[WavAudioFormat::bwavDescription] .copyToUTF8 (b->description, 257);
values[WavAudioFormat::bwavOriginator] .copyToUTF8 (b->originator, 33);
values[WavAudioFormat::bwavOriginatorRef] .copyToUTF8 (b->originatorRef, 33);
values[WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
values[WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
auto time = values[WavAudioFormat::bwavTimeReference].getLargeIntValue();
b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
values[WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
if (b->description[0] != 0
|| b->originator[0] != 0
|| b->originationDate[0] != 0
|| b->originationTime[0] != 0
|| b->codingHistory[0] != 0
|| time != 0)
{
return data;
}
return {};
}
} JUCE_PACKED;
//==============================================================================
inline AudioChannelSet canonicalWavChannelSet (int numChannels)
{
if (numChannels == 1) return AudioChannelSet::mono();
if (numChannels == 2) return AudioChannelSet::stereo();
if (numChannels == 3) return AudioChannelSet::createLCR();
if (numChannels == 4) return AudioChannelSet::quadraphonic();
if (numChannels == 5) return AudioChannelSet::create5point0();
if (numChannels == 6) return AudioChannelSet::create5point1();
if (numChannels == 7) return AudioChannelSet::create7point0SDDS();
if (numChannels == 8) return AudioChannelSet::create7point1SDDS();
return AudioChannelSet::discreteChannels (numChannels);
}
//==============================================================================
struct SMPLChunk
{
struct SampleLoop
{
uint32 identifier;
uint32 type; // these are different in AIFF and WAV
uint32 start;
uint32 end;
uint32 fraction;
uint32 playCount;
} JUCE_PACKED;
uint32 manufacturer;
uint32 product;
uint32 samplePeriod;
uint32 midiUnityNote;
uint32 midiPitchFraction;
uint32 smpteFormat;
uint32 smpteOffset;
uint32 numSampleLoops;
uint32 samplerData;
SampleLoop loops[1];
template <typename NameType>
static void setValue (StringPairArray& values, NameType name, uint32 val)
{
values.set (name, String (ByteOrder::swapIfBigEndian (val)));
}
static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val)
{
setValue (values, "Loop" + String (prefix) + name, val);
}
void copyTo (StringPairArray& values, const int totalSize) const
{
setValue (values, "Manufacturer", manufacturer);
setValue (values, "Product", product);
setValue (values, "SamplePeriod", samplePeriod);
setValue (values, "MidiUnityNote", midiUnityNote);
setValue (values, "MidiPitchFraction", midiPitchFraction);
setValue (values, "SmpteFormat", smpteFormat);
setValue (values, "SmpteOffset", smpteOffset);
setValue (values, "NumSampleLoops", numSampleLoops);
setValue (values, "SamplerData", samplerData);
for (int i = 0; i < (int) numSampleLoops; ++i)
{
if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
break;
setValue (values, i, "Identifier", loops[i].identifier);
setValue (values, i, "Type", loops[i].type);
setValue (values, i, "Start", loops[i].start);
setValue (values, i, "End", loops[i].end);
setValue (values, i, "Fraction", loops[i].fraction);
setValue (values, i, "PlayCount", loops[i].playCount);
}
}
template <typename NameType>
static uint32 getValue (const StringPairArray& values, NameType name, const char* def)
{
return ByteOrder::swapIfBigEndian ((uint32) values.getValue (name, def).getIntValue());
}
static uint32 getValue (const StringPairArray& values, int prefix, const char* name, const char* def)
{
return getValue (values, "Loop" + String (prefix) + name, def);
}
static MemoryBlock createFrom (const StringPairArray& values)
{
MemoryBlock data;
auto numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
data.setSize (roundUpSize (sizeof (SMPLChunk) + (size_t) (jmax (0, numLoops - 1)) * sizeof (SampleLoop)), true);
auto s = static_cast<SMPLChunk*> (data.getData());
s->manufacturer = getValue (values, "Manufacturer", "0");
s->product = getValue (values, "Product", "0");
s->samplePeriod = getValue (values, "SamplePeriod", "0");
s->midiUnityNote = getValue (values, "MidiUnityNote", "60");
s->midiPitchFraction = getValue (values, "MidiPitchFraction", "0");
s->smpteFormat = getValue (values, "SmpteFormat", "0");
s->smpteOffset = getValue (values, "SmpteOffset", "0");
s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
s->samplerData = getValue (values, "SamplerData", "0");
for (int i = 0; i < numLoops; ++i)
{
auto& loop = s->loops[i];
loop.identifier = getValue (values, i, "Identifier", "0");
loop.type = getValue (values, i, "Type", "0");
loop.start = getValue (values, i, "Start", "0");
loop.end = getValue (values, i, "End", "0");
loop.fraction = getValue (values, i, "Fraction", "0");
loop.playCount = getValue (values, i, "PlayCount", "0");
}
return data;
}
} JUCE_PACKED;
//==============================================================================
struct InstChunk
{
int8 baseNote;
int8 detune;
int8 gain;
int8 lowNote;
int8 highNote;
int8 lowVelocity;
int8 highVelocity;
static void setValue (StringPairArray& values, const char* name, int val)
{
values.set (name, String (val));
}
void copyTo (StringPairArray& values) const
{
setValue (values, "MidiUnityNote", baseNote);
setValue (values, "Detune", detune);
setValue (values, "Gain", gain);
setValue (values, "LowNote", lowNote);
setValue (values, "HighNote", highNote);
setValue (values, "LowVelocity", lowVelocity);
setValue (values, "HighVelocity", highVelocity);
}
static int8 getValue (const StringPairArray& values, const char* name, const char* def)
{
return (int8) values.getValue (name, def).getIntValue();
}
static MemoryBlock createFrom (const StringPairArray& values)
{
MemoryBlock data;
auto& keys = values.getAllKeys();
if (keys.contains ("LowNote", true) && keys.contains ("HighNote", true))
{
data.setSize (8, true);
auto* inst = static_cast<InstChunk*> (data.getData());
inst->baseNote = getValue (values, "MidiUnityNote", "60");
inst->detune = getValue (values, "Detune", "0");
inst->gain = getValue (values, "Gain", "0");
inst->lowNote = getValue (values, "LowNote", "0");
inst->highNote = getValue (values, "HighNote", "127");
inst->lowVelocity = getValue (values, "LowVelocity", "1");
inst->highVelocity = getValue (values, "HighVelocity", "127");
}
return data;
}
} JUCE_PACKED;
//==============================================================================
struct CueChunk
{
struct Cue
{
uint32 identifier;
uint32 order;
uint32 chunkID;
uint32 chunkStart;
uint32 blockStart;
uint32 offset;
} JUCE_PACKED;
uint32 numCues;
Cue cues[1];
static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val)
{
values.set ("Cue" + String (prefix) + name, String (ByteOrder::swapIfBigEndian (val)));
}
void copyTo (StringPairArray& values, const int totalSize) const
{
values.set ("NumCuePoints", String (ByteOrder::swapIfBigEndian (numCues)));
for (int i = 0; i < (int) numCues; ++i)
{
if ((uint8*) (cues + (i + 1)) > ((uint8*) this) + totalSize)
break;
setValue (values, i, "Identifier", cues[i].identifier);
setValue (values, i, "Order", cues[i].order);
setValue (values, i, "ChunkID", cues[i].chunkID);
setValue (values, i, "ChunkStart", cues[i].chunkStart);
setValue (values, i, "BlockStart", cues[i].blockStart);
setValue (values, i, "Offset", cues[i].offset);
}
}
static MemoryBlock createFrom (const StringPairArray& values)
{
MemoryBlock data;
const int numCues = values.getValue ("NumCuePoints", "0").getIntValue();
if (numCues > 0)
{
data.setSize (roundUpSize (sizeof (CueChunk) + (size_t) (numCues - 1) * sizeof (Cue)), true);
auto c = static_cast<CueChunk*> (data.getData());
c->numCues = ByteOrder::swapIfBigEndian ((uint32) numCues);
const String dataChunkID (chunkName ("data"));
int nextOrder = 0;
#if JUCE_DEBUG
Array<uint32> identifiers;
#endif
for (int i = 0; i < numCues; ++i)
{
auto prefix = "Cue" + String (i);
auto identifier = (uint32) values.getValue (prefix + "Identifier", "0").getIntValue();
#if JUCE_DEBUG
jassert (! identifiers.contains (identifier));
identifiers.add (identifier);
#endif
auto order = values.getValue (prefix + "Order", String (nextOrder)).getIntValue();
nextOrder = jmax (nextOrder, order) + 1;
auto& cue = c->cues[i];
cue.identifier = ByteOrder::swapIfBigEndian ((uint32) identifier);
cue.order = ByteOrder::swapIfBigEndian ((uint32) order);
cue.chunkID = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkID", dataChunkID).getIntValue());
cue.chunkStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkStart", "0").getIntValue());
cue.blockStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "BlockStart", "0").getIntValue());
cue.offset = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Offset", "0").getIntValue());
}
}
return data;
}
} JUCE_PACKED;
//==============================================================================
namespace ListChunk
{
static int getValue (const StringPairArray& values, const String& name)
{
return values.getValue (name, "0").getIntValue();
}
static int getValue (const StringPairArray& values, const String& prefix, const char* name)
{
return getValue (values, prefix + name);
}
static void appendLabelOrNoteChunk (const StringPairArray& values, const String& prefix,
const int chunkType, MemoryOutputStream& out)
{
auto label = values.getValue (prefix + "Text", prefix);
auto labelLength = (int) label.getNumBytesAsUTF8() + 1;
auto chunkLength = 4 + labelLength + (labelLength & 1);
out.writeInt (chunkType);
out.writeInt (chunkLength);
out.writeInt (getValue (values, prefix, "Identifier"));
out.write (label.toUTF8(), (size_t) labelLength);
if ((out.getDataSize() & 1) != 0)
out.writeByte (0);
}
static void appendExtraChunk (const StringPairArray& values, const String& prefix, MemoryOutputStream& out)
{
auto text = values.getValue (prefix + "Text", prefix);
auto textLength = (int) text.getNumBytesAsUTF8() + 1; // include null terminator
auto chunkLength = textLength + 20 + (textLength & 1);
out.writeInt (chunkName ("ltxt"));
out.writeInt (chunkLength);
out.writeInt (getValue (values, prefix, "Identifier"));
out.writeInt (getValue (values, prefix, "SampleLength"));
out.writeInt (getValue (values, prefix, "Purpose"));
out.writeShort ((short) getValue (values, prefix, "Country"));
out.writeShort ((short) getValue (values, prefix, "Language"));
out.writeShort ((short) getValue (values, prefix, "Dialect"));
out.writeShort ((short) getValue (values, prefix, "CodePage"));
out.write (text.toUTF8(), (size_t) textLength);
if ((out.getDataSize() & 1) != 0)
out.writeByte (0);
}
static MemoryBlock createFrom (const StringPairArray& values)
{
auto numCueLabels = getValue (values, "NumCueLabels");
auto numCueNotes = getValue (values, "NumCueNotes");
auto numCueRegions = getValue (values, "NumCueRegions");
MemoryOutputStream out;
if (numCueLabels + numCueNotes + numCueRegions > 0)
{
out.writeInt (chunkName ("adtl"));
for (int i = 0; i < numCueLabels; ++i)
appendLabelOrNoteChunk (values, "CueLabel" + String (i), chunkName ("labl"), out);
for (int i = 0; i < numCueNotes; ++i)
appendLabelOrNoteChunk (values, "CueNote" + String (i), chunkName ("note"), out);
for (int i = 0; i < numCueRegions; ++i)
appendExtraChunk (values, "CueRegion" + String (i), out);
}
return out.getMemoryBlock();
}
}
//==============================================================================
/** Reads a RIFF List Info chunk from a stream positioned just after the size byte. */
namespace ListInfoChunk
{
static const char* const types[] =
{
WavAudioFormat::riffInfoArchivalLocation,
WavAudioFormat::riffInfoArtist,
WavAudioFormat::riffInfoBaseURL,
WavAudioFormat::riffInfoCinematographer,
WavAudioFormat::riffInfoComment,
WavAudioFormat::riffInfoComments,
WavAudioFormat::riffInfoComment2,
WavAudioFormat::riffInfoCommissioned,
WavAudioFormat::riffInfoCopyright,
WavAudioFormat::riffInfoCostumeDesigner,
WavAudioFormat::riffInfoCountry,
WavAudioFormat::riffInfoCropped,
WavAudioFormat::riffInfoDateCreated,
WavAudioFormat::riffInfoDateTimeOriginal,
WavAudioFormat::riffInfoDefaultAudioStream,
WavAudioFormat::riffInfoDimension,
WavAudioFormat::riffInfoDirectory,
WavAudioFormat::riffInfoDistributedBy,
WavAudioFormat::riffInfoDotsPerInch,
WavAudioFormat::riffInfoEditedBy,
WavAudioFormat::riffInfoEighthLanguage,
WavAudioFormat::riffInfoEncodedBy,
WavAudioFormat::riffInfoEndTimecode,
WavAudioFormat::riffInfoEngineer,
WavAudioFormat::riffInfoFifthLanguage,
WavAudioFormat::riffInfoFirstLanguage,
WavAudioFormat::riffInfoFourthLanguage,
WavAudioFormat::riffInfoGenre,
WavAudioFormat::riffInfoKeywords,
WavAudioFormat::riffInfoLanguage,
WavAudioFormat::riffInfoLength,
WavAudioFormat::riffInfoLightness,
WavAudioFormat::riffInfoLocation,
WavAudioFormat::riffInfoLogoIconURL,
WavAudioFormat::riffInfoLogoURL,
WavAudioFormat::riffInfoMedium,
WavAudioFormat::riffInfoMoreInfoBannerImage,
WavAudioFormat::riffInfoMoreInfoBannerURL,
WavAudioFormat::riffInfoMoreInfoText,
WavAudioFormat::riffInfoMoreInfoURL,
WavAudioFormat::riffInfoMusicBy,
WavAudioFormat::riffInfoNinthLanguage,
WavAudioFormat::riffInfoNumberOfParts,
WavAudioFormat::riffInfoOrganisation,
WavAudioFormat::riffInfoPart,
WavAudioFormat::riffInfoProducedBy,
WavAudioFormat::riffInfoProductName,
WavAudioFormat::riffInfoProductionDesigner,
WavAudioFormat::riffInfoProductionStudio,
WavAudioFormat::riffInfoRate,
WavAudioFormat::riffInfoRated,
WavAudioFormat::riffInfoRating,
WavAudioFormat::riffInfoRippedBy,
WavAudioFormat::riffInfoSecondaryGenre,
WavAudioFormat::riffInfoSecondLanguage,
WavAudioFormat::riffInfoSeventhLanguage,
WavAudioFormat::riffInfoSharpness,
WavAudioFormat::riffInfoSixthLanguage,
WavAudioFormat::riffInfoSoftware,
WavAudioFormat::riffInfoSoundSchemeTitle,
WavAudioFormat::riffInfoSource,
WavAudioFormat::riffInfoSourceFrom,
WavAudioFormat::riffInfoStarring_ISTR,
WavAudioFormat::riffInfoStarring_STAR,
WavAudioFormat::riffInfoStartTimecode,
WavAudioFormat::riffInfoStatistics,
WavAudioFormat::riffInfoSubject,
WavAudioFormat::riffInfoTapeName,
WavAudioFormat::riffInfoTechnician,
WavAudioFormat::riffInfoThirdLanguage,
WavAudioFormat::riffInfoTimeCode,
WavAudioFormat::riffInfoTitle,
WavAudioFormat::riffInfoTrackNo,
WavAudioFormat::riffInfoTrackNumber,
WavAudioFormat::riffInfoURL,
WavAudioFormat::riffInfoVegasVersionMajor,
WavAudioFormat::riffInfoVegasVersionMinor,
WavAudioFormat::riffInfoVersion,
WavAudioFormat::riffInfoWatermarkURL,
WavAudioFormat::riffInfoWrittenBy,
WavAudioFormat::riffInfoYear
};
static bool isMatchingTypeIgnoringCase (const int value, const char* const name) noexcept
{
for (int i = 0; i < 4; ++i)
if ((juce_wchar) name[i] != CharacterFunctions::toUpperCase ((juce_wchar) ((value >> (i * 8)) & 0xff)))
return false;
return true;
}
static void addToMetadata (StringPairArray& values, InputStream& input, int64 chunkEnd)
{
while (input.getPosition() < chunkEnd)
{
auto infoType = input.readInt();
auto infoLength = chunkEnd - input.getPosition();
if (infoLength > 0)
{
infoLength = jmin (infoLength, (int64) input.readInt());
if (infoLength <= 0)
return;
for (auto& type : types)
{
if (isMatchingTypeIgnoringCase (infoType, type))
{
MemoryBlock mb;
input.readIntoMemoryBlock (mb, (ssize_t) infoLength);
values.set (type, String::createStringFromData ((const char*) mb.getData(),
(int) mb.getSize()));
break;
}
}
}
}
}
static bool writeValue (const StringPairArray& values, MemoryOutputStream& out, const char* paramName)
{
auto value = values.getValue (paramName, {});
if (value.isEmpty())
return false;
auto valueLength = (int) value.getNumBytesAsUTF8() + 1;
auto chunkLength = valueLength + (valueLength & 1);
out.writeInt (chunkName (paramName));
out.writeInt (chunkLength);
out.write (value.toUTF8(), (size_t) valueLength);
if ((out.getDataSize() & 1) != 0)
out.writeByte (0);
return true;
}
static MemoryBlock createFrom (const StringPairArray& values)
{
MemoryOutputStream out;
out.writeInt (chunkName ("INFO"));
bool anyParamsDefined = false;
for (auto& type : types)
if (writeValue (values, out, type))
anyParamsDefined = true;
return anyParamsDefined ? out.getMemoryBlock() : MemoryBlock();
}
}
//==============================================================================
struct AcidChunk
{
/** Reads an acid RIFF chunk from a stream positioned just after the size byte. */
AcidChunk (InputStream& input, size_t length)
{
zerostruct (*this);
input.read (this, (int) jmin (sizeof (*this), length));
}
AcidChunk (const StringPairArray& values)
{
zerostruct (*this);
flags = getFlagIfPresent (values, WavAudioFormat::acidOneShot, 0x01)
| getFlagIfPresent (values, WavAudioFormat::acidRootSet, 0x02)
| getFlagIfPresent (values, WavAudioFormat::acidStretch, 0x04)
| getFlagIfPresent (values, WavAudioFormat::acidDiskBased, 0x08)
| getFlagIfPresent (values, WavAudioFormat::acidizerFlag, 0x10);
if (values[WavAudioFormat::acidRootSet].getIntValue() != 0)
rootNote = ByteOrder::swapIfBigEndian ((uint16) values[WavAudioFormat::acidRootNote].getIntValue());
numBeats = ByteOrder::swapIfBigEndian ((uint32) values[WavAudioFormat::acidBeats].getIntValue());
meterDenominator = ByteOrder::swapIfBigEndian ((uint16) values[WavAudioFormat::acidDenominator].getIntValue());
meterNumerator = ByteOrder::swapIfBigEndian ((uint16) values[WavAudioFormat::acidNumerator].getIntValue());
if (values.containsKey (WavAudioFormat::acidTempo))
tempo = swapFloatByteOrder (values[WavAudioFormat::acidTempo].getFloatValue());
}
static MemoryBlock createFrom (const StringPairArray& values)
{
return AcidChunk (values).toMemoryBlock();
}
MemoryBlock toMemoryBlock() const
{
return (flags != 0 || rootNote != 0 || numBeats != 0 || meterDenominator != 0 || meterNumerator != 0)
? MemoryBlock (this, sizeof (*this)) : MemoryBlock();
}
void addToMetadata (StringPairArray& values) const
{
setBoolFlag (values, WavAudioFormat::acidOneShot, 0x01);
setBoolFlag (values, WavAudioFormat::acidRootSet, 0x02);
setBoolFlag (values, WavAudioFormat::acidStretch, 0x04);
setBoolFlag (values, WavAudioFormat::acidDiskBased, 0x08);
setBoolFlag (values, WavAudioFormat::acidizerFlag, 0x10);
if (flags & 0x02) // root note set
values.set (WavAudioFormat::acidRootNote, String (ByteOrder::swapIfBigEndian (rootNote)));
values.set (WavAudioFormat::acidBeats, String (ByteOrder::swapIfBigEndian (numBeats)));
values.set (WavAudioFormat::acidDenominator, String (ByteOrder::swapIfBigEndian (meterDenominator)));
values.set (WavAudioFormat::acidNumerator, String (ByteOrder::swapIfBigEndian (meterNumerator)));
values.set (WavAudioFormat::acidTempo, String (swapFloatByteOrder (tempo)));
}
void setBoolFlag (StringPairArray& values, const char* name, uint32 mask) const
{
values.set (name, (flags & ByteOrder::swapIfBigEndian (mask)) ? "1" : "0");
}
static uint32 getFlagIfPresent (const StringPairArray& values, const char* name, uint32 flag)
{
return values[name].getIntValue() != 0 ? ByteOrder::swapIfBigEndian (flag) : 0;
}
static float swapFloatByteOrder (const float x) noexcept
{
#ifdef JUCE_BIG_ENDIAN
union { uint32 asInt; float asFloat; } n;
n.asFloat = x;
n.asInt = ByteOrder::swap (n.asInt);
return n.asFloat;
#else
return x;
#endif
}
uint32 flags;
uint16 rootNote;
uint16 reserved1;
float reserved2;
uint32 numBeats;
uint16 meterDenominator;
uint16 meterNumerator;
float tempo;
} JUCE_PACKED;
//==============================================================================
struct TracktionChunk
{
static MemoryBlock createFrom (const StringPairArray& values)
{
MemoryOutputStream out;
auto s = values[WavAudioFormat::tracktionLoopInfo];
if (s.isNotEmpty())
{
out.writeString (s);
if ((out.getDataSize() & 1) != 0)
out.writeByte (0);
}
return out.getMemoryBlock();
}
};
//==============================================================================
namespace AXMLChunk
{
static void addToMetadata (StringPairArray& destValues, const String& source)
{
if (auto xml = parseXML (source))
{
if (xml->hasTagName ("ebucore:ebuCoreMain"))
{
if (auto xml2 = xml->getChildByName ("ebucore:coreMetadata"))
{
if (auto xml3 = xml2->getChildByName ("ebucore:identifier"))
{
if (auto xml4 = xml3->getChildByName ("dc:identifier"))
{
auto ISRCCode = xml4->getAllSubText().fromFirstOccurrenceOf ("ISRC:", false, true);
if (ISRCCode.isNotEmpty())
destValues.set (WavAudioFormat::ISRC, ISRCCode);
}
}
}
}
}
}
static MemoryBlock createFrom (const StringPairArray& values)
{
auto ISRC = values.getValue (WavAudioFormat::ISRC, {});
MemoryOutputStream xml;
if (ISRC.isNotEmpty())
{
xml << "<ebucore:ebuCoreMain xmlns:dc=\" http://purl.org/dc/elements/1.1/\" "
"xmlns:ebucore=\"urn:ebu:metadata-schema:ebuCore_2012\">"
"<ebucore:coreMetadata>"
"<ebucore:identifier typeLabel=\"GUID\" "
"typeDefinition=\"Globally Unique Identifier\" "
"formatLabel=\"ISRC\" "
"formatDefinition=\"International Standard Recording Code\" "
"formatLink=\"http://www.ebu.ch/metadata/cs/ebu_IdentifierTypeCodeCS.xml#3.7\">"
"<dc:identifier>ISRC:" << ISRC << "</dc:identifier>"
"</ebucore:identifier>"
"</ebucore:coreMetadata>"
"</ebucore:ebuCoreMain>";
xml.writeRepeatedByte (0, xml.getDataSize()); // ensures even size, null termination and room for future growing
}
return xml.getMemoryBlock();
}
}
//==============================================================================
struct ExtensibleWavSubFormat
{
uint32 data1;
uint16 data2;
uint16 data3;
uint8 data4[8];
bool operator== (const ExtensibleWavSubFormat& other) const noexcept { return memcmp (this, &other, sizeof (*this)) == 0; }
bool operator!= (const ExtensibleWavSubFormat& other) const noexcept { return ! operator== (other); }
} JUCE_PACKED;
static const ExtensibleWavSubFormat pcmFormat = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
static const ExtensibleWavSubFormat IEEEFloatFormat = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
static const ExtensibleWavSubFormat ambisonicFormat = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
{
uint32 riffSizeLow; // low 4 byte size of RF64 block
uint32 riffSizeHigh; // high 4 byte size of RF64 block
uint32 dataSizeLow; // low 4 byte size of data chunk
uint32 dataSizeHigh; // high 4 byte size of data chunk
uint32 sampleCountLow; // low 4 byte sample count of fact chunk
uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
uint32 tableLength; // number of valid entries in array 'table'
} JUCE_PACKED;
#if JUCE_MSVC
#pragma pack (pop)
#endif
}
//==============================================================================
class WavAudioFormatReader : public AudioFormatReader
{
public:
WavAudioFormatReader (InputStream* in) : AudioFormatReader (in, wavFormatName)
{
using namespace WavFileHelpers;
uint64 len = 0, end = 0;
int cueNoteIndex = 0;
int cueLabelIndex = 0;
int cueRegionIndex = 0;
auto streamStartPos = input->getPosition();
auto firstChunkType = input->readInt();
if (firstChunkType == chunkName ("RF64"))
{
input->skipNextBytes (4); // size is -1 for RF64
isRF64 = true;
}
else if (firstChunkType == chunkName ("RIFF"))
{
len = (uint64) (uint32) input->readInt();
end = len + (uint64) input->getPosition();
}
else
{
return;
}
auto startOfRIFFChunk = input->getPosition();
if (input->readInt() == chunkName ("WAVE"))
{
if (isRF64 && input->readInt() == chunkName ("ds64"))
{
auto length = (uint32) input->readInt();
if (length < 28)
return;
auto chunkEnd = input->getPosition() + length + (length & 1);
len = (uint64) input->readInt64();
end = len + (uint64) startOfRIFFChunk;
dataLength = input->readInt64();
input->setPosition (chunkEnd);
}
while ((uint64) input->getPosition() < end && ! input->isExhausted())
{
auto chunkType = input->readInt();
auto length = (uint32) input->readInt();
auto chunkEnd = input->getPosition() + length + (length & 1);
if (chunkType == chunkName ("fmt "))
{
// read the format chunk
auto format = (unsigned short) input->readShort();
numChannels = (unsigned int) input->readShort();
sampleRate = input->readInt();
auto bytesPerSec = input->readInt();
input->skipNextBytes (2);
bitsPerSample = (unsigned int) (int) input->readShort();
if (bitsPerSample > 64)
{
bytesPerFrame = bytesPerSec / (int) sampleRate;
bitsPerSample = 8 * (unsigned int) bytesPerFrame / numChannels;
}
else
{
bytesPerFrame = (int) (numChannels * bitsPerSample / 8);
}
if (format == 3)
{
usesFloatingPointData = true;
}
else if (format == 0xfffe) // WAVE_FORMAT_EXTENSIBLE
{
if (length < 40) // too short
{
bytesPerFrame = 0;
}
else
{
input->skipNextBytes (4); // skip over size and bitsPerSample
auto channelMask = input->readInt();
metadataValues.set ("ChannelMask", String (channelMask));
channelLayout = getChannelLayoutFromMask (channelMask, numChannels);
ExtensibleWavSubFormat subFormat;
subFormat.data1 = (uint32) input->readInt();
subFormat.data2 = (uint16) input->readShort();
subFormat.data3 = (uint16) input->readShort();
input->read (subFormat.data4, sizeof (subFormat.data4));
if (subFormat == IEEEFloatFormat)
usesFloatingPointData = true;
else if (subFormat != pcmFormat && subFormat != ambisonicFormat)
bytesPerFrame = 0;
}
}
else if (format == 0x674f // WAVE_FORMAT_OGG_VORBIS_MODE_1
|| format == 0x6750 // WAVE_FORMAT_OGG_VORBIS_MODE_2
|| format == 0x6751 // WAVE_FORMAT_OGG_VORBIS_MODE_3
|| format == 0x676f // WAVE_FORMAT_OGG_VORBIS_MODE_1_PLUS
|| format == 0x6770 // WAVE_FORMAT_OGG_VORBIS_MODE_2_PLUS
|| format == 0x6771) // WAVE_FORMAT_OGG_VORBIS_MODE_3_PLUS
{
isSubformatOggVorbis = true;
sampleRate = 0; // to mark the wav reader as failed
input->setPosition (streamStartPos);
return;
}
else if (format != 1)
{
bytesPerFrame = 0;
}
}
else if (chunkType == chunkName ("data"))
{
if (isRF64)
{
if (dataLength > 0)
chunkEnd = input->getPosition() + dataLength + (dataLength & 1);
}
else
{
dataLength = length;
}
dataChunkStart = input->getPosition();
lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
}
else if (chunkType == chunkName ("bext"))
{
bwavChunkStart = input->getPosition();
bwavSize = length;
HeapBlock<BWAVChunk> bwav;
bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
input->read (bwav, (int) length);
bwav->copyTo (metadataValues, (int) length);
}
else if (chunkType == chunkName ("smpl"))
{
HeapBlock<SMPLChunk> smpl;
smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
input->read (smpl, (int) length);
smpl->copyTo (metadataValues, (int) length);
}
else if (chunkType == chunkName ("inst") || chunkType == chunkName ("INST")) // need to check which...
{
HeapBlock<InstChunk> inst;
inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1);
input->read (inst, (int) length);
inst->copyTo (metadataValues);
}
else if (chunkType == chunkName ("cue "))
{
HeapBlock<CueChunk> cue;
cue.calloc (jmax ((size_t) length + 1, sizeof (CueChunk)), 1);
input->read (cue, (int) length);
cue->copyTo (metadataValues, (int) length);
}
else if (chunkType == chunkName ("axml"))
{
MemoryBlock axml;
input->readIntoMemoryBlock (axml, (ssize_t) length);
AXMLChunk::addToMetadata (metadataValues, axml.toString());
}
else if (chunkType == chunkName ("LIST"))
{
auto subChunkType = input->readInt();
if (subChunkType == chunkName ("info") || subChunkType == chunkName ("INFO"))
{
ListInfoChunk::addToMetadata (metadataValues, *input, chunkEnd);
}
else if (subChunkType == chunkName ("adtl"))
{
while (input->getPosition() < chunkEnd)
{
auto adtlChunkType = input->readInt();
auto adtlLength = (uint32) input->readInt();
auto adtlChunkEnd = input->getPosition() + (adtlLength + (adtlLength & 1));
if (adtlChunkType == chunkName ("labl") || adtlChunkType == chunkName ("note"))
{
String prefix;
if (adtlChunkType == chunkName ("labl"))
prefix << "CueLabel" << cueLabelIndex++;
else if (adtlChunkType == chunkName ("note"))
prefix << "CueNote" << cueNoteIndex++;
auto identifier = (uint32) input->readInt();
auto stringLength = (int) adtlLength - 4;
MemoryBlock textBlock;
input->readIntoMemoryBlock (textBlock, stringLength);
metadataValues.set (prefix + "Identifier", String (identifier));
metadataValues.set (prefix + "Text", textBlock.toString());
}
else if (adtlChunkType == chunkName ("ltxt"))
{
auto prefix = "CueRegion" + String (cueRegionIndex++);
auto identifier = (uint32) input->readInt();
auto sampleLength = (uint32) input->readInt();
auto purpose = (uint32) input->readInt();
auto country = (uint16) input->readShort();
auto language = (uint16) input->readShort();
auto dialect = (uint16) input->readShort();
auto codePage = (uint16) input->readShort();
auto stringLength = adtlLength - 20;
MemoryBlock textBlock;
input->readIntoMemoryBlock (textBlock, (int) stringLength);
metadataValues.set (prefix + "Identifier", String (identifier));
metadataValues.set (prefix + "SampleLength", String (sampleLength));
metadataValues.set (prefix + "Purpose", String (purpose));
metadataValues.set (prefix + "Country", String (country));
metadataValues.set (prefix + "Language", String (language));
metadataValues.set (prefix + "Dialect", String (dialect));
metadataValues.set (prefix + "CodePage", String (codePage));
metadataValues.set (prefix + "Text", textBlock.toString());
}
input->setPosition (adtlChunkEnd);
}
}
}
else if (chunkType == chunkName ("acid"))
{
AcidChunk (*input, length).addToMetadata (metadataValues);
}
else if (chunkType == chunkName ("Trkn"))
{
MemoryBlock tracktion;
input->readIntoMemoryBlock (tracktion, (ssize_t) length);
metadataValues.set (WavAudioFormat::tracktionLoopInfo, tracktion.toString());
}
else if (chunkEnd <= input->getPosition())
{
break;
}
input->setPosition (chunkEnd);
}
}
if (cueLabelIndex > 0) metadataValues.set ("NumCueLabels", String (cueLabelIndex));
if (cueNoteIndex > 0) metadataValues.set ("NumCueNotes", String (cueNoteIndex));
if (cueRegionIndex > 0) metadataValues.set ("NumCueRegions", String (cueRegionIndex));
if (metadataValues.size() > 0) metadataValues.set ("MetaDataSource", "WAV");
}
//==============================================================================
bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
int64 startSampleInFile, int numSamples) override
{
clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
startSampleInFile, numSamples, lengthInSamples);
if (numSamples <= 0)
return true;
input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
while (numSamples > 0)
{
const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
char tempBuffer[tempBufSize];
auto numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
auto bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
if (bytesRead < numThisTime * bytesPerFrame)
{
jassert (bytesRead >= 0);
zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead));
}
copySampleData (bitsPerSample, usesFloatingPointData,
destSamples, startOffsetInDestBuffer, numDestChannels,
tempBuffer, (int) numChannels, numThisTime);
startOffsetInDestBuffer += numThisTime;
numSamples -= numThisTime;
}
return true;
}
static void copySampleData (unsigned int numBitsPerSample, const bool floatingPointData,
int* const* destSamples, int startOffsetInDestBuffer, int numDestChannels,
const void* sourceData, int numberOfChannels, int numSamples) noexcept
{
switch (numBitsPerSample)
{
case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples); break;
case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples); break;
case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples); break;
case 32: if (floatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples);
else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numberOfChannels, numSamples);
break;
default: jassertfalse; break;
}
}
//==============================================================================
AudioChannelSet getChannelLayout() override
{
if (channelLayout.size() == static_cast<int> (numChannels))
return channelLayout;
return WavFileHelpers::canonicalWavChannelSet (static_cast<int> (numChannels));
}
static AudioChannelSet getChannelLayoutFromMask (int dwChannelMask, size_t totalNumChannels)
{
AudioChannelSet wavFileChannelLayout;
// AudioChannelSet and wav's dwChannelMask are compatible
BigInteger channelBits (dwChannelMask);
for (auto bit = channelBits.findNextSetBit (0); bit >= 0; bit = channelBits.findNextSetBit (bit + 1))
wavFileChannelLayout.addChannel (static_cast<AudioChannelSet::ChannelType> (bit + 1));
// channel layout and number of channels do not match
if (wavFileChannelLayout.size() != static_cast<int> (totalNumChannels))
{
// for backward compatibility with old wav files, assume 1 or 2
// channel wav files are mono/stereo respectively
if (totalNumChannels <= 2 && dwChannelMask == 0)
wavFileChannelLayout = AudioChannelSet::canonicalChannelSet (static_cast<int> (totalNumChannels));
else
{
auto discreteSpeaker = static_cast<int> (AudioChannelSet::discreteChannel0);
while (wavFileChannelLayout.size() < static_cast<int> (totalNumChannels))
wavFileChannelLayout.addChannel (static_cast<AudioChannelSet::ChannelType> (discreteSpeaker++));
}
}
return wavFileChannelLayout;
}
int64 bwavChunkStart = 0, bwavSize = 0;
int64 dataChunkStart = 0, dataLength = 0;
int bytesPerFrame = 0;
bool isRF64 = false;
bool isSubformatOggVorbis = false;
AudioChannelSet channelLayout;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader)
};
//==============================================================================
class WavAudioFormatWriter : public AudioFormatWriter
{
public:
WavAudioFormatWriter (OutputStream* const out, const double rate,
const AudioChannelSet& channelLayoutToUse, const unsigned int bits,
const StringPairArray& metadataValues)
: AudioFormatWriter (out, wavFormatName, rate, channelLayoutToUse, bits)
{
using namespace WavFileHelpers;
if (metadataValues.size() > 0)
{
// The meta data should have been sanitised for the WAV format.
// If it was originally sourced from an AIFF file the MetaDataSource
// key should be removed (or set to "WAV") once this has been done
jassert (metadataValues.getValue ("MetaDataSource", "None") != "AIFF");
bwavChunk = BWAVChunk::createFrom (metadataValues);
axmlChunk = AXMLChunk::createFrom (metadataValues);
smplChunk = SMPLChunk::createFrom (metadataValues);
instChunk = InstChunk::createFrom (metadataValues);
cueChunk = CueChunk ::createFrom (metadataValues);
listChunk = ListChunk::createFrom (metadataValues);
listInfoChunk = ListInfoChunk::createFrom (metadataValues);
acidChunk = AcidChunk::createFrom (metadataValues);
trckChunk = TracktionChunk::createFrom (metadataValues);
}
headerPosition = out->getPosition();
writeHeader();
}
~WavAudioFormatWriter() override
{
writeHeader();
}
//==============================================================================
bool write (const int** data, int numSamples) override
{
jassert (numSamples >= 0);
jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel!
if (writeFailed)
return false;
auto bytes = numChannels * (size_t) numSamples * bitsPerSample / 8;
tempBlock.ensureSize (bytes, false);
switch (bitsPerSample)
{
case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break;
default: jassertfalse; break;
}
if (! output->write (tempBlock.getData(), bytes))
{
// failed to write to disk, so let's try writing the header.
// If it's just run out of disk space, then if it does manage
// to write the header, we'll still have a usable file..
writeHeader();
writeFailed = true;
return false;
}
bytesWritten += bytes;
lengthInSamples += (uint64) numSamples;
return true;
}
bool flush() override
{
auto lastWritePos = output->getPosition();
writeHeader();
if (output->setPosition (lastWritePos))
return true;
// if this fails, you've given it an output stream that can't seek! It needs
// to be able to seek back to write the header
jassertfalse;
return false;
}
private:
MemoryBlock tempBlock, bwavChunk, axmlChunk, smplChunk, instChunk, cueChunk, listChunk, listInfoChunk, acidChunk, trckChunk;
uint64 lengthInSamples = 0, bytesWritten = 0;
int64 headerPosition = 0;
bool writeFailed = false;
void writeHeader()
{
if ((bytesWritten & 1) != 0) // pad to an even length
output->writeByte (0);
using namespace WavFileHelpers;
if (headerPosition != output->getPosition() && ! output->setPosition (headerPosition))
{
// if this fails, you've given it an output stream that can't seek! It needs to be
// able to seek back to go back and write the header after the data has been written.
jassertfalse;
return;
}
const size_t bytesPerFrame = numChannels * bitsPerSample / 8;
uint64 audioDataSize = bytesPerFrame * lengthInSamples;
auto channelMask = getChannelMaskFromChannelLayout (channelLayout);
const bool isRF64 = (bytesWritten >= 0x100000000LL);
const bool isWaveFmtEx = isRF64 || (channelMask != 0);
int64 riffChunkSize = (int64) (4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
+ 8 + audioDataSize + (audioDataSize & 1)
+ chunkSize (bwavChunk)
+ chunkSize (axmlChunk)
+ chunkSize (smplChunk)
+ chunkSize (instChunk)
+ chunkSize (cueChunk)
+ chunkSize (listChunk)
+ chunkSize (listInfoChunk)
+ chunkSize (acidChunk)
+ chunkSize (trckChunk)
+ (8 + 28)); // (ds64 chunk)
riffChunkSize += (riffChunkSize & 1);
if (isRF64)
writeChunkHeader (chunkName ("RF64"), -1);
else
writeChunkHeader (chunkName ("RIFF"), (int) riffChunkSize);
output->writeInt (chunkName ("WAVE"));
if (! isRF64)
{
#if ! JUCE_WAV_DO_NOT_PAD_HEADER_SIZE
/* NB: This junk chunk is added for padding, so that the header is a fixed size
regardless of whether it's RF64 or not. That way, we can begin recording a file,
and when it's finished, can go back and write either a RIFF or RF64 header,
depending on whether more than 2^32 samples were written.
The JUCE_WAV_DO_NOT_PAD_HEADER_SIZE macro allows you to disable this feature in case
you need to create files for crappy WAV players with bugs that stop them skipping chunks
which they don't recognise. But DO NOT USE THIS option unless you really have no choice,
because it means that if you write more than 2^32 samples to the file, you'll corrupt it.
*/
writeChunkHeader (chunkName ("JUNK"), 28 + (isWaveFmtEx? 0 : 24));
output->writeRepeatedByte (0, 28 /* ds64 */ + (isWaveFmtEx? 0 : 24));
#endif
}
else
{
#if JUCE_WAV_DO_NOT_PAD_HEADER_SIZE
// If you disable padding, then you MUST NOT write more than 2^32 samples to a file.
jassertfalse;
#endif
writeChunkHeader (chunkName ("ds64"), 28); // chunk size for uncompressed data (no table)
output->writeInt64 (riffChunkSize);
output->writeInt64 ((int64) audioDataSize);
output->writeRepeatedByte (0, 12);
}
if (isWaveFmtEx)
{
writeChunkHeader (chunkName ("fmt "), 40);
output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
}
else
{
writeChunkHeader (chunkName ("fmt "), 16);
output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
: (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
}
output->writeShort ((short) numChannels);
output->writeInt ((int) sampleRate);
output->writeInt ((int) ((double) bytesPerFrame * sampleRate)); // nAvgBytesPerSec
output->writeShort ((short) bytesPerFrame); // nBlockAlign
output->writeShort ((short) bitsPerSample); // wBitsPerSample
if (isWaveFmtEx)
{
output->writeShort (22); // cbSize (size of the extension)
output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
output->writeInt (channelMask);
const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
output->writeInt ((int) subFormat.data1);
output->writeShort ((short) subFormat.data2);
output->writeShort ((short) subFormat.data3);
output->write (subFormat.data4, sizeof (subFormat.data4));
}
writeChunk (bwavChunk, chunkName ("bext"));
writeChunk (axmlChunk, chunkName ("axml"));
writeChunk (smplChunk, chunkName ("smpl"));
writeChunk (instChunk, chunkName ("inst"), 7);
writeChunk (cueChunk, chunkName ("cue "));
writeChunk (listChunk, chunkName ("LIST"));
writeChunk (listInfoChunk, chunkName ("LIST"));
writeChunk (acidChunk, chunkName ("acid"));
writeChunk (trckChunk, chunkName ("Trkn"));
writeChunkHeader (chunkName ("data"), isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
usesFloatingPointData = (bitsPerSample == 32);
}
static size_t chunkSize (const MemoryBlock& data) noexcept { return data.getSize() > 0 ? (8 + data.getSize()) : 0; }
void writeChunkHeader (int chunkType, int size) const
{
output->writeInt (chunkType);
output->writeInt (size);
}
void writeChunk (const MemoryBlock& data, int chunkType, int size = 0) const
{
if (data.getSize() > 0)
{
writeChunkHeader (chunkType, size != 0 ? size : (int) data.getSize());
*output << data;
}
}
static int getChannelMaskFromChannelLayout (const AudioChannelSet& layout)
{
if (layout.isDiscreteLayout())
return 0;
// Don't add an extended format chunk for mono and stereo. Basically, all wav players
// interpret a wav file with only one or two channels to be mono or stereo anyway.
if (layout == AudioChannelSet::mono() || layout == AudioChannelSet::stereo())
return 0;
auto channels = layout.getChannelTypes();
auto wavChannelMask = 0;
for (auto channel : channels)
{
int wavChannelBit = static_cast<int> (channel) - 1;
jassert (wavChannelBit >= 0 && wavChannelBit <= 31);
wavChannelMask |= (1 << wavChannelBit);
}
return wavChannelMask;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter)
};
//==============================================================================
class MemoryMappedWavReader : public MemoryMappedAudioFormatReader
{
public:
MemoryMappedWavReader (const File& wavFile, const WavAudioFormatReader& reader)
: MemoryMappedAudioFormatReader (wavFile, reader, reader.dataChunkStart,
reader.dataLength, reader.bytesPerFrame)
{
}
bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
int64 startSampleInFile, int numSamples) override
{
clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer,
startSampleInFile, numSamples, lengthInSamples);
if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
{
jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
return false;
}
WavAudioFormatReader::copySampleData (bitsPerSample, usesFloatingPointData,
destSamples, startOffsetInDestBuffer, numDestChannels,
sampleToPointer (startSampleInFile), (int) numChannels, numSamples);
return true;
}
void getSample (int64 sample, float* result) const noexcept override
{
auto num = (int) numChannels;
if (map == nullptr || ! mappedSection.contains (sample))
{
jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read.
zeromem (result, (size_t) num * sizeof (float));
return;
}
auto dest = &result;
auto source = sampleToPointer (sample);
switch (bitsPerSample)
{
case 8: ReadHelper<AudioData::Float32, AudioData::UInt8, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num); break;
case 16: ReadHelper<AudioData::Float32, AudioData::Int16, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num); break;
case 24: ReadHelper<AudioData::Float32, AudioData::Int24, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num); break;
case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num);
else ReadHelper<AudioData::Float32, AudioData::Int32, AudioData::LittleEndian>::read (dest, 0, 1, source, 1, num);
break;
default: jassertfalse; break;
}
}
void readMaxLevels (int64 startSampleInFile, int64 numSamples, Range<float>* results, int numChannelsToRead) override
{
numSamples = jmin (numSamples, lengthInSamples - startSampleInFile);
if (map == nullptr || numSamples <= 0 || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples)))
{
jassert (numSamples <= 0); // you must make sure that the window contains all the samples you're going to attempt to read.
for (int i = 0; i < numChannelsToRead; ++i)
results[i] = {};
return;
}
switch (bitsPerSample)
{
case 8: scanMinAndMax<AudioData::UInt8> (startSampleInFile, numSamples, results, numChannelsToRead); break;
case 16: scanMinAndMax<AudioData::Int16> (startSampleInFile, numSamples, results, numChannelsToRead); break;
case 24: scanMinAndMax<AudioData::Int24> (startSampleInFile, numSamples, results, numChannelsToRead); break;
case 32: if (usesFloatingPointData) scanMinAndMax<AudioData::Float32> (startSampleInFile, numSamples, results, numChannelsToRead);
else scanMinAndMax<AudioData::Int32> (startSampleInFile, numSamples, results, numChannelsToRead);
break;
default: jassertfalse; break;
}
}
using AudioFormatReader::readMaxLevels;
private:
template <typename SampleType>
void scanMinAndMax (int64 startSampleInFile, int64 numSamples, Range<float>* results, int numChannelsToRead) const noexcept
{
for (int i = 0; i < numChannelsToRead; ++i)
results[i] = scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (i, startSampleInFile, numSamples);
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedWavReader)
};
//==============================================================================
WavAudioFormat::WavAudioFormat() : AudioFormat (wavFormatName, ".wav .bwf") {}
WavAudioFormat::~WavAudioFormat() {}
Array<int> WavAudioFormat::getPossibleSampleRates()
{
return { 8000, 11025, 12000, 16000, 22050, 32000, 44100,
48000, 88200, 96000, 176400, 192000, 352800, 384000 };
}
Array<int> WavAudioFormat::getPossibleBitDepths()
{
return { 8, 16, 24, 32 };
}
bool WavAudioFormat::canDoStereo() { return true; }
bool WavAudioFormat::canDoMono() { return true; }
bool WavAudioFormat::isChannelLayoutSupported (const AudioChannelSet& channelSet)
{
auto channelTypes = channelSet.getChannelTypes();
// When
if (channelSet.isDiscreteLayout())
return true;
// WAV supports all channel types from left ... topRearRight
for (auto channel : channelTypes)
if (channel < AudioChannelSet::left || channel > AudioChannelSet::topRearRight)
return false;
return true;
}
AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream, bool deleteStreamIfOpeningFails)
{
std::unique_ptr<WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
#if JUCE_USE_OGGVORBIS
if (r->isSubformatOggVorbis)
{
r->input = nullptr;
return OggVorbisAudioFormat().createReaderFor (sourceStream, deleteStreamIfOpeningFails);
}
#endif
if (r->sampleRate > 0 && r->numChannels > 0 && r->bytesPerFrame > 0 && r->bitsPerSample <= 32)
return r.release();
if (! deleteStreamIfOpeningFails)
r->input = nullptr;
return nullptr;
}
MemoryMappedAudioFormatReader* WavAudioFormat::createMemoryMappedReader (const File& file)
{
return createMemoryMappedReader (file.createInputStream().release());
}
MemoryMappedAudioFormatReader* WavAudioFormat::createMemoryMappedReader (FileInputStream* fin)
{
if (fin != nullptr)
{
WavAudioFormatReader reader (fin);
if (reader.lengthInSamples > 0)
return new MemoryMappedWavReader (fin->getFile(), reader);
}
return nullptr;
}
AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
unsigned int numChannels, int bitsPerSample,
const StringPairArray& metadataValues, int qualityOptionIndex)
{
return createWriterFor (out, sampleRate, WavFileHelpers::canonicalWavChannelSet (static_cast<int> (numChannels)),
bitsPerSample, metadataValues, qualityOptionIndex);
}
AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
double sampleRate,
const AudioChannelSet& channelLayout,
int bitsPerSample,
const StringPairArray& metadataValues,
int /*qualityOptionIndex*/)
{
if (out != nullptr && getPossibleBitDepths().contains (bitsPerSample) && isChannelLayoutSupported (channelLayout))
return new WavAudioFormatWriter (out, sampleRate, channelLayout,
(unsigned int) bitsPerSample, metadataValues);
return nullptr;
}
namespace WavFileHelpers
{
static bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
{
TemporaryFile tempFile (file);
WavAudioFormat wav;
std::unique_ptr<AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
if (reader != nullptr)
{
std::unique_ptr<OutputStream> outStream (tempFile.getFile().createOutputStream());
if (outStream != nullptr)
{
std::unique_ptr<AudioFormatWriter> writer (wav.createWriterFor (outStream.get(), reader->sampleRate,
reader->numChannels, (int) reader->bitsPerSample,
metadata, 0));
if (writer != nullptr)
{
outStream.release();
bool ok = writer->writeFromAudioReader (*reader, 0, -1);
writer.reset();
reader.reset();
return ok && tempFile.overwriteTargetFileWithTemporary();
}
}
}
return false;
}
}
bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
{
using namespace WavFileHelpers;
std::unique_ptr<WavAudioFormatReader> reader (static_cast<WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream().release(), true)));
if (reader != nullptr)
{
auto bwavPos = reader->bwavChunkStart;
auto bwavSize = reader->bwavSize;
reader.reset();
if (bwavSize > 0)
{
auto chunk = BWAVChunk::createFrom (newMetadata);
if (chunk.getSize() <= (size_t) bwavSize)
{
// the new one will fit in the space available, so write it directly..
auto oldSize = wavFile.getSize();
{
FileOutputStream out (wavFile);
if (out.openedOk())
{
out.setPosition (bwavPos);
out << chunk;
out.setPosition (oldSize);
}
}
jassert (wavFile.getSize() == oldSize);
return true;
}
}
}
return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
struct WaveAudioFormatTests : public UnitTest
{
WaveAudioFormatTests()
: UnitTest ("Wave audio format tests", UnitTestCategories::audio)
{}
void runTest() override
{
beginTest ("Setting up metadata");
StringPairArray metadataValues = WavAudioFormat::createBWAVMetadata ("description",
"originator",
"originatorRef",
Time::getCurrentTime(),
numTestAudioBufferSamples,
"codingHistory");
for (int i = numElementsInArray (WavFileHelpers::ListInfoChunk::types); --i >= 0;)
metadataValues.set (WavFileHelpers::ListInfoChunk::types[i],
WavFileHelpers::ListInfoChunk::types[i]);
if (metadataValues.size() > 0)
metadataValues.set ("MetaDataSource", "WAV");
metadataValues.addArray (createDefaultSMPLMetadata());
WavAudioFormat format;
MemoryBlock memoryBlock;
{
beginTest ("Creating a basic wave writer");
std::unique_ptr<AudioFormatWriter> writer (format.createWriterFor (new MemoryOutputStream (memoryBlock, false),
44100.0, numTestAudioBufferChannels,
32, metadataValues, 0));
expect (writer != nullptr);
AudioBuffer<float> buffer (numTestAudioBufferChannels, numTestAudioBufferSamples);
buffer.clear();
beginTest ("Writing audio data to the basic wave writer");
expect (writer->writeFromAudioSampleBuffer (buffer, 0, numTestAudioBufferSamples));
}
{
beginTest ("Creating a basic wave reader");
std::unique_ptr<AudioFormatReader> reader (format.createReaderFor (new MemoryInputStream (memoryBlock, false), false));
expect (reader != nullptr);
expect (reader->metadataValues == metadataValues, "Somehow, the metadata is different!");
}
}
private:
enum
{
numTestAudioBufferChannels = 2,
numTestAudioBufferSamples = 256
};
StringPairArray createDefaultSMPLMetadata() const
{
StringPairArray m;
m.set ("Manufacturer", "0");
m.set ("Product", "0");
m.set ("SamplePeriod", "0");
m.set ("MidiUnityNote", "60");
m.set ("MidiPitchFraction", "0");
m.set ("SmpteFormat", "0");
m.set ("SmpteOffset", "0");
m.set ("NumSampleLoops", "0");
m.set ("SamplerData", "0");
return m;
}
JUCE_DECLARE_NON_COPYABLE (WaveAudioFormatTests)
};
static const WaveAudioFormatTests waveAudioFormatTests;
#endif
} // namespace juce
| gpl-3.0 |
BangL/WGJails | de/bangl/WGJails/core/commands/CmdHelp.java | 1687 | /*
* Copyright (C) 2012 t7seven7t
* BangL <[email protected]>
*
* 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 de.bangl.WGJails.core.commands;
import de.bangl.WGJails.core.SPlugin;
import java.util.ArrayList;
import org.bukkit.ChatColor;
/**
*
* @author t7seven7t
* @author BangL <[email protected]>
*/
public class CmdHelp extends SCommand<SPlugin> {
public CmdHelp() {
this.name = "jailhelp";
this.description = "Shows " + SPlugin.p.getName() + " help.";
}
@Override
public void perform() {
for (String s : getPageLines()) {
msg(s);
}
}
public ArrayList<String> getPageLines() {
ArrayList<String> pageLines = new ArrayList<String>();
pageLines.add(ChatColor.GOLD + SPlugin.p.getName() + " Help:");
for (SCommand<?> command : SPlugin.commandRoot.commands) {
if (command.hasPermission()) {
pageLines.add(command.getUsageTemplate(true));
}
}
return pageLines;
}
}
| gpl-3.0 |
francy51/AnimeProject | proj/RPG-OLD/Assets/Systems/Item System/scripts/interfaces/IISPrefab.cs | 147 | using UnityEngine;
using System.Collections;
namespace Project.ItemSystem {
public interface IISPrefab {
GameObject Prefab { get; }
}
} | gpl-3.0 |
kpfuchs/gMix | gMix/src/staticContent/evaluation/simulator/core/networkComponent/NetworkNode.java | 6333 | /*******************************************************************************
* gMix open source project - https://svs.informatik.uni-hamburg.de/gmix/
* Copyright (C) 2014 SVS
*
* 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 staticContent.evaluation.simulator.core.networkComponent;
import java.util.HashMap;
import staticContent.evaluation.simulator.Simulator;
import staticContent.evaluation.simulator.core.event.Event;
import staticContent.evaluation.simulator.core.event.EventExecutor;
import staticContent.evaluation.simulator.core.event.SimulationEvent;
import staticContent.evaluation.simulator.core.message.NetworkMessage;
import staticContent.evaluation.simulator.core.statistics.Statistics;
import userGeneratedContent.simulatorPlugIns.plugins.delayBox.DelayBoxImpl;
public abstract class NetworkNode implements EventExecutor, Identifiable {
private int numericIdentifier;
private String identifier;
private NetworkConnection connectionToNextHop;
private NetworkConnection connectionToPreviousHop;
private Simulator simulator;
private DelayBoxImpl delayBox;
private int numberOfConnectionsToNextHops = 0;
private int numberOfConnectionsToPreviousHops = 0;
private HashMap<String, NetworkConnection> connectionsToNextHops;
private HashMap<String, NetworkConnection> connectionsToPreviousHops;
protected Statistics statistics;
public NetworkNode(String identifier, Simulator simulator) {
this.identifier = identifier;
this.numericIdentifier = IdGenerator.getId();
this.simulator = simulator;
this.statistics = new Statistics(this);
}
public void sendToNextHop(NetworkMessage networkMessage, int delay, SimulationEvent simulationEvent) {
if (numberOfConnectionsToNextHops == 1)
sendToHop(connectionToNextHop, networkMessage, delay, simulationEvent);
else
sendToHop(connectionsToNextHops.get(networkMessage.getDestination().getIdentifier()), networkMessage, delay, simulationEvent);
}
public void sendToPreviousHop(NetworkMessage networkMessage, int delay, SimulationEvent simulationEvent) {
if (numberOfConnectionsToPreviousHops == 1)
sendToHop(connectionToPreviousHop, networkMessage, delay, simulationEvent);
else
sendToHop(connectionsToPreviousHops.get(networkMessage.getDestination().getIdentifier()), networkMessage, delay, simulationEvent);
}
public void sendToHop(NetworkConnection connectionToHop, NetworkMessage networkMessage, int delay, SimulationEvent simulationEvent) {
Event event = new Event(connectionToHop, Simulator.getNow() + delay, simulationEvent, networkMessage);
simulator.scheduleEvent(event, this);
String destination = networkMessage.isRequest() ? connectionToHop.getDestination().toString() : connectionToHop.getSource().toString();
if (Simulator.DEBUG_ON)
System.out.println(identifier + ": sending " +networkMessage +" to " +destination);
}
/**
* @return the connectionToNextHop
*/
public NetworkConnection getConnectionToNextHop() {
return connectionToNextHop;
}
/**
* @param connectionToNextHop the connectionToNextHop to set
*/
public void setConnectionToNextHop(NetworkConnection connectionToNextHop) {
if (numberOfConnectionsToNextHops == 0) {
this.connectionToNextHop = connectionToNextHop;
numberOfConnectionsToNextHops++;
} else if (numberOfConnectionsToNextHops == 1) {
connectionsToNextHops = new HashMap<String, NetworkConnection>(100);
connectionsToNextHops.put(this.connectionToNextHop.getDestination().toString(), this.connectionToNextHop);
connectionsToNextHops.put(connectionToNextHop.getDestination().toString(), connectionToNextHop);
this.connectionToNextHop = null;
numberOfConnectionsToNextHops++;
} else {
connectionsToNextHops.put(connectionToNextHop.getDestination().toString(), connectionToNextHop);
numberOfConnectionsToNextHops++;
}
}
/**
* @return the connectionToPreviousHop
*/
public NetworkConnection getConnectionToPreviousHop() {
return connectionToPreviousHop;
}
/**
* @param connectionToPreviousHop the connectionToPreviousHop to set
*/
public void setConnectionToPreviousHop(NetworkConnection connectionToPreviousHop) {
if (numberOfConnectionsToPreviousHops == 0) {
this.connectionToPreviousHop = connectionToPreviousHop;
numberOfConnectionsToPreviousHops++;
} else if (numberOfConnectionsToPreviousHops == 1) {
connectionsToPreviousHops = new HashMap<String, NetworkConnection>(100);
connectionsToPreviousHops.put(this.connectionToPreviousHop.getSource().toString(), this.connectionToPreviousHop);
connectionsToPreviousHops.put(connectionToPreviousHop.getSource().toString(), connectionToPreviousHop);
this.connectionToPreviousHop = null;
numberOfConnectionsToPreviousHops++;
} else {
connectionsToPreviousHops.put(connectionToPreviousHop.getSource().toString(), connectionToPreviousHop);
numberOfConnectionsToPreviousHops++;
}
}
/**
* @return the identifier
*/
public String getIdentifier() {
return identifier;
}
public String toString() {
return identifier;
}
/**
* @return the delayBox
*/
public DelayBoxImpl getDelayBox() {
return delayBox;
}
/**
* @param delayBox the delayBox to set
*/
public void setDelayBox(DelayBoxImpl delayBox) {
this.delayBox = delayBox;
}
@Override
public int getGlobalId() {
return numericIdentifier;
}
/**
* @return the statistics
*/
public Statistics getStatistics() {
return statistics;
}
/**
* @param statistics the statistics to set
*/
public void setStatistics(Statistics statistics) {
this.statistics = statistics;
}
}
| gpl-3.0 |
pinkipi/skill-prediction | config/skills.js | 86727 | /* Notes:
* '*' can be used in place of the skill or sub-skill to set default values
Races:
0 = Male Human
1 = Female Human
2 = Male High Elf
3 = Female High Elf
4 = Male Aman
5 = Female Aman
6 = Male Castanic
7 = Female Castanic
8 = Popori
9 = Elin
10 = Baraka
*/
module.exports = {
0: { // Warrior
1: { // Combo Attack
0: {
length: 566,
distance: 47.53,
race: {
4: { distance: 35.49 },
5: { distance: 45 },
7: { distance: 60 },
8: { distance: 54.32 },
9: { distance: 64.29 },
10: { distance: 32.81 }
}
},
1: {
length: 657,
distance: 42.12,
race: {
4: { distance: 42.96 },
5: { distance: 39 },
7: { distance: 27 },
8: { distance: 21.17 },
9: { distance: 51.69 },
10: { distance: 49.22 }
}
},
2: {
length: 657,
distance: 28.08,
race: {
4: { distance: 31.02 },
5: { distance: 26 },
7: { distance: 49 },
8: { distance: 56.2 },
10: { distance: 25.69 }
}
},
3: {
length: 909,
distance: 75.07,
race: {
1: { distance: 82.07 },
2: { distance: 79.9 },
3: { distance: 66.41 },
4: { distance: 64.66 },
5: { distance: 85 },
7: { distance: 58 },
8: { distance: 63.53 },
9: { distance: 73.34 },
10: { distance: 68.69 }
}
}
},
2: { // Evasive Roll
0: {
length: 839,
distance: 150,
forceClip: true,
stamina: 500,
instantStamina: true,
glyphs: {
21015: { stamina: -100 },
21067: { stamina: -100 },
21101: { stamina: -120 }
},
race: {
0: { distance: 149.94 },
7: { length: 837 },
8: { length: 1082 },
10: { length: 778 }
}
}
},
3: { // Torrent of Blows
0: {
length: 1600,
distance: 75,
race: {
9: { distance: 68.26 }
}
}
},
4: { // Rain of Blows
'*': {
distance: 150.25,
race: {
1: { distance: 151.61 },
2: { distance: 152.73 },
3: { distance: 143.35 },
4: { distance: 142.61 },
5: { distance: 150.71 },
6: { distance: 143.47 },
7: { distance: 159 },
8: { distance: 148.9 },
9: { distance: 151.87 },
10: { distance: 96.09 }
}
},
0: {
length: 2545,
noInterrupt: [1, 2, 3, 4, 8, 9, 10, 11, 12, 13, 16, 17, 19, 22, 28, 29, 34, 36, 37, 39],
abnormals: {
100801: { skill: 360100 }
},
chains: {
18: 30,
21: 30,
27: 30,
40: 30
}
},
30: {
length: 2000,
abnormals: {
100801: { skill: 360130 }
}
}
},
5: { // Battle Cry
0: {
length: 1666,
glyphs: {
21040: { speed: 1.5 }
}
}
},
8: { // Assault Stance
'*': {
length: 566,
race: {
3: { length: 657 }
}
},
0: { stamina: 1000 },
50: true
},
9: { // Defensive Stance
'*': {
length: 566,
race: {
3: { length: 657 }
}
},
0: { stamina: 1000 },
50: true
},
10: { // Death From Above
0: {
length: 2066,
race: {
1: { length: 2100 },
3: { length: 2033 },
6: { length: 2033 },
9: { length: 2033 }
}
}
},
11: { // Poison Blade
0: {
length: 933,
distance: 54.85
}
},
12: { // Leaping Strike
0: {
length: 1533,
distance: 250,
glyphs: {
21048: { speed: 1.2 },
21082: { speed: 1.2 }
}
}
},
16: { // Charging Slash
0: {
type: 'dash',
fixedSpeed: 1,
length: 1100,
distance: 467.88,
noRetry: true
},
1: {
length: 800,
distance: 100,
race: {
5: { distance: 93.53 }
}
}
},
17: { // Vortex Slash
0: { length: 1600 },
1: { length: 1600 },
2: { length: 1600 }
},
18: { // Combative Strike
'*': {
length: 1100,
distance: 120.28,
noInterrupt: [32],
race: {
1: { distance: 122.63 },
3: { distance: 127.11 },
4: { distance: 110.46 },
7: { distance: 130 },
8: { distance: 128.89 },
9: { distance: 138.28 },
10: { distance: 94.49 }
}
},
0: true,
1: true,
2: true
},
19: { // Rising Fury
0: {
length: 733,
distance: 148.2,
race: {
1: { distance: 157.28 },
2: { distance: 144.85 },
3: { distance: 155.3 },
4: { distance: 144.85 },
5: { distance: 143.27 },
6: { distance: 170.43 },
7: { distance: 162 },
8: { distance: 161.74 },
9: { distance: 170.67 },
10: { distance: 132.61 }
}
},
1: {
length: 1400,
distance: 92.66,
race: {
1: { distance: 88.17 },
2: { distance: 100.11 },
3: { distance: 92.1 },
4: { distance: 100.11 },
5: { distance: 101.69 },
6: { distance: 117.31 },
7: { distance: 85 },
8: { distance: 116.63 },
9: { distance: 122.34 },
10: { distance: 83.01 }
}
}
},
20: { // Deadly Gamble
0: {
fixedSpeed: 1,
length: 320
}
},
21: { // Cascade of Stuns
0: {
length: 1400,
distance: 92.66,
race: {
1: { distance: 88.17 },
2: { distance: 100.11 },
3: { distance: 92.1 },
4: { distance: 100.11 },
5: { distance: 101.69 },
6: { distance: 117.31 },
7: { distance: 85 },
8: { distance: 116.63 },
9: { distance: 122.34 },
10: { distance: 83.01 }
}
}
},
24: { // Smoke Aggressor
0: {
fixedSpeed: 1,
length: 481
}
},
25: { // Command: Attack
0: {
fixedSpeed: 1,
length: 700
}
},
26: { // Command: Follow
0: {
fixedSpeed: 1,
length: 700
}
},
27: { // Pounce (removed)
0: {
length: 2000,
distance: 180,
glyphs: {
21048: { speed: 1.3 },
21082: { speed: 1.3 }
}
}
},
28: { // Traverse Cut
0: {
length: 2000,
distance: 160,
noInterrupt: [1, 2, 3, 4, 8, 9, 10, 12, 13, 16, 17, 19, 21, 22, 28, 29, 34, 36, 37, 39],
chains: {
11: 30,
18: 30,
27: 30,
40: 30
},
level: {
9: {
abnormals: {
100201: { skill: 390100 }
}
}
}
},
30: {
length: 2667,
distance: 210,
level: {
9: {
abnormals: {
100201: { skill: 390130 }
}
}
}
}
},
29: { // Blade Draw
0: {
length: 3000,
distance: 94.5,
noInterrupt: [1, 2, 3, 4, 8, 9, 10, 11, 12, 13, '16-0', 18, '19-0', 21, 22, 27, 29, 34, 36, 37],
interruptibleWithAbnormal: { 102010: 3 },
abnormals: {
102010: { chain: 30 },
100801: { skill: 370100 }
},
chains: {
3: 30,
16: 30,
17: 30,
19: 30,
28: 30,
32: 30,
39: 30,
40: 30
}
},
30: {
length: 1333,
distance: 135,
abnormals: {
100801: { skill: 370130 }
}
}
},
30: { // Scythe
0: {
length: 1833,
distance: 150,
noInterrupt: [1, 3, 8, 9, 10, 13, 16, 17, 18, 19, 21, 22, 27, 28, 34, 39],
abnormals: {
100801: { skill: 380100 }
},
chains: {
2: 30,
4: 30,
11: 30,
12: 30,
29: 30,
36: 30,
37: 30,
40: 30
}
},
30: {
length: 1387,
distance: 150,
abnormals: {
100801: { skill: 380130 }
}
}
},
31: { // Reaping Slash
'*': { distance: 110 },
0: {
length: 2292,
noInterrupt: [1, 2, 3, 8, 9, 10, 11, 12, 13, 16, 17, 19, 21, 22, 27, 28, 29, 34, 37, 39],
chains: {
4: 30,
18: 30,
36: 30,
40: 30
}
},
30: { length: 1668 }
},
32: { // Cross Parry
0: {
type: 'holdInfinite',
fixedSpeed: 1,
requiredBuff: [100200, 100201],
stamina: 50
}
},
34: { // Binding Sword
0: { length: 1855 }
},
35: { // Infuriate
0: {
length: 2423,
requiredBuff: [100200, 100201]
}
},
36: { // Rain of Blows (Deadly Gamble)
'*': {
distance: 150.25,
race: {
1: { distance: 151.61 },
2: { distance: 152.73 },
3: { distance: 152.73 },
4: { distance: 142.61 },
5: { distance: 150.71 },
6: { distance: 143.47 },
7: { distance: 159 },
8: { distance: 148.9 },
9: { distance: 151.87 },
10: { distance: 96.09 }
}
},
0: { length: 2800 },
30: { length: 2000 }
},
37: { // Blade Draw (Deadly Gamble)
'*': { hasChains: true },
0: {
length: 3000,
distance: 94.5,
abnormalChains: { 102010: 30 }
},
30: {
length: 1333,
distance: 135
}
},
38: { // Scythe (Deadly Gamble)
'*': { distance: 150 },
0: { length: 1833 },
30: { length: 1387 }
},
39: { // Traverse Cut (Defensive Stance)
0: {
length: 2000,
distance: 160
},
30: {
length: 2667,
distance: 210
}
}
},
1: { // Lancer
1: { // Combo Attack
'*': { noInterrupt: [1, 2] },
0: {
length: 624,
distance: 78.55,
race: {
1: { distance: 74.89 },
2: { distance: 74.41 },
3: { distance: 74.36 },
4: { distance: 70 },
5: { distance: 69.8 },
6: { distance: 76.42 },
7: { distance: 74.89 },
8: { distance: 72.89 },
9: { distance: 74.45 },
10: { distance: 74.88 }
}
},
1: {
length: 1021,
distance: 25,
race: {
1: { distance: 28.39 },
2: { distance: 30.8 },
3: { distance: 30.68 },
5: { distance: 30.52 },
6: { distance: 30.8 },
7: { distance: 28.39 },
8: { distance: 39.05 },
9: { distance: 19.2 },
10: { distance: 30.8 }
}
},
2: {
length: 1818,
distance: 70,
race: {
1: { distance: 59.53 },
3: { distance: 64.36 },
4: { distance: 60 },
5: { distance: 54.48 },
7: { distance: 59.53 },
8: { distance: 41.06 },
9: { distance: 66.07 },
10: { distance: 69.98 }
}
}
},
2: { // Stand Fast
0: {
type: 'holdInfinite',
fixedSpeed: 1,
stamina: 50,
level: {
1: {
length: 333,
stamina: 40,
endType51: true
}
},
noRetry: true
}
},
3: { // Onslaught
'*': {
distance: [0, 100, 100, 100, 100, 62.7],
noInterrupt: ['1-0', '1-1', 2, 3, 8, 10, 13, 15, 21, 25, 26],
abnormals: {
22060: { speed: 1.25 }
},
chains: {
1: 30,
5: 30,
18: 30
}
},
0: { length: [950, 500, 500, 500, 400, 775] },
30: { length: [713, 375, 375, 375, 300, 582] }
},
4: { // Challenging Shout
'*': {
length: 2203,
glyphs: {
22056: { speed: 1.25 },
22085: { speed: 1.25 }
}
},
0: true,
30: true
},
5: { // Shield Bash
'*': {
length: 820,
distance: 43.69,
chains: { 10: 30 }
},
1: true,
2: true,
30: { length: 683 }
},
7: { // Guardian Shout
0: {
length: 550,
race: {
8: { length: 800 } // Popori
}
}
},
8: { // Shield Counter
0: {
length: 1450,
distance: 108.06,
onlyDefenceSuccess: true
}
},
9: { // Leash
0: { length: [725, 850] }
},
10: { // Debilitate
'*': {
distance: 43.69,
noInterrupt: [2, 3, 5, 10, 13, 21, 25, 26],
chains: {
1: 30,
18: 30
}
},
0: { length: 925 },
30: { length: 832 }
},
11: { // Retaliate
0: {
type: 'retaliate',
length: 1625,
noRetry: true
}
},
12: { // Infuriate
0: { length: 2425 }
},
13: { // Spring Attack
0: {
length: 2799,
distance: 85,
noInterrupt: ['1-0', '1-1', 2, 3, 13, 15, 25, 26],
chains: {
1: 30,
5: 30,
8: 30,
10: 30,
18: 30,
21: 30
}
},
30: {
length: 1850,
distance: 85
}
},
15: { // Charging Lunge
0: {
type: 'dash',
fixedSpeed: 1,
length: 1125,
distance: 474.5,
noInterrupt: [15]
},
1: { length: 925 }
},
16: { // Second Wind
0: {
noWeapon: true,
fixedSpeed: 1,
length: 700
}
},
17: { // Adrenaline Rush
0: {
fixedSpeed: 1,
length: 700
}
},
18: { // Shield Barrage
0: {
length: 598,
distance: 100.13,
abnormals: {
201550: { speed: 1.2 }
},
race: {
2: {
length: 503,
distance: 102.7
},
3: { distance: 103.43 },
4: { distance: 95 },
6: { distance: 110.39 },
7: { distance: 116.18 },
8: { distance: 92.39 },
9: { distance: 122.66 },
10: { distance: 92.13 }
}
},
1: {
length: 800,
distance: 74.84,
race: {
2: { distance: 80.43 },
3: { distance: 70.32 },
4: { distance: 87 },
8: { distance: 89.46 },
9: { distance: 66.04 }
}
}
},
19: { // Pledge of Protection
0: {
fixedSpeed: 1,
length: 1000
}
},
20: { // Menacing Wave (removed)
0: {
fixedSpeed: 1,
length: [700, 800]
}
},
21: { // Lockdown Blow
'*': {
length: 1400,
distance: 122.66,
chains: {
10: 30,
18: 30
}
},
1: true,
2: true,
30: { length: 1260 }
},
22: { // Iron Will
0: {
fixedSpeed: 1,
length: 800
}
},
23: { // Master's Leash
0: {
length: [725, 850],
requiredBuff: 201000
}
},
24: { // Chained Leash
0: { length: [725, 850] }
},
25: { // Wallop
0: {
length: 2375,
distance: 100,
noInterrupt: [1, 2, 3, 5, 25, 26],
chains: {
8: 30,
10: 30,
13: 30,
15: 30,
18: 30,
21: 30
}
},
30: {
length: 1900,
distance: 100
}
},
26: { // Backstep
0: {
length: 725,
distance: -150,
forceClip: true,
stamina: 800,
instantStamina: true,
noInterrupt: [26],
glyphs: {
22067: { stamina: -100 },
22089: { stamina: -100 }
}
}
},
27: { // Rallying Cry
0: { length: 620 }
},
28: { // Righteous Leap
'*': {
distance: [29.48, 445.52, 0],
race: {
1: {
distance: [20.32, 398.47, 0]
},
5: {
distance: [20.32, 398.47, 0]
},
6: {
distance: [20.32, 398.47, 0]
}
}
},
0: {
length: [333, 1055, 3122],
noInterrupt: [1, 3, 4, 5, 9, 10, 12, 13, 18, 21, 23, 24, 26, 28],
chains: {
15: 1,
25: 1
}
},
1: { length: [250, 791, 834] }
},
29: { // Guardian's Barrier
0: {
type: 'holdInfinite',
fixedSpeed: 1,
length: 700,
endType51: true
}
},
30: { // Divine Protection
0: { length: 1250 }
}
},
2: { // Slayer
1: { // Combo Attack
'*': { noRetry: true },
0: {
length: 761,
distance: 36.68,
race: {
2: { distance: 50.68 },
3: { distance: 38.8 },
4: { distance: 40 },
7: { distance: 60 },
8: { distance: 31.53 },
10: { distance: 25.08 }
}
},
1: {
length: 1021,
distance: 35.67,
race: {
2: {
length: 1051,
distance: 30.67
},
3: { distance: 38.84 },
4: { distance: 35 },
5: { distance: 35.68 },
7: { distance: 17 },
8: { distance: 49.4 },
10: { distance: 32.95 }
}
},
2: {
length: 748,
distance: 28.05,
race: {
2: { distance: 33.05 },
3: { distance: 24.22 },
4: { distance: 20 },
6: { distance: 22.3 },
7: { distance: 23 },
8: { distance: 19.33 },
10: { distance: 22.5 }
}
},
3: {
length: 1636,
distance: 46.76,
race: {
3: {
length: 1545,
distance: 45.32
},
4: { distance: 40 },
5: { distance: 64.36 },
6: { distance: 118.2 },
7: { distance: 45 },
8: { distance: 19.85 },
10: { distance: 37.5 }
}
}
},
2: { // Knockdown Strike
'*': {
length: 2385,
distance: 220.47,
noInterrupt: [1, 2, 3, 4, 6, 8, 10, 12, 13, 15, 16, 17, 24, 25],
abnormals: {
23070: {speed: 1.25}
},
chains: { 14: 30 }
},
0: true,
1: true,
2: true,
30: {
length: 2400,
distance: 300
}
},
3: { // Whirlwind
0: {
length: 3125,
distance: 128.69,
abnormals: {
23080: { speed: 1.25 }
}
}
},
4: { // Evasive Roll
'*': { hasChains: true },
0: {
length: 900,
distance: 150,
forceclip: true,
abnormalChains: { 40300: 30 },
race: {
8: { length: 1185 } // Popori
}
},
30: {
length: 900,
distance: 150,
forceclip: true
}
},
5: { // Dash
0: {
noWeapon: true,
fixedSpeed: 1,
length: 700
}
},
8: { // Overhand Strike
0: {
length: 3365,
distance: 170,
noInterrupt: ['1-0', '1-1', '1-2', 4, 6, 8, 10, '14-0', '14-1', 17, 25],
abnormals: {
300801: { skill: 250100 }
},
chains: {
1: 30,
2: 30,
3: 30,
9: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
24: 30
}
},
30: {
length: 1325,
distance: 169.65,
abnormals: {
300801: { skill: 250130 }
}
}
},
9: { // Leaping Strike
0: {
length: 2175,
distance: 250
}
},
12: { // Heart Thrust
0: {
length: 2315,
distance: 230,
abnormals: {
23060: { speed: 1.25 },
23061: { speed: 1.35 }
}
}
},
13: { // Stunning Backhand
0: {
length: 2125,
distance: 76.71
}
},
14: { // Distant Blade
'*': {
triggerAbnormal: { 23220: 3000 },
consumeAbnormalEnd: 23220
},
0: {
length: 600,
distance: 75
},
1: {
length: 600,
distance: 100.02,
},
2: {
length: 1500,
distance: 104.82
}
},
15: { // Startling Kick
0: {
length: 1475,
distance: -175,
forceClip: true,
glyphs: {
23060: { speed: 1.25 }
}
}
},
16: { // Fury Strike
0: {
length: 1000,
distance: 142.53
}
},
17: { // Headlong Rush
0: {
type: 'dash',
fixedSpeed: 1,
length: 1000,
distance: 413
}
},
18: { // Overpower
0: {
fixedSpeed: 1,
length: 200
}
},
19: { // Tenacity
'*': {
fixedSpeed: 1,
length: 700
}
},
20: { // In Cold Blood
0: {
fixedSpeed: 1,
length: 1185
}
},
23: { // Measured Slice
'*': {
distance: 190
},
0: {
length: 3685,
noInterrupt: [1, 2, 3, 4, 6, 9, 12, 13, 15, 17, 22],
chains: {
8: 30,
24: 30,
25: 30
}
},
30: { length: 1670 }
},
24: { // Eviscerate
'*': {
distance: 50
},
0: {
length: 1900,
noInterrupt: ['1-0', '1-1', '1-2', 4, 6, 14, 16, 17, 22, 24],
chains: {
1: 30,
2: 30,
3: 30,
8: 30,
9: 30,
12: 30,
13: 30,
15: 30,
25: 30
}
},
30: { length: 1500 }
},
25: { // Ultimate Overhand Strike
'*': {
distance: 170
},
0: { length: 3365 },
30: { length: 1300 }
}
},
3: { // Berserker
1: { // Combo Attack
'*': { noRetry: true },
0: {
length: 1112,
distance: 58.1,
race: {
1: { distance: 61.96 },
2: { distance: 54.87 },
3: { distance: 63.24 },
4: { distance: 27.72 },
5: {
length: 1082,
distance: 62.34
},
6: { distance: 55.69 },
7: { distance: 64.06 },
8: { distance: 48.89 },
9: { distance: 78.01 },
10: { distance: 44.22 }
}
},
1: {
length: 930,
distance: 23.28,
race: {
2: { distance: 26.02 },
3: { distance: 27.33 },
4: { distance: 25 },
5: {
length: 960,
distance: 24.52
},
6: { distance: 23.27 },
7: { distance: 16.05 },
8: { distance: 7.06 },
9: { distance: 21.05 },
10: { distance: 21.08 }
}
},
2: {
length: 1112,
distance: 22.83,
race: {
2: { distance: 23.3 },
3: { distance: 32.47 },
4: { distance: 25 },
5: { distance: 17.1 },
7: { distance: 42.59 },
8: { distance: 40.93 },
9: { distance: 31.84 },
10: { distance: 20.68 }
}
},
3: {
length: 1818,
distance: 69.27,
race: {
1: { distance: 70.41 },
2: {
length: 1636,
distance: 47.29
},
3: { distance: 55.25 },
4: {
length: 2000,
distance: 45
},
5: {
length: 2000,
distance: 61.6
},
6: { distance: 59.47 },
7: { distance: 51.11 },
8: { distance: 43.68 },
9: { distance: 54.28 },
10: { distance: 63.26 }
}
}
},
2: { // Axe Block
'*': {
type: 'holdInfinite',
consumeAbnormal: 401701
},
0: { fixedSpeed: 1 },
30: true,
31: { fixedSpeed: 1 }
},
3: { // Thunder Strike
'*': {
length: 1748,
abnormals: {
24170: { speed: 1.25 }
}
},
0: {
type: 'charging',
length: [650, 650, 650],
noInterrupt: [2],
overcharge: 450,
glyphs: {
24067: { chargeSpeed: 0.25 }
},
abnormals: {
24130: { chargeSpeed: 0.3 },
24170: { speed: 1.25 },
400500: { chargeSpeed: 0.2 },
400501: { chargeSpeed: 0.4 },
400508: { chargeSpeed: 0.4 },
401150: { chargeSpeed: 0.2 }
},
level: [
{ length: 800 },
{ length: [800, 800] },
{ length: [800, 800] }
],
noRetry: true
},
10: {
distance: 69.7,
rearCancelStartTime: 455,
race: {
1: { distance: 79.03 },
3: { distance: 72.79 },
4: { distance: 35 },
7: { distance: 85.74 },
8: { distance: 69.51 },
9: { distance: 87.27 },
10: { distance: 64.88 }
},
noRetry: true
},
11: {
distance: 69.7,
rearCancelStartTime: 455,
race: {
1: { distance: 79.03 },
3: { distance: 72.79 },
4: { distance: 35 },
7: { distance: 85.74 },
8: { distance: 69.51 },
9: { distance: 87.27 },
10: { distance: 64.88 }
},
noRetry: true
},
12: {
distance: 69.7,
rearCancelStartTime: 455,
race: {
1: { distance: 79.03 },
3: { distance: 72.79 },
4: { distance: 35 },
7: { distance: 85.74 },
8: { distance: 69.51 },
9: { distance: 87.27 },
10: { distance: 64.88 }
},
noRetry: true
},
13: {
distance: 69.7,
rearCancelStartTime: 455,
race: {
1: { distance: 79.03 },
3: { distance: 72.79 },
4: { distance: 35 },
7: { distance: 85.74 },
8: { distance: 69.51 },
9: { distance: 87.27 },
10: { distance: 64.88 }
}
}
},
4: { // Flatten
'*': {
length: 3112,
distance: 75,
glyphs: {
24008: { speed: 1.25 },
24050: { speed: 1.25 }
},
race: {
1: { distance: 78 },
2: { distance: 70.79 },
3: { distance: 90.6 },
4: { distance: 80 },
5: { distance: 69.01 },
7: { distance: 86.6 },
8: { distance: 73.34 },
9: { distance: 105.68 },
10: { distance: 70.23 }
}
},
0: {
noInterrupt: ['3-10', '3-11', '3-12', '3-13', 4, '10-10', '10-11', '10-12', 11, '10-13', '15-10', '15-11', '15-12', '15-13', '15-14', '18-10', '18-11', '18-12', '18-13', 24, 26, 28, 29, '32-0'],
abnormals: {
401400: { chain: 1 }
},
chains: {
6: 30,
25: 30,
31: 30,
32: 30
}
},
1: true,
30: {
length: 2337,
distance: 75,
abnormals: {
401400: { chain: 31 }
},
race: {
1: { distance: 78 },
2: { distance: 70.79 },
3: { distance: 90.6 },
4: { distance: 80 },
5: { distance: 69.01 },
7: { distance: 86.6 },
8: { distance: 73.34 },
9: { distance: 105.68 },
10: { distance: 70.23 }
}
},
31: {
length: 2337,
distance: 75,
race: {
1: { distance: 78 },
2: { distance: 70.79 },
3: { distance: 90.6 },
4: { distance: 80 },
5: { distance: 69.01 },
7: { distance: 86.6 },
8: { distance: 73.34 },
9: { distance: 105.68 },
10: { distance: 70.23 }
}
}
},
5: { // Dash
0: {
noWeapon: true,
fixedSpeed: 1,
length: 700
}
},
6: { // Staggering Strike
'*': {
length: 1294,
distance: 66.21,
race: {
1: { distance: 79.19 },
2: {
length: 1385,
distance: 82.34
},
3: { distance: 71.34 },
4: { distance: 50.07 },
7: { distance: 82.34 },
8: { distance: 53.41 },
9: {
length: 1264,
distance: 80.47
},
10: { distance: 70 }
},
hasChains: true,
noRetry: true
},
0: {
abnormalChains: { 401400: 30 }
},
30: true
},
7: { // Mocking Shout (removed)
'*': {
length: [308, 1079],
fixedSpeed: 1
},
0: true
},
8: { // Fiery Rage
'*': { fixedSpeed: 1 },
0: {
length: 1415,
abnormalChains: { 401400: 30 },
race: {
7: { length: 1445 }
}
},
1: { length: [455, 597] },
30: {
length: 1742,
race: {
7: { length: 1767 }
}
}
},
10: { // Cyclone
0: {
type: 'charging',
length: [650, 650, 650],
overcharge: 365,
canInstantCharge: true,
glyphs: {
24009: { chargeSpeed: 0.25 },
24052: { chargeSpeed: 0.25 },
24096: { chargeSpeed: 0.3 }
},
abnormals: {
24190: { chargeSpeed: 0.3 },
400500: { chargeSpeed: 0.2 },
400501: { chargeSpeed: 0.4 },
400508: { chargeSpeed: 0.4 },
401150: { chargeSpeed: 0.2 }
},
level: [
{ length: 800 },
{ length: [800, 800] },
{ length: [800, 800] }
],
noRetry: true
},
10: {
length: 1333,
distance: 50,
rearCancelStartTime: 300,
race: {
2: { length: 1400 },
3: { length: 1800 },
6: { length: 1366 }
},
noRetry: true
},
11: {
length: [366, 366, 1333],
distance: [33.33, 33.33, 50],
rearCancelStartTime: 300,
noRetry: true
},
12: {
length: [366, 366, 366, 366, 1333],
distance: [33.33, 33.33, 33.33, 33.33, 50],
rearCancelStartTime: 300,
noRetry: true
},
13: {
length: [366, 366, 366, 366, 1333],
distance: [33.33, 33.33, 33.33, 33.33, 50],
rearCancelStartTime: 300
}
},
11: { // Leaping Strike
0: {
length: 2191,
distance: 250,
race: {
8: { length: 2232 }
}
}
},
13: { // Retaliate
0: {
type: 'retaliate',
length: 1633,
noRetry: true
}
},
15: { // Vampiric Blow
'*': { length: 1933 },
0: {
type: 'charging',
length: [800, 800, 800],
noInterrupt: [2],
overchargeReleaseChain: 14,
abnormals: {
400500: { chargeSpeed: 0.2 },
400501: { chargeSpeed: 0.4 }
},
noRetry: true
},
10: {
distance: 69.7,
race: {
1: { distance: 79.03 },
3: { distance: 72.79 },
4: { distance: 35 },
7: { distance: 85.74 },
8: { distance: 69.51 },
9: { distance: 87.27 },
10: { distance: 64.88 }
},
noRetry: true
},
11: {
distance: 69.7,
race: {
1: { distance: 79.03 },
3: { distance: 72.79 },
4: { distance: 35 },
7: { distance: 85.74 },
8: { distance: 69.51 },
9: { distance: 87.27 },
10: { distance: 64.88 }
},
noRetry: true
},
12: {
distance: 69.7,
race: {
1: { distance: 79.03 },
3: { distance: 72.79 },
4: { distance: 35 },
7: { distance: 85.74 },
8: { distance: 69.51 },
9: { distance: 87.27 },
10: { distance: 64.88 }
},
noRetry: true
},
13: {
distance: 69.7,
race: {
1: { distance: 79.03 },
3: { distance: 72.79 },
4: { distance: 35 },
7: { distance: 85.74 },
8: { distance: 69.51 },
9: { distance: 87.27 },
10: { distance: 64.88 }
}
},
14: {
distance: 69.7,
race: {
1: { distance: 79.03 },
3: { distance: 72.79 },
4: { distance: 35 },
7: { distance: 85.74 },
8: { distance: 69.51 },
9: { distance: 87.27 },
10: { distance: 64.88 }
},
noRetry: true
}
},
16: { // Fearsome Shout
0: {
fixedSpeed: 1,
length: [700, 1433]
}
},
18: { // Lethal Strike
'*': {
distance: 168.11,
race: {
1: { distance: 188.37 },
3: { distance: 173.19 },
4: { distance: 145 },
7: { distance: 191.79 },
8: { distance: 240.4 },
9: { distance: 167.62 },
10: { distance: 158.11 }
}
},
0: {
length: 687,
noInterrupt: [1, 4, 6, 13, 18, 24, 25, 26, 27, 28, 29, 31, 34, 35, 36, 37],
chains: {
// Correct
/*3: 30,
10: 30,
11: 30,
15: 30*/
// Workaround: C_CANCEL_SKILL is not emulated properly for charging skills (TODO)
'3-10': 30,
'3-11': 30,
'3-12': 30,
'3-13': 30,
'10-10': 30,
'10-11': 30,
'10-12': 30,
'10-13': 30,
11: 30,
'15-10': 30,
'15-11': 30,
'15-12': 30,
'15-13': 30,
'15-14': 30
}
},
30: { length: 550 }
},
19: { // Triumphant Shout
'*': {
fixedSpeed: 1,
length: [500, 700]
},
0: true
},
20: { // Inescapable Doom
0: {
fixedSpeed: 1,
length: [600, 900]
}
},
21: { // Bloodlust
0: {
fixedSpeed: 1,
length: 700
}
},
24: { // Evasive Smash
'*': {
length: 1833,
distance: 168.11,
race: {
1: { distance: 188.37 },
3: { distance: 173.19 },
4: { distance: 145 },
7: { distance: 191.79 },
8: { distance: 240.4 },
9: {
length: 1633,
distance: 167.62
},
10: { distance: 158.11 }
}
},
0: {
type: 'storeCharge',
length: 1000,
distance: 150
},
5: { type: 'grantCharge' },
10: true,
11: true,
12: true,
13: true
},
25: { // Raze
'*': {
length: 1200,
distance: 96,
glyphs: {
24078: { speed: 1.25 }
}
},
0: {
noInterrupt: [4, 6, '6-30', 11, '18-10', '18-11', '18-12', '18-13', 24, 26, 28, 29, '32-0'],
abnormals: {
401400: { chain: 1 }
},
chains: {
1: 30,
3: 30,
10: 30,
'15-10': 30,
'15-11': 30,
'15-12': 30,
'15-13': 30,
'15-14': 30,
30: 30,
32: 30
}
},
1: true,
30: {
length: 960,
abnormals: {
401400: { chain: 31 }
}
},
31: { length: 960 }
},
26: { // Tackle
0: {
length: 1010,
distance: 80
}
},
27: { // Unbreakable
0: {
length: 2066,
noInterrupt: [1, '3-10', '3-11', '3-12', '3-13', 4, 6, '8-30', '10-10', '10-11', '10-12', '10-13', 11, 13, '15-10', '15-11', '15-12', '15-13', '15-14', 18, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33],
interruptibleWithAbnormal: { 401705: 33 },
abnormalChains: { 401705: 30 },
race: {
7: { length: 2099 }
}
},
30: { length: 1455 }
},
28: { // Intimiation
'*': {
length: 1566,
race: {
7: { length: 1599 }
}
},
0: true,
50: true
},
29: { // Evasive Roll
0: {
length: 909,
distance: 150,
forceClip: true,
noInterrupt: [29]
}
},
30: { // Axe Counter
'*': {
length: 655,
distance: 23.28,
noInterrupt: [1, '3-10', '3-11', '3-12', '3-13', 4, 6, '8-30', '10-10', '10-11', '10-12', '10-13', 11, 12, 13, '15-10', '15-11', '15-12', '15-13', '15-14', '18-10', '18-11', '18-12', '18-13', 24, 25, 26, 27, 28, 29, 30, 31, 32],
requiredBuff: 401402,
chains: { 2: 30 },
race: {
2: { distance: 26.02 },
3: { distance: 27.33 },
4: { distance: 25 },
5: {
length: 677,
distance: 24.52
},
6: { distance: 23.27 },
7: { distance: 16.05 },
8: {
length: 1189,
distance: 240.4
},
9: { distance: 21.05 },
10: { distance: 21.08 }
}
},
0: true,
30: true
},
31: { // Overwhelm
0: {
type: 'dash',
fixedSpeed: 1,
length: 1115,
distance: 467.88
},
1: {
length: 1511,
distance: 168.11,
race: {
1: { distance: 188.37 },
3: { distance: 173.19 },
4: { distance: 145 },
7: { distance: 191.79 },
8: { distance: 240.4 },
9: {
length: 1344,
distance: 167.62
},
10: { distance: 158.11 }
}
}
},
32: { // Punishing Strike
0: {
length: 772,
distance: 34.93,
race: {
2: { distance: 39.03 },
3: { distance: 40.99 },
4: { distance: 37.5 },
5: {
length: 797,
distance: 36.78
},
6: { distance: 34.91 },
7: { distance: 24.08 },
8: {
length: 925,
distance: 61.39
},
9: { distance: 31.57 },
10: { distance: 31.63 }
}
},
1: {
length: 800,
distance: 134.49,
race: {
1: { distance: 150.7 },
3: { distance: 138.55 },
4: { distance: 116 },
7: { distance: 153.43 },
8: { distance: 192.32 },
9: { distance: 134.1 },
10: { distance: 126.49 }
}
}
},
33: { // Unleash
0: { length: [700, 1500, 1766] }
},
34: { // Unleash: Dexter
'*': {
length: [600, 833, 833],
distance: [0, 25, 0],
requiredBuff: 401705,
abnormals: {
401706: { speed: 1.2 },
401716: { chain: 31 }
},
noRetry: true
},
0: {
noInterrupt: [34, 36],
chains: {
33: 30,
35: 30,
37: 30
}
},
1: true,
30: {
length: [833, 833],
distance: [25, 0]
},
31: {
length: [833, 833],
distance: [25, 0]
}
},
35: { // Unleash: Sinister
'*': {
length: [1133, 833],
distance: [180, 0],
requiredBuff: 401705,
abnormals: {
401707: { speed: 1.2 },
401717: { chain: 31 }
},
noRetry: true
},
0: {
noInterrupt: [35, 36, 37],
chains: {
33: 1,
34: 30
}
},
1: true,
30: {
length: [641, 833],
distance: [25, 0]
},
31: {
length: [641, 833],
distance: [25, 0]
}
},
36: { // Unleash: Rampage
'*': {
length: 1589,
distance: 35,
requiredBuff: 401705,
abnormals: {
401708: { speed: 1.2 },
401718: { chain: 31 }
},
noRetry: true
},
0: {
length: 2714,
noInterrupt: [37],
chains: {
34: 30,
35: 30,
36: 30
}
},
30: true,
31: true
},
37: { // Unleash: Beast Fury
'*': {
length: [611, 694, 722, 396, 1094],
distance: [114.55, 131.66, 137.36, 8.55, 114.74],
noInterrupt: [37],
requiredBuff: 401705,
race: {
2: { distance: [120, 137.14, 142.86, 8.55, 114.74] },
3: { distance: [120, 137.14, 142.86, 8.55, 114.74] },
9: { distance: [120, 137.14, 142.86, 8.55, 114.74] }
}
},
0: {
chains: {
33: 30,
34: 30,
35: 30,
36: 30
}
},
30: true
}
},
4: { // Sorcerer
1: { // Fireball
0: { length: 725 }
},
2: { // Frost Sphere
0: {
length: 800,
race: {
4: { length: 1250 }, // Male Aman
9: { length: 1000 }, // Elin
10: { length: 900 } // Baraka
}
}
},
3: { // Lightning Trap
0: {
length: 1300,
abnormals: {
25090: { speed: 1.4 }
}
}
},
4: { // Arcane Pulse
'*': {
length: 1293,
race: {
9: { length: 991 }
},
noRetry: true
},
0: {
type: 'charging',
length: [800, 800],
abnormals: {
25140: { chargeSpeed: 0.3 }
}
},
10: {
abnormals: {
500150: { skill: 330110 },
501650: { skill: 330150 }
}
},
11: {
abnormals: {
500150: { skill: 330111 },
501650: { skill: 330150 }
}
},
12: {
abnormals: {
500150: { skill: 330112 },
501650: { skill: 330150 }
}
}
},
5: { // Mana Infusion
0: { length: 4600 }
},
6: { // Meteor Strike
0: {
length: 3925,
glyphs: {
25003: { speed: 1.17 },
25069: { speed: 1.25 }
},
abnormals: {
25100: { speed: 1.25 },
500150: { skill: 320100 },
501650: { skill: 320150 }
},
race: {
9: { length: 3700 } // Elin
}
}
},
7: { // Backstep
0: {
length: 650,
distance: -200,
forceClip: true
}
},
8: { // Flame Pillar
0: {
length: 1200,
abnormals: {
25070: { speed: 1.25 }
}
}
},
10: { // Mana Barrier
0: { length: 625 }
},
11: { // Lightning Strike
0: {
length: 840,
checkReset: true,
race: {
9: { length: 800 } // Elin
}
}
},
12: { // Void Pulse
0: { length: 925 }
},
13: { // Mindblast
0: {
length: 2325,
glyphs: {
25048: { speed: 1.3 }
},
abnormals: {
25110: { speed: 1.4 }
}
}
},
16: { // Painblast
0: {
length: 1580,
race: {
9: { length: 1330 } // Elin
}
}
},
17: { // Painful Trap
0: { length: 1100 }
},
18: { // Glacial Retreat
0: {
length: 1100,
distance: -187.5,
forceClip: true
}
},
19: { // Mana Siphon
'*': {
length: 900,
noRetry: true
},
0: {
type: 'charging',
length: [1005, 1005],
autoRelease: 0
},
10: true,
11: true,
12: true
},
20: { // Flaming Barrage
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
length: 1500,
glyphs: {
25001: { speed: 1.3 },
25096: { speed: 1.4 }
},
abnormals: {
25060: { speed: 1.25 }
}
}
},
21: { // Nerve Exhaustion
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: [300, 1200]
}
},
22: { // Burning Breath
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: [300, 1200]
}
},
23: { // Mana Volley
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: [325, 875]
}
},
25: { // Time Gyre
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: 700
}
},
26: { // Teleport Jaunt
0: {
type: 'teleport',
length: [200, 260],
distance: [0, 333],
noInterrupt: [26],
teleportStage: 1,
noRetry: true
}
},
27: { // Hailstorm
0: { length: 950 }
},
30: { // Nova
0: {
length: 2850,
glyphs: {
25092: { speed: 1.3 }
}
}
},
31: { // Warp Barrier
'*': { length: 475 },
0: true,
10: true,
20: true
},
32: { // Meteor Shower
'*': {
length: 6775,
glyphs: {
25003: { speed: 1.17 },
25069: { speed: 1.25 }
},
noRetry: true,
race: {
9: { length: 6475 } // Elin
}
},
0: true,
50: { length: 3700 }
},
33: { // Arcane Pulse (Mana Boost)
'*': {
length: 1275,
noRetry: true,
race: {
9: { length: 1015 } // Elin
}
},
10: true,
11: true,
12: true,
50: true
},
34: { // Mana Boost
0: { length: 750 }
}
},
5: { // Archer
1: { // Arrow
0: { length: 400 }
},
2: { // Arrow Volley
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
length: 1225
}
},
3: { // Radiant Arrow
'*': {
length: 1750,
noRetry: true
},
0: {
type: 'charging',
length: [600, 600, 600],
abnormals: {
26180: { chargeSpeed: 0.3 },
601450: { chargeSpeed: 0.5 }
}
},
10: { distance: -100 }, // Cast F. - TODO
11: { distance: -100 },
12: { distance: -100 },
13: { distance: -100 }
},
4: { // Penetrating Arrow
'*': {
length: 1300,
noRetry: true
},
0: {
type: 'charging',
length: [800, 800, 800],
abnormals: {
26160: { chargeSpeed: 0.3 },
26170: { chargeSpeed: 0.3 },
26171: { chargeSpeed: 0.4 },
26190: { chargeSpeed: 0.3 },
601450: { chargeSpeed: 0.5 }
}
},
10: { distance: -50 }, // Cast F. - TODO
11: { distance: -50 },
12: { distance: -50 },
13: { distance: -50 }
},
5: { // Rain of Arrows
0: {
length: 3150,
glyphs: {
26077: { speed: 1.4 }
},
abnormals: {
902: { speed: 1.15 },
911: { speed: 1.15 },
912: { speed: 1.15 },
913: { speed: 1.15 },
916: { speed: 1.15 },
917: { speed: 1.15 },
920: { speed: 1.225 },
921: { speed: 1.225 },
922: { speed: 1.225 },
999010000: { speed: 1.15 }
}
}
},
6: { // Backstep
0: {
length: 650,
distance: -200,
forceClip: true
}
},
7: { // Feign Death
0: {
length: [2950, 54525, 1675],
distance: [-114.05, 0, 0]
}
},
8: { // Rapid Fire
'*': { noRetry: true },
0: {
length: 425,
noInterrupt: [6]
},
1: { length: 600 },
2: { length: 700 },
3: { length: 700 },
4: { length: 700 },
5: { length: 700 },
6: { length: 1235 }
},
9: { // Slow Trap
0: { length: 1150 }
},
10: { // Stunning Trap
0: { length: 1150 }
},
12: { // Velik's Mark
0: { length: 200 }
},
15: { // Incendiary Trap
0: { length: 1150 }
},
16: { // Breakaway Bolt
0: {
length: 1325,
distance: -250,
forceClip: true
}
},
17: { // Web Arrow
0: { length: 525 }
},
18: { // Close Quarters
0: {
length: 300,
distance: 64.46,
race: {
1: {
length: 333,
distance: 48.1
},
2: { distance: 57.88 },
3: { distance: 63.42 },
4: { length: 333 },
6: { distance: 60.95 },
7: {
length: 333,
distance: 48
},
8: {
length: 333,
distance: 89.8
},
9: { distance: 54.68 },
10: {
length: 333,
distance: 54.46
}
}
},
1: {
length: 1200,
distance: 73.69,
race: {
1: { distance: 87.29 },
2: { distance: 79.11 },
3: { distance: 54.45 },
4: { distance: 66.18 },
5: { distance: 26.65 },
6: { distance: 77.2 },
7: { distance: 66 },
8: { distance: 48.35 },
9: { distance: 56.9 },
10: { distance: 83.69 }
}
}
},
19: { // Poison Arrow
0: { length: 1125 }
},
20: { // Restraining Arrow
0: { length: 525 }
},
22: { // Sequential Fire
0: {
length: 425,
requiredBuff: 600200,
noRetry: true
}
},
25: { // Incendiary Trap Arrow
0: { length: 1200 }
},
29: { // Thunderbolt
0: {
length: 3750,
glyphs: {
26089: { speed: 1.3 },
26102: { speed: 1.3 }
}
}
},
31: { // Tenacity
0: {
fixedSpeed: 1,
length: [500, 700]
}
},
32: { // Find Weakness
0: {
fixedSpeed: 1,
length: 200
}
},
33: { // Chase
0: {
type: 'dash',
fixedSpeed: 1,
length: 1000,
distance: 413
}
}
},
6: { // Priest
1: { // Divine Radiance
0: { length: 619 },
1: { length: 650 },
2: { length: 684 },
3: { length: 722 }
},
2: { // Regeneration Circle
0: {
length: 2149,
abnormals: {
902: { speed: 1.15 },
911: { speed: 1.15 },
912: { speed: 1.15 },
913: { speed: 1.15 },
916: { speed: 1.15 },
917: { speed: 1.15 },
920: { speed: 1.225 },
921: { speed: 1.225 },
922: { speed: 1.225 },
999010000: { speed: 1.15 }
},
race: {
10: { length: 2774 }
}
}
},
3: { // Healing Circle
0: {
length: 1763,
chains: {
19: 30,
26: 30,
38: 30
}
},
30: { length: 1477 }
},
5: { // Blessing of Shakan
0: { length: 1294 }
},
6: { // Arise
0: { length: 839 }
},
8: { // Mana Infusion
0: {
length: 4595,
glyphs: {
28044: { speed: 1.25 }
},
race: {
0: { length: 4625 }
}
}
},
10: { // Purifying Circle
0: { length: 1294 }
},
11: { // Metamorphic Blast
'*': { length: 839 },
0: true,
1: true,
2: true
},
12: { // Resurrect
0: {
length: 5900,
glyphs: {
28045: { speed: 1.3 }
},
abnormals: {
902: { speed: 1.15 },
911: { speed: 1.15 },
912: { speed: 1.15 },
913: { speed: 1.15 },
916: { speed: 1.15 },
917: { speed: 1.15 },
920: { speed: 1.225 },
921: { speed: 1.225 },
922: { speed: 1.225 },
999010000: { speed: 1.15 }
}
}
},
14: { // Summon: Party
0: {
length: 4505,
race: {
0: { length: 4535 }
}
}
},
16: { // Shocking Implosion
'*': { length: 1718 },
0: {
chains: {
11: 30,
27: 30
}
},
10: {
chains: {
11: 11,
27: 11
}
},
11: { length: 1438 },
20: {
chains: {
11: 21,
27: 21
}
},
21: { length: 1438 },
30: { length: 1438 }
},
17: { // Prayer of Peace
0: {
length: [925, 925, 850],
glyphs: {
28021: { speed: 2 }
}
}
},
18: { // Heal Thyself
0: {
noWeapon: true,
length: 1266
}
},
19: { // Focus Heal
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 54440
},
10: {
type: 'lockonCast',
length: 1950
}
},
22: { // Kaia's Shield
0: { length: 667 }
},
23: { // Blessing of Balder
0: { length: 1300 }
},
26: { // Fiery Escape
0: {
length: 1125,
distance: -250.5,
forceClip: true
}
},
27: { // Final Reprisal
'*': {
length: 2933,
noInterrupt: [27],
race: {
9: { length: 3333 }
}
},
0: {
chains: {
11: 30,
16: 30,
29: 30,
40: 30
}
},
10: {
chains: {
11: 11,
16: 11,
29: 11,
40: 11
}
},
11: {
length: 1113,
race: {
9: { length: 1273 }
}
},
20: {
chains: {
11: 21,
16: 21,
29: 21,
40: 21
}
},
21: {
length: 1113,
race: {
9: { length: 1273 }
}
},
30: {
length: 1113,
race: {
9: { length: 1273 }
}
}
},
28: { // Mana Charge / Words of Vitality
'*': {
length: 827,
noRetry: true,
level: {
1: { length: 700 }
}
},
0: {
type: 'charging',
length: [800, 1600],
autoRelease: 0,
glyphs: {
28031: { chargeSpeed: 0.25 }
},
level: {
1: {
length: [833, 833, 833], // TODO: DC says 900, 900, 900
autoRelease: 3200
}
}
},
10: true,
11: true,
12: true,
13: true
},
29: { // Triple Nemesis
0: { length: 800 },
1: { length: 800 },
2: { length: 1250 }
},
30: { // Plague of Exhaustion
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: 1430
}
},
31: { // Guardian Sanctuary
0: {
fixedSpeed: 1,
length: 700
}
},
32: { // Divine Respite
0: {
noWeapon: true,
fixedSpeed: 1,
length: [1300, 900]
}
},
33: { // Ishara's Lulliby
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: [300, 1430]
}
},
34: { // Restorative Burst
0: { length: 1433 }
},
35: { // Energy Stars
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: 1430
}
},
37: { // Healing Immersion
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900,
noInterrupt: [37],
partyOnly: true
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: 1430,
noInterrupt: ['37-10']
}
},
38: { // Backstep
0: {
length: 650,
distance: -200,
forceClip: true
}
},
39: { // Grace of Resurrection
0: { length: 5904 }
},
40: { // Zenobia's Vortex
'*': { length: 1071 },
0: true,
10: true,
20: true
},
41: { // Divine Intervention / Divine Vitality
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 54445,
partyOnly: true
},
10: {
type: 'lockonCast',
length: 925
}
},
42: { // Holy Burst
'*': { length: 800 },
20: true,
30: true
},
43: { // Words of Judgement
0: { length: 1417 },
50: { length: 200 }
}
},
7: { // Mystic
1: { // Sharan Bolt
'*': { length: 689 },
0: true,
1: true,
2: true,
3: true
},
2: { // Corruption Ring
0: {
type: 'hold',
length: 10869,
chainOnRelease: 11
},
11: { length: 839 },
12: {
length: 1294,
race: {
1: { length: 1224 }
}
}
},
4: { // Ancient Binding (removed)
0: { length: 1294 }
},
5: { // Titanic Favor
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 59900
},
10: {
type: 'lockonCast',
length: 1950
}
},
6: { // Shara's Lash
0: { length: 1294 }
},
8: { // Metamorphic Blast
0: {
length: 839,
noInterrupt: [1, 2, 6, 17],
checkReset: true,
chains: {
8: 30,
23: 30
}
},
30: { length: 839 }
},
9: { // Arun's Cleansing
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 59900
},
10: {
type: 'lockonCast',
length: 800
}
},
10: { // Resurrect
0: {
length: 8066,
glyphs: {
27049: { speed: 1.2 },
27079: { speed: 1.2 }
},
abnormals: {
902: { speed: 1.25 },
911: { speed: 1.25 },
912: { speed: 1.25 },
913: { speed: 1.25 },
916: { speed: 1.25 },
917: { speed: 1.25 },
920: { speed: 1.375 },
921: { speed: 1.375 },
922: { speed: 1.375 },
999010000: { speed: 1.25 }
}
}
},
11: { // Summon: Party
0: { length: 4445 }
},
12: { // Vow of Rebirth
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 59900,
partyOnly: true
},
10: {
type: 'lockonCast',
length: 1950,
race: {
4: { length: 939 }
}
}
},
13: { // Aura of the Merciless
'*': { length: 1294 },
0: true,
50: true
},
14: { // Aura of the Swift
'*': { length: 1294 },
0: true,
50: true
},
15: { // Aura of the Unyielding
'*': { length: 1294 },
0: true,
50: true
},
16: { // Aura of the Tenacious
'*': { length: 1294 },
0: true,
50: true
},
17: { // Teleport Jaunt
0: {
type: 'teleport',
length: [222, 255],
distance: [0, 333],
noInterrupt: [17],
teleportStage: 1,
cooldownEnd: 200,
noRetry: true
}
},
18: { // Arun's Vitae
'*': { noRetry: true },
0: {
type: 'charging',
length: 1240,
chargeLevels: [10, 10],
autoRelease: 10,
abnormals: {
27070: { chargeSpeed: 0.25 },
27080: { chargeSpeed: 0.25 }
}
},
10: {
length: 800,
race: {
9: { length: 833 }
}
}
},
21: { // Retaliate
0: {
type: 'retaliate',
length: 1633,
noRetry: true
}
},
22: { // Arun's Tears
'*': { noRetry: true },
0: {
type: 'charging',
length: 1240,
chargeLevels: [10, 10],
autoRelease: 10,
abnormals: {
27100: { chargeSpeed: 0.25 }
}
},
10: {
length: 800,
race: {
9: { length: 833 }
}
}
},
23: { // Metmorphic Smite
0: {
length: 1440,
noInterrupt: [1, 2, 6, 17, 23],
chains: { 8: 30 }
},
30: { length: 1108 }
},
24: { // Volley of Curses
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: [533, 667]
}
},
25: { // Thrall of Protection
'*': {
fixedSpeed: 1,
length: [1000, 1700],
cooldownEnd: 300
},
0: true,
10: true,
30: { length: [500, 700] }
},
27: { // Thrall of Life
'*': {
fixedSpeed: 1,
length: [229, 438],
cooldownEnd: 300
},
0: true,
10: true,
30: { length: [500, 700] }
},
28: { // Sonorous Dreams
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: 1400
}
},
29: { // Regression
fixedSpeed: 1,
length: [500, 700]
},
30: { // Curse of Exhaustion
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: 1400
}
},
31: { // Curse of Confusion
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: 1400
}
},
32: { // Mire
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
fixedSpeed: 1,
length: 1400
}
},
33: { // Thrall of Vengeance
'*': {
fixedSpeed: 1,
length: [267, 511],
cooldownEnd: 300
},
0: true,
10: true,
30: { length: [500, 700] }
},
34: { // Thrall of Wrath
'*': {
fixedSpeed: 1,
length: [1000, 1700],
cooldownEnd: 300
},
0: true,
10: true,
30: { length: [500, 1200] }
},
35: { // Command: Attack
0: {
fixedSpeed: 1,
length: 700
}
},
36: { // Command: Follow
0: {
fixedSpeed: 1,
length: 700
}
},
37: { // Warding Totem
0: { length: 1900 }
},
41: { // Contagion
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 4900
},
10: {
type: 'lockonCast',
length: 1020
}
},
42: { // Boomerang Pulse
0: {
length: 545,
noInterrupt: [42],
cooldownEnd: 300
}
},
43: { // Unsummon Thrall
0: { length: 575 }
},
44: { // Mass Teleport
0: {
type: 'teleport',
length: [222, 255],
distance: [0, 333],
noInterrupt: [17],
teleportStage: 1,
cooldownEnd: 200,
noRetry: true
}
},
45: { // Thrall Augmentation
'*': { length: 91 },
0: true,
50: true
},
47: { // Arunic Release
0: { length: 1060 }
},
48: { // Thrall Lord
0: {
fixedSpeed: 1,
length: 4050
}
}
},
8: { // Reaper
'*': { consumeAbnormal: [10151020, 10151021, 10151022, 10151023, 10151040, 10151041, 10151042] },
1: { // Spiral Barrage
'*': {
length: 1000,
distance: 48,
inPlace: {
movement: [{
duration: 766,
speed: 1,
unk: 1,
distance: 0
},
{
duration: 346,
speed: 1,
unk: 1,
distance: 0
}],
distance: 0
},
noInterrupt: [3, 4, 12, 20],
triggerAbnormal: { 10151020: 2000 },
abnormals: {
10151020: { chain: 2 },
10151021: { chain: 3 },
10151022: { chain: 4 },
10151023: { chain: 5 }
},
chains: { 1: 1 },
noRetry: true
},
0: true,
1: true,
2: {
length: 1200,
distance: 42,
inPlace: {
movement: [{
duration: 950,
speed: 1,
unk: 1,
distance: 0
},
{
duration: 346,
speed: 1,
unk: 1,
distance: 0
}],
distance: 0
},
triggerAbnormal: { 10151021: 2000 }
},
3: {
length: 860,
distance: 56,
inPlace: {
movement: [{
duration: 616,
speed: 1,
unk: 1,
distance: 0
},
{
duration: 346,
speed: 1,
unk: 1,
distance: 0
}],
distance: 0
},
triggerAbnormal: { 10151022: 1800 }
},
4: {
length: 1400,
distance: 60,
inPlace: {
movement: [{
duration: 1150,
speed: 1,
unk: 1,
distance: 0
},
{
duration: 346,
speed: 1,
unk: 1,
distance: 0
}],
distance: 0
},
triggerAbnormal: { 10151023: 2000 }
},
5: {
length: 1900,
distance: 91,
inPlace: {
movement: [{
duration: 2016,
speed: 1,
unk: 1,
distance: 0
}],
distance: 0
}
}
},
3: { // Double Shear
'*': {
length: 2025,
noInterrupt: ['1-0', '1-2', 3, 4, 12, 20],
abnormals: {
29030: { speed: 1.25 }
},
chains: {
1: 30,
5: 30,
6: 30,
8: 30,
9: 30,
10: 30,
11: 30
}
},
0: true,
30: true
},
4: { // Sundering Strike
'*': {
noInterrupt: [1, 4, 8, 9, 10, 11, 12, 20],
chains: {
1: null,
3: null,
4: null,
5: null,
6: null,
8: null,
9: null,
10: null,
11: null,
12: null
},
noRetry: true
},
0: {
length: [1175, 1750, 1025],
distance: [0, 100, 0],
inPlace: {
movement: [
[],
[{
duration: 1757,
speed: 1,
unk: 1,
distance: 0
}],
[]
],
distance: [0, 0, 0]
}
},
30: {
length: [1750, 1025],
distance: [100, 0],
inPlace: {
movement: [
[{
duration: 1757,
speed: 1,
unk: 1,
distance: 0
}],
[]
],
distance: [0, 0]
}
}
},
5: { // Grim Strike
'*': {
distance: [120, 0],
inPlace: {
movement: [
[{
duration: 2416,
speed: 1,
unk: 1,
distance: 0
}],
[{
duration: 1065,
speed: 1,
unk: 1,
distance: 0
}]
],
distance: [0, 0]
}
},
0: {
length: [2400, 975],
noInterrupt: ['1-0', '1-2', 4, 12, 20],
chains: {
1: 30,
3: 30,
5: 30,
6: 30,
8: 30,
9: 30,
10: 30,
11: 30
}
},
30: { length: [1450, 975] }
},
6: { // Death Spiral
'*': {
length: 1250,
abnormals: {
10151131: { chain: 31 }
},
chains: {
1: 30,
3: 30,
4: 30,
5: 30,
6: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30
},
noRetry: true
},
0: true,
30: true,
31: true
},
8: { // Whipsaw
'*': {
length: 2500,
noInterrupt: [4, 5, 6, 8, 9, 11, 12, 20],
chains: {
1: 30,
3: 30,
10: 30
}
},
0: true,
30: true
},
9: { // Smite
0: {
length: 1725,
distance: 168,
inPlace: {
movement: [{
duration: 1832,
speed: 1,
unk: 1,
distance: 0
}],
distance: 0
},
noInterrupt: [1, 3, 4, 5, 6, 8, 9, 10, 11, 12, 20]
}
},
10: { // Pendulum Strike
'*': {
length: 1000,
distance: -200,
chains: {
1: 30,
3: 30,
4: 30,
5: 30,
6: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30
}
},
0: true,
30: true
},
11: { // Shadow Lash
'*': {
length: 1250,
noRetry: true
},
0: {
length: 2150,
triggerAbnormal: { 10151040: 2000 },
abnormals: {
10151040: { chain: 1 },
10151041: { chain: 2 },
10151042: { chain: 3 }
}
},
1: { triggerAbnormal: { 10151041: 2000 } },
2: { triggerAbnormal: { 10151042: 2000 } },
3: true
},
12: { // Shadow Burst
'*': {
glyphs: {
29026: { speed: 1.25 }
}
},
0: {
length: 3225,
noInterrupt: [1, 3, 4, 5, 6, 8, 9, 10, 11, 20],
chains: {
12: 1
}
},
1: {
length: 2025
}
},
15: { // Retribution
0: {
fixedSpeed: 1,
length: 1575
}
},
16: { // Shadow Reaping
0: {
fixedSpeed: 1,
length: 775
}
},
18: { // Shrouded Escape
0: {
length: 850,
distance: 150
}
},
/*20: { // Cable Step
0: {
type: 'dynamicDistance',
length: 1250
}
},*/
40: { // Shadow Step
'*': {
length: 700,
distance: 180,
forceClip: true,
abnormalChains: { 10151000: 30 }
},
0: true,
30: true
}
},
9: { // Gunner
'*': { consumeAbnormal: [10152010, 10152011] },
1: { // Blast
'*': {
fixedSpeed: 1,
length: 1195,
noInterrupt: [1],
projectiles: [20],
triggerAbnormal: { 10152011: 3100 }
},
1: true,
2: { noRetry: true },
20: {
type: 'userProjectile',
flyingSpeed: 800,
flyingDistance: 500,
explodeOnHit: true
}
},
2: { // Bombardment
'*': { noRetry: true },
0: {
type: 'lockon',
fixedSpeed: 1,
length: 59900
},
1: {
type: 'lockonCast',
length: 3000,
glyphs: {
30004: { speed: 1.25 }
}
}
},
3: { // Scattershot
'*': {
length: 1725,
distance: -108,
noInterrupt: [3],
glyphs: {
30007: {
movement: [
{
duration: 394,
speed: 1,
unk: 1,
distance: 0
},
{
duration: 111,
speed: 1,
unk: 1,
distance: 0
},
{
duration: 1333,
speed: 1.8,
unk: 1,
distance: 64.8
}
],
distance: 0.6
}
},
chains: {
'2-1': 30,
4: 30,
'7-3': 30,
'9-11': 30,
10: 30,
11: 30,
13: 30,
15: 30,
19: 30,
40: 30
}
},
1: true,
2: true,
30: true
},
4: { // Point Blank
'*': {
length: 1525,
distance: 137.88,
noInterrupt: ['4-3', '4-4'],
chains: {
'2-1': 30,
3: 30,
4: 4,
'7-3': 30,
'9-10': 30,
'9-11': 30,
10: 30,
11: 30,
13: 30,
15: 30,
19: 30,
40: 30
}
},
1: {
noInterrupt: [4],
noRetry: true
},
2: { noRetry: true },
3: {
length: 1195,
distance: -198.53
},
4: {
length: 1195,
distance: -198.53
},
30: { noRetry: true }
},
5: { // Burst Fire
'*':{ noInterrupt: ['9-0'] },
0: {
length: 850,
noRetry: true
},
1: {
fixedSpeed: 1,
length: 122,
stamina: 75,
instantStamina: true,
glyphs: {
30046: { stamina: -10 }
},
level: [
{ stamina: 50 },
{ stamina: 55 },
{ stamina: 60 },
{ stamina: 65 }
]
}
},
6: { // Time Bomb
'*': {
fixedSpeed: 1,
length: 1000,
projectiles: [20],
triggerAbnormal: {
10152010: 3100,
10152084: 4100
}
},
1: true,
2: true,
20: {
type: 'userProjectile',
flyingSpeed: 800
}
},
7: { // Arcane Barrage
'*': { length: 1525 },
1: {
fixedSpeed: 1,
noInterrupt: [7],
triggerAbnormal: { 10152010: 3100 },
noRetry: true
},
2: {
fixedSpeed: 1,
noInterrupt: [7],
triggerAbnormal: { 10152010: 3100 },
noRetry: true
},
3: { length: 1200 }
},
9: { // Mana Missiles
'*': { length: 1250 },
0: {
type: 'charging',
length: 1200,
autoRelease: 0
},
10: {
distance: -50,
projectiles: [21, 22],
noRetry: true
},
11: {
distance: -100,
projectiles: [21, 22, 23, 24, 25],
noRetry: true
},
21: {
type: 'userProjectile',
flyingSpeed: 600,
flyingDistance: 750
},
22: {
type: 'userProjectile',
flyingSpeed: 500,
flyingDistance: 750
},
23: {
type: 'userProjectile',
flyingSpeed: 400,
flyingDistance: 750
},
24: {
type: 'userProjectile',
flyingSpeed: 350,
flyingDistance: 750
},
25: {
type: 'userProjectile',
flyingSpeed: 300,
flyingDistance: 750
}
},
10: { // Arc Bomb
'*': {
length: 1325,
projectiles: [20],
chains: {
'2-1': null,
3: null,
4: null,
'7-3': null,
'9-10': null,
'9-11': null,
10: null,
11: null,
13: null,
15: null,
19: null,
40: null
},
noRetry: true
},
1: true,
2: true,
20: {
type: 'userProjectile',
delay: 450,
flyingSpeed: 700,
flyingDistance: 350,
level: [
{ flyingSpeed: 800 },
{ flyingSpeed: 800 },
{ flyingSpeed: 800 },
{ flyingSpeed: 800 },
{ flyingSpeed: 800 },
{ flyingSpeed: 800 },
{ flyingSpeed: 800 },
{ flyingSpeed: 800 }
]
},
// TODO: Chain projectiles
/*21: {
type: 'userProjectile',
flyingSpeed: 300,
flyingDistance: 100
},
22: {
type: 'userProjectile',
flyingSpeed: 300,
flyingDistance: 75
},
23: {
type: 'userProjectile',
flyingSpeed: 300,
flyingDistance: 50
},
24: {
type: 'projectile',
length: 1000
},*/
30: true
},
11: { // Rocket Jump
'*': {
length: 1400,
distance: 415.45,
noInterrupt: [15],
chains: {
'2-1': 30,
3: 30,
4: 30,
'7-3': 30,
'9-10': 30,
'9-11': 30,
10: 30,
11: 30,
13: 30,
15: 30,
19: 30,
40: 31
}
},
1: true,
2: true,
30: true,
31: {
length: 1675,
distance: 506.27,
race: {
7: { // Female Castanic
length: 1700,
distance: 503.64
}
}
}
},
13: { // Balder's Vengeance
'*': {
length: 5800,
distance: -269.09,
noInterrupt: [13],
chains: {
'2-1': null,
3: null,
4: null,
'7-3': null,
'9-10': null,
'9-11': null,
10: null,
11: null,
13: null,
15: null,
19: null,
40: null
},
noRetry: true
},
1: true,
2: true,
30: true
},
15: { // Replenishment
'*': {
fixedSpeed: 1,
length: 1325,
noInterrupt: [15],
chains: {
'2-1': 30,
3: 30,
4: 30,
'7-3': 30,
'9-10': 30,
'9-11': 30,
10: 30,
11: 30,
13: 30,
15: 30,
19: 30,
40: 30
}
},
1: true,
2: true,
30: true
},
18: { // HB
'*': {
fixedSpeed: 1,
length: 1430
},
1: true,
2: true
},
19: { // ST
'*': {
length: 1325,
projectiles: [20],
chains: {
'2-1': null,
3: null,
4: null,
'7-3': null,
'9-10': null,
'9-11': null,
10: null,
11: null,
13: null,
15: null,
19: null,
40: null
},
noRetry: true
},
1: true,
2: true,
20: {
type: 'userProjectile',
delay: 350,
flyingSpeed: 700,
flyingDistance: 450
},
// TODO: Chain projectiles
/*21: {
type: 'projectile',
length: 5000
},*/
30: true
},
20: { // Retaliate
0: {
type: 'retaliate',
length: 1485,
noRetry: true
}
},
40: { // Rolling Reload
0: {
fixedSpeed: 1,
length: 935,
distance: 172.5,
triggerAbnormal: {
10152010: 3100,
10152012: 3100
},
forceClip: true
}
}
},
10: { // Brawler
1: { // Punch
'*': {
length: 1579,
distance: 70.2,
triggerAbnormal: { 10153060: 3000 },
consumeAbnormalEnd: 10153060,
noInterrupt: ['1-3'],
chains: {
'1-0': 1,
'1-1': 2,
'1-2': 3,
'1-30': 1,
'1-31': 32,
'1-32': 2,
'2-2': 31,
'2-3': 31,
2: 30,
'3-1': 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
13: 30,
14: 30,
15: 30,
16: 30,
17: 30,
18: 30,
19: 30,
20: 30,
21: 30,
40: 30
},
noRetry: true,
race: {
1: { distance: 71.28 }
}
},
0: true,
1: {
length: 1277,
distance: 67.57,
race: {
1: { distance: 68.63 }
}
},
2: {
length: 933,
distance: 50.7
},
3: {
length: 1733,
distance: 121
},
30: true,
31: true,
32: {
length: 1277,
distance: 67.57,
race: {
1: { distance: 68.63 }
}
}
},
2: { // Counter
'*': {
hasChains: true,
noRetry: true
},
1: {
length: 1200,
distance: 138.39,
triggerAbnormal: { 10153001: 0x7fffffff },
consumeAbnormalEnd: 10153001,
race: {
1: { distance: 139.97 }
}
},
2: {
length: 1818,
distance: 84,
triggerAbnormal: { 10153002: 0x7fffffff },
consumeAbnormalEnd: 10153002
},
3: {
length: 1932,
distance: 130.65,
triggerAbnormal: { 10153003: 0x7fffffff },
consumeAbnormalEnd: 10153003,
race: {
1: { distance: 131.2 }
}
},
4: {
length: 1973,
distance: 142.86,
triggerAbnormal: { 10153004: 0x7fffffff },
consumeAbnormalEnd: 10153004
},
10: {
type: 'holdInfinite',
fixedSpeed: 1,
distance: 33.38,
triggerAbnormal: { 10153006: 0x7fffffff },
consumeAbnormalEnd: 10153006,
endType51: true
},
11: {
type: 'holdInfinite',
fixedSpeed: 1,
distance: 33.38,
triggerAbnormal: { 10153005: 0x7fffffff },
consumeAbnormalEnd: 10153005,
endType51: true
},
12: {
chains: {
'1-0': 1,
'1-1': 2,
'1-2': 3,
'1-3': 4,
'1-30': 1,
'1-31': 1,
'1-32': 2
}
}
},
3: { // Divine Wrath
'*': {
fixedSpeed: 1,
noRetry: true
},
0: { length: 29900 },
1: {
type: 'lockonCast',
length: [1800, 1433, 1366],
setEndpointStage: 1
}
},
4: { // Ground Pound
'*': { length: 3235 },
0: true,
30: true
},
5: { // Bullrush
0: {
fixedSpeed: 1,
length: [2950, 650],
distance: [0, 135]
}
},
6: { // Haymaker
'*': {
length: [1022, 1833],
distance: [0, 171.61],
abnormalChains: { 31120: 31 },
chains: {
1: 30,
2: 30,
'3-1': 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
14: 30,
15: 30,
16: 30,
17: 30,
18: 30,
20: 30,
40: 30
}
},
1: true,
2: true,
30: true,
31: true
},
7: { // Roundhouse Kick
'*': {
length: 860,
distance: 105,
noInterrupt: [7],
hasChains: true
},
0: true,
30: true
},
8: { // Piledriver
'*': {
length: 1950,
distance: 164.94,
abnormalChains: { 31120: 31 },
chains: {
1: 30,
2: 30,
'3-1': 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
14: 30,
15: 30,
16: 30,
17: 30,
18: 30,
20: 30,
40: 30
}
},
1: true,
2: true,
30: true,
31: true
},
9: { // Jackhammer
'*': {
fixedSpeed: 1,
length: 1540,
distance: 40,
noInterrupt: [9],
abnormalChains: { 31120: 31 },
chains: {
1: 30,
2: 30,
'3-1': 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
14: 30,
15: 30,
16: 30,
17: 30,
18: 30,
20: 30,
40: 30
}
},
1: true,
2: true,
30: true,
31: true
},
10: { // Counterpunch
'*': {
length: 1850,
distance: 155,
requiredBuff: 10153000,
chains: {
1: 30,
2: 30,
'3-1': 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
14: 30,
15: 30,
16: 30,
17: 30,
18: 30,
20: 30,
40: 30
}
},
0: true,
30: true
},
13: { // Provoke
'*': {
fixedSpeed: 1,
length: 1275
},
1: true,
2: true
},
14: { // Infuriate
'*': { length: 1650 },
1: true,
2: true,
30: true
},
16: { // Flip Kick
'*': {
length: 2050,
distance: 134,
hasChains: true
},
1: true,
2: true,
30: true
},
21: { // Mounting Rage
'*': {
fixedSpeed: 1,
length: 1275
},
1: true,
2: true
},
22: { // Flying Kick
'*': { hasChains: true },
0: {
length: 1815,
distance: 245.21,
noInterrupt: [22],
abnormalChains: {
10153190: 30,
10153191: 30,
10153192: 30,
10153193: 30,
10153194: 30,
10153195: 30
},
chains: {
1: 30,
2: 30,
'3-1': 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
13: 30,
14: 30,
15: 30,
16: 30,
17: 30,
18: 30,
19: 30,
20: 30,
22: 30,
21: 30,
24: 30,
26: 30,
40: 30
},
race: {
1: { distance: 246.02 }
}
},
30: {
length: 1222,
distance: 351.98
}
},
24: { // One-Inch Punch
'*': {
length: 2000,
distance: 16.59,
race: {
1: { distance: 23.7 }
},
hasChains: true
},
1: {
abnormalChains: { 31120: 31 },
chains: {
1: 30,
2: 30,
'3-1': 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
13: 30,
14: 30,
15: 30,
16: 30,
17: 30,
18: 30,
19: 30,
20: 30,
21: 30,
22: 30,
24: 30,
26: 30,
40: 30
}
},
2: {
abnormalChains: {
31120: 31,
10153190: 30,
10153191: 30,
10153192: 30,
10153193: 30,
10153194: 30,
10153195: 30
},
chains: {
1: 30,
2: 30,
'3-1': 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
13: 30,
14: 30,
15: 30,
16: 30,
17: 30,
18: 30,
19: 30,
20: 30,
21: 30,
22: 30,
24: 30,
26: 30,
40: 30
}
},
30: { length: 950 },
31: { length: 950 }
},
26: { // Rythmic Blows
'*': {
length: [179, 413],
distance: [0, 30],
hasChains: true,
noRetry: true
},
0: {
abnormalChains: {
10153001: 3,
10153002: 3,
10153003: 3,
10153004: 3,
10153190: 2,
10153191: 3,
10153192: 4,
10153193: 5,
10153194: 6,
10153195: 7
},
chains: {
1: 2,
2: 2,
'3-1': 2,
4: 2,
5: 2,
6: 2,
7: 2,
8: 2,
9: 2,
10: 2,
13: 2,
14: 2,
15: 2,
16: 2,
17: 2,
18: 2,
19: 2,
20: 2,
21: 2,
22: 2,
24: 2,
26: 2,
40: 2
}
},
1: true,
2: {
length: 782,
distance: 6
},
3: {
length: 782,
distance: 6
},
4: {
length: 716,
distance: 6
},
5: {
length: 916,
distance: 6
},
6: {
length: 2780,
distance: 24
},
7: {
length: 1571,
distance: 24
}
},
40: { // Quick Dash
'*': {
fixedSpeed: 1,
length: 588,
distance: 144,
forceClip: true,
abnormalChains: { 10153150: 30 },
noRetry: true
},
0: true,
30: true,
}
},
11: { // Ninja
'*': { consumeAbnormal: [10154000, 10154001, 10154002, 10154003, 10154004, 10154005, 10154006] },
1: { // Combo Attack
'*': {
fixedSpeed: 1,
length: 650,
distance: 44.86,
triggerAbnormal: { 10154000: 1650 },
hasChains: true,
noRetry: true
},
0: {
abnormalChains: {
10154000: 1,
10154001: 2,
10154002: 3,
10154003: 4,
10154004: 5,
10154005: 6
},
chains: {
1: 30,
3: 30,
4: 30,
6: 30,
7: 30,
9: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
18: 30,
19: 30,
20: 30
}
},
1: {
length: 1125,
distance: 52.47,
consumeAbnormal: 10154000,
triggerAbnormal: { 10154001: 1500 }
},
2: {
length: 1200,
distance: 69.96,
consumeAbnormal: 10154001,
triggerAbnormal: { 10154002: 1400 }
},
3: {
length: 1225,
distance: 38.01,
consumeAbnormal: 10154002,
triggerAbnormal: { 10154003: 1400 }
},
4: {
length: 1700,
distance: 54.69,
consumeAbnormal: 10154003,
triggerAbnormal: { 10154004: 1400 }
},
5: {
length: 1500,
distance: 37.80,
consumeAbnormal: 10154004,
triggerAbnormal: { 10154005: 1600 }
},
6: {
length: 1150,
distance: 82.62,
consumeAbnormal: 10154005,
triggerAbnormal: { 10154006: 100 }
},
30: true,
40: {
abnormalChains: {
10154000: 41,
10154001: 42,
10154002: 43,
10154003: 44,
10154004: 45,
10154005: 46
},
chains: {
1: 70,
3: 70,
4: 70,
6: 70,
7: 70,
9: 70,
12: 70,
13: 70,
14: 70,
15: 70,
16: 70,
18: 70,
19: 70,
20: 70
}
},
41: {
length: 1125,
distance: 52.47,
consumeAbnormal: 10154000,
triggerAbnormal: { 10154001: 1500 }
},
42: {
length: 1200,
distance: 69.96,
consumeAbnormal: 10154001,
triggerAbnormal: { 10154002: 1400 }
},
43: {
length: 1225,
distance: 38.01,
consumeAbnormal: 10154002,
triggerAbnormal: { 10154003: 1400 }
},
44: {
length: 1700,
distance: 54.69,
consumeAbnormal: 10154003,
triggerAbnormal: { 10154004: 1400 }
},
45: {
length: 1500,
distance: 37.80,
consumeAbnormal: 10154004,
triggerAbnormal: { 10154005: 1600 }
},
46: {
length: 1150,
distance: 82.62,
consumeAbnormal: 10154005,
triggerAbnormal: { 10154006: 100 }
},
70: true
},
2: { // Shadow Jump
'*': {
fixedSpeed: 1,
length: 650,
distance: 175,
forceClip: true,
abnormalChains: { 10154010: 30 }
},
0: true,
30: true
},
3: { // Leaves on the Wind
0: { length: 1275 }
},
4: { // Jagged Path
1: {
type: 'dash',
fixedSpeed: 1,
length: 665,
distance: 469
},
10: { length: 1500 },
11: {
length: 300,
distance: 150
}
},
5: { // Impact Bomb
'*': {
length: 1025,
distance: -291.6,
noInterrupt: [5],
chains: {
1: null,
3: null,
4: null,
6: null,
7: null,
12: null,
13: null,
14: null,
15: null,
16: null,
17: null,
18: null,
19: null,
20: null
},
forceClip: true,
noRetry: true
},
0: true,
30: true
},
6: { // One Thousand Cuts
'*': {
length: 400,
chains: {
1: 30,
3: 30,
4: 30,
7: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
17: 30,
19: 30,
20: 30
}
},
0: true,
1: {
type: 'dash',
fixedSpeed: 1,
length: 300,
distance: 246
},
10: { length: 3500 },
30: true
},
7: { // Decoy Jutsu
0: {
length: 1550,
onlyTarget: true
}
},
8: { // Fire Avalanche
'*': {
length: [700, 1375, 325],
distance: [0, 367.31, 0],
hasChains: true,
noRetry: true
},
0: {
noInterrupt: [9, 18],
abnormalChains: {
10154080: 1,
10154081: 2
},
chains: {
1: 30,
3: 30,
4: 30,
6: 30,
7: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
17: 30,
19: 30,
20: 30
}
},
1: {
length: [1375, 325],
distance: [411.39, 0]
},
2: {
length: [1375, 325],
distance: [455.47, 0]
},
30: true
},
9: { // Smoke Bomb
0: { length: 700 }
},
11: { // Focus
0: { length: 1430 },
50: { length: 1430 }
},
12: { // Skyfall
'*': {
length: 1325,
distance: 154.72,
noInterrupt: [9, 18],
chains: {
1: 30,
3: 30,
4: 30,
6: 30,
7: 30,
8: 30,
13: 30,
14: 30,
15: 30,
16: 30,
17: 30,
19: 30,
20: 30
}
},
1: true,
2: true,
30: true
},
13: { // Circle of Steel
'*': {
length: 3225,
distance: 245.06,
noInterrupt: [9, 18],
chains: {
1: 30,
3: 30,
4: 30,
6: 30,
7: 30,
8: 30,
12: 30,
14: 30,
15: 30,
16: 30,
17: 30,
19: 30,
20: 30
}
},
1: true,
2: true,
30: true
},
14: { // Double Cut
'*': {
length: 1425,
distance: 162,
noInterrupt: [9, 18],
chains: {
1: 30,
3: 30,
4: 30,
6: 30,
7: 30,
8: 30,
12: 30,
13: 30,
15: 30,
16: 30,
17: 30,
19: 30,
20: 30
}
},
1: true,
2: true,
30: true
},
15: { // Burning Heart
'*': {
stamina: 100,
instantStamina: true,
abnormals: {
32033: { speed: 1.2 },
32058: { speed: 1.3 }
}
},
0: { length: 900 },
1: { length: 400 },
2: { length: 400 },
3: { length: 400 },
4: { length: 400 },
5: { length: 400 },
6: { length: 400 },
7: { length: 400 },
8: { length: 400 },
9: { length: 400 }
},
16: { // Death Blossom
0: {
fixedSpeed: 1,
length: 1525
}
},
17: { // Attunement
0: { length: 1000 }
},
18: { // Bladestorm
0: { length: 1000 }
},
19: { // Chakra Thrust
'*': {
length: [225, 825],
distance: 127.5,
chains: {
1: 30,
3: 30,
4: 30,
6: 30,
7: 30,
8: 30,
9: 30,
12: 30,
13: 30,
15: 30,
16: 30,
17: 30,
18: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
20: { // Clone Jutsu
0: {
fixedSpeed: 1,
length: 1275
}
}
},
12: { // Valkyrie
1: { // Slash
'*': {
length: 1100,
distance: 47.13,
noInterrupt: ['1-3'],
chains: {
'1-0': 1,
'1-1': 2,
'1-2': 3,
'1-30': 1,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
},
noRetry: true
},
0: true,
1: {
length: 1200,
distance: 43.37
},
2: {
length: 1450,
distance: 58.54
},
3: {
length: 1925,
distance: 90.1
},
30: true
},
2: { // Overhead Slash
'*': {
length: 1900,
distance: 102.47,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
3: { // Glaive Strike
'*': {
length: 2450,
distance: 105.62,
requiredBuff: 10155112,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
4: { // Charge
0: {
type: 'dash',
fixedSpeed: 1,
length: 550,
distance: 436,
noInterrupt: ['4-0']
},
10: { length: 900 },
11: {
length: 400,
distance: 50,
noInterrupt: ['4-11']
}
},
5: { // Maelstrom
'*': {
length: 3150,
distance: 125.11,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
6: { // Leaping Strike
'*': {
length: 1775,
distance: 105,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
7: { // Spinning Death
'*': {
length: 1775,
distance: 139.72,
hasChains: true,
noRetry: true
},
0: {
noInterrupt: ['7-2'],
abnormalChains: {
10155070: 1,
10155071: 2
},
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
1: true,
2: {
length: 2300,
distance: 197.82
},
30: true
},
8: { // Titansbane
'*': {
fixedSpeed: 1,
length: 7700,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 1,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
1: { length: 2000 },
30: true
},
9: { // Ground Bash
'*': {
length: 1450,
distance: 136,
requiredBuff: 10155112,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
10: { // Dream Slash
'*': {
length: 1775,
distance: 11.18,
noInterrupt: [10],
glyphs: {
33020: { speed: 1.2 }
},
chains: {
1: null,
2: null,
3: null,
4: null,
5: null,
6: null,
7: null,
8: null,
9: null,
10: null,
11: null,
12: null,
13: null,
14: null,
15: null,
16: null,
19: null,
20: null
},
noRetry: true
},
0: true,
30: true
},
11: { // Shining Crescent
'*': {
length: 2725,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: {
distance: 227.49,
noInterrupt: [11]
},
1: {
length: 2500,
chains: {
1: 31,
2: 31,
3: 31,
4: 31,
5: 31,
6: 31,
7: 31,
8: 31,
9: 31,
10: 31,
11: 31,
12: 31,
13: 31,
14: 31,
15: 31,
16: 31,
19: 31,
20: 31
}
},
30: { distance: 227.49 },
31: { length: 2500 }
},
12: { // Ragnarok
'*': {
length: 2800,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
13: { // Bloodflower
'*': {
length: 1700,
distance: 20.57,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
14: { // Evasion
'*': {
fixedSpeed: 1,
length: 825,
distance: 188.18,
forceClip: true,
abnormalChains: { 10155020: 1 }
},
0: true,
1: true
},
15: { // Windslash
'*': {
length: 1100,
distance: 152.82,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
16: { // Runeburst
'*': {
fixedSpeed: 1,
length: 1325,
distance: 25,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
17: { // Balder's Tears
0: {
fixedSpeed: 1,
length: 1075
}
},
19: { // Reclamation
'*': {
length: 1525,
chains: {
1: 30,
2: 30,
3: 30,
4: 30,
5: 30,
6: 30,
7: 30,
8: 30,
9: 30,
10: 30,
11: 30,
12: 30,
13: 30,
14: 30,
15: 30,
16: 30,
19: 30,
20: 30
}
},
0: true,
30: true
},
20: { // Backstab
0: {
length: 1500,
onlyTarget: true
}
},
21: { // Dark Herald
0: {
fixedSpeed: 1,
length: 925,
requiredBuff: 10155201
}
}
}
}
| gpl-3.0 |
kubokkey/vmportal | config/application.rb | 1323 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Vmportal
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.autoload_paths += %W(#{config.root}/lib/assets)
config.time_zone = 'Tokyo'
config.active_record.default_timezone = :local
config.generators do |g|
g.template_engine :slim
end
end
end
| gpl-3.0 |
MoyinOtubela/autonomous_controllers | build/robot_controllers/robbie_control/catkin_generated/pkg.develspace.context.pc.py | 392 | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "robbie_control"
PROJECT_SPACE_DIR = "/home/moyin/dev/autonomous_controllers/devel"
PROJECT_VERSION = "0.0.0"
| gpl-3.0 |
zenn1989/ffcms | resource/xbbcode/lib/geshi/c_mac.php | 7726 | <?php
/*************************************************************************************
* c_mac.php
* ---------
* Author: M. Uli Kusterer ([email protected])
* Copyright: (c) 2004 M. Uli Kusterer, Nigel McNie (http://qbnz.com/highlighter/)
* Release Version: 1.0.7.18
* Date Started: 2004/06/04
*
* C for Macs language file for GeSHi.
*
* CHANGES
* -------
* 2004/11/27
* - First Release
*
* TODO (updated 2004/11/27)
* -------------------------
*
*************************************************************************************
*
* This file is part of GeSHi.
*
* GeSHi 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.
*
* GeSHi 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 GeSHi; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
************************************************************************************/
$language_data = array(
'LANG_NAME' => 'C (Mac)',
'COMMENT_SINGLE' => array(1 => '//', 2 => '#'),
'COMMENT_MULTI' => array('/*' => '*/'),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array("'", '"'),
'ESCAPE_CHAR' => '\\',
'KEYWORDS' => array(
1 => array(
'if', 'return', 'while', 'case', 'continue', 'default',
'do', 'else', 'for', 'switch', 'goto'
),
2 => array(
'NULL', 'false', 'break', 'true', 'enum', 'errno', 'EDOM',
'ERANGE', 'FLT_RADIX', 'FLT_ROUNDS', 'FLT_DIG', 'DBL_DIG', 'LDBL_DIG',
'FLT_EPSILON', 'DBL_EPSILON', 'LDBL_EPSILON', 'FLT_MANT_DIG', 'DBL_MANT_DIG',
'LDBL_MANT_DIG', 'FLT_MAX', 'DBL_MAX', 'LDBL_MAX', 'FLT_MAX_EXP', 'DBL_MAX_EXP',
'LDBL_MAX_EXP', 'FLT_MIN', 'DBL_MIN', 'LDBL_MIN', 'FLT_MIN_EXP', 'DBL_MIN_EXP',
'LDBL_MIN_EXP', 'CHAR_BIT', 'CHAR_MAX', 'CHAR_MIN', 'SCHAR_MAX', 'SCHAR_MIN',
'UCHAR_MAX', 'SHRT_MAX', 'SHRT_MIN', 'USHRT_MAX', 'INT_MAX', 'INT_MIN',
'UINT_MAX', 'LONG_MAX', 'LONG_MIN', 'ULONG_MAX', 'HUGE_VAL', 'SIGABRT',
'SIGFPE', 'SIGILL', 'SIGINT', 'SIGSEGV', 'SIGTERM', 'SIG_DFL', 'SIG_ERR',
'SIG_IGN', 'BUFSIZ', 'EOF', 'FILENAME_MAX', 'FOPEN_MAX', 'L_tmpnam', 'NULL',
'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'stdin', 'stdout', 'stderr',
'EXIT_FAILURE', 'EXIT_SUCCESS', 'RAND_MAX', 'CLOCKS_PER_SEC',
// Mac-specific constants:
'kCFAllocatorDefault'
),
3 => array(
'printf', 'fprintf', 'snprintf', 'sprintf', 'assert',
'isalnum', 'isalpha', 'isdigit', 'iscntrl', 'isgraph', 'islower', 'isprint',
'ispunct', 'isspace', 'ispunct', 'isupper', 'isxdigit', 'tolower', 'toupper',
'exp', 'log', 'log10', 'pow', 'sqrt', 'ceil', 'floor', 'fabs', 'ldexp',
'frexp', 'modf', 'fmod', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2',
'sinh', 'cosh', 'tanh', 'setjmp', 'longjmp', 'asin', 'acos', 'atan', 'atan2',
'va_start', 'va_arg', 'va_end', 'offsetof', 'sizeof', 'fopen', 'freopen',
'fflush', 'fclose', 'remove', 'rename', 'tmpfile', 'tmpname', 'setvbuf',
'setbuf', 'vfprintf', 'vprintf', 'vsprintf', 'fscanf', 'scanf', 'sscanf',
'fgetc', 'fgets', 'fputc', 'fputs', 'getc', 'getchar', 'gets', 'putc',
'putchar', 'puts', 'ungetc', 'fread', 'fwrite', 'fseek', 'ftell', 'rewind',
'fgetpos', 'fsetpos', 'clearerr', 'feof', 'ferror', 'perror', 'abs', 'labs',
'div', 'ldiv', 'atof', 'atoi', 'atol', 'strtod', 'strtol', 'strtoul', 'calloc',
'malloc', 'realloc', 'free', 'abort', 'exit', 'atexit', 'system', 'getenv',
'bsearch', 'qsort', 'rand', 'srand', 'strcpy', 'strncpy', 'strcat', 'strncat',
'strcmp', 'strncmp', 'strcoll', 'strchr', 'strrchr', 'strspn', 'strcspn',
'strpbrk', 'strstr', 'strlen', 'strerror', 'strtok', 'strxfrm', 'memcpy',
'memmove', 'memcmp', 'memchr', 'memset', 'clock', 'time', 'difftime', 'mktime',
'asctime', 'ctime', 'gmtime', 'localtime', 'strftime'
),
4 => array(
'auto', 'char', 'const', 'double', 'float', 'int', 'long',
'register', 'short', 'signed', 'sizeof', 'static', 'string', 'struct',
'typedef', 'union', 'unsigned', 'void', 'volatile', 'extern', 'jmp_buf',
'signal', 'raise', 'va_list', 'ptrdiff_t', 'size_t', 'FILE', 'fpos_t',
'div_t', 'ldiv_t', 'clock_t', 'time_t', 'tm',
// Mac-specific types:
'CFArrayRef', 'CFDictionaryRef', 'CFMutableDictionaryRef', 'CFBundleRef', 'CFSetRef', 'CFStringRef',
'CFURLRef', 'CFLocaleRef', 'CFDateFormatterRef', 'CFNumberFormatterRef', 'CFPropertyListRef',
'CFTreeRef', 'CFWriteStreamRef', 'CFCharacterSetRef', 'CFMutableStringRef', 'CFNotificationRef',
'CFNotificationRef', 'CFReadStreamRef', 'CFNull', 'CFAllocatorRef', 'CFBagRef', 'CFBinaryHeapRef',
'CFBitVectorRef', 'CFBooleanRef', 'CFDataRef', 'CFDateRef', 'CFMachPortRef', 'CFMessagePortRef',
'CFMutableArrayRef', 'CFMutableBagRef', 'CFMutableBitVectorRef', 'CFMutableCharacterSetRef',
'CFMutableDataRef', 'CFMutableSetRef', 'CFNumberRef', 'CFPlugInRef', 'CFPlugInInstanceRef',
'CFRunLoopRef', 'CFRunLoopObserverRef', 'CFRunLoopSourceRef', 'CFRunLoopTimerRef', 'CFSocketRef',
'CFTimeZoneRef', 'CFTypeRef', 'CFUserNotificationRef', 'CFUUIDRef', 'CFXMLNodeRef', 'CFXMLParserRef',
'CFXMLTreeRef'
),
),
'SYMBOLS' => array(
'(', ')', '{', '}', '[', ']', '=', '+', '-', '*', '/', '!', '%', '^', '&', ':'
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => true,
1 => false,
2 => false,
3 => false,
4 => false,
),
'STYLES' => array(
'KEYWORDS' => array(
1 => 'color: #0000ff;',
2 => 'color: #0000ff;',
3 => 'color: #0000dd;',
4 => 'color: #0000ff;'
),
'COMMENTS' => array(
1 => 'color: #ff0000;',
2 => 'color: #339900;',
'MULTI' => 'color: #ff0000; font-style: italic;'
),
'ESCAPE_CHAR' => array(
0 => 'color: #666666; font-weight: bold;'
),
'BRACKETS' => array(
0 => 'color: #000000;'
),
'STRINGS' => array(
0 => 'color: #666666;'
),
'NUMBERS' => array(
0 => 'color: #0000dd;'
),
'METHODS' => array(
1 => 'color: #00eeff;',
2 => 'color: #00eeff;'
),
'SYMBOLS' => array(
0 => 'color: #000000;'
),
'REGEXPS' => array(),
'SCRIPT' => array()
),
'URLS' => array(
1 => '',
2 => '',
3 => 'http://www.opengroup.org/onlinepubs/009695399/functions/{FNAME}.html',
4 => ''
),
'OOLANG' => true,
'OBJECT_SPLITTERS' => array(
1 => '.',
2 => '::'
),
'REGEXPS' => array(),
'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array(),
'HIGHLIGHT_STRICT_BLOCK' => array()
);
?>
| gpl-3.0 |
kaleidos/Weather-Prophet | android/.metadata/.plugins/org.eclipse.wst.jsdt.core/libraries/xhr.js | 2783 | /*******************************************************************************
* Copyright (c) 2009, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************
*
* Based on information from https://developer.mozilla.org/En/XMLHttpRequest
* and http://msdn2.microsoft.com/en-us/library/ms533062.aspx
**/
/**
* function createRequest
* @type XMLHttpRequest
* @memberOf Window
*/
Window.prototype.createRequest= function(){return new XMLHttpRequest();};
/**
* Object XMLHttpRequest
* @super Global
* @type constructor
* @memberOf Global
*/
XMLHttpRequest.prototype=new Object();
function XMLHttpRequest(){};
/**
* function onreadystatechange
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.onreadystatechange=function(){};
/**
* property readyState
* @type Number
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.readyState=0;
/**
* property responseText
* @type String
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.responseText="";
/**
* property responseXML
* @type Document
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.responseXML=new Document();
/**
* property status
* @type Number
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.status=0;
/**
* property statusText
* @type String
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.statusText="";
/**
* function abort()
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.abort=function(){};
/**
* function getAllResponseHeaders()
* @type String
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.getAllResponseHeaders=function(){return "";};
/**
* function open(method, url, async, username, password)
* @param {String} method
* @param {String} url
* @param {Boolean} optional async
* @param {String} optional username
* @param {String} optional password
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.open=function(method, url, async, username, password){};
/**
* function send(body)
* @param {Object} body
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.send=function(body){};
/**
* function setRequestHeader(header,value)
* @param {String} header
* @param {String} value
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.setRequestHeader=function(header,value){};
/**
* function getAllResponseHeaders()
* @param {String} header
* @type String
* @memberOf XMLHttpRequest
*/
XMLHttpRequest.prototype.getResponseHeader=function(header){return "";};
| gpl-3.0 |
wegener-center/pyCAT | pycat/analysis/indices.py | 8838 | # (C) Wegener Center for Climate and Global Change, University of Graz, 2015
#
# This file is part of pyCAT.
#
# pyCAT 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.
#
# pyCAT 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 pyCAT. If not, see <http://www.gnu.org/licenses/>.
"""
Calculation of climate indices
"""
import iris
import iris.coord_categorisation as ccat
import numpy as np
from iris.analysis import Aggregator
from iris.exceptions import CoordinateNotFoundError
from pycat.analysis.utils import _create_cube, _make_time_dimension
def consecutive_dry_days(cube, period='year', length=6, threshold=1.):
"""
calculate consecutive dry days within an iris.cube.Cube
Args:
* cube (iris.cube.Cube):
An iris.cube.Cube holding precipiation amount in mm/day
* period (string):
Period over that the CDD will be calculated. Can be 'year', 'season'
or 'month'. If period is 'season' or 'month' the CDD will be averaged
over the years
Kwargs:
* length (int):
The number of days without rainfall that define a dry period
* threshold (float):
The upper limit of daily rainfall in mm that indicates
'no precipitation'
Returns:
An iris.cube.CubeList that holds two iris.cube.Cubes with the longest
period of dry days in the given period and the mean of the number of
dry periods with respect to the given length
"""
def _cdd_index(array, axis, threshold):
"""
Calculate the consecutive dry days index.
This function is used as an iris.analysis.Aggregator
Args:
* array (numpy.array or numpy.ma.array):
array that holds the precipitation data
* axis (int):
the number of the time-axis
* threshold (float):
the threshold that indicates a precipiation-less day
Returns:
the aggregation result, collapsing the 'axis' dimension of
the 'data' argument
"""
from pycat.analysis.utils import (
_get_max_true_block_length, _get_true_block_lengths)
up_down = _get_true_block_lengths(array < threshold, axis)
return _get_max_true_block_length(up_down)
def _cdd_periods(array, axis, threshold, length):
"""
Calculate the number of consecutive dry days periods.
This function is used as an iris.analysis.Aggregator
Args:
* array (numpy.array or numpy.ma.array):
array that holds the precipitation data
* axis (int):
the number of the time-axis
* threshold (float):
the threshold that indicates a precipiation-less day
* length (int):
number of days that a dry period must last
Returns:
the aggregation result, collapsing the 'axis' dimension
of the 'data' argument
"""
from pycat.analysis.utils import (
_get_len_true_block_length, _get_true_block_lengths)
up_down = _get_true_block_lengths(array < threshold, axis)
return _get_len_true_block_length(up_down, length)
# build the iris.analysis.Aggregators
cdd_index = Aggregator('cdd_index', _cdd_index)
cdd_periods = Aggregator('cdd_periods', _cdd_periods)
# check if the cube already has the needed auxiliary coordinates
if period == 'season':
# add the season_year auxiliary coordinate
try:
years = np.unique(cube.coord('season_year').points)
except CoordinateNotFoundError:
ccat.add_season_year(cube, 'time')
years = np.unique(cube.coord('season_year').points)
constraint_year_key = 'season_year'
else:
# add calendar years
try:
years = np.unique(cube.coord('year').points)
except CoordinateNotFoundError:
ccat.add_year(cube, 'time')
years = np.unique(cube.coord('year').points)
constraint_year_key = 'year'
if period in ['season', 'month']:
try:
index_period = np.unique(cube.coord('%s_number' % period).points)
except CoordinateNotFoundError:
cat = getattr(ccat, 'add_%s_number' % period)
cat(cube, 'time')
index_period = np.unique(cube.coord('%s_number' % period).points)
# create time-axis of resulting cubes
time_dimension = _make_time_dimension(
cube.coord('time').units.num2date(cube.coord('time').points[0]),
cube.coord('time').units.num2date(cube.coord('time').points[-1]),
period=period)
# create the empty resulting cubes
dim_coords_and_dims = []
slices = []
for coord in cube.dim_coords:
if coord.units.is_time_reference():
dim_coords_and_dims.append(
(time_dimension, cube.coord_dims(coord)))
slices.append(0)
time_axis = cube.coord_dims(coord)[0]
else:
dim_coords_and_dims.append((coord, cube.coord_dims(coord)))
slices.append(slice(None, None, None))
cdd_index_cube = _create_cube(
long_name='Consecutive dry days is the greatest number of '
'consecutive days per time period with daily '
'precipitation amount below %s mm.' % threshold,
var_name='consecutive_dry_days_index_per_time_period',
units=iris.unit.Unit('1'),
dim_coords_and_dims=dim_coords_and_dims)
cdd_periods_cube = _create_cube(
long_name='Number of cdd periods in given time period '
'with more than %d days.' % length,
var_name='number_of_cdd_periods_with_more_than_'
'%ddays_per_time_period' % length,
units=iris.unit.Unit('1'),
dim_coords_and_dims=dim_coords_and_dims)
# differentiate between the considered period
if period == 'year':
# just run the aggregation over all given years resulting in
# the maximum cdd length and the number of cdd periods for each year
for year in years:
tmp_cube = cube.extract(iris.Constraint(year=year))
slices[time_axis] = year - years[0]
cdd_index_data = tmp_cube.collapsed(
'time', cdd_index, threshold=threshold).data
cdd_periods_data = tmp_cube.collapsed(
'time', cdd_periods, threshold=threshold, length=length).data
cdd_index_cube.data[slices] = cdd_index_data
cdd_periods_cube.data[slices] = cdd_periods_data
return iris.cube.CubeList(
(cdd_index_cube, cdd_periods_cube)
)
else:
# run the aggregation over all seasons/months of all years
# afterwards aggregate the seasons/month by MAX Aggregator
# for the cdd_index and the MEAN Aggregator for cdd_periods
for year in years:
for p in index_period:
constraint_dict = {'%s_number' % period: p,
constraint_year_key: year}
tmp_cube = cube.extract(iris.Constraint(**constraint_dict))
if tmp_cube:
# the extraction can lead to empty cubes for seasons
# in the last year
time_index = (year - years[0]) * len(index_period) + p
# months numbers start at 1
if period == 'month':
time_index -= 1
slices[time_axis] = time_index
cdd_index_data = tmp_cube.collapsed(
'time', cdd_index, threshold=threshold).data
cdd_periods_data = tmp_cube.collapsed(
'time', cdd_periods, threshold=threshold,
length=length).data
cdd_index_cube.data[slices] = cdd_index_data
cdd_periods_cube.data[slices] = cdd_periods_data
# aggregate over seasons/months
cat = getattr(ccat, 'add_%s' % period)
cat(cdd_index_cube, 'time')
cat(cdd_periods_cube, 'time')
cdd_index_mean = cdd_index_cube.aggregated_by(
period, iris.analysis.MEAN)
cdd_periods_mean = cdd_periods_cube.aggregated_by(
period, iris.analysis.MEAN)
cdd_index_mean.remove_coord('time')
cdd_periods_mean.remove_coord('time')
return iris.cube.CubeList(
(cdd_index_mean, cdd_periods_mean)
)
| gpl-3.0 |
insitu-project/foss-browser-extensions | commons/gulp/lib.js | 1636 | /**
* Copyright 2015 Benjamin Menant <[email protected]>
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
'use strict';
const gulp = require('gulp');
const gulpIf = require('gulp-if');
const uglify = require('gulp-uglify');
module.exports =
function buildLib(dest) {
const basepath = __dirname + '/../src/';
const path = {
src: basepath + 'shared/*/lib',
dest: dest + 'shared/*/lib',
};
return gulp.src(path.src + '**/*', { base: path.src })
.pipe(gulpIf('**/*js', uglify()))
.pipe(gulp.dest(path.dest));
};
| gpl-3.0 |
rotace/sample_java | sample-maven/src/main/java/app/HelloWorld.java | 155 | package app;
public class HelloWorld {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
| gpl-3.0 |
DuelMonster/SuperMiner | src/main/java/duelmonster/superminer/objects/NotSoRandom.java | 926 | package duelmonster.superminer.objects;
import java.util.Random;
/**
* NotSoRandom provides an implementation of Random that can be used to obtain determinate results when calculating
* random occurrences. E.g. insert it into the World object, call a random function, then replace.
*
* @author thebombzen
*/
public class NotSoRandom extends Random {
private static final long serialVersionUID = 7668644027932430864L;
private boolean useZero;
public NotSoRandom(boolean useZero) {
this.useZero = useZero;
}
@Override
public double nextDouble() {
if (useZero) {
return 0.0D;
} else {
return 1.0D;
}
}
@Override
public float nextFloat() {
if (useZero) {
return 0.0F;
} else {
return 1.0F;
}
}
@Override
public double nextGaussian() {
return nextDouble();
}
@Override
public int nextInt(int n) {
if (useZero) {
return 0;
} else {
return n - 1;
}
}
}
| gpl-3.0 |
envelope-project/mlem | src/mpicsr4mlem2.cpp | 25091 | /**
Copyright © 2019 Technische Universitaet Muenchen
Authors: Tilman Kuestner
Dai Yang
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The above copyright notice and this permission notice shall be
included in all copies and/or substantial portions of the Software,
including binaries.
*/
#include "../include/csr4matrix.hpp"
#include "../include/vector.hpp"
#include <iostream>
#include <string>
#include <stdexcept>
#include <cassert>
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <sys/stat.h>
#include <stdio.h>
#include <sys/time.h>
#include <mpi.h>
#ifdef _OMP_
#include <omp.h>
#endif
#ifdef XEON_PHI
#include <hbwmalloc.h>
#define MALLOC(type, num) (type*) hbw_malloc((num) * sizeof(type))
#define FREE(x) hbw_free(x)
#else
#define MALLOC(type, num) (type*) malloc((num) * sizeof(type));
#define FREE(x) free(x)
#endif
#include <unistd.h> // TODO remove me
struct ProgramOptions
{
std::string mtxfilename;
std::string infilename;
std::string outfilename;
int iterations;
int numberOfThreads; // number of threads each MPI node
};
struct Range
{
int startRow;
int endRow;
};
struct CSR
{
int nRowIndex, nColumn;
uint32_t startRow, endRow;
uint32_t *columns;
uint64_t *rowIndex;
float *values;
};
struct MpiData
{
int size, rank, numberOfThreads;
uint64_t numberOfElements = 0;
Range range;
#ifdef _OMP_
CSR** threadsCSR;
#else
CSR* mpiCSR;
#endif
};
ProgramOptions handleCommandLine(int argc, char *argv[])
{
if (argc != 6)
throw std::runtime_error("wrong number of command line parameters");
ProgramOptions progops;
progops.mtxfilename = std::string(argv[1]);
progops.infilename = std::string(argv[2]);
progops.outfilename = std::string(argv[3]);
progops.iterations = std::stoi(argv[4]);
progops.numberOfThreads = std::stoi(argv[5]);
return progops;
}
MpiData initializeMpiOmp(int argc, char *argv[], int numberOfThreads)
{
MpiData mpi;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi.rank);
MPI_Comm_size(MPI_COMM_WORLD, &mpi.size);
#ifdef _OMP_
omp_set_num_threads(numberOfThreads);
mpi.numberOfThreads = numberOfThreads;
#endif
return mpi;
}
void calcColumnSums(const MpiData& mpi, float* norm, const int normSize)
{
#ifdef _OMP_
for (size_t i = 0; i < mpi.numberOfThreads; ++i) {
for (size_t j = 0; j < mpi.threadsCSR[i]->nColumn; ++j) {
norm[mpi.threadsCSR[i]->columns[j]] +=
mpi.threadsCSR[i]->values[j];
}
}
#else
for (size_t j = 0; j < mpi.mpiCSR->nColumn; ++j) {
norm[mpi.mpiCSR->columns[j]] += mpi.mpiCSR->values[j];
}
#endif
MPI_Allreduce(MPI_IN_PLACE, norm, normSize, MPI_FLOAT, MPI_SUM,
MPI_COMM_WORLD);
}
void initImage(const MpiData& mpi, float* norm, Vector<float>& image,
const Vector<int>& lmsino, const size_t normSize)
{
double sumnorm = 0.0, sumin = 0.0;
float initial;
size_t i = 0;
// Sum up norm vector, creating sum of all matrix elements
for (i = 0; i < normSize; ++i) sumnorm += norm[i];
for (i = 0; i < lmsino.size(); ++i) sumin += lmsino[i];
initial = static_cast<float>(sumin / sumnorm);
for (i = 0; i < image.size(); ++i) image[i] = initial;
#ifndef MESSUNG
std::cout << "MLEM [" << mpi.rank << "/" << mpi.size << "]: "
<< "INIT: sumnorm=" << sumnorm << ", sumin=" << sumin
<< ", initial value=" << initial << std::endl;
#endif
}
#ifdef _OMP_
void calcFwProj(const MpiData& mpi, const Vector<float>& input,
float* fwproj, const int fwprojSize)
{
// Fill with zeros
std::fill(fwproj, fwproj + fwprojSize, 0.0);
#pragma omp parallel
{
const int tidx = omp_get_thread_num();
float res = 0.0;
uint32_t i, j, startColumnIndex, endColumnIndex;
uint32_t length = mpi.threadsCSR[tidx]->nRowIndex;
uint32_t row = mpi.threadsCSR[tidx]->startRow;
for(i = 1, startColumnIndex = 0;
row < mpi.threadsCSR[tidx]->endRow && i < length;
++i, ++row, startColumnIndex = endColumnIndex) {
endColumnIndex = startColumnIndex +
(mpi.threadsCSR[tidx]->rowIndex[i] - mpi.threadsCSR[tidx]->rowIndex[i-1]);
res = 0.0;
#pragma unroll (16)
for(j = startColumnIndex; j < endColumnIndex; ++j)
res += mpi.threadsCSR[tidx]->values[j] * input[mpi.threadsCSR[tidx]->columns[j]];
fwproj[row] = res;
}
}
MPI_Allreduce(MPI_IN_PLACE, fwproj, fwprojSize, MPI_FLOAT, MPI_SUM,
MPI_COMM_WORLD);
}
#else
void calcFwProj(const MpiData& mpi, const Vector<float>& input,
float* fwproj, const int fwprojSize)
{
float res = 0.0;
uint32_t i, j, startColumnIndex, endColumnIndex;
uint32_t length = mpi.mpiCSR->nRowIndex;
uint32_t row = mpi.mpiCSR->startRow;
// Fill with zeros
std::fill(fwproj, fwproj + fwprojSize, 0.0);
for(i = 1, startColumnIndex = 0;
row < mpi.mpiCSR->endRow && i < length;
++i, ++row, startColumnIndex = endColumnIndex) {
endColumnIndex = startColumnIndex +
(mpi.mpiCSR->rowIndex[i] - mpi.mpiCSR->rowIndex[i-1]);
res = 0.0;
for(j = startColumnIndex; j < endColumnIndex; ++j)
res += mpi.mpiCSR->values[j] * input[mpi.mpiCSR->columns[j]];
fwproj[row] = res;
}
MPI_Allreduce(MPI_IN_PLACE, fwproj, fwprojSize, MPI_FLOAT, MPI_SUM,
MPI_COMM_WORLD);
}
#endif
void calcCorrel(float* fwproj, const Vector<int>& input, float* correlation,
const int fwprojSize)
{
for (size_t i = 0; i < fwprojSize; ++i)
correlation[i] = (fwproj[i] != 0.0) ? (input[i] / fwproj[i]) : 0.0;
}
#ifdef _OMP_
void calcBkProj(const MpiData& mpi, float* correlation, float* update,
const size_t updateSize)
{
// Fill with zerons
std::fill(update, update + updateSize, 0.0);
#pragma omp parallel
{
Vector<float> private_update(updateSize, 0);
const int tidx = omp_get_thread_num();
uint32_t i, j, startColumnIndex, endColumnIndex;
uint32_t length = mpi.threadsCSR[tidx]->nRowIndex;
uint32_t row = mpi.threadsCSR[tidx]->startRow;
for(i = 1, startColumnIndex = 0;
row < mpi.threadsCSR[tidx]->endRow && i < length;
++i, ++row, startColumnIndex = endColumnIndex) {
endColumnIndex = startColumnIndex +
(mpi.threadsCSR[tidx]->rowIndex[i] - mpi.threadsCSR[tidx]->rowIndex[i-1]);
CSR* temp_thd = mpi.threadsCSR[tidx];
#pragma vector aligned
#pragma ivdep
for(j = startColumnIndex; j < endColumnIndex; ++j)
private_update[temp_thd->columns[j]] +=
temp_thd->values[j] * correlation[row];
}
#pragma omp critical
{
for (size_t i = 0; i < updateSize; ++i) update[i] += private_update[i];
}
}
MPI_Allreduce(MPI_IN_PLACE, update, updateSize, MPI_FLOAT, MPI_SUM,
MPI_COMM_WORLD);
}
#else
void calcBkProj(const MpiData& mpi, float* correlation, float* update,
const size_t updateSize)
{
// Fill with zerons
std::fill(update, update + updateSize, 0.0);
uint32_t i, j, startColumnIndex, endColumnIndex;
uint32_t length = mpi.mpiCSR->nRowIndex;
uint32_t row = mpi.mpiCSR->startRow;
for(i = 1, startColumnIndex = 0;
row < mpi.mpiCSR->endRow && i < length;
++i, ++row, startColumnIndex = endColumnIndex) {
endColumnIndex = startColumnIndex +
(mpi.mpiCSR->rowIndex[i] - mpi.mpiCSR->rowIndex[i-1]);
for(j = startColumnIndex; j < endColumnIndex; ++j)
update[mpi.mpiCSR->columns[j]] +=
mpi.mpiCSR->values[j] * correlation[row];
}
MPI_Allreduce(MPI_IN_PLACE, update, updateSize, MPI_FLOAT, MPI_SUM,
MPI_COMM_WORLD);
}
#endif
void calcUpdate(float* update, float* norm, Vector<float>& image,
const size_t updateSize)
{
for (size_t i = 0; i < updateSize; ++i)
image[i] *= (norm[i] != 0.0) ? (update[i] / norm[i]) : update[i];
}
void mlem(const MpiData& mpi, const Vector<int>& lmsino, Vector<float>& image,
const int nIterations, const uint32_t nRows, const uint32_t nColumns)
{
size_t i = 0;
double sum = 0;
double startTime, endTime, gElapsed, gBkProj, gFwProj, elapsed;
double endFwProj, startBkProj, endBkProj, elapsedFwProj, elapsedBkProj;
// Allocate temporary vectors
float *fwproj = MALLOC(float, nRows);
float *correlation = MALLOC(float, nRows);
float *update = MALLOC(float, nColumns);
float *norm = MALLOC(float, nColumns);
for (i = 0; i < nRows; ++i) fwproj[i] = correlation[i] = 0.0;
for (i = 0; i < nColumns; ++i) update[i] = norm[i] = 0.0;
startTime = MPI_Wtime();
calcColumnSums(mpi, norm, nColumns);
endTime = MPI_Wtime();
elapsed = endTime - startTime;
#ifndef MESSUNG
if(0 == mpi.rank)
std::cout << "MLEM [" << mpi.rank << "/" << mpi.size << "]:"
<< "Calculated norm, elapsed time: " << elapsed << "s\n";
#endif
// Fill image with initial estimate
initImage(mpi, norm, image, lmsino, nColumns);
if(0 == mpi.rank) {
#ifndef MESSUNG
std::cout << "MLEM [" << mpi.rank << "/" << mpi.size << "]:"
<< "Starting " << nIterations << " MLEM iterations" << std::endl;
printf("#, Elapsed Time (seconds), Forward Projection (seconds), "
"Backward Projection (seconds), Image Sum\n");
#else
printf("#, Elapsed Time (seconds)\n");
#endif
}
for (int iter = 0; iter < nIterations; ++iter) {
startTime = MPI_Wtime();
calcFwProj(mpi, image, fwproj, nRows);
#ifndef MESSUNG
endFwProj = MPI_Wtime();
calcCorrel(fwproj, lmsino, correlation, nRows);
startBkProj = MPI_Wtime();
calcBkProj(mpi, correlation, update, nColumns);
endBkProj = MPI_Wtime();
#else
calcCorrel(fwproj, lmsino, correlation, nRows);
calcBkProj(mpi, correlation, update, nColumns);
#endif
calcUpdate(update, norm, image, nColumns);
endTime = MPI_Wtime();
elapsed = endTime - startTime;
#ifndef MESSUNG
elapsedFwProj = endFwProj - startTime;
elapsedBkProj = endBkProj - startBkProj;
MPI_Reduce(&elapsedFwProj, &gFwProj, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
MPI_Reduce(&elapsedBkProj, &gBkProj, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
#endif
// Max time between all nodes
MPI_Reduce(&elapsed, &gElapsed, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
if(mpi.rank == 0) {
#ifndef MESSUNG
for(i = 0, sum = 0; i < image.size(); ++i) sum += image[i];
printf("%d, %.15f, %.15f, %.15f, %.15lf\n", iter, gElapsed,
gFwProj, gBkProj, sum);
#else
printf("%d, %.15f \n", iter, gElapsed);
#endif
}
// TODO reconsider
MPI_Barrier(MPI_COMM_WORLD);
}
FREE(fwproj);
FREE(correlation);
FREE(update);
FREE(norm);
}
#ifdef _OMP_
void splitMatrix(Csr4Matrix* matrix, MpiData& mpi)
{
uint64_t sum = 0, numOfElem = 0, totalElements;
uint32_t nRows = matrix->rows();
float avgElemsPerNode, avgElemsPerThread;
int idx = 0;
totalElements = matrix->elements();
// Creating correct row index vector; starting with 0!
const uint64_t *rowidxA = matrix->getRowIdx();
const RowElement<float> *rowElements = matrix->getData();
printf("[MPI Rank %d]: #Row Elements: %d, Allocating Memory Size: %f MBytes\n", mpi.rank, nRows, (double)(nRows + 1) * sizeof(uint64_t) / 1000000.);
uint64_t *rowidx = (uint64_t *) malloc((nRows + 1) * sizeof(uint64_t));
if (rowidx==NULL) throw std::runtime_error("Bad Allocation of RowIdx");
rowidx[0] = 0;
for (uint32_t row = 0; row < nRows; ++row) rowidx[row + 1] = rowidxA[row];
// Allocate a shared array of pointer for CSR struct of each thread
mpi.threadsCSR = MALLOC(CSR*, mpi.numberOfThreads);
if(mpi.threadsCSR == NULL){
printf("MLEM%d / %d: Cannot Allocate threadsCSR Pointers, exiting...\n",
mpi.rank, mpi.size);
throw std::runtime_error("Cannot Alloc Memory. ");
}
// Each thread malloc its own struct
#pragma omp parallel
{
const int tidx = omp_get_thread_num();
mpi.threadsCSR[tidx] = MALLOC(CSR, 1);
if(mpi.threadsCSR[tidx] == NULL){
printf("MLEM[%d [%d/%d]/ %d]: Cannot Allocate threadsCSR Struct, exiting...\n"
,mpi.rank, tidx, mpi.numberOfThreads, mpi.size);
throw std::runtime_error("Cannot Alloc Memory. ");
}
}
// Assign a range of rows for each MPI node
avgElemsPerNode = (float) totalElements / (float) mpi.size;
if (idx == mpi.rank) mpi.range.startRow = 0;
for (uint32_t row = 0; row < nRows; ++row) {
sum += matrix->elementsInRow(row);
numOfElem += matrix->elementsInRow(row);
if (sum > avgElemsPerNode * (idx + 1)) {
if (mpi.rank == idx) {
mpi.range.endRow = row;
mpi.numberOfElements = numOfElem;
}
++idx;
numOfElem = 0;
if (mpi.rank == idx) mpi.range.startRow = row;
}
}
if (mpi.rank == mpi.size - 1) {
mpi.range.endRow = nRows;
mpi.numberOfElements = numOfElem;
}
idx = 0;
sum = 0;
numOfElem = 0;
avgElemsPerThread = (float) mpi.numberOfElements / (float) mpi.numberOfThreads;
// Assign a range of rows for each thread of each node
mpi.threadsCSR[idx]->startRow = mpi.range.startRow;
for (uint32_t row = mpi.range.startRow; row < mpi.range.endRow && idx < mpi.numberOfThreads - 1; ++row) {
sum += matrix->elementsInRow(row);
if (sum > avgElemsPerThread * (idx + 1)) {
mpi.threadsCSR[idx]->endRow = row;
++idx;
mpi.threadsCSR[idx]->startRow = row;
}
}
mpi.threadsCSR[mpi.numberOfThreads - 1]->endRow = mpi.range.endRow;
// Create the the split matrix for each node or each thread
#pragma omp parallel
{
const int tidx = omp_get_thread_num();
uint32_t i, start, end, length;
uint64_t base;
std::vector<uint64_t> *rowIndexTemp = new std::vector<uint64_t>();
//std::vector<uint32_t> *columnsTemp = new std::vector<uint32_t>();
//std::vector<float> *valuesTemp = new std::vector<float>();
start = mpi.threadsCSR[tidx]->startRow;
end = mpi.threadsCSR[tidx]->endRow;
base = rowidx[mpi.threadsCSR[tidx]->startRow];
// Building row index array
for (i = start; i < end; ++i) rowIndexTemp->push_back(rowidx[i] - base);
if (tidx < mpi.numberOfThreads - 1 || mpi.rank < mpi.size - 1)
rowIndexTemp->push_back(rowidx[mpi.threadsCSR[tidx]->endRow] - base);
uint64_t sz_Value=0, sz_Column=0;
// Building columns & values arrays
printf("MLEM[%d [%d/%d]/ %d]: Calculation of Column and Value Ranges: rowidx[start] %u, rowidx[end] %u\n",
mpi.rank, tidx, mpi.numberOfThreads, mpi.size,
rowidx[start], rowidx[end]);
//for (i = rowidx[start]; i < rowidx[end]; ++i) {
//columnsTemp->push_back(rowElements[i].column());
// sz_Column++;
//valuesTemp->push_back(rowElements[i].value());
// sz_Value++;
//}
// DY: All we need is the length of these arries to allocate corresponding memory space.
sz_Value = sz_Column = rowidx[end] - rowidx[start];
mpi.threadsCSR[tidx]->nRowIndex = rowIndexTemp->size();
//mpi.threadsCSR[tidx]->nColumn = columnsTemp->size();
//DY: Now this show have a off by one, (overallocating by one)
mpi.threadsCSR[tidx]->nColumn = sz_Column + 1;
printf("MLEM[%d [%d/%d]/ %d]: Prepare to Allocate Memory for CSR Matrix Storage\n",
mpi.rank, tidx, mpi.numberOfThreads, mpi.size);
// Allocate memory
mpi.threadsCSR[tidx]->rowIndex =
MALLOC(uint64_t, mpi.threadsCSR[tidx]->nRowIndex);
if (mpi.threadsCSR[tidx]->rowIndex != NULL){
printf("MLEM[%d [%d/%d]/ %d]: Successfully Allocated rowIndex: %u Bytes. \n",
mpi.rank, tidx, mpi.numberOfThreads, mpi.size,
(mpi.threadsCSR[tidx]->nRowIndex)*sizeof(uint64_t));
}else{
throw std::runtime_error("Cannot Allocate Memory");
}
mpi.threadsCSR[tidx]->columns =
MALLOC(uint32_t, mpi.threadsCSR[tidx]->nColumn);
if (mpi.threadsCSR[tidx]->columns != NULL){
printf("MLEM[%d [%d/%d]/ %d]: Successfully Allocated columns: %u Bytes. \n",
mpi.rank, tidx, mpi.numberOfThreads, mpi.size,
(mpi.threadsCSR[tidx]->nRowIndex)*sizeof(uint32_t));
}else{
throw std::runtime_error("Cannot Allocate Memory");
}
mpi.threadsCSR[tidx]->values =
MALLOC(float, mpi.threadsCSR[tidx]->nColumn);
if (mpi.threadsCSR[tidx]->values != NULL){
printf("MLEM[%d [%d/%d]/ %d]: Successfully Allocated values: %u Bytes. \n",
mpi.rank, tidx, mpi.numberOfThreads, mpi.size,
(mpi.threadsCSR[tidx]->nRowIndex)*sizeof(float));
}else{
throw std::runtime_error("Cannot Allocate Memory");
}
// Copy the values from the temp arrays to the array real ones
for (i = 0; i < mpi.threadsCSR[tidx]->nRowIndex; ++i)
mpi.threadsCSR[tidx]->rowIndex[i] = rowIndexTemp->at(i);
for (i = 0; i < mpi.threadsCSR[tidx]->nColumn; ++i) {
//for (i = rowidx[start]; i < rowidx[end]; ++i) {
mpi.threadsCSR[tidx]->columns[i] = rowElements[i + rowidx[start]].column();
mpi.threadsCSR[tidx]->values[i] = rowElements[ i + rowidx[start]].value();
}
delete rowIndexTemp;
//delete columnsTemp;
//delete valuesTemp;
}
free(rowidx);
#ifndef MESSUNG
printf("\nThreads Partitioning\n"
"Rows: %d, Columns: %d Matrix elements: %u, \n"
"MPI Node: %d, avg per node: %f, avg per thread: %f\n",
matrix->rows(), matrix->columns(), matrix->elements(),
mpi.rank, avgElemsPerNode, avgElemsPerThread);
uint64_t totalE = 0, totalR = 0;
for (int i = 0; i < mpi.numberOfThreads; ++i) {
printf("MLEM[%d [%d/%d]/ %d]: Range from %d - %d, Elements: %d\n",
mpi.rank, i, mpi.numberOfThreads, mpi.size,
mpi.threadsCSR[i]->startRow, mpi.threadsCSR[i]->endRow,
mpi.threadsCSR[i]->nColumn);
totalE += mpi.threadsCSR[i]->nColumn;
totalR += mpi.threadsCSR[i]->nRowIndex;
}
printf("Total elements: %u, total Rows: %d \n", totalE, totalR);
#endif
}
#else
void splitMatrix(Csr4Matrix* matrix, MpiData& mpi)
{
uint64_t sum = 0, numOfElem = 0, totalElements = 0;
uint32_t row = 0;
int idx = 0;
totalElements = matrix->elements();
// Creating correct row index vector; starting with 0!
const uint64_t *rowidxA = matrix->getRowIdx();
const RowElement<float> *rowElements = matrix->getData();
uint64_t *rowidx = (uint64_t *) malloc((matrix->rows() + 1) * sizeof(uint64_t));
rowidx[0] = 0;
for (row = 0; row < matrix->rows(); ++row) rowidx[row + 1] = rowidxA[row];
mpi.mpiCSR = MALLOC(CSR, 1);
// Assign a range of rows for each MPI node
float avgElemsPerNode = (float)totalElements / (float)mpi.size;
if (0 == mpi.rank) mpi.range.startRow = 0;
for (row = 0; row < matrix->rows(); ++row) {
sum += matrix->elementsInRow(row);
numOfElem += matrix->elementsInRow(row);
if (sum > avgElemsPerNode * (idx + 1)) {
if (mpi.rank == idx) {
mpi.range.endRow = row;
mpi.numberOfElements = numOfElem;
}
++idx;
numOfElem = 0;
if (mpi.rank == idx) mpi.range.startRow = row;
}
}
if (mpi.rank == mpi.size - 1) {
mpi.range.endRow = matrix->rows();
mpi.numberOfElements = numOfElem;
}
// Assgin a range of rows for each thread in MPI (OMP)
mpi.mpiCSR->startRow = mpi.range.startRow;
mpi.mpiCSR->endRow = mpi.range.endRow;
// Create the the split matrix for each node or each thread
uint32_t i, start, end, length;
uint64_t base;
std::vector<uint64_t> *rowIndexTemp = new std::vector<uint64_t>();
std::vector<uint32_t> *columnsTemp = new std::vector<uint32_t>();
std::vector<float> *valuesTemp = new std::vector<float>();
start = mpi.mpiCSR->startRow;
end = mpi.mpiCSR->endRow;
base = rowidx[start];
// Building row index array
for (i = start; i < end; ++i) rowIndexTemp->push_back(rowidx[i] - base);
if (mpi.rank < mpi.size - 1)
rowIndexTemp->push_back(rowidx[end] - base);
// Building columns & values arrays
for (i = rowidx[start]; i < rowidx[end]; ++i) {
columnsTemp->push_back(rowElements[i].column());
valuesTemp->push_back(rowElements[i].value());
}
mpi.mpiCSR->nRowIndex = rowIndexTemp->size();
mpi.mpiCSR->nColumn = columnsTemp->size();
// Allocate memory
mpi.mpiCSR->rowIndex = MALLOC(uint64_t, mpi.mpiCSR->nRowIndex);
mpi.mpiCSR->columns = MALLOC(uint32_t, mpi.mpiCSR->nColumn);
mpi.mpiCSR->values = MALLOC(float, mpi.mpiCSR->nColumn);
// Copy the values from the temp arrays to the array real ones
for (i = 0; i < mpi.mpiCSR->nRowIndex; ++i)
mpi.mpiCSR->rowIndex[i] = rowIndexTemp->at(i);
for (i = 0; i < mpi.mpiCSR->nColumn; ++i) {
mpi.mpiCSR->columns[i] = columnsTemp->at(i);
mpi.mpiCSR->values[i] = valuesTemp->at(i);
}
delete rowIndexTemp;
delete columnsTemp;
delete valuesTemp;
free(rowidx);
#ifndef MESSUNG
printf("MLEM[%d/%d]: Range from %d to %d, Elements: %d\n",
mpi.rank, mpi.size, mpi.mpiCSR->startRow, mpi.mpiCSR->endRow,
mpi.mpiCSR->nColumn);
#endif
}
#endif
void cleanMemory(MpiData& mpi)
{
#ifdef _OMP_
#pragma omp parallel
{
const int tidx = omp_get_thread_num();
FREE(mpi.threadsCSR[tidx]->rowIndex);
FREE(mpi.threadsCSR[tidx]->columns);
FREE(mpi.threadsCSR[tidx]->values);
FREE(mpi.threadsCSR[tidx]);
#pragma omp master
FREE(mpi.threadsCSR);
}
#else
FREE(mpi.mpiCSR->rowIndex);
FREE(mpi.mpiCSR->columns);
FREE(mpi.mpiCSR->values);
FREE(mpi.mpiCSR);
#endif
}
int main(int argc, char *argv[])
{
ProgramOptions progops = handleCommandLine(argc, argv);
#ifndef MESSUNG
std::cout << "Matrix file: " << progops.mtxfilename << std::endl;
std::cout << "Input file: " << progops.infilename << std::endl;
std::cout << "Output file: " << progops.outfilename << std::endl;
std::cout << "Iterations: " << progops.iterations << std::endl;
std::cout << "Number of threads each MPI node: " << progops.numberOfThreads << std::endl;
#endif
Csr4Matrix* matrix = new Csr4Matrix (progops.mtxfilename);
uint32_t nRows = matrix->rows();
uint32_t nColumns = matrix->columns();
Vector<int> lmsino(progops.infilename);
Vector<float> image(nColumns, 0.0);
matrix->mapRows(0, nRows);
MpiData mpi = initializeMpiOmp(argc, argv, progops.numberOfThreads);
splitMatrix(matrix, mpi);
if (mpi.rank == 0) delete matrix;
// Main algorithm
mlem(mpi, lmsino, image, progops.iterations, nRows, nColumns);
if (0 == mpi.rank) image.writeToFile(progops.outfilename);
cleanMemory(mpi);
MPI_Finalize();
return 0;
}
| gpl-3.0 |
axpokl/display | cpp/3-4.cpp | 572 | #include "disp.h"//ʹÓÃDisplayµ¥Ôª¿â
pbitmap img1,img2;
int main(){
createwin(800,600);//½¨Á¢´°¿Ú
img1=loadbmp("display.png");//¶ÁȡͼƬ
img2=loadbmp("display.png");//¶ÁȡͼƬ
drawbmp(img1,(getwidth()-img1->width)/2,(getheight()-img1->height)/2);//»æÖÆÍ¼Æ¬1
freshwin();//ˢд°¿Ú
msgbox("ͼƬ1");//Êä³ö»æÖÆÍê³ÉÐÅÏ¢
bar(img2,img2->width/4,img2->height/4,img2->width/2,img2->height/2,transparent,blue);//»æÖƾØÐε½Í¼Æ¬2Öмä
drawbmp(img2,(getwidth()-img2->width)/2,(getheight()-img2->height)/2);//»æÖÆÍ¼Æ¬2
freshwin();//ˢд°¿Ú
msgbox("ͼƬ2");//Êä³ö»æÖÆÍê³ÉÐÅÏ¢
return 0;}
| gpl-3.0 |
archtaurus/laozhao-python-codes | src/pycode0x0019.py | 1588 | #!/usr/bin/env python2
# -*- coding:utf-8 -*-
"""老赵的Python代码碎片之一
文件: pycode0x0019.py
功能: 读心术(人类版)
许可: General Public License
作者: Zhao Xin (赵鑫) <[email protected]>
时间: 2016.02.27
"""
# import randint for make_a_guess
from random import randint as make_a_guess
# define the constants
MIN, MAX = 0, 100
BINGO = make_a_guess(MIN, MAX)
REQUEST_INPUT = "Take a guess: "
TOO_LOW = "Your guess was too low!\n"
TOO_HIGH = "Your guess was too high!\n"
PLAYER_WON = "You've guessed my number in %d times!"
def guess_game():
"""Player guess a random number in range 0~100
"""
# define the variables
guess = None
user_input = ''
times = 0
# game start
print ("Let's play a guessing game!\n\n"
"The computer will think of a number\n"
"I(the computer) have thought of a number between 0 and 100.\n")
# game playing
while True:
while True:
# player makes a guess
user_input = raw_input(REQUEST_INPUT).strip()
# validate user input
if user_input.isdigit():
break
guess = int(user_input)
times += 1
# computer checks the guess
if guess < BINGO: # player's guess is lower
print (TOO_LOW)
elif guess > BINGO: # player's guess is higher
print (TOO_HIGH)
else: # otherwise is BINGO
break
# computer always wins
print (PLAYER_WON % times)
if __name__ == '__main__':
guess_game()
| gpl-3.0 |
angrySCV/scala-sample-from-Codingame.com | src/main/scala/Organic_Compounds/Solution.scala | 1996 | /**
* Created by Kotobotov.ru on 01.10.2018.
*/
object Solution extends App {
val n = readInt
val rowString= (for(i <- 0 until n) yield readLine).toArray
val maxElementsSize = rowString.map(_.size / 3).max
sealed trait Carbon extends Product with Serializable {
var allowedLinks = 0
}
case class CH(h: Int) extends Carbon {
allowedLinks = 4 - h
}
case class Link(input: Int) extends Carbon {
allowedLinks = 0
}
case object NoLink extends Carbon {
allowedLinks = 0
}
def toCarbon(input: String) =
if (input.startsWith("CH")) CH(input.substring(2).toInt)
else if (input.startsWith("("))
Link(
input
.replace("(", "")
.replace(")", "")
.toInt
)
else NoLink
val preparedDate: Array[Array[Carbon]] =
rowString.map { item =>
val result = item
.sliding(3, 3)
.map(toCarbon)
.toArray
result ++ Array.fill[Carbon](maxElementsSize - result.size)(NoLink) // in order to create Square Matrix
}.toArray ++ Array(Array.fill[Carbon](maxElementsSize)(NoLink)) // need at least 2 argument (so 2x2 matrix - minimum)
def validationTest(input: Array[Array[Carbon]]) = {
def eval(arg1: Carbon, arg2: Carbon) = { (arg1, arg2)
match {
case (Link(n), _) =>
arg2.allowedLinks -= n
case (_, Link(n))=>
arg1.allowedLinks -= n
case _ =>
}
}
def calculateAllowedLinks(input: Array[Array[Carbon]]) = {
input
.sliding(1, 2)
.toArray
.flatten
.foreach(
line => line.sliding(2, 1).foreach { case Array(a, b) => eval(a, b) }
)
}
calculateAllowedLinks(preparedDate)
calculateAllowedLinks(preparedDate.transpose)
preparedDate.map(item => item.map(_.allowedLinks)).flatten.forall(_ == 0)
}
val isValid = validationTest(preparedDate)
println(if (isValid) "VALID" else "INVALID")
}
| gpl-3.0 |
jameskirkpatrick23/ProLineContracting | Pro_Line_Contracting/app/controllers/testimonials_controller.rb | 182 | class TestimonialsController < ApplicationController
def index
end
def new
end
def create
end
def show
end
def edit
end
def update
end
def destroy
end
end | gpl-3.0 |
niavok/einheri | src/einheri/client/ClientGameManager.cpp | 333 | #include "ClientGameManager.h"
namespace ein {
ClientGameManager::ClientGameManager() {
inputModel = new InputModel();
cameraModel = new CameraModel();
decorationModel = new DecorationModel();
}
ClientGameManager::~ClientGameManager() {
delete cameraModel;
delete inputModel;
delete decorationModel;
}
}
| gpl-3.0 |
yamstudio/leetcode | csharp/1388.pizza-with-3-n-slices.cs | 872 | /*
* @lc app=leetcode id=1388 lang=csharp
*
* [1388] Pizza With 3n Slices
*/
using System;
using System.Linq;
// @lc code=start
public class Solution {
private static int MaxSizeSlices(int[] slices, int k) {
int n = slices.Length;
int[,] dp = new int[n + 1, k + 1];
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= k; ++j) {
if (i == 1) {
dp[i, j] = slices[0];
} else {
dp[i, j] = Math.Max(dp[i - 1, j], dp[i - 2, j - 1] + slices[i - 1]);
}
}
}
return dp[n, k];
}
public int MaxSizeSlices(int[] slices) {
int n = slices.Length, k = n / 3;
return Math.Max(MaxSizeSlices(slices.SkipLast(1).ToArray(), k), MaxSizeSlices(slices.Skip(1).ToArray(), k));
}
}
// @lc code=end
| gpl-3.0 |
jamescheney/database-wiki | src/org/dbwiki/data/query/handler/SingleVariableQueryNodeHandler.java | 1953 | /*
BEGIN LICENSE BLOCK
Copyright 2010-2011, Heiko Mueller, Sam Lindley, James Cheney and
University of Edinburgh
This file is part of Database Wiki.
Database Wiki 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.
Database Wiki 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 Database Wiki. If not, see <http://www.gnu.org/licenses/>.
END LICENSE BLOCK
*/
package org.dbwiki.data.query.handler;
/** QueryNodeHandler for queries with a single variable. In this case the
* root of the query variable tree is the only variable and the where clause
* and select clause cam be evaluated immediately on the given database node.
*
* @author hmueller
*
*/
import org.dbwiki.data.database.DatabaseElementNode;
import org.dbwiki.data.query.xaql.QueryVariable;
import org.dbwiki.data.query.xaql.SelectClause;
import org.dbwiki.data.query.xaql.WhereClause;
public class SingleVariableQueryNodeHandler extends QueryRootNodeHandler {
/*
* Private Variables
*/
private QueryVariable _variable;
/*
* Constructors
*/
public SingleVariableQueryNodeHandler(SelectClause selectClause, WhereClause whereClause, QueryVariable variable, QueryNodeHandler consumer) {
super(selectClause, whereClause, consumer);
_variable = variable;
}
/*
* Public Methods
*/
public void handle(DatabaseElementNode node) {
this.handle(new QueryNodeSet(_variable.name(), node));
}
}
| gpl-3.0 |
SplatDevs/HBRelog | Controls/TaskEditor.xaml.cs | 6352 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using HighVoltz.HBRelog.Converters;
using HighVoltz.HBRelog.Tasks;
namespace HighVoltz.HBRelog.Controls
{
/// <summary>
/// Interaction logic for TaskEditor.xaml
/// </summary>
public partial class TaskEditor : UserControl
{
public TaskEditor()
{
InitializeComponent();
}
object _source;
public object Source
{
get { return _source; }
set { _source = value; NotifyPropertyChanged("Source"); SourceChanged(value); }
}
void SourceChanged(object source)
{
if (!(source is BMTask))
throw new InvalidOperationException("Can only assign a BMTask derived class to Source");
BMTask task = (BMTask)source;
List<PropertyInfo> propertyList = task.GetType().GetProperties().
Where(pi => pi.GetCustomAttributesData().All(cad => cad.Constructor.DeclaringType != typeof(XmlIgnoreAttribute))).ToList();
PropertyGrid.Children.Clear();
PropertyGrid.RowDefinitions.Clear();
for (int index = 0; index < propertyList.Count; index++)
{
PropertyGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(22) });
var propNameText = new TextBlock()
{
Text = SpacifierConverter.GetSpaciousString(propertyList[index].Name),
Margin = new Thickness(2, 0, 2, 0)
};
Grid.SetRow(propNameText, index);
PropertyGrid.Children.Add(propNameText);
Control propEdit;
// check if the property has CustomTaskEditControl attribute attached
CustomTaskEditControlAttribute customControlAttr =
(CustomTaskEditControlAttribute)propertyList[index].GetCustomAttributes(typeof(CustomTaskEditControlAttribute), false).FirstOrDefault();
if (customControlAttr != null)
{
propEdit = (Control)Activator.CreateInstance(customControlAttr.ControlType);
if (!(propEdit is ICustomTaskEditControlDataBound))
throw new InvalidOperationException("CustomTaskEditControl must implement the ICustomTaskEditControlDataBound interface");
((ICustomTaskEditControlDataBound)propEdit).SetValue(propertyList[index].GetValue(task, null));
((ICustomTaskEditControlDataBound)propEdit).SetBinding(task, propertyList[index].Name);
}
else // no custom controls attached to property so load the default control for the property type
propEdit = GetControlForType(propertyList[index].PropertyType, propertyList[index].GetValue(task, null));
propEdit.Margin = new Thickness(0, 1, 0, 1);
propEdit.Tag = new { Task = task, Property = propertyList[index] };
Grid.SetColumn((UIElement)propEdit, 1);
Grid.SetRow((UIElement)propEdit, index);
PropertyGrid.Children.Add((UIElement)propEdit);
}
}
private Control GetCustomControl(Type type, object value)
{
Control ctrl = null;
return ctrl;
}
private Control GetControlForType(Type type, object value)
{
Control ctrl = null;
if (type == typeof(bool))
{
ctrl = new ComboBox();
((ComboBox)ctrl).Items.Add(true);
((ComboBox)ctrl).Items.Add(false);
((ComboBox)ctrl).SelectedItem = value;
((ComboBox)ctrl).SelectionChanged += TaskPropertyChanged;
}
else if (value is Enum)
{
ctrl = new ComboBox();
foreach (object val in Enum.GetValues(type))
((ComboBox)ctrl).Items.Add(val);
((ComboBox)ctrl).SelectedItem = value;
((ComboBox)ctrl).SelectionChanged += TaskPropertyChanged;
}
else
{
ctrl = new TextBox();
if (value != null)
((TextBox)ctrl).Text = value.ToString();
((TextBox)ctrl).TextChanged += TaskPropertyChanged;
}
return ctrl;
}
void TaskPropertyChanged(object sender, EventArgs e)
{
BMTask task = ((dynamic)((Control)sender).Tag).Task;
PropertyInfo pi = ((dynamic)((Control)sender).Tag).Property;
if (sender is ComboBox)
{
pi.SetValue(task, ((ComboBox)sender).SelectedValue, null);
}
else if (sender is TextBox)
{
string str = ((TextBox)sender).Text;
try
{
object val = Convert.ChangeType(str, pi.PropertyType);
pi.SetValue(task, val, null);
} // in case the type conversion fails fall back to default value.
catch (FormatException)
{
object defaultValue = GetDefaultValue(pi.PropertyType);
pi.SetValue(task, defaultValue, null);
}
}
((RoutedEventArgs)e).Handled = true;
}
public object GetDefaultValue(Type t)
{
if (t.IsValueType)
{
return Activator.CreateInstance(t);
}
else
{
return null;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}
| gpl-3.0 |
simondona/img-fft-filter-bec-tn | libraries/results.py | 8269 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2016 Simone Donadello
#
# 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/>.
class ResultList(object):
"""
This class contains the list of results objects and the methods
to modify them.
"""
def __init__(self, time_delta, frames_id):
"""
Initialize with an empty results list and time intervals.
Args:
frames_id (tuple): list of the frame ids
"""
self.results = []
#list of time intervals: each time it is modified update_time() must
#be called in order to propagate the time to the results
self.time_delta = time_delta
self.frames_id = frames_id
def frames_list(self):
"""
Returns the list of frames contained in the results list.
"""
return tuple(res.n_frame for res in self.results)
def set_fit_result(self, n_frame, res_keys, res_pars, res_xy, res_z):
"""
Add or update a fit result in the results list.
Args:
n_frame (int): frame number of the result
res_keys (list): ordered keys of the dictionary of the fit result
res_pars (dict): dictionary of the fit results
res_xy (tuple): tuple of np.array with the xy coordinates of the
fitted region
res_z (np.array): the values of the fitted function
"""
#if result already exists get it, otherwise create an empty result
#and append it
if n_frame in self.frames_list():
res = self.results[self._get_id(n_frame)]
else:
res = Result(n_frame)
self.results.append(res)
self.results.sort()
#set the result
res.fit_keys = res_keys
res.fit = res_pars
res.fit_xy = res_xy
res.fit_frame = res_z
#update keys since they can be non uniform now
self.update_results()
def set_pick(self, n_frame, pick_keys, pick_coords):
"""
Add or update a coordinates pick in the results list.
Args:
n_frame (int): frame number of the result
pick_keys (list): ordered keys of the dictionary of the pick
pick_coords (dict): dictionary of the picked coordinates
"""
#if result already exists get it, otherwise create an empty result
#and append it
if n_frame in self.frames_list():
res = self.results[self._get_id(n_frame)]
else:
res = Result(n_frame)
self.results.append(res)
self.results.sort()
#set the result
res.pick_keys = pick_keys
res.pick = pick_coords
#update keys since they can be non uniform now
self.update_results()
def update_results(self):
"""
Iterate over results in order to get uniform results
with the same keys and updates the frame times.
"""
for _r1 in self.results:
for _r2 in self.results:
_r2.fill_key_values(pick_keys=_r1.pick_keys,
fit_keys=_r1.fit_keys)
self.update_time()
def update_time(self):
"""
Updates the frame time in the results from the list of time intervals
stored in the class.
"""
time = 0
if len(self.frames_id) == len(self.time_delta):
for n_l, n_frame in enumerate(self.frames_id):
res = self.get_result(n_frame)
if res is not None:
#if the frame has a result set the time
res.time = time
time += self.time_delta[n_l]
else:
print "Error: wrong time-list format"
def _get_id(self, n_frame):
"""
Returns the id in the results list relative to a frame number id.
If the frame doesn not already have a result in the list None is
returned.
Args:
n_frame (int): frame id
"""
lst = self.frames_list()
if n_frame in lst:
return lst.index(n_frame)
else:
return None
def get_data(self, n_frame):
"""
Returns the dictionary with all the data contained in the result
relative to the specified frame.
Returns None if the frame doesn't have a result.
Args:
n_frame (int): frame number
"""
r_id = self._get_id(n_frame)
if r_id is not None:
return self.results[r_id].get_data()
else:
return None
def get_result(self, n_frame):
"""
Returns the result instance relative to the specified frame.
Returns None if the frame doesn't have a result.
Args:
n_frame (int): frame number
"""
r_id = self._get_id(n_frame)
if r_id is not None:
return self.results[r_id]
else:
return None
def keys(self):
"""
Returns the list of the ordered keys of the results in the list,
assuming that they are uniform (call update_results() if not).
"""
if len(self.results) > 0:
return self.results[0].keys()
else:
return []
class Result(object):
"""
This class contains the results (e.g. of the fitting and the picked
coordinates) for a specific frame.
"""
def __init__(self, n_frame):
"""
Initialize and empty result for a specific frame number.
Args:
n_frame (int): frame number of the result
"""
self.n_frame = int(n_frame)
#the results must be initialized with None if not present,
#and the keys with an empty list
self.fit = None
self.fit_keys = []
self.fit_xy = None
self.fit_frame = None
self.pick = None
self.pick_keys = []
self.time = 0
def __cmp__(self, other):
"""
Compares and order two results using frame number values.
"""
return self.n_frame.__cmp__(other.n_frame)
def fill_key_values(self, fit_keys, pick_keys):
"""
If the provided keys are not present in the result, they are added
and the result is filled with None for each field. This is needed when
different results must have uniform keys.
Args:
fit_keys (list): the list of keys relative to the fit results
to be (eventually) added
pick_keys (list): the list of keys relative to the picked
coordinates to be (eventually) added
"""
#the keys are updated only if the result is empty and if the keys
#are spcified
if self.fit is None and len(fit_keys) > 0:
#dictionary with None in every key
self.fit = dict(zip(fit_keys, tuple(None for _k in fit_keys)))
self.fit_keys = fit_keys
if self.pick is None and len(pick_keys) > 0:
#dictionary with None in every key
self.pick = dict(zip(pick_keys, tuple(None for _k in pick_keys)))
self.pick_keys = pick_keys
def keys(self):
"""
Returns a list of the ordered keys contained in the result.
"""
return ["frame", "time"] + self.fit_keys + self.pick_keys
def get_data(self):
"""
Returns a dictionary with all the results.
"""
values = [self.n_frame, self.time] + \
[self.fit[k] for k in self.fit_keys] + \
[self.pick[k] for k in self.pick_keys]
return dict(zip(self.keys(), values))
| gpl-3.0 |
sapphon/minecraftpython | src/main/resources/assets/techmage/scripts/techmage/warrior/drink_some_tussin.py | 365 | #name<=>Drink Some 'Tussin
#texture<=>potion_bottle_drinkable
#cooldown<=>12000
def drink_some_tussin(duration=9,power=1):
yell('Puttin\' some \'Tussin on it..and then comin\' for YOU!')
console('effect @p 2 '+str(int(duration/3)))
console('effect @p 10 '+str(int(duration))+' '+str(int(power)))
console('effect @p 22 '+str(int(duration/3)))
drink_some_tussin() | gpl-3.0 |
hellasmoon/graylog2-server | graylog2-server/src/main/java/org/graylog2/periodical/NodePingThread.java | 4905 | /**
* This file is part of Graylog.
*
* Graylog 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.
*
* Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>.
*/
package org.graylog2.periodical;
import org.graylog2.Configuration;
import org.graylog2.cluster.Node;
import org.graylog2.cluster.NodeNotFoundException;
import org.graylog2.cluster.NodeService;
import org.graylog2.notifications.Notification;
import org.graylog2.notifications.NotificationImpl;
import org.graylog2.notifications.NotificationService;
import org.graylog2.plugin.ServerStatus;
import org.graylog2.plugin.Tools;
import org.graylog2.plugin.periodical.Periodical;
import org.graylog2.shared.system.activities.Activity;
import org.graylog2.shared.system.activities.ActivityWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
/**
* @author Lennart Koopmann <[email protected]>
*/
public class NodePingThread extends Periodical {
private static final Logger LOG = LoggerFactory.getLogger(NodePingThread.class);
private final NodeService nodeService;
private final NotificationService notificationService;
private final ActivityWriter activityWriter;
private final Configuration configuration;
private final ServerStatus serverStatus;
@Inject
public NodePingThread(NodeService nodeService,
NotificationService notificationService,
ActivityWriter activityWriter,
Configuration configuration,
ServerStatus serverStatus) {
this.nodeService = nodeService;
this.notificationService = notificationService;
this.activityWriter = activityWriter;
this.configuration = configuration;
this.serverStatus = serverStatus;
}
@Override
public void doRun() {
final boolean isMaster = serverStatus.hasCapability(ServerStatus.Capability.MASTER);
try {
Node node = nodeService.byNodeId(serverStatus.getNodeId());
nodeService.markAsAlive(node, isMaster, configuration.getRestTransportUri());
} catch (NodeNotFoundException e) {
LOG.warn("Did not find meta info of this node. Re-registering.");
nodeService.registerServer(serverStatus.getNodeId().toString(),
isMaster,
configuration.getRestTransportUri(),
Tools.getLocalCanonicalHostname());
}
try {
// Remove old nodes that are no longer running. (Just some housekeeping)
nodeService.dropOutdated();
// Check that we still have a master node in the cluster, if not, warn the user.
if (nodeService.isAnyMasterPresent()) {
Notification notification = notificationService.build()
.addType(Notification.Type.NO_MASTER);
boolean removedNotification = notificationService.fixed(notification);
if (removedNotification) {
activityWriter.write(
new Activity("Notification condition [" + NotificationImpl.Type.NO_MASTER + "] " +
"has been fixed.", NodePingThread.class));
}
} else {
Notification notification = notificationService.buildNow()
.addNode(serverStatus.getNodeId().toString())
.addType(Notification.Type.NO_MASTER)
.addSeverity(Notification.Severity.URGENT);
notificationService.publishIfFirst(notification);
}
} catch (Exception e) {
LOG.warn("Caught exception during node ping.", e);
}
}
@Override
protected Logger getLogger() {
return LOG;
}
@Override
public boolean runsForever() {
return false;
}
@Override
public boolean stopOnGracefulShutdown() {
return false;
}
@Override
public boolean masterOnly() {
return false;
}
@Override
public boolean startOnThisNode() {
return true;
}
@Override
public boolean isDaemon() {
return true;
}
@Override
public int getInitialDelaySeconds() {
return 0;
}
@Override
public int getPeriodSeconds() {
return 1;
}
}
| gpl-3.0 |
tunacasserole/omni | app/models/omni/location_user.rb | 3350 | class Omni::LocationUser < ActiveRecord::Base
# METADATA (Start) ====================================================================
self.table_name = :location_users
self.primary_key = :location_user_id
# METADATA (End)
# BEHAVIOR (Start) ====================================================================
supports_fulltext
# BEHAVIOR (End)
# VALIDATIONS (Start) =================================================================
validates :display, presence: true, uniqueness: true
validates :user_id, presence: true
validates :location_id, presence: true
# VALIDATIONS (End)
# DEFAULTS (Start) ====================================================================
default :location_user_id, override: false, with: :guid
default :display, :override => true, to: lambda{|m| "#{m.user_display} - #{m.location_display}"}
default :is_manager, override: false, to: false
default :is_cashier, override: false, to: false
default :is_sales, override: false, to: false
default :is_back_office, override: false, to: false
default :is_destroyed, override: false, to: false
default :is_purchase_approver_1, override: false, to: false
default :is_purchase_approver_2, override: false, to: false
default :is_purchase_approver_3, override: false, to: false
# DEFAULTS (End)
# REFERENCE (Start) ===================================================================
reference do
display_attribute :display
query_attribute :display
item_template '{display}'
end
# REFERENCE (End)
# ASSOCIATIONS (Start) ================================================================
belongs_to :user, class_name: 'Buildit::User', foreign_key: 'user_id'
belongs_to :location, class_name: 'Omni::Location', foreign_key: 'location_id'
# ASSOCIATIONS (End)
# MAPPED ATTRIBUTES (Start) ===========================================================
mapped_attributes do
map :user_display, to: 'user.full_name'
map :location_display, to: 'location.display'
end
# MAPPED ATTRIBUTES (End)
# HOOKS (Start) =======================================================================
# HOOKS (End)
# INDEXING (Start) ====================================================================
searchable do
# Exact match attributes
string :location_user_id
string :location_id
string :user_id
string :display
string :location_display
string :user_display
# Partial match (contains) attributes
text :display_fulltext, using: :display
text :location_fulltext, using: :location_display
text :user_fulltext, using: :user_display
end
# STATES (Start) ====================================================================
# STATES (End)
def display_as
self.display
end
end # class Omni::LocationUser
| gpl-3.0 |
Vapekreng/SR | game/room/map_generator/titles/types_of_titles/mob/mob_data.py | 369 | from bearlibterminal import terminal
USED_KEYS = [terminal.TK_ESCAPE, terminal.TK_LEFT, terminal.TK_RIGHT, terminal.TK_DOWN, terminal.TK_UP]
COMMANDS = dict()
COMMANDS[terminal.TK_ESCAPE] = 'quit'
COMMANDS[terminal.TK_LEFT] = 'move left'
COMMANDS[terminal.TK_RIGHT] = 'move right'
COMMANDS[terminal.TK_DOWN] = 'move down'
COMMANDS[terminal.TK_UP] = 'move up'
| gpl-3.0 |
einsteinx2/WaveBox | WaveBox.Server/src/Transcoding/FFMpegOpusTranscoder.cs | 7533 | using System;
using System.Diagnostics;
using System.IO;
using Ninject;
using WaveBox.Core;
using WaveBox.Core.Extensions;
using WaveBox.Core.Model;
using WaveBox.Core.Model.Repository;
using WaveBox.Server.Extensions;
using WaveBox.Static;
namespace WaveBox.Transcoding {
public class FFMpegOpusTranscoder : AbstractTranscoder {
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public override TranscodeType Type { get { return TranscodeType.OPUS; } }
// Placeholder for ffmpeg opus support
public override string Codec { get { return "libopus"; } }
public override string Command { get { return "ffmpeg"; } }
public override string OutputExtension { get { return "opus"; } }
public override string MimeType { get { return "audio/opus"; } }
private Process FfmpegProcess;
public FFMpegOpusTranscoder(IMediaItem item, uint quality, bool isDirect, uint offsetSeconds, uint lengthSeconds) : base(item, quality, isDirect, offsetSeconds, lengthSeconds) {
}
public override void Run() {
try {
string ffmpegArguments = "-loglevel quiet -i \"" + Item.FilePath() + "\" -f wav -";
logger.IfInfo("Forking the process");
logger.IfInfo("ffmpeg " + ffmpegArguments);
// Create the ffmpeg process
FfmpegProcess = new Process();
FfmpegProcess.StartInfo.FileName = "ffmpeg";
FfmpegProcess.StartInfo.Arguments = ffmpegArguments;
FfmpegProcess.StartInfo.UseShellExecute = false;
FfmpegProcess.StartInfo.RedirectStandardOutput = true;
FfmpegProcess.StartInfo.RedirectStandardError = true;
// Create the opusenc object
logger.IfInfo("opusenc " + Arguments);
TranscodeProcess = new Process();
TranscodeProcess.StartInfo.FileName = "opusenc";
TranscodeProcess.StartInfo.Arguments = Arguments;
TranscodeProcess.StartInfo.UseShellExecute = false;
TranscodeProcess.StartInfo.RedirectStandardInput = true;
TranscodeProcess.StartInfo.RedirectStandardOutput = true;
TranscodeProcess.StartInfo.RedirectStandardError = false;
var buffer = new byte[8192];
FfmpegProcess.Start();
TranscodeProcess.Start();
var input = new BinaryWriter(TranscodeProcess.StandardInput.BaseStream);
int totalWritten = 0;
while (true) {
int bytesRead = FfmpegProcess.StandardOutput.BaseStream.Read(buffer, 0, 8192);
totalWritten += bytesRead;
if (bytesRead > 0) {
input.Write(buffer, 0, bytesRead);
}
if (bytesRead == 0 && FfmpegProcess.HasExited) {
input.Close();
FfmpegProcess.Close();
break;
}
}
logger.IfInfo("Waiting for processes to finish");
// Block until done
TranscodeProcess.WaitForExit();
logger.IfInfo("Process finished");
} catch (Exception e) {
logger.IfInfo("\t" + "Failed to start transcode process " + e);
try {
TranscodeProcess.Kill();
TranscodeProcess.Close();
} catch { /* do nothing if killing the process fails */ }
try {
FfmpegProcess.Kill();
FfmpegProcess.Close();
} catch { /* do nothing if killing the process fails */ }
// Set the state
State = TranscodeState.Failed;
// Inform the delegate
if ((object)TranscoderDelegate != null) {
TranscoderDelegate.TranscodeFailed(this);
}
return;
}
if (TranscodeProcess != null) {
int exitValue = TranscodeProcess.ExitCode;
logger.IfInfo("Exit value " + exitValue);
if (exitValue == 0) {
State = TranscodeState.Finished;
if ((object)TranscoderDelegate != null) {
TranscoderDelegate.TranscodeFinished(this);
}
} else {
State = TranscodeState.Failed;
if ((object)TranscoderDelegate != null) {
TranscoderDelegate.TranscodeFailed(this);
}
}
}
}
public override string Arguments {
get {
string codec = "libopus";
string options = null;
switch (Quality) {
case (uint)TranscodeQuality.Low:
// VBR - V9 quality (~64 kbps)
options = OpusencOptions(codec, 64);
break;
case (uint)TranscodeQuality.Medium:
// VBR - V5 quality (~128 kbps)
options = OpusencOptions(codec, 96);
break;
case (uint)TranscodeQuality.High:
// VBR - V2 quality (~192 kbps)
options = OpusencOptions(codec, 128);
break;
case (uint)TranscodeQuality.Extreme:
// VBR - V0 quality (~224 kbps)
options = OpusencOptions(codec, 160);
break;
default:
options = OpusencOptions(codec, Quality);
break;
}
return options;
}
}
public override uint? EstimatedBitrate {
get {
uint? bitrate = null;
switch (Quality) {
case (uint)TranscodeQuality.Low:
bitrate = 64;
break;
case (uint)TranscodeQuality.Medium:
bitrate = 96;
break;
case (uint)TranscodeQuality.High:
bitrate = 128;
break;
case (uint)TranscodeQuality.Extreme:
bitrate = 160;
break;
default:
bitrate = Quality;
break;
}
return bitrate;
}
}
private string OpusencOptions(String codec, uint quality) {
string theString = "--bitrate " + quality;
theString += " --quiet";
Song song = Injection.Kernel.Get<ISongRepository>().SongForId(Item.ItemId.Value);
theString += song.ArtistName == null ? String.Empty : " --comment ARTIST=\"" + song.ArtistName + "\"";
theString += song.AlbumName == null ? String.Empty : " --comment ALBUM=\"" + song.AlbumName + "\"";
theString += song.SongName == null ? String.Empty : " --comment TITLE=\"" + song.SongName + "\"";
theString += song.ReleaseYear == null ? String.Empty : " --comment DATE=\"" + song.ReleaseYear + "\"";
theString += " --vbr - " + OutputPath;
return theString;
}
}
}
| gpl-3.0 |
PeterTh/gedosato | source/utils/string_utils.cpp | 1338 | #include "utils/string_utils.h"
#include <stdarg.h>
#include <iomanip>
#include <dxgi1_2.h>
#include <d3d11_2.h>
bool matchWildcard(const string& str, const string& pattern) {
string regex = pattern;
const char* escapeChars[] = { ".", "+", "(", ")", "[", "]", "^", "$"};
for(auto ch : escapeChars) {
boost::replace_all(regex, ch, string("\\") + ch);
}
boost::replace_all(regex, "*", ".*");
boost::replace_all(regex, "?", ".");
regex = string(".*") + regex;
std::regex rx(regex, std::regex::icase);
return std::regex_match(str, rx);
}
std::ostream& operator<<(std::ostream& os, REFGUID guid) {
os << "{";
os << std::setfill('0');
os.width(8);
os << std::hex << guid.Data1 << '-';
os.width(4);
os << std::hex << guid.Data2 << '-';
os.width(4);
os << std::hex << guid.Data3 << '-';
os.width(2);
os << std::hex
<< static_cast<short>(guid.Data4[0])
<< static_cast<short>(guid.Data4[1])
<< '-'
<< static_cast<short>(guid.Data4[2])
<< static_cast<short>(guid.Data4[3])
<< static_cast<short>(guid.Data4[4])
<< static_cast<short>(guid.Data4[5])
<< static_cast<short>(guid.Data4[6])
<< static_cast<short>(guid.Data4[7]);
os << "}";
#define UUID_OBJECT(__UUID_OBJECT_) \
if(guid == __uuidof(__UUID_OBJECT_)) { \
os << "(__uuidof(" #__UUID_OBJECT_ "))"; \
}
#include "uuids.def"
return os;
}
| gpl-3.0 |
elffy/Meizhi | app/src/main/java/me/drakeet/meizhi/data/休息视频Data.java | 950 | /*
* Copyright (C) 2015 Drakeet <[email protected]>
*
* This file is part of Meizhi
*
* Meizhi 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.
*
* Meizhi 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 Meizhi. If not, see <http://www.gnu.org/licenses/>.
*/
package me.drakeet.meizhi.data;
import java.util.List;
import me.drakeet.meizhi.data.entity.Gank;
/**
* Created by drakeet on 8/15/15.
*/
public class 休息视频Data extends BaseData {
public List<Gank> results;
}
| gpl-3.0 |
Pneumaticat/Aperture | Aperture.Parser/HTML/Microsyntaxes/DatesAndTimes/Dates.cs | 1635 | using Aperture.Parser.DataStructures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aperture.Parser.HTML.Microsyntaxes.DatesAndTimes
{
public static class Dates
{
public static bool IsValidDateString(string input)
{
return ParseDateString(input) != null;
}
public static Date? ParseDateString(string input)
{
int position = 0;
Date? date = ParseDateComponent(input, ref position);
if (date == null || position < input.Length)
return null;
else
return date;
}
public static Date? ParseDateComponent(string input, ref int position)
{
YearAndMonth? yam = Months.ParseMonthComponent(input, ref position);
if (yam == null)
return null;
int maxday = DatesAndTimesUtils.DaysInMonth(yam.Value.Month, yam.Value.Year);
if (position >= input.Length || input[position] != '-')
return null;
else
position++;
int day;
string dayChars = ParserIdioms.CollectSequenceOfCharacters(input, ref position,
ch => ParserIdioms.ASCIIDigits.Contains(ch));
if (dayChars.Length != 2)
return null;
else
day = int.Parse(dayChars);
if (day < 1 || day > maxday)
return null;
else
return new Date(yam.Value.Year, yam.Value.Month, day);
}
}
}
| gpl-3.0 |
bobthebutcher/netconnect | tests/test_messages.py | 165 | from netconnect import messages
def test_message_output():
assert messages.send_command_error_msg('stuff', 'things') == 'stuff error sending "things" command'
| gpl-3.0 |
MitchTalmadge/Emoji-Tools | src/main/java/com/mitchtalmadge/emojitools/operations/splitting/SplittingOperation.java | 1708 | /*
* Copyright (C) 2015 - 2016 Mitch Talmadge (https://mitchtalmadge.com/)
* Emoji Tools helps users and developers of Android, iOS, and OS X extract, modify, and repackage Emoji fonts.
*
* 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.mitchtalmadge.emojitools.operations.splitting;
import com.mitchtalmadge.emojitools.gui.dialogs.OperationProgressDialog;
import com.mitchtalmadge.emojitools.operations.Operation;
import com.mitchtalmadge.emojitools.operations.OperationWorker;
import com.mitchtalmadge.emojitools.operations.splitting.splitters.AppleSplitterWorker;
import java.io.File;
public class SplittingOperation extends Operation {
private final File fontFile;
private final File extractionDirectory;
public SplittingOperation(File fontFile, File extractionDirectory) {
this.fontFile = fontFile;
this.extractionDirectory = extractionDirectory;
}
@Override
protected OperationWorker getWorker() {
return new AppleSplitterWorker(this, new OperationProgressDialog("Splitting Emoji Font..."), fontFile, extractionDirectory);
}
}
| gpl-3.0 |
lingcarzy/v5cart | system/cache/zone/214.php | 1778 | <?php return array (
0 =>
array (
'zone_id' => '3291',
'name' => 'Ariana',
),
1 =>
array (
'zone_id' => '3292',
'name' => 'Beja',
),
2 =>
array (
'zone_id' => '3293',
'name' => 'Ben Arous',
),
3 =>
array (
'zone_id' => '3294',
'name' => 'Bizerte',
),
4 =>
array (
'zone_id' => '3295',
'name' => 'Gabes',
),
5 =>
array (
'zone_id' => '3296',
'name' => 'Gafsa',
),
6 =>
array (
'zone_id' => '3297',
'name' => 'Jendouba',
),
7 =>
array (
'zone_id' => '3298',
'name' => 'Kairouan',
),
8 =>
array (
'zone_id' => '3299',
'name' => 'Kasserine',
),
9 =>
array (
'zone_id' => '3300',
'name' => 'Kebili',
),
10 =>
array (
'zone_id' => '3301',
'name' => 'Kef',
),
11 =>
array (
'zone_id' => '3302',
'name' => 'Mahdia',
),
12 =>
array (
'zone_id' => '3303',
'name' => 'Manouba',
),
13 =>
array (
'zone_id' => '3304',
'name' => 'Medenine',
),
14 =>
array (
'zone_id' => '3305',
'name' => 'Monastir',
),
15 =>
array (
'zone_id' => '3306',
'name' => 'Nabeul',
),
16 =>
array (
'zone_id' => '3307',
'name' => 'Sfax',
),
17 =>
array (
'zone_id' => '3308',
'name' => 'Sidi',
),
18 =>
array (
'zone_id' => '3309',
'name' => 'Siliana',
),
19 =>
array (
'zone_id' => '3310',
'name' => 'Sousse',
),
20 =>
array (
'zone_id' => '3311',
'name' => 'Tataouine',
),
21 =>
array (
'zone_id' => '3312',
'name' => 'Tozeur',
),
22 =>
array (
'zone_id' => '3313',
'name' => 'Tunis',
),
23 =>
array (
'zone_id' => '3314',
'name' => 'Zaghouan',
),
); ?> | gpl-3.0 |
rossbarclay/safepost | app/controllers/forwardings.js | 873 | /*
Safepost Messaging System https://safepo.st
Copyright (C) 2014 Ross Barclay
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/>.
*/
/*
*/
var ForwardingsController = Ember.Controller.extend( {
needs: [ 'settings' ]
} );
export
default ForwardingsController;
| gpl-3.0 |
Gnzlt/UCOmove | app/src/main/java/com/gnzlt/ucotren/ui/schedule/ScheduleFragment.java | 3338 | package com.gnzlt.ucotren.ui.schedule;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.gnzlt.ucotren.R;
import com.gnzlt.ucotren.adapter.ScheduleHoursAdapter;
import com.gnzlt.ucotren.databinding.FragmentScheduleBinding;
import com.gnzlt.ucotren.util.Constants;
import java.util.ArrayList;
import java.util.List;
public class ScheduleFragment extends Fragment implements ScheduleContract.View {
private static final String ARG_TRANSPORT_TYPE = "ARG_TRANSPORT_TYPE";
private SchedulePresenter mPresenter;
private FragmentScheduleBinding mBinding;
private String mTransportType;
private ScheduleHoursAdapter mAdapter;
public static ScheduleFragment newInstance(int transportType) {
ScheduleFragment fragment = new ScheduleFragment();
Bundle args = new Bundle();
args.putInt(ARG_TRANSPORT_TYPE, transportType);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTransportType = Constants.TRANSPORT_TYPES[getArguments().getInt(ARG_TRANSPORT_TYPE, 0)];
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mPresenter = new SchedulePresenter(this);
mBinding = DataBindingUtil.inflate(inflater,
R.layout.fragment_schedule,
container,
false);
mAdapter = new ScheduleHoursAdapter(new ArrayList<String>(0));
final GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
return mAdapter.isHeader(position) ? layoutManager.getSpanCount() : 1;
}
});
mBinding.list.setHasFixedSize(true);
mBinding.list.setLayoutManager(layoutManager);
mBinding.list.setAdapter(mAdapter);
mBinding.empty.message.setText(getString(R.string.error_no_departures));
if (Constants.TRANSPORT_TYPE_BUS.equals(mTransportType)) {
mBinding.titleCordoba.setText(getString(R.string.text_colon));
}
mPresenter.getSchedules(mTransportType);
return mBinding.getRoot();
}
@Override
public void onDestroyView() {
mPresenter.detachView();
super.onDestroyView();
}
@Override
public void showSchedules(List<String> departures) {
mAdapter.updateList(departures);
}
@Override
public void setProgressView(boolean active) {
mBinding.progress.progressView.setVisibility(active ? View.VISIBLE : View.GONE);
}
@Override
public void setEmptyView(boolean active) {
mBinding.empty.emptyView.setVisibility(active ? View.VISIBLE : View.GONE);
}
@Override
public void showToastMessage(String message) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
}
| gpl-3.0 |
MaladaN/MaladaN-Messenger-Client | src/net/strangled/maladan/shared/LocalLoginDataStore.java | 1701 | package net.strangled.maladan.shared;
import net.MaladaN.Tor.thoughtcrime.GetSQLConnection;
import net.strangled.maladan.cli.Main;
import net.strangled.maladan.serializables.Authentication.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class LocalLoginDataStore {
public static void saveLocaluser(User user) throws Exception {
Connection conn = GetSQLConnection.getConn();
if (conn != null && !dataSaved()) {
String sql = "INSERT INTO username (user) VALUES (?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setBytes(1, Main.serializeObject(user));
ps.execute();
conn.close();
}
}
public static boolean dataSaved() throws Exception {
Connection conn = GetSQLConnection.getConn();
if (conn != null) {
String sql = "SELECT user FROM username";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
boolean exists = rs.next();
conn.close();
return exists;
}
return false;
}
public static User getData() throws Exception {
Connection conn = GetSQLConnection.getConn();
if (conn != null) {
String sql = "SELECT user FROM username";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
rs.next();
byte[] serializedUser = rs.getBytes("user");
conn.close();
return (User) Main.reconstructSerializedObject(serializedUser);
}
return null;
}
}
| gpl-3.0 |
dev06/UpKeep | Assets/scripts/ui/Container.cs | 423 | using UnityEngine;
using System.Collections;
namespace Game
{
[RequireComponent (typeof(CanvasGroup))]
public class Container : MonoBehaviour {
public bool ShowInEdit;
private CanvasGroup canvasGroup;
public virtual void OnValidate()
{
if (canvasGroup == null) canvasGroup = GetComponent<CanvasGroup>();
canvasGroup.alpha = ShowInEdit ? 1 : 0;
}
public virtual void Enable()
{
}
}
}
| gpl-3.0 |
damienmarchal/genearead | GeneareadGUI/src/algorithm/text/adaptiveThreshold.cpp | 1074 | #include <header/algorithm/text/adaptiveThreshold.h>
AdaptiveThreshold::AdaptiveThreshold()
: w(5)
, C(2)
, thresholdType(cv::THRESH_BINARY)
, adaptiveMethod(cv::ADAPTIVE_THRESH_MEAN_C)
{
}
QString AdaptiveThreshold::getName() {
return "adaptiveThreshold";
}
void AdaptiveThreshold::setParameters(QObject* parameters) {
QVariant v;
if(!(v = parameters->property("w")).isNull()) {
w = (std::round(v.toFloat()*4.0f)+1)*2+1;
}
if(!(v = parameters->property("inv_mean")).isNull()) {
float vf = v.toFloat();
thresholdType = vf>0.5f ? cv::THRESH_BINARY_INV : cv::THRESH_BINARY;
adaptiveMethod = vf<=0.25f || vf>0.75f ? cv::ADAPTIVE_THRESH_MEAN_C : cv::ADAPTIVE_THRESH_GAUSSIAN_C;
}
/*if(!(v = parameters->property("mean")).isNull()) {
float vf = v.toFloat();
}*/
}
void AdaptiveThreshold::apply(Layer* in, Layer* out, Layer* mask) {
cv::adaptiveThreshold(*in, *out, 255, adaptiveMethod, thresholdType, w, C);
applyMask(in, out, mask);
}
| gpl-3.0 |
FSofTlpz/Garmin-DEM-Build | Input2/Properties/Resources.Designer.cs | 3000 | //------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Input2.Properties {
using System;
/// <summary>
/// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
/// </summary>
// Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
// -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
// Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
// mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Input2.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
/// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| gpl-3.0 |
r0ug3-Mary/Sr.GUI | build-FAKKIT-Desktop-Debug/moc_httprequestworker.cpp | 5302 | /****************************************************************************
** Meta object code from reading C++ file 'httprequestworker.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../FAKKIT/httprequestworker.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'httprequestworker.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.3.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_HttpRequestWorker_t {
QByteArrayData data[8];
char stringdata[108];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_HttpRequestWorker_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_HttpRequestWorker_t qt_meta_stringdata_HttpRequestWorker = {
{
QT_MOC_LITERAL(0, 0, 17),
QT_MOC_LITERAL(1, 18, 21),
QT_MOC_LITERAL(2, 40, 0),
QT_MOC_LITERAL(3, 41, 18),
QT_MOC_LITERAL(4, 60, 6),
QT_MOC_LITERAL(5, 67, 19),
QT_MOC_LITERAL(6, 87, 14),
QT_MOC_LITERAL(7, 102, 5)
},
"HttpRequestWorker\0on_execution_finished\0"
"\0HttpRequestWorker*\0worker\0"
"on_manager_finished\0QNetworkReply*\0"
"reply"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_HttpRequestWorker[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 24, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
5, 1, 27, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, 0x80000000 | 3, 4,
// slots: parameters
QMetaType::Void, 0x80000000 | 6, 7,
0 // eod
};
void HttpRequestWorker::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
HttpRequestWorker *_t = static_cast<HttpRequestWorker *>(_o);
switch (_id) {
case 0: _t->on_execution_finished((*reinterpret_cast< HttpRequestWorker*(*)>(_a[1]))); break;
case 1: _t->on_manager_finished((*reinterpret_cast< QNetworkReply*(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< HttpRequestWorker* >(); break;
}
break;
case 1:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QNetworkReply* >(); break;
}
break;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (HttpRequestWorker::*_t)(HttpRequestWorker * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&HttpRequestWorker::on_execution_finished)) {
*result = 0;
}
}
}
}
const QMetaObject HttpRequestWorker::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_HttpRequestWorker.data,
qt_meta_data_HttpRequestWorker, qt_static_metacall, 0, 0}
};
const QMetaObject *HttpRequestWorker::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *HttpRequestWorker::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_HttpRequestWorker.stringdata))
return static_cast<void*>(const_cast< HttpRequestWorker*>(this));
return QObject::qt_metacast(_clname);
}
int HttpRequestWorker::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
}
return _id;
}
// SIGNAL 0
void HttpRequestWorker::on_execution_finished(HttpRequestWorker * _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_END_MOC_NAMESPACE
| gpl-3.0 |
will-bainbridge/OpenFOAM-dev | src/regionModels/surfaceFilmModels/submodels/kinematic/filmMomentumTransportModel/filmMomentumTransportModel/filmMomentumTransportModel.H | 4257 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2013-2020 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::regionModels::surfaceFilmModels::filmMomentumTransportModel
Description
Base class for film turbulence models
SourceFiles
filmMomentumTransportModel.C
filmMomentumTransportModelNew.C
\*---------------------------------------------------------------------------*/
#ifndef filmMomentumTransportModel_H
#define filmMomentumTransportModel_H
#include "filmSubModelBase.H"
#include "runTimeSelectionTables.H"
#include "fvMatricesFwd.H"
#include "volFieldsFwd.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace regionModels
{
namespace surfaceFilmModels
{
/*---------------------------------------------------------------------------*\
Class filmMomentumTransportModel Declaration
\*---------------------------------------------------------------------------*/
class filmMomentumTransportModel
:
public filmSubModelBase
{
public:
//- Runtime type information
TypeName("filmMomentumTransportModel");
// Declare runtime constructor selection table
declareRunTimeSelectionTable
(
autoPtr,
filmMomentumTransportModel,
dictionary,
(
surfaceFilmRegionModel& film,
const dictionary& dict
),
(film, dict)
);
// Constructors
//- Construct null
filmMomentumTransportModel(surfaceFilmRegionModel& film);
//- Construct from type name, dictionary and surface film model
filmMomentumTransportModel
(
const word& modelType,
surfaceFilmRegionModel& film,
const dictionary& dict
);
//- Disallow default bitwise copy construction
filmMomentumTransportModel(const filmMomentumTransportModel&) = delete;
// Selectors
//- Return a reference to the selected injection model
static autoPtr<filmMomentumTransportModel> New
(
surfaceFilmRegionModel& film,
const dictionary& dict
);
//- Destructor
virtual ~filmMomentumTransportModel();
// Member Functions
// Evolution
//- Return the film surface velocity
virtual tmp<volVectorField::Internal> Us() const = 0;
//- Return the film turbulence viscosity
virtual tmp<volScalarField> mut() const = 0;
//- Correct/update the model
virtual void correct() = 0;
//- Return the source for the film momentum equation
virtual tmp<fvVectorMatrix> Su(volVectorField& U) const = 0;
// Member Operators
//- Disallow default bitwise assignment
void operator=(const filmMomentumTransportModel&) = delete;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace surfaceFilmModels
} // End namespace regionModels
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
ratrecommends/dice-heroes | main/src/com/vlaaad/dice/game/actions/imp/AreaOfDefence.java | 1428 | /*
* Dice heroes is a turn based rpg-strategy game where characters are dice.
* Copyright (C) 2016 Vladislav Protsenko
*
* 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.vlaaad.dice.game.actions.imp;
import com.badlogic.gdx.utils.Array;
import com.vlaaad.dice.game.actions.results.IActionResult;
import com.vlaaad.dice.game.actions.results.imp.AreaOfDefenceResult;
import com.vlaaad.dice.game.config.abilities.Ability;
import com.vlaaad.dice.game.objects.Creature;
/**
* Created 22.01.14 by vlaaad
*/
public class AreaOfDefence extends AreaOfAttack {
public AreaOfDefence(Ability owner) {
super(owner);
}
@Override protected IActionResult createResult(Creature creature, Array<Creature> targets) {
return new AreaOfDefenceResult(owner, creature, targets, type, level);
}
}
| gpl-3.0 |
PhoenixDevTeam/Phoenix-for-VK | app/src/main/java/biz/dealnote/messenger/db/interfaces/ITopicsStore.java | 916 | package biz.dealnote.messenger.db.interfaces;
import java.util.List;
import androidx.annotation.CheckResult;
import androidx.annotation.NonNull;
import biz.dealnote.messenger.db.model.entity.OwnerEntities;
import biz.dealnote.messenger.db.model.entity.PollEntity;
import biz.dealnote.messenger.db.model.entity.TopicEntity;
import biz.dealnote.messenger.model.criteria.TopicsCriteria;
import io.reactivex.Completable;
import io.reactivex.Single;
/**
* Created by admin on 13.12.2016.
* phoenix
*/
public interface ITopicsStore {
@CheckResult
Single<List<TopicEntity>> getByCriteria(@NonNull TopicsCriteria criteria);
@CheckResult
Completable store(int accountId, int ownerId, List<TopicEntity> topics, OwnerEntities owners, boolean canAddTopic, int defaultOrder, boolean clearBefore);
@CheckResult
Completable attachPoll(int accountId, int ownerId, int topicId, PollEntity pollDbo);
} | gpl-3.0 |
habedi/Emacs-theme-creator | Ethemer/MeThemerApp/views.py | 370 | from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
#def index(request):
# return HttpResponse("i'm going to show you the world on!.")
def index(request):
template = loader.get_template('index.html')
context = RequestContext(request)
return HttpResponse(template.render(context))
| gpl-3.0 |
resistor58/deaths-gmod-server | wire/lua/entities/gmod_wire_plug/cl_init.lua | 267 |
include('shared.lua')
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.RenderGroup = RENDERGROUP_OPAQUE
function ENT:DrawEntityOutline()
if (GetConVar("wire_plug_drawoutline"):GetBool()) then
self.BaseClass.DrawEntityOutline( self )
end
end | gpl-3.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.