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) 2014 www.cybersearch2.com.au 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 au.com.cybersearch2.classy_logic.tutorial18; import java.io.File; import au.com.cybersearch2.classy_logic.JavaTestResourceEnvironment; import au.com.cybersearch2.classy_logic.ProviderManager; import au.com.cybersearch2.classy_logic.QueryParams; import au.com.cybersearch2.classy_logic.QueryProgram; import au.com.cybersearch2.classy_logic.expression.ExpressionException; import au.com.cybersearch2.classy_logic.interfaces.SolutionHandler; import au.com.cybersearch2.classy_logic.parser.FileAxiomProvider; import au.com.cybersearch2.classy_logic.pattern.Axiom; import au.com.cybersearch2.classy_logic.query.QueryExecutionException; import au.com.cybersearch2.classy_logic.query.Solution; import au.com.cybersearch2.classy_logic.terms.Parameter; /** * ForeignColors * Demonstrates Choice selection terms consisting of local axiom terms for locale-sensitive matching of values. * The Choice selects a color swatch by name in the language of the locale. * @author Andrew Bowley * 17 Mar 2015 */ public class ForeignColors { static final String FOREIGN_LEXICON = "list<term> german_list(german.colors : resource);\n" + "list<term> french_list(french.colors : resource);\n" + "scope french (language=\"fr\", region=\"FR\"){}\n" + "scope german (language=\"de\", region=\"DE\"){}\n" + "axiom french.colors (aqua, black, blue, white)\n" + " {\"bleu vert\", \"noir\", \"bleu\", \"blanc\"};\n" + "axiom german.colors (aqua, black, blue, white)\n" + " {\"Wasser\", \"schwarz\", \"blau\", \"weiß\"};\n" + "query color_query (german.colors:german.colors) >> (french.colors:french.colors);\n"; static final String FOREIGN_COLORS = "axiom colors (aqua, black, blue, white);\n" + "axiom german.colors (aqua, black, blue, white) : resource;\n" + "axiom french.colors (aqua, black, blue, white) : resource;\n" + "local select(colors);\n" + "choice swatch (name, red, green, blue)\n" + "{select[aqua], 0, 255, 255}\n" + "{select[black], 0, 0, 0}\n" + "{select[blue], 0, 0, 255}\n" + "{select[white], 255, 255, 255};\n" + "axiom shade (name) : parameter;\n" + "scope french (language=\"fr\", region=\"FR\")\n" + "{\n" + " query color_query (shade : swatch);\n" + "}" + "scope german (language=\"de\", region=\"DE\")\n" + "{\n" + " query color_query (shade : swatch);\n" + "}"; /** ProviderManager is Axiom source for eXPL compiler */ private ProviderManager providerManager; private static FileAxiomProvider[] fileAxiomProviders; public ForeignColors() { providerManager = new ProviderManager(); File testPath = new File(JavaTestResourceEnvironment.DEFAULT_RESOURCE_LOCATION); if (!testPath.exists()) testPath.mkdir(); fileAxiomProviders = new FileAxiomProvider[2]; fileAxiomProviders[0] = new FileAxiomProvider("german.colors", testPath); fileAxiomProviders[1] = new FileAxiomProvider("french.colors", testPath); for (FileAxiomProvider provider: fileAxiomProviders) providerManager.putAxiomProvider(provider); } public void createForeignLexicon() { QueryProgram queryProgram = new QueryProgram(providerManager); queryProgram.parseScript(FOREIGN_LEXICON); try { queryProgram.executeQuery("color_query", new SolutionHandler(){ @Override public boolean onSolution(Solution solution) { System.out.println(solution.getAxiom("german.colors").toString()); System.out.println(solution.getAxiom("french.colors").toString()); return true; }}); } finally { fileAxiomProviders[0].close(); fileAxiomProviders[1].close(); } } /** * Compiles the GERMAN_COLORS script and runs the "color_query" query, displaying the solution on the console. * @return AxiomTermList iterator containing the final Calculator solution */ public String getColorSwatch(String language, String name) { QueryProgram queryProgram = new QueryProgram(providerManager); queryProgram.parseScript(FOREIGN_COLORS); // Create QueryParams object for Global scope and query "stamp_duty_query" QueryParams queryParams = queryProgram.getQueryParams(language, "color_query"); // Add a shade Axiom with a specified color term // This axiom goes into the Global scope and is removed at the start of the next query. Solution initialSolution = queryParams.getInitialSolution(); initialSolution.put("shade", new Axiom("shade", new Parameter("name", name))); final StringBuilder builder = new StringBuilder(); queryParams.setSolutionHandler(new SolutionHandler(){ @Override public boolean onSolution(Solution solution) { builder.append(solution.getAxiom("swatch").toString()); return true; }}); queryProgram.executeQuery(queryParams); return builder.toString(); } /** * Run tutorial * The expected result:<br/> colors(aqua = Wasser, black = schwarz, blue = blau, white = weiß)<br/> colors(aqua = bleu vert, black = noir, blue = bleu, white = blanc)<br/> swatch(name = Wasser, red = 0, green = 255, blue = 255)<br/> swatch(name = schwarz, red = 0, green = 0, blue = 0)<br/> swatch(name = weiß, red = 255, green = 255, blue = 255)<br/> swatch(name = blau, red = 0, green = 0, blue = 255)<br/> * @param args */ public static void main(String[] args) { try { ForeignColors foreignColors = new ForeignColors(); foreignColors.createForeignLexicon(); System.out.println(foreignColors.getColorSwatch("french", "bleu vert")); System.out.println(foreignColors.getColorSwatch("french", "noir")); System.out.println(foreignColors.getColorSwatch("french", "blanc")); System.out.println(foreignColors.getColorSwatch("french", "bleu")); System.out.println(foreignColors.getColorSwatch("german", "Wasser")); System.out.println(foreignColors.getColorSwatch("german", "schwarz")); System.out.println(foreignColors.getColorSwatch("german", "weiß")); System.out.println(foreignColors.getColorSwatch("german", "blau")); } catch (ExpressionException e) { e.printStackTrace(); System.exit(1); } catch (QueryExecutionException e) { e.printStackTrace(); System.exit(1); } finally { fileAxiomProviders[0].close(); fileAxiomProviders[1].close(); } System.exit(0); } }
andrew-bowley/xpl
tutorial/src/main/java/au/com/cybersearch2/classy_logic/tutorial18/ForeignColors.java
Java
gpl-3.0
7,706
/* Copyright 2015 Philipp Adam, Manuel Caspari, Nicolas Lukaschek contact@ravenapp.org This file is part of Raven. Raven 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. Raven 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 Raven. If not, see <http://www.gnu.org/licenses/>. */ package hash; import java.security.SecureRandom; import org.spongycastle.crypto.generators.SCrypt; public class ScryptTool { public static byte [] hash(byte [] plain, byte [] salt){ return SCrypt.generate(plain, salt, 16384, 8, 1, 64); // Colin Percival default values } public static byte [] hash(String plain, String salt){ return SCrypt.generate(plain.getBytes(), salt.getBytes(), 16384, 8, 1, 64); // Colin Percival default values } public static byte [] hashLow(byte [] plain, byte [] salt){ return SCrypt.generate(plain, salt, 8192, 8, 1, 64); } public static byte [] hashLow(String plain, String salt){ return SCrypt.generate(plain.getBytes(), salt.getBytes(), 8192, 8, 1, 64); } public static byte [] hashUltraLow(byte [] plain, byte [] salt){ return SCrypt.generate(plain, salt, 4096, 8, 1, 64); // } public static byte [] hashUltraLow(String plain, String salt){ return SCrypt.generate(plain.getBytes(), salt.getBytes(), 4096, 8, 1, 64); } public static byte [] generateSalt(int length){ byte [] erg = new byte[length]; SecureRandom random = new SecureRandom(); random.nextBytes(erg); return erg; } }
manuelsc/Raven-Messenger
Raven Core/src/hash/ScryptTool.java
Java
gpl-3.0
1,890
package cn.ac.rcpa.bio.proteomics.filter; import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptide; import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptideHit; import cn.ac.rcpa.filter.IFilter; public class IdentifiedPeptideHitFilterByPeptideFilter implements IFilter<IIdentifiedPeptideHit> { private IFilter<IIdentifiedPeptide> pepFilter; public IdentifiedPeptideHitFilterByPeptideFilter(IFilter<IIdentifiedPeptide> pepFilter) { this.pepFilter = pepFilter; } public boolean accept(IIdentifiedPeptideHit e) { return e.getPeptideCount() > 0 && pepFilter.accept(e.getPeptide(0)); } public String getType() { return pepFilter.getType(); } }
shengqh/RcpaBioJava
src/cn/ac/rcpa/bio/proteomics/filter/IdentifiedPeptideHitFilterByPeptideFilter.java
Java
gpl-3.0
695
package it.unibas.lunatic.test.mc.dbms.basicscenario; import it.unibas.lunatic.Scenario; import it.unibas.lunatic.model.chase.chasemc.operators.ChaseMCScenario; import it.unibas.lunatic.model.chase.chasemc.DeltaChaseStep; import it.unibas.lunatic.model.chase.commons.operators.ChaserFactoryMC; import it.unibas.lunatic.test.References; import it.unibas.lunatic.test.UtilityTest; import it.unibas.lunatic.test.checker.CheckExpectedSolutionsTest; import junit.framework.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestSQLPersons extends CheckExpectedSolutionsTest { private static Logger logger = LoggerFactory.getLogger(TestSQLPersons.class); public void testScenarioNoPermutation() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); setConfigurationForTest(scenario); scenario.getCostManagerConfiguration().setDoBackward(false); scenario.getCostManagerConfiguration().setDoPermutations(false); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); if (logger.isDebugEnabled()) logger.debug("Scenario " + getTestName("persons", scenario)); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(1, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expected-nop", result); } public void testScenario() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); setConfigurationForTest(scenario); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); // if (logger.isDebugEnabled()) logger.debug("Scenario " + getTestName("persons", scenario)); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(9, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expectedPersons", result); } public void testScenarioNoPermutationNonSymmetric() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); setConfigurationForTest(scenario); scenario.getConfiguration().setUseSymmetricOptimization(false); scenario.getCostManagerConfiguration().setDoBackward(false); scenario.getCostManagerConfiguration().setDoPermutations(false); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); if (logger.isDebugEnabled()) logger.debug("Scenario " + getTestName("persons", scenario)); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(1, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expected-nop", result); } public void testScenarioNonSymmetric() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); setConfigurationForTest(scenario); scenario.getConfiguration().setUseSymmetricOptimization(false); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(9, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expectedPersons", result); } }
donatellosantoro/Llunatic
lunaticEngine/test/it/unibas/lunatic/test/mc/dbms/basicscenario/TestSQLPersons.java
Java
gpl-3.0
4,992
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.engine.export.ooxml; import java.io.Writer; import java.util.List; import net.sf.jasperreports.engine.JRStyle; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.design.JRDesignStyle; import net.sf.jasperreports.engine.util.JRDataUtils; import net.sf.jasperreports.engine.util.JRStyleResolver; import net.sf.jasperreports.export.ExporterInput; import net.sf.jasperreports.export.ExporterInputItem; /** * @author Teodor Danciu (teodord@users.sourceforge.net) */ public class DocxStyleHelper extends BaseHelper { /** * */ private DocxParagraphHelper paragraphHelper; private DocxRunHelper runHelper; /** * */ public DocxStyleHelper(JasperReportsContext jasperReportsContext, Writer writer, String exporterKey) { super(jasperReportsContext, writer); paragraphHelper = new DocxParagraphHelper(jasperReportsContext, writer, false); runHelper = new DocxRunHelper(jasperReportsContext, writer, exporterKey); } /** * */ public void export(ExporterInput exporterInput) { write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); write("<w:styles\n"); write(" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"\n"); write(" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">\n"); write(" <w:docDefaults>\n"); write(" <w:rPrDefault>\n"); //write(" <w:rPr>\n"); //write(" <w:rFonts w:ascii=\"Times New Roman\" w:eastAsia=\"Times New Roman\" w:hAnsi=\"Times New Roman\" w:cs=\"Times New Roman\"/>\n"); //write(" </w:rPr>\n"); write(" </w:rPrDefault>\n"); write(" <w:pPrDefault>\n"); write(" <w:pPr>\n"); write(" <w:spacing w:line=\"" + DocxParagraphHelper.LINE_SPACING_FACTOR + "\"/>\n"); write(" </w:pPr>\n"); write(" </w:pPrDefault>\n"); write(" </w:docDefaults>\n"); List<ExporterInputItem> items = exporterInput.getItems(); for(int reportIndex = 0; reportIndex < items.size(); reportIndex++) { ExporterInputItem item = items.get(reportIndex); JasperPrint jasperPrint = item.getJasperPrint(); String localeCode = jasperPrint.getLocaleCode(); if (reportIndex == 0) { JRDesignStyle style = new JRDesignStyle(); style.setName("EMPTY_CELL_STYLE"); style.setParentStyle(jasperPrint.getDefaultStyle()); style.setFontSize(0f); exportHeader(style); paragraphHelper.exportProps(style); runHelper.exportProps(style, (localeCode == null ? null : JRDataUtils.getLocale(localeCode)));//FIXMEDOCX reuse exporter exportFooter(); } JRStyle[] styles = jasperPrint.getStyles(); if (styles != null) { for(int i = 0; i < styles.length; i++) { JRStyle style = styles[i]; exportHeader(style); paragraphHelper.exportProps(style); runHelper.exportProps(style, (localeCode == null ? null : JRDataUtils.getLocale(localeCode)));//FIXMEDOCX reuse exporter exportFooter(); } } } write("</w:styles>\n"); } /** * */ private void exportHeader(JRStyle style) { //write(" <w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"" + style.getName() + "\">\n"); write(" <w:style w:type=\"paragraph\" w:styleId=\"" + style.getName() + "\""); if (style.isDefault()) { write(" w:default=\"1\""); } write(">\n"); write(" <w:name w:val=\"" + style.getName() + "\" />\n"); write(" <w:qFormat />\n"); JRStyle baseStyle = JRStyleResolver.getBaseStyle(style); String styleNameReference = baseStyle == null ? null : baseStyle.getName(); //javadoc says getStyleNameReference is not supposed to work for print elements if (styleNameReference != null) { write(" <w:basedOn w:val=\"" + styleNameReference + "\" />\n"); } } /** * */ private void exportFooter() { write(" </w:style>\n"); } }
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/engine/export/ooxml/DocxStyleHelper.java
Java
gpl-3.0
4,862
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cereal64.Common.Rom { interface IXMLRomProjectItem { string GetXMLName(); string GetXMLPath(); } }
mib-f8sm9c/Cereal64
Common/Rom/IXMLRomProjectItem.cs
C#
gpl-3.0
228
import data.Host; import java.net.InetAddress; import java.net.UnknownHostException; public class DCMCommandLibraryLinux { private Host host; private String command = ""; private InetAddress inetAddress; private String dcmServerIP; private String mpstatDataFile; private String iostatDataFile; private String psCPUFile; private String psMEMFile; private final String OS = "Linux"; private final int AWK = 0; private final int BC = 1; private final int DF = 2; private final int ECHO = 3; private final int EGREP = 4; private final int FREE = 5; private final int GREP = 6; private final int HEAD = 7; private final int IOSTAT = 8; private final int MPSTAT = 9; private final int NETSTAT = 10; private final int PS = 11; private final int SED = 12; private final int SORT = 13; private final int TAIL = 14; private final int TR = 15; private final int W = 16; private final int WC = 17; private final int WHO = 18; private static String[][] cmdArray; public DCMCommandLibraryLinux(Host hostParam) throws UnknownHostException { host = hostParam; try { inetAddress = InetAddress.getLocalHost(); } catch (UnknownHostException ex) { } dcmServerIP = inetAddress.getHostAddress(); mpstatDataFile = ".dcmmpstat_" + dcmServerIP + "_" + host.getHostname() + ".dat"; iostatDataFile = ".dcmiostat_" + dcmServerIP + "_" + host.getHostname() + ".dat"; psCPUFile = ".dcmpscpu_" + dcmServerIP + "_" + host.getHostname() + ".dat"; psMEMFile = ".dcmpsmem_" + dcmServerIP + "_" + host.getHostname() + ".dat"; cmdArray = new String[19][4]; cmdArray[AWK][0] = Integer.toString(AWK); cmdArray[AWK][1] = "awk"; cmdArray[AWK][2] = OS + " install media"; cmdArray[AWK][3] = "binary " + cmdArray[AWK][1] + " not found, please set PATH or install from " + cmdArray[AWK][2]; cmdArray[BC][0] = Integer.toString(BC); cmdArray[BC][1] = "bc"; cmdArray[BC][2] = OS + " install media"; cmdArray[BC][3] = "binary " + cmdArray[BC][1] + " not found, please set PATH or install from " + cmdArray[BC][2]; cmdArray[DF][0] = Integer.toString(DF); cmdArray[DF][1] = "df"; cmdArray[DF][2] = OS + " install media"; cmdArray[DF][3] = "binary " + cmdArray[DF][1] + " not found, please set PATH or install from " + cmdArray[DF][2]; cmdArray[ECHO][0] = Integer.toString(ECHO); cmdArray[ECHO][1] = "echo"; cmdArray[ECHO][2] = OS + " install media"; cmdArray[ECHO][3] = "binary " + cmdArray[ECHO][1] + " not found, please set PATH or install from " + cmdArray[ECHO][2]; cmdArray[EGREP][0] = Integer.toString(EGREP); cmdArray[EGREP][1] = "egrep"; cmdArray[EGREP][2] = OS + " install media"; cmdArray[EGREP][3] = "binary " + cmdArray[EGREP][1] + " not found, please set PATH or install from " + cmdArray[EGREP][2]; cmdArray[FREE][0] = Integer.toString(FREE); cmdArray[FREE][1] = "free"; cmdArray[FREE][2] = OS + " install media"; cmdArray[FREE][3] = "binary " + cmdArray[FREE][1] + " not found, please set PATH or install from " + cmdArray[FREE][2]; cmdArray[GREP][0] = Integer.toString(GREP); cmdArray[GREP][1] = "grep"; cmdArray[GREP][2] = OS + " install media"; cmdArray[GREP][3] = "binary " + cmdArray[GREP][1] + " not found, please set PATH or install from " + cmdArray[GREP][2]; cmdArray[HEAD][0] = Integer.toString(HEAD); cmdArray[HEAD][1] = "head"; cmdArray[HEAD][2] = OS + " install media"; cmdArray[HEAD][3] = "binary " + cmdArray[HEAD][1] + " not found, please set PATH or install from " + cmdArray[HEAD][2]; cmdArray[IOSTAT][0] = Integer.toString(IOSTAT); cmdArray[IOSTAT][1] = "iostat"; cmdArray[IOSTAT][2] = OS + " install media sysstat package"; cmdArray[IOSTAT][3] = "binary " + cmdArray[IOSTAT][1] + " not found, please set PATH or install from " + cmdArray[IOSTAT][2]; cmdArray[MPSTAT][0] = Integer.toString(MPSTAT); cmdArray[MPSTAT][1] = "mpstat"; cmdArray[MPSTAT][2] = OS + " install media sysstat package"; cmdArray[MPSTAT][3] = "binary " + cmdArray[MPSTAT][1] + " not found, please set PATH or install from " + cmdArray[MPSTAT][2]; cmdArray[NETSTAT][0] = Integer.toString(NETSTAT); cmdArray[NETSTAT][1] = "netstat"; cmdArray[NETSTAT][2] = OS + " install media"; cmdArray[NETSTAT][3] = "binary " + cmdArray[NETSTAT][1] + " not found, please set PATH or install from " + cmdArray[NETSTAT][2]; cmdArray[PS][0] = Integer.toString(PS); cmdArray[PS][1] = "ps"; cmdArray[PS][2] = OS + " install media"; cmdArray[PS][3] = "binary " + cmdArray[PS][1] + " not found, please set PATH or install from " + cmdArray[PS][2]; cmdArray[SED][0] = Integer.toString(SED); cmdArray[SED][1] = "sed"; cmdArray[SED][2] = OS + " install media"; cmdArray[SED][3] = "binary " + cmdArray[SED][1] + " not found, please set PATH or install from " + cmdArray[SED][2]; cmdArray[SORT][0] = Integer.toString(SORT); cmdArray[SORT][1] = "sort"; cmdArray[SORT][2] = OS + " install media"; cmdArray[SORT][3] = "binary " + cmdArray[SORT][1] + " not found, please set PATH or install from " + cmdArray[SORT][2]; cmdArray[TAIL][0] = Integer.toString(TAIL); cmdArray[TAIL][1] = "tail"; cmdArray[TAIL][2] = OS + " install media"; cmdArray[TAIL][3] = "binary " + cmdArray[TAIL][1] + " not found, please set PATH or install from " + cmdArray[TAIL][2]; cmdArray[TR][0] = Integer.toString(TR); cmdArray[TR][1] = "tr"; cmdArray[TR][2] = OS + " install media"; cmdArray[TR][3] = "binary " + cmdArray[TR][1] + " not found, please set PATH or install from " + cmdArray[TR][2]; cmdArray[W][0] = Integer.toString(W); cmdArray[W][1] = "w"; cmdArray[W][2] = OS + " install media"; cmdArray[W][3] = "binary " + cmdArray[W][1] + " not found, please set PATH or install from " + cmdArray[W][2]; cmdArray[WC][0] = Integer.toString(WC); cmdArray[WC][1] = "wc"; cmdArray[WC][2] = OS + " install media"; cmdArray[WC][3] = "binary " + cmdArray[WC][1] + " not found, please set PATH or install from " + cmdArray[WC][2]; cmdArray[WHO][0] = Integer.toString(WHO); cmdArray[WHO][1] = "who"; cmdArray[WHO][2] = OS + " install media"; cmdArray[WHO][3] = "binary " + cmdArray[WHO][1] + " not found, please set PATH or install from " + cmdArray[WHO][2]; } // PS public String getPSCPUHostCommand() { if (host.getSysinfo().contains(OS)) { command = cmdArray[PS][1] + " -e -o pid,pcpu,comm | " + cmdArray[GREP][1] + " -iv \"pid\" | " + cmdArray[SORT][1] + " -k 2nr > " + psCPUFile + " \n"; } return command; } public String getPSMEMHostCommand() { if (host.getSysinfo().contains(OS)) { command = cmdArray[PS][1] + " -e -o pid,pmem,comm | " + cmdArray[GREP][1] + " -iv \"pid\" | " + cmdArray[SORT][1] + " -k 2nr > " + psMEMFile + " \n"; } return command; } // CPU // mpstat -P ALL 1 1 | " + cmdArray[TAIL][1] + " -`" + cmdArray[MPSTAT][1] + " -P ALL | " + cmdArray[EGREP][1] + " -vie "^$|CPU" | " + cmdArray[WC][1] + " -l` public String getCPUHostCommand() // This a HOST Command { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P ALL 50 1 | " + cmdArray[TAIL][1] + " -`" + cmdArray[MPSTAT][1] + " -P ALL | " + cmdArray[EGREP][1] + " -vie \"^$|CPU\" | " + cmdArray[WC][1] + " -l` > " + mpstatDataFile + " & \n"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P ALL 50 1 > " + mpstatDataFile + " & \n"; } return command; } public String getCPUUSERCommand(String resourceParam)// usr nice sys idle { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getCPUSYSCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getCPUIDLECommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $11 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $11 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getCPUWIOCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $6 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $6 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } // WORKLOAD public String getWorkload() { if (host.getSysinfo().contains(OS)) { command = cmdArray[W][1] + " | " + cmdArray[GREP][1] + " -i \"average\" | " + cmdArray[AWK][1] + " '{ print $10 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } // DiskIO public String getDiskIOHostCommand() // This a HOST Command { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -x -d 50 2 | " + cmdArray[EGREP][1] + " -vie \"^$|Device|Linux\" | " + cmdArray[TAIL][1] + " -`iostat -x -d | " + cmdArray[EGREP][1] + " -vie \"^$|Device|Linux\" | " + cmdArray[WC][1] + " -l` > " + iostatDataFile + " & \n"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -x -d 50 2 > " + iostatDataFile + " & \n"; } return command; } public String getDiskIOReadsPerSecondQuedCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOWritesPerSecondQuedCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $3 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOReadPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $4 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOWritesPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $5 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOKBReadPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $6 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $6 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOKBWritesPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $7 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $7 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageTranscationSectorsCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $8 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $8 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageQueueLengthCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $9 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $9 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageTranscationResponseTimeMiliSecondsCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $10 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $10 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageTranscationServiceTimeMiliSecondsCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $11 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $11 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOTransactionCPUUtilizationPercentageCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $12 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $12 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } // Memory public String getRAMTOTCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Mem | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; } public String getRAMUSEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " 'buffers/cache' | " + cmdArray[AWK][1] + " '{ print $3 }'"; } return command; } public String getRAMFREECommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " 'buffers/cache' | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; } public String getSWAPTOTCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; } public String getSWAPUSEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $3 }'"; } return command; } public String getSWAPFREECommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; } public String getTOTMEMCommand(Host hostParam) { // if (host.getSysinfo().contains(OS)) { command = "ramtot=`free -m | " + cmdArray[GREP][1] + " Mem | " + cmdArray[AWK][1] + " '{ print $2 }'`; swaptot=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $2 }'` totmem=$((ramtot + swaptot)); " + cmdArray[ECHO][1] + " $totmem"; } if (host.getSysinfo().contains(OS)) { command = "ramtot=`free -m | " + cmdArray[GREP][1] + " Mem | " + cmdArray[AWK][1] + " '{ print $2 }'`; swaptot=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $2 }'` totmem=`" + cmdArray[ECHO][1] + " \"$ramtot + $swaptot\" | " + cmdArray[BC][1] + "`; " + cmdArray[ECHO][1] + " $totmem"; } return command; } public String getTOTUSEDCommand(Host hostParam) { // if (host.getSysinfo().contains(OS)) { command = "ramused=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $3 }'`; swapused=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $3 }'`; totused=$(( ramused + swapused )); " + cmdArray[ECHO][1] + " $totused"; } if (host.getSysinfo().contains(OS)) { command = "ramused=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $3 }'`; swapused=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $3 }'`; totused=`" + cmdArray[ECHO][1] + " \"$ramused + $swapused\" | " + cmdArray[BC][1] + "`; " + cmdArray[ECHO][1] + " $totused"; } return command; } public String getTOTFREECommand(Host hostParam) { // if (host.getSysinfo().contains(OS)) { command = "ramfree=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $4 }'`; swapfree=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $4 }'` totfree=$((ramfree + swapfree)); " + cmdArray[ECHO][1] + " $totfree"; } if (host.getSysinfo().contains(OS)) { command = "ramfree=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $4 }'`; swapfree=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $4 }'` totfree=`" + cmdArray[ECHO][1] + " \"$ramfree + $swapfree\" | " + cmdArray[BC][1] + "`; " + cmdArray[ECHO][1] + " $totfree"; } return command; } // Storage public String getFSTOTCommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[TAIL][1] + " -1"; } return command; } public String getFSUSEDCommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[TAIL][1] + " -1"; } return command; } public String getFSFREECommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $4 }' | " + cmdArray[TAIL][1] + " -1"; } return command; } public String getFSUSEDPercCommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[TR][1] + " -d \"%\""; } return command; } // Network ethtool requires superuer unfortunately //Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg public String getIF_RX_OK_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; } public String getIF_RX_ERR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $5 }'"; } return command; } public String getIF_RX_Drop_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $6 }'"; } return command; } public String getIF_RX_OVR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $7 }'"; } return command; } public String getIF_TX_OK_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $8 }'"; } return command; } public String getIF_TX_ERR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $9 }'"; } return command; } public String getIF_TX_Drop_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $10 }'"; } return command; } public String getIF_TX_OVR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $11 }'"; } return command; } // Network public String getTCPSTATESTABLISHEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+ESTABLISHED\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATSYN_SENTCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+SYN_SENT\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATSYN_RECVCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+SYN_RECV\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATFIN_WAIT1Command(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+FIN_WAIT1\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATFIN_WAIT2Command(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+FIN_WAIT2\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATTIME_WAITCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+TIME_WAIT\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATCLOSEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+CLOSED\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATCLOSE_WAITCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+CLOSE_WAIT\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATLAST_ACKCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+LAST_ACK\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATLISTENCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+LISTEN\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATCLOSINGCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+CLOSING\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATUNKNOWNCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+UNKNOWN\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } // Generic public String getNUMOFUSERSCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[WHO][1] + " | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getNUMOFPROCSCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[PS][1] + " -e | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } // PS public String getPS1CPUPIDCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS1CPUCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2CPUPIDCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2CPUCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3CPUPIDCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3CPUCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS1MEMPIDCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS1MEMCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2MEMPIDCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2MEMCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3MEMPIDCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3MEMCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String[][] getCommandArray() { return cmdArray; } }
ron-from-nl/DataCenterManager
src/DCMCommandLibraryLinux.java
Java
gpl-3.0
37,200
<? //________________________________________________________________________________________________________ // // Fichero de idiomas php: restaurarsoftincremental_esp.php (Comandos) // Idioma: Español //________________________________________________________________________________________________________ $TbMsg=array(); $TbMsg[0]='Centros'; $TbMsg[1]='Grupo de aulas'; $TbMsg[2]='Aulas'; $TbMsg[3]='Grupo de ordenadores'; $TbMsg[4]='Ordenadores'; $TbMsg[5]='Restaurar Software Incremental <br> (experimental)'; $TbMsg[6]='Ámbito'; $TbMsg[7]='Datos a suministrar'; $TbMsg[8]='Par'; $TbMsg[9]='Repositorio'; $TbMsg[10]='Imagen'; $TbMsg[11]='Opciones Adicionales'; $TbMsg[12]='Desconocido'; $TbMsg[13]='Caché'; $TbMsg[14]='Ámbito'; $TbMsg[15]='Ordenadores'; $TbMsg[16]='Desde'; $TbMsg[17]=''; $TbMsg[18]="DESAGRUPAR SEGÚN VALORES DISTINTOS DE:"; $TbMsg[19]="Datos a suministrar"; // Cabeceras de tabla de configuración $TbMsg[20]='Partición'; $TbMsg[21]='S.O. Instalado'; $TbMsg[22]='Tamaño'; $TbMsg[23]='Datos de configuration'; $TbMsg[24]='Tipo'; $TbMsg[25]='Imagen'; $TbMsg[26]='Perfil Software'; $TbMsg[27]='S.F.'; $TbMsg[28]='Ninguno'; $TbMsg[29]='Desconocido'; // Desagrupamiento $TbMsg[30]='Sistema de Ficheros'; $TbMsg[31]='Nombre del S.O.'; $TbMsg[32]='Tamaño de partición'; $TbMsg[33]='Nombre de la Imagen '; $TbMsg[34]='Perfil software'; // OPciones adicionales $TbMsg[35]='Borrar la Partición Previamente'; $TbMsg[36]='Copiar Imagen en cache'; $TbMsg[37]='Borrarla previamente de la cache'; $TbMsg[38]='Software Incremental'; $TbMsg[39]='No borrar archivos en destino'; ?>
DreamaerD/Opengnsys
admin/WebConsole/idiomas/php/esp/comandos/restaurarsoftincremental_esp.php
PHP
gpl-3.0
1,652
<?php namespace Claroline\CoreBundle\Controller\Mooc; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Claroline\CoreBundle\Entity\Mooc\MoocAccessConstraints; use Claroline\CoreBundle\Form\Mooc\MoocAccessConstraintsType; use JMS\SecurityExtraBundle\Annotation\Secure; /** * Mooc\MoocAccessConstraints controller. */ class MoocAccessConstraintsController extends Controller { /** * Lists all Mooc\MoocAccessConstraints entities. * * @Route("/", name="admin_parameters_mooc_accessconstraints") * @Method("GET") * @Template() * @Secure(roles="ROLE_WS_CREATOR") */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->findAll(); $forms = array(); foreach( $entities as $entity ) { $deleteForm = $this->createDeleteForm( $entity->getId()); $forms[] = $deleteForm->createView(); } return array( 'entities' => $entities, 'forms' => $forms ); } /** * Creates a new Mooc\MoocAccessConstraints entity. * * @Route("/", name="admin_parameters_mooc_accessconstraints_create") * @Method("POST") * @Template("ClarolineCoreBundle:Mooc\MoocAccessConstraints:new.html.twig") * @Secure(roles="ROLE_WS_CREATOR") */ public function createAction(Request $request) { $entity = new MoocAccessConstraints(); $form = $this->createCreateForm( $entity ); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('admin_parameters_mooc_accessconstraints', array('id' => $entity->getId()))); } return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Creates a form to create a Mooc\MoocAccessConstraints entity. * * @param MoocAccessConstraints $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm( MoocAccessConstraints $entity) { $form = $this->createForm(new MoocAccessConstraintsType(), $entity, array( 'action' => $this->generateUrl('admin_parameters_mooc_accessconstraints_create'), 'method' => 'POST', )); $form->add('save', 'submit', array('label' => 'Create', 'attr' => array('class' => 'hide'))); return $form; } /** * Displays a form to create a new Mooc\MoocAccessConstraints entity. * * @Route("/new", name="admin_parameters_mooc_accessconstraints_new") * @Method("GET") * @Template() * @Secure(roles="ROLE_WS_CREATOR") */ public function newAction() { $entity = new MoocAccessConstraints(); $form = $this->createCreateForm( $entity ); return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Displays a form to edit an existing Mooc\MoocAccessConstraints entity. * * @Route("/{id}/edit", name="admin_parameters_mooc_accessconstraints_edit") * @Method("GET") * @Template() * @Secure(roles="ROLE_WS_CREATOR") */ public function editAction( $id ) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Mooc\MoocAccessConstraints entity.'); } $editForm = $this->createEditForm($entity); $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Creates a form to edit a Mooc\MoocAccessConstraints entity. * * @param MoocAccessConstraints $entity The entity * @return \Symfony\Component\Form\Form The form */ private function createEditForm(MoocAccessConstraints $entity) { $form = $this->createForm(new MoocAccessConstraintsType(), $entity, array( 'action' => $this->generateUrl('admin_parameters_mooc_accessconstraints_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $form->add('save', 'submit', array('label' => 'Update', 'attr' => array('class' => 'hide'))); return $form; } /** * Edits an existing Mooc\MoocAccessConstraints entity. * * @Route("/{id}", name="admin_parameters_mooc_accessconstraints_update") * @Method("PUT") * @Template("ClarolineCoreBundle:Mooc\MoocAccessConstraints:edit.html.twig") * @Secure(roles="ROLE_WS_CREATOR") */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Mooc\MoocAccessConstraints entity.'); } $deleteForm = $this->createDeleteForm( $id ); $editForm = $this->createEditForm( $entity ); $editForm->handleRequest($request); if ($editForm->isValid()) { foreach ( $entity->getMoocs() as $mooc ) { foreach ( $mooc->getMoocSessions() as $session ) { //TODO By the listener $this->get('orange.search.indexer_todo_manager') ->toIndex($session); } } $em->flush(); return $this->redirect($this->generateUrl('admin_parameters_mooc_accessconstraints', array('id' => $id))); } return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Deletes a Mooc\MoocAccessConstraints entity. * * @Route("/{id}", name="admin_parameters_mooc_accessconstraints_delete") * @Method("DELETE") * @Secure(roles="ROLE_WS_CREATOR") */ public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Mooc\MoocAccessConstraints entity.'); } $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('admin_parameters_mooc_accessconstraints')); } /** * Creates a form to delete a Mooc\MoocAccessConstraints entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('admin_parameters_mooc_accessconstraints_delete', array( 'id' => $id ))) ->setMethod('DELETE') ->add('save', 'submit', array('label' => 'Delete')) ->getForm() ; } }
Solerni-R1-1/CoreBundle
Controller/Mooc/MoocAccessConstraintsController.php
PHP
gpl-3.0
7,982
package br.com.hebertmorais.movierating; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
hebertmorais/ZMovieRating
app/src/androidTest/java/br/com/hebertmorais/movierating/ApplicationTest.java
Java
gpl-3.0
362
package offeneBibel.parser; public class ObParallelPassageNode extends ObAstNode { private String m_book; private int m_chapter; private int m_startVerse; private int m_stopVerse; public ObParallelPassageNode(String book, int chapter, int verse) { super(NodeType.parallelPassage); m_book = BookNameHelper.getInstance().getUnifiedBookNameForString(book); m_chapter = chapter; m_startVerse = verse; m_stopVerse = -1; } public ObParallelPassageNode(String book, int chapter, int startVerse, int stopVerse) { super(NodeType.parallelPassage); m_book = BookNameHelper.getInstance().getUnifiedBookNameForString(book); m_chapter = chapter; m_startVerse = startVerse; m_stopVerse = stopVerse; } public String getOsisBookId() { return m_book; } public int getChapter() { return m_chapter; } public int getStartVerse() { return m_startVerse; } /** * Stop verse. Returns -1 if no stop verse was set. * @return */ public int getStopVerse() { return m_stopVerse; } }
freie-bibel/free-offene-bibel-converter
src/main/java/offeneBibel/parser/ObParallelPassageNode.java
Java
gpl-3.0
1,155
/* Copyright (C) 2014-2016 de4dot@gmail.com This file is part of dnSpy dnSpy 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. dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>. */ //TODO: CDataSection, Keyword, ProcessingInstruction using System; using System.Diagnostics; using Microsoft.VisualStudio.Text; namespace dnSpy.Text.Tagging.Xml { enum XmlKind { /// <summary> /// Eg. &lt; or &amp; /// </summary> EntityReference, /// <summary> /// Text inside of elements /// </summary> Text, /// <summary> /// Text inside of elements that is pure whitespace /// </summary> TextWhitespace, /// <summary> /// Delimiter, eg. > /// </summary> Delimiter, /// <summary> /// Comment, eg. <!-- hello --> /// </summary> Comment, /// <summary> /// Whitespace inside of an element which separates attributes, attribute values, etc. /// </summary> ElementWhitespace, /// <summary> /// Name of element /// </summary> ElementName, /// <summary> /// Name of attribute /// </summary> AttributeName, /// <summary> /// Attribute value quote /// </summary> AttributeQuote, /// <summary> /// Attribute value (inside quotes) /// </summary> AttributeValue, /// <summary> /// Attribute value (inside quotes). The first character of the value is { /// </summary> AttributeValueXaml, } struct XmlSpanKind { public Span Span { get; } public XmlKind Kind { get; } public XmlSpanKind(Span span, XmlKind kind) { Span = span; Kind = kind; } } sealed class XmlClassifier { readonly ITextSnapshot snapshot; readonly int snapshotLength; readonly char[] buffer; int bufferLen; int bufferPos; int snapshotPos; State state; int spanStart; const int BUFFER_SIZE = 4096; enum State { // Initial state, look for elements, text Element, // Read element name ElementName, // Read attributes Attribute, // Read = AttributeEquals, // Read attribute quote AttributeQuoteStart, // Read attribute value AttributeValue, // Read attribute quote AttributeQuoteEnd, } public XmlClassifier(ITextSnapshot snapshot) { if (snapshot == null) throw new ArgumentNullException(nameof(snapshot)); this.snapshot = snapshot; snapshotLength = snapshot.Length; buffer = new char[Math.Min(BUFFER_SIZE, snapshot.Length)]; state = State.Element; } public XmlSpanKind? GetNext() { for (;;) { var kind = GetNextCore(); if (kind == null) break; Debug.Assert(spanStart != snapshotPos); if (spanStart == snapshotPos) break; return new XmlSpanKind(Span.FromBounds(spanStart, snapshotPos), kind.Value); } return null; } XmlKind? GetNextCore() { spanStart = snapshotPos; int c, pos; switch (state) { case State.Element: c = NextChar(); if (c < 0) return null; switch ((char)c) { case '<': c = PeekChar(); if (c < 0) return XmlKind.Delimiter; if (c == '/' || c == '?') { // </tag> or <?xml ... ?> SkipChar(); state = State.ElementName; return XmlKind.Delimiter; } if (c != '!') { // <tag> state = State.ElementName; return XmlKind.Delimiter; } SkipChar(); if (PeekChar() != '-') { // Error state = State.ElementName; return XmlKind.Delimiter; } SkipChar(); if (PeekChar() != '-') { // Error state = State.ElementName; return XmlKind.Delimiter; } SkipChar(); ReadComment(); return XmlKind.Comment; case '&': ReadEntityReference(); return XmlKind.EntityReference; default: return ReadWhitespaceOrText(c); } case State.ElementName: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c == ':') { NextChar(); return XmlKind.Delimiter; } if (c == '<' || c == '>') { // Error state = State.Element; goto case State.Element; } pos = snapshotPos; ReadName(); if (pos == snapshotPos) { NextChar(); return XmlKind.Delimiter; } if (PeekChar() != ':') state = State.Attribute; return XmlKind.ElementName; case State.Attribute: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c == ':') { NextChar(); return XmlKind.Delimiter; } if (c == '/') { SkipChar(); if (PeekChar() == '>') { SkipChar(); state = State.Element; return XmlKind.Delimiter; } return XmlKind.Delimiter; } if (c == '>') { SkipChar(); state = State.Element; return XmlKind.Delimiter; } if (c == '<') { // Error state = State.Element; goto case State.Element; } pos = snapshotPos; ReadName(); if (pos == snapshotPos) { NextChar(); return XmlKind.Delimiter; } if (PeekChar() != ':') state = State.AttributeEquals; return XmlKind.AttributeName; case State.AttributeEquals: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c != '=') { // Error state = State.Attribute; goto case State.Attribute; } SkipChar(); state = State.AttributeQuoteStart; return XmlKind.Delimiter; case State.AttributeQuoteStart: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c != '\'' && c != '"') { // Error state = State.Attribute; goto case State.Attribute; } isDoubleQuote = c == '"'; SkipChar(); state = State.AttributeValue; return XmlKind.AttributeQuote; case State.AttributeValue: c = PeekChar(); if (c == (isDoubleQuote ? '"' : '\'')) { state = State.AttributeQuoteEnd; goto case State.AttributeQuoteEnd; } var firstChar = ReadString(isDoubleQuote); state = State.AttributeQuoteEnd; return firstChar == '{' ? XmlKind.AttributeValueXaml : XmlKind.AttributeValue; case State.AttributeQuoteEnd: c = NextChar(); if (c < 0) return null; Debug.Assert(c == (isDoubleQuote ? '"' : '\'')); state = State.Attribute; return XmlKind.AttributeQuote; default: throw new InvalidOperationException(); } } bool isDoubleQuote; char ReadString(bool isDoubleQuote) { var quoteChar = isDoubleQuote ? '"' : '\''; char firstChar = (char)0; bool firstCharInitd = false; for (;;) { int c = PeekChar(); if (c < 0 || c == quoteChar) break; SkipChar(); if (!firstCharInitd) { firstCharInitd = true; firstChar = (char)c; } } return firstChar; } void ReadName() { int c = PeekChar(); if (c < 0) return; if (!IsNameStartChar((char)c)) return; SkipChar(); for (;;) { c = PeekChar(); if (c < 0) break; if (!IsNameChar((char)c)) break; SkipChar(); } } // https://www.w3.org/TR/REC-xml/#d0e804 bool IsNameStartChar(char c) => //c == ':' || ('A' <= c && c <= 'Z') || c == '_' || ('a' <= c && c <= 'z') || (0xC0 <= c && c <= 0xD6) || (0xD8 <= c && c <= 0xF6) || (0xF8 <= c && c <= 0x02FF) || (0x0370 <= c && c <= 0x037D) || (0x037F <= c && c <= 0x1FFF) || (0x200C <= c && c <= 0x200D) || (0x2070 <= c && c <= 0x218F) || (0x2C00 <= c && c <= 0x2FEF) || (0x3001 <= c && c <= 0xD7FF) || (0xF900 <= c && c <= 0xFDCF) || (0xFDF0 <= c && c <= 0xFFFD);//#x10000-#xEFFFF bool IsNameChar(char c) => IsNameStartChar(c) || c == '-' || c == '.' || ('0' <= c && c <= '9') || c == 0xB7 || (0x0300 <= c && c <= 0x036F) || (0x203F <= c && c <= 0x2040); void ReadElementWhitespace() { for (;;) { int c = PeekChar(); if (c < 0) break; if (!char.IsWhiteSpace((char)c)) break; SkipChar(); } } void ReadComment() { // We've already read <!-- for (;;) { int c = NextChar(); if (c < 0) break; if (c != '-') continue; c = NextChar(); if (c < 0) break; if (c != '-') continue; c = NextChar(); if (c < 0) break; if (c != '>') continue; break; } } XmlKind ReadWhitespaceOrText(int c) { bool isText = !char.IsWhiteSpace((char)c); while ((c = PeekChar()) >= 0) { if (!char.IsWhiteSpace((char)c)) { if (c == '&' || c == '<') break; isText = true; } SkipChar(); } return isText ? XmlKind.Text : XmlKind.TextWhitespace; } void ReadEntityReference() { // We've already read & for (;;) { int c = PeekChar(); if (c < 0) break; if (c == ';') { SkipChar(); break; } if (!char.IsLetterOrDigit((char)c)) break; SkipChar(); } } int NextChar() { if (bufferPos >= bufferLen) { int len = snapshotLength - snapshotPos; if (len == 0) return -1; if (len > buffer.Length) len = buffer.Length; snapshot.CopyTo(snapshotPos, buffer, 0, len); bufferLen = len; bufferPos = 0; } snapshotPos++; return buffer[bufferPos++]; } int PeekChar() { if (bufferPos >= bufferLen) { int len = snapshotLength - snapshotPos; if (len == 0) return -1; if (len > buffer.Length) len = buffer.Length; snapshot.CopyTo(snapshotPos, buffer, 0, len); bufferLen = len; bufferPos = 0; } return buffer[bufferPos]; } void SkipChar() { Debug.Assert(snapshotPos < snapshotLength); Debug.Assert(bufferPos < bufferLen); snapshotPos++; bufferPos++; } } }
MeteorAdminz/dnSpy
dnSpy/dnSpy/Text/Tagging/Xml/XmlClassifier.cs
C#
gpl-3.0
10,423
/*************************************************************** * This source files comes from the xLights project * https://www.xlights.org * https://github.com/smeighan/xLights * See the github commit history for a record of contributing * developers. * Copyright claimed based on commit dates recorded in Github * License: https://github.com/smeighan/xLights/blob/master/License.txt **************************************************************/ #include <wx/propgrid/propgrid.h> #include <wx/propgrid/advprops.h> #include <wx/xml/xml.h> #include <glm/mat4x4.hpp> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "DmxSkulltronix.h" #include "../../ModelPreview.h" #include "../../xLightsVersion.h" #include "../../xLightsMain.h" #include "../../UtilFunctions.h" DmxSkulltronix::DmxSkulltronix(wxXmlNode *node, const ModelManager &manager, bool zeroBased) : DmxModel(node, manager, zeroBased) { color_ability = this; SetFromXml(node, zeroBased); } DmxSkulltronix::~DmxSkulltronix() { //dtor } class dmxPoint3 { public: float x; float y; float z; dmxPoint3(float x_, float y_, float z_, int cx_, int cy_, float scale_, float pan_angle_, float tilt_angle_, float nod_angle_ = 0.0) : x(x_), y(y_), z(z_) { float pan_angle = wxDegToRad(pan_angle_); float tilt_angle = wxDegToRad(tilt_angle_); float nod_angle = wxDegToRad(nod_angle_); glm::vec4 position = glm::vec4(glm::vec3(x_, y_, z_), 1.0); glm::mat4 rotationMatrixPan = glm::rotate(glm::mat4(1.0f), pan_angle, glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 rotationMatrixTilt = glm::rotate(glm::mat4(1.0f), tilt_angle, glm::vec3(0.0f, 0.0f, 1.0f)); glm::mat4 rotationMatrixNod = glm::rotate(glm::mat4(1.0f), nod_angle, glm::vec3(1.0f, 0.0f, 0.0f)); glm::mat4 translateMatrix = glm::translate(glm::mat4(1.0f), glm::vec3((float)cx_, (float)cy_, 0.0f)); glm::mat4 scaleMatrix = glm::scale(glm::mat4(1.0f), glm::vec3(scale_)); glm::vec4 model_position = translateMatrix * rotationMatrixPan * rotationMatrixTilt * rotationMatrixNod * scaleMatrix * position; x = model_position.x; y = model_position.y; } }; class dmxPoint3d { public: float x; float y; float z; dmxPoint3d(float x_, float y_, float z_, float cx_, float cy_, float cz_, float scale_, float pan_angle_, float tilt_angle_, float nod_angle_ = 0.0) : x(x_), y(y_), z(z_) { float pan_angle = wxDegToRad(pan_angle_); float tilt_angle = wxDegToRad(tilt_angle_); float nod_angle = wxDegToRad(nod_angle_); glm::vec4 position = glm::vec4(glm::vec3(x_, y_, z_), 1.0); glm::mat4 rotationMatrixPan = glm::rotate(glm::mat4(1.0f), pan_angle, glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 rotationMatrixTilt = glm::rotate(glm::mat4(1.0f), tilt_angle, glm::vec3(0.0f, 0.0f, 1.0f)); glm::mat4 rotationMatrixNod = glm::rotate(glm::mat4(1.0f), nod_angle, glm::vec3(1.0f, 0.0f, 0.0f)); glm::mat4 translateMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(cx_, cy_, cz_)); glm::mat4 scaleMatrix = glm::scale(glm::mat4(1.0f), glm::vec3(scale_)); glm::vec4 model_position = translateMatrix * rotationMatrixPan * rotationMatrixTilt * rotationMatrixNod * scaleMatrix * position; x = model_position.x; y = model_position.y; z = model_position.z; } }; void DmxSkulltronix::AddTypeProperties(wxPropertyGridInterface* grid) { DmxModel::AddTypeProperties(grid); AddPanTiltTypeProperties(grid); wxPGProperty* p = grid->Append(new wxUIntProperty("Pan Min Limit", "DmxPanMinLimit", pan_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Pan Max Limit", "DmxPanMaxLimit", pan_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Tilt Min Limit", "DmxTiltMinLimit", tilt_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Tilt Max Limit", "DmxTiltMaxLimit", tilt_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Channel", "DmxNodChannel", nod_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Orientation", "DmxNodOrient", nod_orient)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 360); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Deg of Rot", "DmxNodDegOfRot", nod_deg_of_rot)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 1000); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Min Limit", "DmxNodMinLimit", nod_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Max Limit", "DmxNodMaxLimit", nod_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Jaw Channel", "DmxJawChannel", jaw_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Jaw Min Limit", "DmxJawMinLimit", jaw_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Jaw Max Limit", "DmxJawMaxLimit", jaw_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye UD Channel", "DmxEyeUDChannel", eye_ud_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye UD Min Limit", "DmxEyeUDMinLimit", eye_ud_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye UD Max Limit", "DmxEyeUDMaxLimit", eye_ud_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye LR Channel", "DmxEyeLRChannel", eye_lr_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye LR Min Limit", "DmxEyeLRMinLimit", eye_lr_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye LR Max Limit", "DmxEyeLRMaxLimit", eye_lr_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye Brightness Channel", "DmxEyeBrtChannel", eye_brightness_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); AddColorTypeProperties(grid); } int DmxSkulltronix::OnPropertyGridChange(wxPropertyGridInterface* grid, wxPropertyGridEvent& event) { if (OnColorPropertyGridChange(grid, event, ModelXml, this) == 0) { return 0; } if (OnPanTiltPropertyGridChange(grid, event, ModelXml, this) == 0) { return 0; } if ("DmxPanMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxPanMinLimit"); ModelXml->AddAttribute("DmxPanMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXPanMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXPanMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXPanMinLimit"); return 0; } else if ("DmxPanMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxPanMaxLimit"); ModelXml->AddAttribute("DmxPanMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXPanMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXPanMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXPanMaxLimit"); return 0; } else if ("DmxTiltMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxTiltMinLimit"); ModelXml->AddAttribute("DmxTiltMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMinLimit"); return 0; } else if ("DmxTiltMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxTiltMaxLimit"); ModelXml->AddAttribute("DmxTiltMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMaxLimit"); return 0; } else if ("DmxNodChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodChannel"); ModelXml->AddAttribute("DmxNodChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXNodChannel"); return 0; } else if ("DmxNodOrient" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodOrient"); ModelXml->AddAttribute("DmxNodOrient", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodOrient"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodOrient"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodOrient"); return 0; } else if ("DmxNodDegOfRot" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodDegOfRot"); ModelXml->AddAttribute("DmxNodDegOfRot", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodDegOfRot"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodDegOfRot"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodDegOfRot"); return 0; } else if ("DmxNodMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodMinLimit"); ModelXml->AddAttribute("DmxNodMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodMinLimit"); return 0; } else if ("DmxNodMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodMaxLimit"); ModelXml->AddAttribute("DmxNodMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodMaxLimit"); return 0; } else if ("DmxJawChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxJawChannel"); ModelXml->AddAttribute("DmxJawChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXJawChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXJawChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXJawChannel"); return 0; } else if ("DmxJawMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxJawMinLimit"); ModelXml->AddAttribute("DmxJawMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXJawMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXJawMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXJawMinLimit"); return 0; } else if ("DmxJawMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxJawMaxLimit"); ModelXml->AddAttribute("DmxJawMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXJawMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXJawMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXJawMaxLimit"); return 0; } else if ("DmxEyeBrtChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeBrtChannel"); ModelXml->AddAttribute("DmxEyeBrtChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeBrtChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeBrtChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXEyeBrtChannel"); return 0; } else if ("DmxEyeUDChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeUDChannel"); ModelXml->AddAttribute("DmxEyeUDChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDChannel"); return 0; } else if ("DmxEyeUDMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeUDMinLimit"); ModelXml->AddAttribute("DmxEyeUDMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMinLimit"); return 0; } else if ("DmxEyeUDMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeUDMaxLimit"); ModelXml->AddAttribute("DmxEyeUDMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMaxLimit"); return 0; } else if ("DmxEyeLRChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeLRChannel"); ModelXml->AddAttribute("DmxEyeLRChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRChannel"); return 0; } else if ("DmxEyeLRMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeLRMinLimit"); ModelXml->AddAttribute("DmxEyeLRMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMinLimit"); return 0; } else if ("DmxEyeLRMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeLRMaxLimit"); ModelXml->AddAttribute("DmxEyeLRMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMaxLimit"); return 0; } return DmxModel::OnPropertyGridChange(grid, event); } void DmxSkulltronix::InitModel() { DmxModel::InitModel(); DisplayAs = "DmxSkulltronix"; screenLocation.SetRenderSize(1, 1); pan_channel = wxAtoi(ModelXml->GetAttribute("DmxPanChannel", "13")); pan_orient = wxAtoi(ModelXml->GetAttribute("DmxPanOrient", "90")); pan_deg_of_rot = wxAtoi(ModelXml->GetAttribute("DmxPanDegOfRot", "180")); pan_slew_limit = wxAtof(ModelXml->GetAttribute("DmxPanSlewLimit", "0")); tilt_channel = wxAtoi(ModelXml->GetAttribute("DmxTiltChannel", "19")); tilt_orient = wxAtoi(ModelXml->GetAttribute("DmxTiltOrient", "315")); tilt_deg_of_rot = wxAtoi(ModelXml->GetAttribute("DmxTiltDegOfRot", "90")); tilt_slew_limit = wxAtof(ModelXml->GetAttribute("DmxTiltSlewLimit", "0")); red_channel = wxAtoi(ModelXml->GetAttribute("DmxRedChannel", "24")); green_channel = wxAtoi(ModelXml->GetAttribute("DmxGreenChannel", "25")); blue_channel = wxAtoi(ModelXml->GetAttribute("DmxBlueChannel", "26")); white_channel = wxAtoi(ModelXml->GetAttribute("DmxWhiteChannel", "0")); tilt_min_limit = wxAtoi(ModelXml->GetAttribute("DmxTiltMinLimit", "442")); tilt_max_limit = wxAtoi(ModelXml->GetAttribute("DmxTiltMaxLimit", "836")); pan_min_limit = wxAtoi(ModelXml->GetAttribute("DmxPanMinLimit", "250")); pan_max_limit = wxAtoi(ModelXml->GetAttribute("DmxPanMaxLimit", "1250")); nod_channel = wxAtoi(ModelXml->GetAttribute("DmxNodChannel", "11")); nod_orient = wxAtoi(ModelXml->GetAttribute("DmxNodOrient", "331")); nod_deg_of_rot = wxAtoi(ModelXml->GetAttribute("DmxNodDegOfRot", "58")); nod_min_limit = wxAtoi(ModelXml->GetAttribute("DmxNodMinLimit", "452")); nod_max_limit = wxAtoi(ModelXml->GetAttribute("DmxNodMaxLimit", "745")); jaw_channel = wxAtoi(ModelXml->GetAttribute("DmxJawChannel", "9")); jaw_min_limit = wxAtoi(ModelXml->GetAttribute("DmxJawMinLimit", "500")); jaw_max_limit = wxAtoi(ModelXml->GetAttribute("DmxJawMaxLimit", "750")); eye_brightness_channel = wxAtoi(ModelXml->GetAttribute("DmxEyeBrtChannel", "23")); eye_ud_channel = wxAtoi(ModelXml->GetAttribute("DmxEyeUDChannel", "15")); eye_ud_min_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeUDMinLimit", "575")); eye_ud_max_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeUDMaxLimit", "1000")); eye_lr_channel = wxAtoi(ModelXml->GetAttribute("DmxEyeLRChannel", "17")); eye_lr_min_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeLRMinLimit", "499")); eye_lr_max_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeLRMaxLimit", "878")); SetNodeNames(",,,,,,,Power,Jaw,-Jaw Fine,Nod,-Nod Fine,Pan,-Pan Fine,Eye UD,-Eye UD Fine,Eye LR,-Eye LR Fine,Tilt,-Tilt Fine,-Torso,-Torso Fine,Eye Brightness,Eye Red,Eye Green,Eye Blue"); } void DmxSkulltronix::DisplayModelOnWindow(ModelPreview* preview, xlGraphicsContext* ctx, xlGraphicsProgram* sprogram, xlGraphicsProgram* tprogram, bool is_3d, const xlColor* c, bool allowSelected, bool wiring, bool highlightFirst, int highlightpixel, float* boundingBox) { if (!IsActive()) return; screenLocation.PrepareToDraw(is_3d, allowSelected); screenLocation.UpdateBoundingBox(Nodes); sprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PushMatrix(); if (!is_3d) { //not 3d, flatten to the 0 plane ctx->Scale(1.0, 1.0, 0.0); } GetModelScreenLocation().ApplyModelViewMatrices(ctx); }); tprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PushMatrix(); if (!is_3d) { //not 3d, flatten to the 0 plane ctx->Scale(1.0, 1.0, 0.0); } GetModelScreenLocation().ApplyModelViewMatrices(ctx); }); DrawModel(preview, ctx, sprogram, tprogram, is_3d, !allowSelected, c); sprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PopMatrix(); }); tprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PopMatrix(); }); if ((Selected || (Highlighted && is_3d)) && c != nullptr && allowSelected) { if (is_3d) { GetModelScreenLocation().DrawHandles(tprogram, preview->GetCameraZoomForHandles(), preview->GetHandleScale(), Highlighted); } else { GetModelScreenLocation().DrawHandles(tprogram, preview->GetCameraZoomForHandles(), preview->GetHandleScale()); } } } void DmxSkulltronix::DisplayEffectOnWindow(ModelPreview* preview, double pointSize) { if (!IsActive() && preview->IsNoCurrentModel()) { return; } bool mustEnd = false; xlGraphicsContext* ctx = preview->getCurrentGraphicsContext(); if (ctx == nullptr) { bool success = preview->StartDrawing(pointSize); if (success) { ctx = preview->getCurrentGraphicsContext(); mustEnd = true; } } if (ctx) { int w, h; preview->GetSize(&w, &h); float scaleX = float(w) * 0.95 / GetModelScreenLocation().RenderWi; float scaleY = float(h) * 0.95 / GetModelScreenLocation().RenderHt; float aspect = screenLocation.GetScaleX(); aspect /= screenLocation.GetScaleY(); if (scaleY < scaleX) { scaleX = scaleY * aspect; } else { scaleY = scaleX / aspect; } float ml, mb; GetMinScreenXY(ml, mb); ml += GetModelScreenLocation().RenderWi / 2; mb += GetModelScreenLocation().RenderHt / 2; preview->getCurrentTransparentProgram()->addStep([=](xlGraphicsContext* ctx) { ctx->PushMatrix(); ctx->Translate(w / 2.0f - (ml < 0.0f ? ml : 0.0f), h / 2.0f - (mb < 0.0f ? mb : 0.0f), 0.0f); ctx->Scale(scaleX, scaleY, 1.0); }); DrawModel(preview, ctx, preview->getCurrentSolidProgram(), preview->getCurrentTransparentProgram(), false, false, nullptr); preview->getCurrentTransparentProgram()->addStep([=](xlGraphicsContext* ctx) { ctx->PopMatrix(); }); } if (mustEnd) { preview->EndDrawing(); } } void DmxSkulltronix::DrawModel(ModelPreview* preview, xlGraphicsContext* ctx, xlGraphicsProgram* sprogram, xlGraphicsProgram* tprogram, bool is3d, bool active, const xlColor* c) { } /* void DmxSkulltronix::DrawModelOnWindow(ModelPreview* preview, DrawGLUtils::xlAccumulator &va, const xlColor *c, float &sx, float &sy, bool active) { if (!IsActive()) return; float pan_angle, pan_angle_raw, tilt_angle, nod_angle, jaw_pos, eye_x, eye_y; float jaw_range_of_motion = -4.0f; float eye_range_of_motion = 3.8f; int channel_value; size_t NodeCount=Nodes.size(); bool beam_off = false; if( pan_channel > NodeCount || tilt_channel > NodeCount || red_channel > NodeCount || green_channel > NodeCount || blue_channel > NodeCount ) { return; } xlColor ccolor(xlWHITE); xlColor pnt_color(xlRED); xlColor eye_color(xlWHITE); xlColor marker_color(xlBLACK); xlColor black(xlBLACK); xlColor base_color(200, 200, 200); xlColor base_color2(150, 150, 150); xlColor color; if (c != nullptr) { color = *c; } int dmx_size = ((BoxedScreenLocation)screenLocation).GetScaleX(); float radius = (float)(dmx_size) / 2.0f; xlColor color_angle; int trans = color == xlBLACK ? blackTransparency : transparency; if( red_channel > 0 && green_channel > 0 && blue_channel > 0 ) { xlColor proxy; Nodes[red_channel-1]->GetColor(proxy); eye_color.red = proxy.red; Nodes[green_channel-1]->GetColor(proxy); eye_color.green = proxy.red; Nodes[blue_channel-1]->GetColor(proxy); eye_color.blue = proxy.red; } if( (eye_color.red == 0 && eye_color.green == 0 && eye_color.blue == 0) || !active ) { eye_color = xlWHITE; beam_off = true; } else { ApplyTransparency(eye_color, trans, trans); marker_color = eye_color; } ApplyTransparency(ccolor, trans, trans); ApplyTransparency(base_color, trans, trans); ApplyTransparency(base_color2, trans, trans); ApplyTransparency(pnt_color, trans, trans); if( pan_channel > 0 ) { channel_value = GetChannelValue(pan_channel-1, true); pan_angle = ((channel_value - pan_min_limit) / (double)(pan_max_limit - pan_min_limit)) * pan_deg_of_rot + pan_orient; } else { pan_angle = 0.0f; } pan_angle_raw = pan_angle; if( tilt_channel > 0 ) { channel_value = GetChannelValue(tilt_channel-1, true); tilt_angle = (1.0 - ((channel_value - tilt_min_limit) / (double)(tilt_max_limit - tilt_min_limit))) * tilt_deg_of_rot + tilt_orient; } else { tilt_angle = 0.0f; } if( nod_channel > 0 ) { channel_value = GetChannelValue(nod_channel-1, true); nod_angle = (1.0 - ((channel_value - nod_min_limit) / (double)(nod_max_limit - nod_min_limit))) * nod_deg_of_rot + nod_orient; } else { nod_angle = 0.0f; } if( jaw_channel > 0 ) { channel_value = GetChannelValue(jaw_channel-1, true); jaw_pos = ((channel_value - jaw_min_limit) / (double)(jaw_max_limit - jaw_min_limit)) * jaw_range_of_motion - 0.5f; } else { jaw_pos = -0.5f; } if( eye_lr_channel > 0 ) { channel_value = GetChannelValue(eye_lr_channel-1, true); eye_x = (1.0 - ((channel_value - eye_lr_min_limit) / (double)(eye_lr_max_limit - eye_lr_min_limit))) * eye_range_of_motion - eye_range_of_motion/2.0; } else { eye_x = 0.0f; } if( eye_ud_channel > 0 ) { channel_value = GetChannelValue(eye_ud_channel-1, true); eye_y = ((channel_value - eye_ud_min_limit) / (double)(eye_ud_max_limit - eye_ud_min_limit)) * eye_range_of_motion - eye_range_of_motion/2.0; } else { eye_y = 0.0f; } if( !active ) { pan_angle = 0.5f * 180 + 90; tilt_angle = 0.5f * 90 + 315; nod_angle = 0.5f * 58 + 331; jaw_pos = -0.5f; eye_x = 0.5f * eye_range_of_motion - eye_range_of_motion/2.0; eye_y = 0.5f * eye_range_of_motion - eye_range_of_motion/2.0; } float sf = 12.0f; float scale = radius / sf; // Create Head dmxPoint3 p1(-7.5f, 13.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p2(7.5f, 13.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p3(13.2f, 6.0f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p8(-13.2f, 6.0f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p4(9, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p7(-9, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p5(6.3f, -16, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p6(-6.3f, -16, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p9(0, 3.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p10(-2.5f, -1.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p11(2.5f, -1.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p14(0, -6.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p12(-6, -6.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p16(6, -6.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p13(-3, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p15(3, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Create Back of Head dmxPoint3 p1b(-7.5f, 13.7f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p2b(7.5f, 13.7f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p3b(13.2f, 6.0f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p8b(-13.2f, 6.0f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p4b(9, -11.4f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p7b(-9, -11.4f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p5b(6.3f, -16, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p6b(-6.3f, -16, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Create Lower Mouth dmxPoint3 p4m(9, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p7m(-9, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p5m(6.3f, -16+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p6m(-6.3f, -16+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p14m(0, -6.5f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p12m(-6, -6.5f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p16m(6, -6.5f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p13m(-3, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p15m(3, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Create Eyes dmxPoint3 left_eye_socket(-5, 7.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 right_eye_socket(5, 7.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 left_eye(-5+eye_x, 7.5f+eye_y, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 right_eye(5+eye_x, 7.5f+eye_y, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Draw Back of Head va.AddVertex(p1.x, p1.y, base_color2); va.AddVertex(p1b.x, p1b.y, base_color2); va.AddVertex(p2.x, p2.y, base_color2); va.AddVertex(p2b.x, p2b.y, base_color2); va.AddVertex(p1b.x, p1b.y, base_color2); va.AddVertex(p2.x, p2.y, base_color2); va.AddVertex(p2.x, p2.y, base_color); va.AddVertex(p2b.x, p2b.y, base_color); va.AddVertex(p3.x, p3.y, base_color); va.AddVertex(p3b.x, p3b.y, base_color); va.AddVertex(p2b.x, p2b.y, base_color); va.AddVertex(p3.x, p3.y, base_color); va.AddVertex(p3.x, p3.y, base_color2); va.AddVertex(p3b.x, p3b.y, base_color2); va.AddVertex(p4.x, p4.y, base_color2); va.AddVertex(p4b.x, p4b.y, base_color2); va.AddVertex(p3b.x, p3b.y, base_color2); va.AddVertex(p4.x, p4.y, base_color2); va.AddVertex(p4.x, p4.y, base_color); va.AddVertex(p4b.x, p4b.y, base_color); va.AddVertex(p5.x, p5.y, base_color); va.AddVertex(p5b.x, p5b.y, base_color); va.AddVertex(p4b.x, p4b.y, base_color); va.AddVertex(p5.x, p5.y, base_color); va.AddVertex(p5.x, p5.y, base_color2); va.AddVertex(p5b.x, p5b.y, base_color2); va.AddVertex(p6.x, p6.y, base_color2); va.AddVertex(p6b.x, p6b.y, base_color2); va.AddVertex(p5b.x, p5b.y, base_color2); va.AddVertex(p6.x, p6.y, base_color2); va.AddVertex(p6.x, p6.y, base_color); va.AddVertex(p6b.x, p6b.y, base_color); va.AddVertex(p7.x, p7.y, base_color); va.AddVertex(p7b.x, p7b.y, base_color); va.AddVertex(p6b.x, p6b.y, base_color); va.AddVertex(p7.x, p7.y, base_color); va.AddVertex(p7.x, p7.y, base_color2); va.AddVertex(p7b.x, p7b.y, base_color2); va.AddVertex(p8.x, p8.y, base_color2); va.AddVertex(p8b.x, p8b.y, base_color2); va.AddVertex(p7b.x, p7b.y, base_color2); va.AddVertex(p8.x, p8.y, base_color2); va.AddVertex(p8.x, p8.y, base_color); va.AddVertex(p8b.x, p8b.y, base_color); va.AddVertex(p1.x, p1.y, base_color); va.AddVertex(p1b.x, p1b.y, base_color); va.AddVertex(p8b.x, p8b.y, base_color); va.AddVertex(p1.x, p1.y, base_color); // Draw Front of Head va.AddVertex(p1.x, p1.y, ccolor); va.AddVertex(p2.x, p2.y, ccolor); va.AddVertex(p9.x, p9.y, ccolor); va.AddVertex(p2.x, p2.y, ccolor); va.AddVertex(p9.x, p9.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p1.x, p1.y, ccolor); va.AddVertex(p9.x, p9.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p1.x, p1.y, ccolor); va.AddVertex(p8.x, p8.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p2.x, p2.y, ccolor); va.AddVertex(p3.x, p3.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p8.x, p8.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p3.x, p3.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); va.AddVertex(p7.x, p7.y, ccolor); va.AddVertex(p8.x, p8.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p3.x, p3.y, ccolor); va.AddVertex(p4.x, p4.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p13.x, p13.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p15.x, p15.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); // Draw Lower Mouth va.AddVertex(p4m.x, p4m.y, ccolor); va.AddVertex(p6m.x, p6m.y, ccolor); va.AddVertex(p7m.x, p7m.y, ccolor); va.AddVertex(p4m.x, p4m.y, ccolor); va.AddVertex(p5m.x, p5m.y, ccolor); va.AddVertex(p6m.x, p6m.y, ccolor); va.AddVertex(p7m.x, p7m.y, ccolor); va.AddVertex(p12m.x, p12m.y, ccolor); va.AddVertex(p13m.x, p13m.y, ccolor); va.AddVertex(p13m.x, p13m.y, ccolor); va.AddVertex(p14m.x, p14m.y, ccolor); va.AddVertex(p15m.x, p15m.y, ccolor); va.AddVertex(p4m.x, p4m.y, ccolor); va.AddVertex(p15m.x, p15m.y, ccolor); va.AddVertex(p16m.x, p16m.y, ccolor); // Draw Eyes va.AddCircleAsTriangles(left_eye_socket.x, left_eye_socket.y, scale*sf*0.25, black, black); va.AddCircleAsTriangles(right_eye_socket.x, right_eye_socket.y, scale*sf*0.25, black, black); va.AddCircleAsTriangles(left_eye.x, left_eye.y, scale*sf*0.10, eye_color, eye_color); va.AddCircleAsTriangles(right_eye.x, right_eye.y, scale*sf*0.10, eye_color, eye_color); va.Finish(GL_TRIANGLES); } void DmxSkulltronix::DrawModelOnWindow(ModelPreview* preview, DrawGLUtils::xl3Accumulator &va, const xlColor *c, float &sx, float &sy, float &sz, bool active) { if (!IsActive()) return; float pan_angle, pan_angle_raw, tilt_angle, nod_angle, jaw_pos, eye_x, eye_y; float jaw_range_of_motion = -4.0f; float eye_range_of_motion = 3.8f; int channel_value; size_t NodeCount = Nodes.size(); bool beam_off = false; if (pan_channel > NodeCount || tilt_channel > NodeCount || red_channel > NodeCount || green_channel > NodeCount || blue_channel > NodeCount) { return; } xlColor ccolor(xlWHITE); xlColor pnt_color(xlRED); xlColor eye_color(xlWHITE); xlColor marker_color(xlBLACK); xlColor black(xlBLACK); xlColor base_color(200, 200, 200); xlColor base_color2(150, 150, 150); xlColor color; if (c != nullptr) { color = *c; } int dmx_size = ((BoxedScreenLocation)screenLocation).GetScaleX(); float radius = (float)(dmx_size) / 2.0f; xlColor color_angle; int trans = color == xlBLACK ? blackTransparency : transparency; if (red_channel > 0 && green_channel > 0 && blue_channel > 0) { xlColor proxy; Nodes[red_channel - 1]->GetColor(proxy); eye_color.red = proxy.red; Nodes[green_channel - 1]->GetColor(proxy); eye_color.green = proxy.red; Nodes[blue_channel - 1]->GetColor(proxy); eye_color.blue = proxy.red; } if ((eye_color.red == 0 && eye_color.green == 0 && eye_color.blue == 0) || !active) { eye_color = xlWHITE; beam_off = true; } else { ApplyTransparency(eye_color, trans, trans); marker_color = eye_color; } ApplyTransparency(ccolor, trans, trans); ApplyTransparency(base_color, trans, trans); ApplyTransparency(base_color2, trans, trans); ApplyTransparency(pnt_color, trans, trans); if (pan_channel > 0) { channel_value = GetChannelValue(pan_channel - 1, true); pan_angle = ((channel_value - pan_min_limit) / (double)(pan_max_limit - pan_min_limit)) * pan_deg_of_rot + pan_orient; } else { pan_angle = 0.0f; } pan_angle_raw = pan_angle; if (tilt_channel > 0) { channel_value = GetChannelValue(tilt_channel - 1, true); tilt_angle = (1.0 - ((channel_value - tilt_min_limit) / (double)(tilt_max_limit - tilt_min_limit))) * tilt_deg_of_rot + tilt_orient; } else { tilt_angle = 0.0f; } if (nod_channel > 0) { channel_value = GetChannelValue(nod_channel - 1, true); nod_angle = (1.0 - ((channel_value - nod_min_limit) / (double)(nod_max_limit - nod_min_limit))) * nod_deg_of_rot + nod_orient; } else { nod_angle = 0.0f; } if (jaw_channel > 0) { channel_value = GetChannelValue(jaw_channel - 1, true); jaw_pos = ((channel_value - jaw_min_limit) / (double)(jaw_max_limit - jaw_min_limit)) * jaw_range_of_motion - 0.5f; } else { jaw_pos = -0.5f; } if (eye_lr_channel > 0) { channel_value = GetChannelValue(eye_lr_channel - 1, true); eye_x = (1.0 - ((channel_value - eye_lr_min_limit) / (double)(eye_lr_max_limit - eye_lr_min_limit))) * eye_range_of_motion - eye_range_of_motion / 2.0; } else { eye_x = 0.0f; } if (eye_ud_channel > 0) { channel_value = GetChannelValue(eye_ud_channel - 1, true); eye_y = ((channel_value - eye_ud_min_limit) / (double)(eye_ud_max_limit - eye_ud_min_limit)) * eye_range_of_motion - eye_range_of_motion / 2.0; } else { eye_y = 0.0f; } if (!active) { pan_angle = 0.5f * 180 + 90; tilt_angle = 0.5f * 90 + 315; nod_angle = 0.5f * 58 + 331; jaw_pos = -0.5f; eye_x = 0.5f * eye_range_of_motion - eye_range_of_motion / 2.0; eye_y = 0.5f * eye_range_of_motion - eye_range_of_motion / 2.0; } float sf = 12.0f; float scale = radius / sf; // Create Head dmxPoint3d p1(-7.5f, 13.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p2(7.5f, 13.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p3(13.2f, 6.0f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p8(-13.2f, 6.0f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p4(9, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p7(-9, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p5(6.3f, -16, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p6(-6.3f, -16, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p9(0, 3.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p10(-2.5f, -1.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p11(2.5f, -1.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p14(0, -6.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p12(-6, -6.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p16(6, -6.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p13(-3, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p15(3, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Create Back of Head dmxPoint3d p1b(-7.5f, 13.7f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p2b(7.5f, 13.7f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p3b(13.2f, 6.0f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p8b(-13.2f, 6.0f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p4b(9, -11.4f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p7b(-9, -11.4f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p5b(6.3f, -16, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p6b(-6.3f, -16, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Create Lower Mouth dmxPoint3d p4m(9, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p7m(-9, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p5m(6.3f, -16 + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p6m(-6.3f, -16 + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p14m(0, -6.5f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p12m(-6, -6.5f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p16m(6, -6.5f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p13m(-3, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p15m(3, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Create Eyes dmxPoint3d left_eye_socket(-5, 7.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d right_eye_socket(5, 7.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d left_eye(-5 + eye_x, 7.5f + eye_y, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d right_eye(5 + eye_x, 7.5f + eye_y, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Draw Back of Head va.AddVertex(p1.x, p1.y, p1.z, base_color2); va.AddVertex(p1b.x, p1b.y, p1b.z, base_color2); va.AddVertex(p2.x, p2.y, p2.z, base_color2); va.AddVertex(p2b.x, p2b.y, p2b.z, base_color2); va.AddVertex(p1b.x, p1b.y, p1b.z, base_color2); va.AddVertex(p2.x, p2.y, p2.z, base_color2); va.AddVertex(p2.x, p2.y, p2.z, base_color); va.AddVertex(p2b.x, p2b.y, p2b.z, base_color); va.AddVertex(p3.x, p3.y, p3.z, base_color); va.AddVertex(p3b.x, p3b.y, p3b.z, base_color); va.AddVertex(p2b.x, p2b.y, p2b.z, base_color); va.AddVertex(p3.x, p3.y, p3.z, base_color); va.AddVertex(p3.x, p3.y, p3.z, base_color2); va.AddVertex(p3b.x, p3b.y, p3b.z, base_color2); va.AddVertex(p4.x, p4.y, p4.z, base_color2); va.AddVertex(p4b.x, p4b.y, p4b.z, base_color2); va.AddVertex(p3b.x, p3b.y, p3b.z, base_color2); va.AddVertex(p4.x, p4.y, p4.z, base_color2); va.AddVertex(p4.x, p4.y, p4.z, base_color); va.AddVertex(p4b.x, p4b.y, p4b.z, base_color); va.AddVertex(p5.x, p5.y, p5.z, base_color); va.AddVertex(p5b.x, p5b.y, p5b.z, base_color); va.AddVertex(p4b.x, p4b.y, p4b.z, base_color); va.AddVertex(p5.x, p5.y, p5.z, base_color); va.AddVertex(p5.x, p5.y, p5.z, base_color2); va.AddVertex(p5b.x, p5b.y, p5b.z, base_color2); va.AddVertex(p6.x, p6.y, p6.z, base_color2); va.AddVertex(p6b.x, p6b.y, p6b.z, base_color2); va.AddVertex(p5b.x, p5b.y, p5b.z, base_color2); va.AddVertex(p6.x, p6.y, p6.z, base_color2); va.AddVertex(p6.x, p6.y, p6.z, base_color); va.AddVertex(p6b.x, p6b.y, p6b.z, base_color); va.AddVertex(p7.x, p7.y, p7.z, base_color); va.AddVertex(p7b.x, p7b.y, p7b.z, base_color); va.AddVertex(p6b.x, p6b.y, p6b.z, base_color); va.AddVertex(p7.x, p7.y, p7.z, base_color); va.AddVertex(p7.x, p7.y, p7.z, base_color2); va.AddVertex(p7b.x, p7b.y, p7b.z, base_color2); va.AddVertex(p8.x, p8.y, p8.z, base_color2); va.AddVertex(p8b.x, p8b.y, p8b.z, base_color2); va.AddVertex(p7b.x, p7b.y, p7b.z, base_color2); va.AddVertex(p8.x, p8.y, p8.z, base_color2); va.AddVertex(p8.x, p8.y, p8.z, base_color); va.AddVertex(p8b.x, p8b.y, p8b.z, base_color); va.AddVertex(p1.x, p1.y, p1.z, base_color); va.AddVertex(p1b.x, p1b.y, p1b.z, base_color); va.AddVertex(p8b.x, p8b.y, p8b.z, base_color); va.AddVertex(p1.x, p1.y, p1.z, base_color); // Draw Front of Head va.AddVertex(p1.x, p1.y, p1.z, ccolor); va.AddVertex(p2.x, p2.y, p2.z, ccolor); va.AddVertex(p9.x, p9.y, p9.z, ccolor); va.AddVertex(p2.x, p2.y, p2.z, ccolor); va.AddVertex(p9.x, p9.y, p9.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p1.x, p1.y, p1.z, ccolor); va.AddVertex(p9.x, p9.y, p9.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p1.x, p1.y, p1.z, ccolor); va.AddVertex(p8.x, p8.y, p8.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p2.x, p2.y, p2.z, ccolor); va.AddVertex(p3.x, p3.y, p3.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p8.x, p8.y, p8.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p3.x, p3.y, p3.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); va.AddVertex(p7.x, p7.y, p7.z, ccolor); va.AddVertex(p8.x, p8.y, p8.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p3.x, p3.y, p3.z, ccolor); va.AddVertex(p4.x, p4.y, p4.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p13.x, p13.y, p13.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p15.x, p15.y, p15.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); // Draw Lower Mouth va.AddVertex(p4m.x, p4m.y, p4m.z, ccolor); va.AddVertex(p6m.x, p6m.y, p6m.z, ccolor); va.AddVertex(p7m.x, p7m.y, p7m.z, ccolor); va.AddVertex(p4m.x, p4m.y, p4m.z, ccolor); va.AddVertex(p5m.x, p5m.y, p5m.z, ccolor); va.AddVertex(p6m.x, p6m.y, p6m.z, ccolor); va.AddVertex(p7m.x, p7m.y, p7m.z, ccolor); va.AddVertex(p12m.x, p12m.y, p12m.z, ccolor); va.AddVertex(p13m.x, p13m.y, p13m.z, ccolor); va.AddVertex(p13m.x, p13m.y, p13m.z, ccolor); va.AddVertex(p14m.x, p14m.y, p14m.z, ccolor); va.AddVertex(p15m.x, p15m.y, p15m.z, ccolor); va.AddVertex(p4m.x, p4m.y, p4m.z, ccolor); va.AddVertex(p15m.x, p15m.y, p15m.z, ccolor); va.AddVertex(p16m.x, p16m.y, p16m.z, ccolor); // Draw Eyes va.AddCircleAsTriangles(left_eye_socket.x, left_eye_socket.y, left_eye_socket.z, scale*sf*0.25, black, black); va.AddCircleAsTriangles(right_eye_socket.x, right_eye_socket.y, right_eye_socket.z, scale*sf*0.25, black, black); va.AddCircleAsTriangles(left_eye.x, left_eye.y, left_eye.z, scale*sf*0.10, eye_color, eye_color); va.AddCircleAsTriangles(right_eye.x, right_eye.y, right_eye.z, scale*sf*0.10, eye_color, eye_color); va.Finish(GL_TRIANGLES); } */ void DmxSkulltronix::ExportXlightsModel() { wxString name = ModelXml->GetAttribute("name"); wxLogNull logNo; //kludge: avoid "error 0" message from wxWidgets after new file is written wxString filename = wxFileSelector(_("Choose output file"), wxEmptyString, name, wxEmptyString, "Custom Model files (*.xmodel)|*.xmodel", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (filename.IsEmpty()) return; wxFile f(filename); // bool isnew = !FileExists(filename); if (!f.Create(filename, true) || !f.IsOpened()) DisplayError(wxString::Format("Unable to create file %s. Error %d\n", filename, f.GetLastError()).ToStdString()); f.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<dmxmodel \n"); ExportBaseParameters(f); wxString pdr = ModelXml->GetAttribute("DmxPanDegOfRot", "180"); wxString tdr = ModelXml->GetAttribute("DmxTiltDegOfRot", "90"); wxString s = ModelXml->GetAttribute("DmxStyle"); wxString pc = ModelXml->GetAttribute("DmxPanChannel", "13"); wxString po = ModelXml->GetAttribute("DmxPanOrient", "90"); wxString tc = ModelXml->GetAttribute("DmxTiltChannel", "19"); wxString to = ModelXml->GetAttribute("DmxTiltOrient", "315"); wxString rc = ModelXml->GetAttribute("DmxRedChannel", "24"); wxString gc = ModelXml->GetAttribute("DmxGreenChannel", "25"); wxString bc = ModelXml->GetAttribute("DmxBlueChannel", "26"); wxString wc = ModelXml->GetAttribute("DmxWhiteChannel", "0"); wxString sc = ModelXml->GetAttribute("DmxShutterChannel", "0"); wxString so = ModelXml->GetAttribute("DmxShutterOpen", "1"); wxString tml = ModelXml->GetAttribute("DmxTiltMinLimit", "442"); wxString tmxl = ModelXml->GetAttribute("DmxTiltMaxLimit", "836"); wxString pml = ModelXml->GetAttribute("DmxPanMinLimit", "250"); wxString pmxl = ModelXml->GetAttribute("DmxPanMaxLimit", "1250"); wxString nc = ModelXml->GetAttribute("DmxNodChannel", "11"); wxString no = ModelXml->GetAttribute("DmxNodOrient", "331"); wxString ndr = ModelXml->GetAttribute("DmxNodDegOfRot", "58"); wxString nml = ModelXml->GetAttribute("DmxNodMinLimit", "452"); wxString nmxl = ModelXml->GetAttribute("DmxNodMaxLimit", "745"); wxString jc = ModelXml->GetAttribute("DmxJawChannel", "9"); wxString jml = ModelXml->GetAttribute("DmxJawMinLimit", "500"); wxString jmxl = ModelXml->GetAttribute("DmxJawMaxLimit", "750"); wxString eb = ModelXml->GetAttribute("DmxEyeBrtChannel", "23"); wxString eudc = ModelXml->GetAttribute("DmxEyeUDChannel", "15"); wxString eudml = ModelXml->GetAttribute("DmxEyeUDMinLimit", "575"); wxString eudmxl = ModelXml->GetAttribute("DmxEyeUDMaxLimit", "1000"); wxString elrc = ModelXml->GetAttribute("DmxEyeLRChannel", "17"); wxString elml = ModelXml->GetAttribute("DmxEyeLRMinLimit", "499"); wxString elrmxl = ModelXml->GetAttribute("DmxEyeLRMaxLimit", "878"); f.Write(wxString::Format("DmxPanDegOfRot=\"%s\" ", pdr)); f.Write(wxString::Format("DmxTiltDegOfRot=\"%s\" ", tdr)); f.Write(wxString::Format("DmxStyle=\"%s\" ", s)); f.Write(wxString::Format("DmxPanChannel=\"%s\" ", pc)); f.Write(wxString::Format("DmxPanOrient=\"%s\" ", po)); f.Write(wxString::Format("DmxTiltChannel=\"%s\" ", tc)); f.Write(wxString::Format("DmxTiltOrient=\"%s\" ", to)); f.Write(wxString::Format("DmxRedChannel=\"%s\" ", rc)); f.Write(wxString::Format("DmxGreenChannel=\"%s\" ", gc)); f.Write(wxString::Format("DmxBlueChannel=\"%s\" ", bc)); f.Write(wxString::Format("DmxWhiteChannel=\"%s\" ", wc)); f.Write(wxString::Format("DmxShutterChannel=\"%s\" ", sc)); f.Write(wxString::Format("DmxShutterOpen=\"%s\" ", so)); f.Write(wxString::Format("DmxTiltMinLimit=\"%s\" ", tml)); f.Write(wxString::Format("DmxTiltMaxLimit=\"%s\" ", tmxl)); f.Write(wxString::Format("DmxPanMinLimit=\"%s\" ", pml)); f.Write(wxString::Format("DmxPanMaxLimit=\"%s\" ", pmxl)); f.Write(wxString::Format("DmxNodChannel=\"%s\" ", nc)); f.Write(wxString::Format("DmxNodOrient=\"%s\" ", no)); f.Write(wxString::Format("DmxNodDegOfRot=\"%s\" ", ndr)); f.Write(wxString::Format("DmxNodMinLimit=\"%s\" ", nml)); f.Write(wxString::Format("DmxNodMaxLimit=\"%s\" ", nmxl)); f.Write(wxString::Format("DmxJawChannel=\"%s\" ", jc)); f.Write(wxString::Format("DmxJawMinLimit=\"%s\" ", jml)); f.Write(wxString::Format("DmxJawMaxLimit=\"%s\" ", jmxl)); f.Write(wxString::Format("DmxEyeBrtChannel=\"%s\" ", eb)); f.Write(wxString::Format("DmxEyeUDChannel=\"%s\" ", eudc)); f.Write(wxString::Format("DmxEyeUDMinLimit=\"%s\" ", eudml)); f.Write(wxString::Format("DmxEyeUDMaxLimit=\"%s\" ", eudmxl)); f.Write(wxString::Format("DmxEyeLRChannel=\"%s\" ", elrc)); f.Write(wxString::Format("DmxEyeLRMinLimit=\"%s\" ", elml)); f.Write(wxString::Format("DmxEyeLRMaxLimit=\"%s\" ", elrmxl)); f.Write(" >\n"); wxString submodel = SerialiseSubmodel(); if (submodel != "") { f.Write(submodel); } wxString state = SerialiseState(); if (state != "") { f.Write(state); } wxString groups = SerialiseGroups(); if (groups != "") { f.Write(groups); } f.Write("</dmxmodel>"); f.Close(); } void DmxSkulltronix::ImportXlightsModel(wxXmlNode* root, xLightsFrame* xlights, float& min_x, float& max_x, float& min_y, float& max_y) { if (root->GetName() == "dmxmodel") { ImportBaseParameters(root); wxString name = root->GetAttribute("name"); wxString v = root->GetAttribute("SourceVersion"); wxString pdr = root->GetAttribute("DmxPanDegOfRot"); wxString tdr = root->GetAttribute("DmxTiltDegOfRot"); wxString s = root->GetAttribute("DmxStyle"); wxString pc = root->GetAttribute("DmxPanChannel"); wxString po = root->GetAttribute("DmxPanOrient"); wxString psl = root->GetAttribute("DmxPanSlewLimit"); wxString tc = root->GetAttribute("DmxTiltChannel"); wxString to = root->GetAttribute("DmxTiltOrient"); wxString tsl = root->GetAttribute("DmxTiltSlewLimit"); wxString rc = root->GetAttribute("DmxRedChannel"); wxString gc = root->GetAttribute("DmxGreenChannel"); wxString bc = root->GetAttribute("DmxBlueChannel"); wxString wc = root->GetAttribute("DmxWhiteChannel"); wxString sc = root->GetAttribute("DmxShutterChannel"); wxString so = root->GetAttribute("DmxShutterOpen"); wxString bl = root->GetAttribute("DmxBeamLimit"); wxString tml = root->GetAttribute("DmxTiltMinLimit"); wxString tmxl = root->GetAttribute("DmxTiltMaxLimit"); wxString pml = root->GetAttribute("DmxPanMinLimit"); wxString pmxl = root->GetAttribute("DmxPanMaxLimit"); wxString nc = root->GetAttribute("DmxNodChannel"); wxString no = root->GetAttribute("DmxNodOrient"); wxString ndr = root->GetAttribute("DmxNodDegOfRot"); wxString nml = root->GetAttribute("DmxNodMinLimit"); wxString nmxl = root->GetAttribute("DmxNodMaxLimit"); wxString jc = root->GetAttribute("DmxJawChannel"); wxString jml = root->GetAttribute("DmxJawMinLimit"); wxString jmxl = root->GetAttribute("DmxJawMaxLimit"); wxString eb = root->GetAttribute("DmxEyeBrtChannel"); wxString eudc = root->GetAttribute("DmxEyeUDChannel"); wxString eudml = root->GetAttribute("DmxEyeUDMinLimit"); wxString eudmxl = root->GetAttribute("DmxEyeUDMaxLimit"); wxString elrc = root->GetAttribute("DmxEyeLRChannel"); wxString elml = root->GetAttribute("DmxEyeLRMinLimit"); wxString elrmxl = root->GetAttribute("DmxEyeLRMaxLimit"); // Add any model version conversion logic here // Source version will be the program version that created the custom model SetProperty("DmxPanDegOfRot", pdr); SetProperty("DmxTiltDegOfRot", tdr); SetProperty("DmxStyle", s); SetProperty("DmxPanChannel", pc); SetProperty("DmxPanOrient", po); SetProperty("DmxPanSlewLimit", psl); SetProperty("DmxTiltChannel", tc); SetProperty("DmxTiltOrient", to); SetProperty("DmxTiltSlewLimit", tsl); SetProperty("DmxRedChannel", rc); SetProperty("DmxGreenChannel", gc); SetProperty("DmxBlueChannel", bc); SetProperty("DmxWhiteChannel", wc); SetProperty("DmxShutterChannel", sc); SetProperty("DmxShutterOpen", so); SetProperty("DmxBeamLimit", bl); SetProperty("DmxTiltMinLimit", tml); SetProperty("DmxTiltMaxLimit", tmxl); SetProperty("DmxPanMinLimit", pml); SetProperty("DmxPanMaxLimit", pmxl); SetProperty("DmxNodChannel", nc); SetProperty("DmxNodOrient", no); SetProperty("DmxNodDegOfRot", ndr); SetProperty("DmxNodMinLimit", nml); SetProperty("DmxNodMaxLimit", nmxl); SetProperty("DmxJawChannel", jc); SetProperty("DmxJawMinLimit", jml); SetProperty("DmxJawMaxLimit", jmxl); SetProperty("DmxEyeBrtChannel", eb); SetProperty("DmxEyeUDChannel", eudc); SetProperty("DmxEyeUDMinLimit", eudml); SetProperty("DmxEyeUDMaxLimit", eudmxl); SetProperty("DmxEyeLRChannel", elrc); SetProperty("DmxEyeLRMinLimit", elml); SetProperty("DmxEyeLRMaxLimit", elrmxl); wxString newname = xlights->AllModels.GenerateModelName(name.ToStdString()); GetModelScreenLocation().Write(ModelXml); SetProperty("name", newname, true); ImportModelChildren(root, xlights, newname); xlights->GetOutputModelManager()->AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::ImportXlightsModel"); xlights->GetOutputModelManager()->AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::ImportXlightsModel"); } else { DisplayError("Failure loading DmxSkulltronix model file."); } }
smeighan/xLights
xLights/models/DMX/DmxSkulltronix.cpp
C++
gpl-3.0
61,427
#region LICENSE /* Copyright 2014 - 2015 LeagueSharp Orbwalking.cs is part of LeagueSharp.Common. LeagueSharp.Common 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. LeagueSharp.Common 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 LeagueSharp.Common. If not, see <http://www.gnu.org/licenses/>. */ #endregion #region using System; using System.Collections.Generic; using System.Linq; using LeagueSharp; using LeagueSharp.Common; using SharpDX; using Color = System.Drawing.Color; #endregion namespace YasuoPro { /// <summary> /// This class offers everything related to auto-attacks and orbwalking. /// </summary> public static class Orbwalking { /// <summary> /// Delegate AfterAttackEvenH /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> public delegate void AfterAttackEvenH(AttackableUnit unit, AttackableUnit target); /// <summary> /// Delegate BeforeAttackEvenH /// </summary> /// <param name="args">The <see cref="BeforeAttackEventArgs" /> instance containing the event data.</param> public delegate void BeforeAttackEvenH(BeforeAttackEventArgs args); /// <summary> /// Delegate OnAttackEvenH /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> public delegate void OnAttackEvenH(AttackableUnit unit, AttackableUnit target); /// <summary> /// Delegate OnNonKillableMinionH /// </summary> /// <param name="minion">The minion.</param> public delegate void OnNonKillableMinionH(AttackableUnit minion); /// <summary> /// Delegate OnTargetChangeH /// </summary> /// <param name="oldTarget">The old target.</param> /// <param name="newTarget">The new target.</param> public delegate void OnTargetChangeH(AttackableUnit oldTarget, AttackableUnit newTarget); /// <summary> /// The orbwalking mode. /// </summary> public enum OrbwalkingMode { /// <summary> /// The orbwalker will only last hit minions. /// </summary> LastHit, /// <summary> /// The orbwalker will alternate between last hitting and auto attacking champions. /// </summary> Mixed, /// <summary> /// The orbwalker will clear the lane of minions as fast as possible while attempting to get the last hit. /// </summary> LaneClear, /// <summary> /// The orbwalker will only attack the target. /// </summary> Combo, /// <summary> /// The orbwalker will only last hit minions as late as possible. /// </summary> Freeze, /// <summary> /// The orbwalker will only move. /// </summary> CustomMode, /// <summary> /// The orbwalker does nothing. /// </summary> None } /// <summary> /// Spells that reset the attack timer. /// </summary> private static readonly string[] AttackResets = { "dariusnoxiantacticsonh", "fiorae", "garenq", "gravesmove", "hecarimrapidslash", "jaxempowertwo", "jaycehypercharge", "leonashieldofdaybreak", "luciane", "monkeykingdoubleattack", "mordekaisermaceofspades", "nasusq", "nautiluspiercinggaze", "netherblade", "gangplankqwrapper", "powerfist", "renektonpreexecute", "rengarq", "aspectofthecougar", "shyvanadoubleattack", "sivirw", "takedown", "talonnoxiandiplomacy", "trundletrollsmash", "vaynetumble", "vie", "volibearq", "xenzhaocombotarget", "yorickspectral", "reksaiq", "itemtitanichydracleave", "masochism", "illaoiw", "elisespiderw", "fiorae", "meditate", "sejuaninorthernwinds", "asheq" }; /// <summary> /// Spells that are not attacks even if they have the "attack" word in their name. /// </summary> private static readonly string[] NoAttacks = { "volleyattack", "volleyattackwithsound", "jarvanivcataclysmattack", "monkeykingdoubleattack", "shyvanadoubleattack", "shyvanadoubleattackdragon", "zyragraspingplantattack", "zyragraspingplantattack2", "zyragraspingplantattackfire", "zyragraspingplantattack2fire", "viktorpowertransfer", "sivirwattackbounce", "asheqattacknoonhit", "elisespiderlingbasicattack", "heimertyellowbasicattack", "heimertyellowbasicattack2", "heimertbluebasicattack", "annietibbersbasicattack", "annietibbersbasicattack2", "yorickdecayedghoulbasicattack", "yorickravenousghoulbasicattack", "yorickspectralghoulbasicattack", "malzaharvoidlingbasicattack", "malzaharvoidlingbasicattack2", "malzaharvoidlingbasicattack3", "kindredwolfbasicattack" }; /// <summary> /// Spells that are attacks even if they dont have the "attack" word in their name. /// </summary> private static readonly string[] Attacks = { "caitlynheadshotmissile", "frostarrow", "garenslash2", "kennenmegaproc", "masteryidoublestrike", "quinnwenhanced", "renektonexecute", "renektonsuperexecute", "rengarnewpassivebuffdash", "trundleq", "xenzhaothrust", "xenzhaothrust2", "xenzhaothrust3", "viktorqbuff", "lucianpassiveshot" }; /// <summary> /// Champs whose auto attacks can't be cancelled /// </summary> private static readonly string[] NoCancelChamps = { "Kalista" }; /// <summary> /// The last auto attack tick /// </summary> public static int LastAATick; /// <summary> /// <c>true</c> if the orbwalker will attack. /// </summary> public static bool Attack = true; /// <summary> /// <c>true</c> if the orbwalker will skip the next attack. /// </summary> public static bool DisableNextAttack; /// <summary> /// <c>true</c> if the orbwalker will move. /// </summary> public static bool Move = true; /// <summary> /// The tick the most recent attack command was sent. /// </summary> public static int LastAttackCommandT; /// <summary> /// The tick the most recent move command was sent. /// </summary> public static int LastMoveCommandT; /// <summary> /// The last move command position /// </summary> public static Vector3 LastMoveCommandPosition = Vector3.Zero; /// <summary> /// The last target /// </summary> private static AttackableUnit _lastTarget; /// <summary> /// The player /// </summary> private static readonly Obj_AI_Hero Player; /// <summary> /// The delay /// </summary> private static int _delay; /// <summary> /// The minimum distance /// </summary> private static float _minDistance = 400; /// <summary> /// <c>true</c> if the auto attack missile was launched from the player. /// </summary> private static bool _missileLaunched; /// <summary> /// The champion name /// </summary> private static readonly string _championName; /// <summary> /// The random /// </summary> private static readonly Random _random = new Random(DateTime.Now.Millisecond); private static int _autoattackCounter; /// <summary> /// Initializes static members of the <see cref="Orbwalking" /> class. /// </summary> static Orbwalking() { Player = ObjectManager.Player; _championName = Player.ChampionName; Obj_AI_Base.OnProcessSpellCast += OnProcessSpell; Obj_AI_Base.OnDoCast += Obj_AI_Base_OnDoCast; Spellbook.OnStopCast += SpellbookOnStopCast; if (_championName == "Rengar") { Obj_AI_Base.OnPlayAnimation += delegate (Obj_AI_Base sender, GameObjectPlayAnimationEventArgs args) { if (sender.IsMe && args.Animation == "Spell5") { var t = 0; if (_lastTarget != null && _lastTarget.IsValid) { t += (int)Math.Min(ObjectManager.Player.Distance(_lastTarget) / 1.5f, 0.6f); } LastAATick = Utils.GameTimeTickCount - Game.Ping / 2 + t; } }; } } /// <summary> /// This event is fired before the player auto attacks. /// </summary> public static event BeforeAttackEvenH BeforeAttack; /// <summary> /// This event is fired when a unit is about to auto-attack another unit. /// </summary> public static event OnAttackEvenH OnAttack; /// <summary> /// This event is fired after a unit finishes auto-attacking another unit (Only works with player for now). /// </summary> public static event AfterAttackEvenH AfterAttack; /// <summary> /// Gets called on target changes /// </summary> public static event OnTargetChangeH OnTargetChange; /// <summary> /// Occurs when a minion is not killable by an auto attack. /// </summary> public static event OnNonKillableMinionH OnNonKillableMinion; /// <summary> /// Fires the before attack event. /// </summary> /// <param name="target">The target.</param> private static void FireBeforeAttack(AttackableUnit target) { if (BeforeAttack != null) { BeforeAttack(new BeforeAttackEventArgs { Target = target }); } else { DisableNextAttack = false; } } /// <summary> /// Fires the on attack event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> private static void FireOnAttack(AttackableUnit unit, AttackableUnit target) { if (OnAttack != null) { OnAttack(unit, target); } } /// <summary> /// Fires the after attack event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> private static void FireAfterAttack(AttackableUnit unit, AttackableUnit target) { if (AfterAttack != null && target.IsValidTarget()) { AfterAttack(unit, target); } } /// <summary> /// Fires the on target switch event. /// </summary> /// <param name="newTarget">The new target.</param> private static void FireOnTargetSwitch(AttackableUnit newTarget) { if (OnTargetChange != null && (!_lastTarget.IsValidTarget() || _lastTarget != newTarget)) { OnTargetChange(_lastTarget, newTarget); } } /// <summary> /// Fires the on non killable minion event. /// </summary> /// <param name="minion">The minion.</param> private static void FireOnNonKillableMinion(AttackableUnit minion) { if (OnNonKillableMinion != null) { OnNonKillableMinion(minion); } } /// <summary> /// Returns true if the spellname resets the attack timer. /// </summary> /// <param name="name">The name.</param> /// <returns><c>true</c> if the specified name is an auto attack reset; otherwise, <c>false</c>.</returns> public static bool IsAutoAttackReset(string name) { return AttackResets.Contains(name.ToLower()); } /// <summary> /// Returns true if the unit is melee /// </summary> /// <param name="unit">The unit.</param> /// <returns><c>true</c> if the specified unit is melee; otherwise, <c>false</c>.</returns> public static bool IsMelee(this Obj_AI_Base unit) { return unit.CombatType == GameObjectCombatType.Melee; } /// <summary> /// Returns true if the spellname is an auto-attack. /// </summary> /// <param name="name">The name.</param> /// <returns><c>true</c> if the name is an auto attack; otherwise, <c>false</c>.</returns> public static bool IsAutoAttack(string name) { return (name.ToLower().Contains("attack") && !NoAttacks.Contains(name.ToLower())) || Attacks.Contains(name.ToLower()); } /// <summary> /// Returns the auto-attack range of local player with respect to the target. /// </summary> /// <param name="target">The target.</param> /// <returns>System.Single.</returns> public static float GetRealAutoAttackRange(AttackableUnit target) { var result = Player.AttackRange + Player.BoundingRadius; if (target.IsValidTarget()) { var aiBase = target as Obj_AI_Base; if (aiBase != null && Player.ChampionName == "Caitlyn") { if (aiBase.HasBuff("caitlynyordletrapinternal")) { result += 650; } } return result + target.BoundingRadius; } return result; } /// <summary> /// Returns the auto-attack range of the target. /// </summary> /// <param name="target">The target.</param> /// <returns>System.Single.</returns> public static float GetAttackRange(Obj_AI_Hero target) { var result = target.AttackRange + target.BoundingRadius; return result; } /// <summary> /// Returns true if the target is in auto-attack range. /// </summary> /// <param name="target">The target.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public static bool InAutoAttackRange(AttackableUnit target) { if (!target.IsValidTarget()) { return false; } var myRange = GetRealAutoAttackRange(target); return Vector2.DistanceSquared( target is Obj_AI_Base ? ((Obj_AI_Base)target).ServerPosition.To2D() : target.Position.To2D(), Player.ServerPosition.To2D()) <= myRange * myRange; } /// <summary> /// Returns player auto-attack missile speed. /// </summary> /// <returns>System.Single.</returns> public static float GetMyProjectileSpeed() { return IsMelee(Player) || _championName == "Azir" || _championName == "Velkoz" || _championName == "Viktor" && Player.HasBuff("ViktorPowerTransferReturn") ? float.MaxValue : Player.BasicAttack.MissileSpeed; } /// <summary> /// Returns if the player's auto-attack is ready. /// </summary> /// <returns><c>true</c> if this instance can attack; otherwise, <c>false</c>.</returns> public static bool CanAttack() { if (Player.ChampionName == "Graves") { var attackDelay = 1.0740296828d * 1000 * Player.AttackDelay - 716.2381256175d; if (Utils.GameTimeTickCount + Game.Ping / 2 + 25 >= LastAATick + attackDelay && Player.HasBuff("GravesBasicAttackAmmo1")) { return true; } return false; } if (Player.ChampionName == "Jhin") { if (Player.HasBuff("JhinPassiveReload")) { return false; } } if (Player.IsCastingInterruptableSpell()) { return false; } return Utils.GameTimeTickCount + Game.Ping / 2 + 25 >= LastAATick + Player.AttackDelay * 1000; } /// <summary> /// Returns true if moving won't cancel the auto-attack. /// </summary> /// <param name="extraWindup">The extra windup.</param> /// <returns><c>true</c> if this instance can move the specified extra windup; otherwise, <c>false</c>.</returns> public static bool CanMove(float extraWindup, bool disableMissileCheck = false) { if (_missileLaunched && Orbwalker.MissileCheck && !disableMissileCheck) { return true; } var localExtraWindup = 0; if (_championName == "Rengar" && (Player.HasBuff("rengarqbase") || Player.HasBuff("rengarqemp"))) { localExtraWindup = 200; } return NoCancelChamps.Contains(_championName) || (Utils.GameTimeTickCount + Game.Ping / 2 >= LastAATick + Player.AttackCastDelay * 1000 + extraWindup + localExtraWindup); } /// <summary> /// Sets the movement delay. /// </summary> /// <param name="delay">The delay.</param> public static void SetMovementDelay(int delay) { _delay = delay; } /// <summary> /// Sets the minimum orbwalk distance. /// </summary> /// <param name="d">The d.</param> public static void SetMinimumOrbwalkDistance(float d) { _minDistance = d; } /// <summary> /// Gets the last move time. /// </summary> /// <returns>System.Single.</returns> public static float GetLastMoveTime() { return LastMoveCommandT; } /// <summary> /// Gets the last move position. /// </summary> /// <returns>Vector3.</returns> public static Vector3 GetLastMovePosition() { return LastMoveCommandPosition; } /// <summary> /// Moves to the position. /// </summary> /// <param name="position">The position.</param> /// <param name="holdAreaRadius">The hold area radius.</param> /// <param name="overrideTimer">if set to <c>true</c> [override timer].</param> /// <param name="useFixedDistance">if set to <c>true</c> [use fixed distance].</param> /// <param name="randomizeMinDistance">if set to <c>true</c> [randomize minimum distance].</param> public static void MoveTo(Vector3 position, float holdAreaRadius = 0, bool overrideTimer = false, bool useFixedDistance = true, bool randomizeMinDistance = true) { var playerPosition = Player.ServerPosition; if (playerPosition.Distance(position, true) < (holdAreaRadius * holdAreaRadius)) { /* if (Player.Path.Length > 0) { Player.IssueOrder(GameObjectOrder.Stop, playerPosition); LastMoveCommandPosition = playerPosition; LastMoveCommandT = Utils.GameTimeTickCount - 70; } */ return; } var point = position; if (Player.Distance(point, true) < 150 * 150) { point = playerPosition.Extend( position, randomizeMinDistance ? (_random.NextFloat(0.6f, 1) + 0.2f) * _minDistance : _minDistance); } var angle = 0f; var currentPath = Player.GetWaypoints(); if (currentPath.Count > 1 && currentPath.PathLength() > 100) { var movePath = Player.GetPath(point); if (movePath.Length > 1) { var v1 = currentPath[1] - currentPath[0]; var v2 = movePath[1] - movePath[0]; angle = v1.AngleBetween(v2.To2D()); var distance = movePath.Last().To2D().Distance(currentPath.Last(), true); if ((angle < 10 && distance < 500 * 500) || distance < 50 * 50) { return; } } } if (Utils.GameTimeTickCount - LastMoveCommandT < 70 + Math.Min(60, Game.Ping) && !overrideTimer && angle < 60) { return; } if (angle >= 60 && Utils.GameTimeTickCount - LastMoveCommandT < 60) { return; } Player.IssueOrder(GameObjectOrder.MoveTo, point); LastMoveCommandPosition = point; LastMoveCommandT = Utils.GameTimeTickCount; } /// <summary> /// Orbwalks a target while moving to Position. /// </summary> /// <param name="target">The target.</param> /// <param name="position">The position.</param> /// <param name="extraWindup">The extra windup.</param> /// <param name="holdAreaRadius">The hold area radius.</param> /// <param name="useFixedDistance">if set to <c>true</c> [use fixed distance].</param> /// <param name="randomizeMinDistance">if set to <c>true</c> [randomize minimum distance].</param> public static void Orbwalk(AttackableUnit target, Vector3 position, float extraWindup = 90, float holdAreaRadius = 0, bool useFixedDistance = true, bool randomizeMinDistance = true) { if (Utils.GameTimeTickCount - LastAttackCommandT < 70 + Math.Min(60, Game.Ping)) { return; } try { if (target.IsValidTarget() && CanAttack() && Attack) { DisableNextAttack = false; FireBeforeAttack(target); if (!DisableNextAttack) { if (!NoCancelChamps.Contains(_championName)) { _missileLaunched = false; } if (Player.IssueOrder(GameObjectOrder.AttackUnit, target)) { LastAttackCommandT = Utils.GameTimeTickCount; _lastTarget = target; } return; } } if (CanMove(extraWindup) && Move) { if (Orbwalker.LimitAttackSpeed && (Player.AttackDelay < 1 / 2.6f) && _autoattackCounter % 3 != 0 && !CanMove(500, true)) { return; } MoveTo(position, Math.Max(holdAreaRadius, 30), false, useFixedDistance, randomizeMinDistance); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } /// <summary> /// Resets the Auto-Attack timer. /// </summary> public static void ResetAutoAttackTimer() { LastAATick = 0; } /// <summary> /// Fired when the spellbook stops casting a spell. /// </summary> /// <param name="spellbook">The spellbook.</param> /// <param name="args">The <see cref="SpellbookStopCastEventArgs" /> instance containing the event data.</param> private static void SpellbookOnStopCast(Spellbook spellbook, SpellbookStopCastEventArgs args) { if (spellbook.Owner.IsValid && spellbook.Owner.IsMe && args.DestroyMissile && args.StopAnimation) { ResetAutoAttackTimer(); } } /// <summary> /// Fired when an auto attack is fired. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="GameObjectProcessSpellCastEventArgs" /> instance containing the event data.</param> private static void Obj_AI_Base_OnDoCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender.IsMe) { var ping = Game.Ping; if (ping <= 30) //First world problems kappa { Utility.DelayAction.Add(30 - ping, () => Obj_AI_Base_OnDoCast_Delayed(sender, args)); return; } Obj_AI_Base_OnDoCast_Delayed(sender, args); } } /// <summary> /// Fired 30ms after an auto attack is launched. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="GameObjectProcessSpellCastEventArgs" /> instance containing the event data.</param> private static void Obj_AI_Base_OnDoCast_Delayed(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (IsAutoAttackReset(args.SData.Name)) { ResetAutoAttackTimer(); } if (IsAutoAttack(args.SData.Name)) { FireAfterAttack(sender, args.Target as AttackableUnit); _missileLaunched = true; } } /// <summary> /// Handles the <see cref="E:ProcessSpell" /> event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="Spell">The <see cref="GameObjectProcessSpellCastEventArgs" /> instance containing the event data.</param> private static void OnProcessSpell(Obj_AI_Base unit, GameObjectProcessSpellCastEventArgs Spell) { try { var spellName = Spell.SData.Name; if (unit.IsMe && IsAutoAttackReset(spellName) && Spell.SData.SpellCastTime == 0) { ResetAutoAttackTimer(); } if (!IsAutoAttack(spellName)) { return; } if (unit.IsMe && (Spell.Target is Obj_AI_Base || Spell.Target is Obj_BarracksDampener || Spell.Target is Obj_HQ)) { LastAATick = Utils.GameTimeTickCount - Game.Ping / 2; _missileLaunched = false; LastMoveCommandT = 0; _autoattackCounter++; if (Spell.Target is Obj_AI_Base) { var target = (Obj_AI_Base)Spell.Target; if (target.IsValid) { FireOnTargetSwitch(target); _lastTarget = target; } } } FireOnAttack(unit, _lastTarget); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// The before attack event arguments. /// </summary> public class BeforeAttackEventArgs : EventArgs { /// <summary> /// <c>true</c> if the orbwalker should continue with the attack. /// </summary> private bool _process = true; /// <summary> /// The target /// </summary> public AttackableUnit Target; /// <summary> /// The unit /// </summary> public Obj_AI_Base Unit = ObjectManager.Player; /// <summary> /// Gets or sets a value indicating whether this <see cref="BeforeAttackEventArgs" /> should continue with the attack. /// </summary> /// <value><c>true</c> if the orbwalker should continue with the attack; otherwise, <c>false</c>.</value> public bool Process { get { return _process; } set { DisableNextAttack = !value; _process = value; } } } /// <summary> /// This class allows you to add an instance of "Orbwalker" to your assembly in order to control the orbwalking in an /// easy way. /// </summary> public class Orbwalker : IDisposable { /// <summary> /// The lane clear wait time modifier. /// </summary> private const float LaneClearWaitTimeMod = 2f; /// <summary> /// The configuration /// </summary> private static Menu _config; /// <summary> /// The instances of the orbwalker. /// </summary> public static List<Orbwalker> Instances = new List<Orbwalker>(); /// <summary> /// The player /// </summary> private readonly Obj_AI_Hero Player; /// <summary> /// The forced target /// </summary> private Obj_AI_Base _forcedTarget; /// <summary> /// The orbalker mode /// </summary> private OrbwalkingMode _mode = OrbwalkingMode.None; /// <summary> /// The orbwalking point /// </summary> private Vector3 _orbwalkingPoint; /// <summary> /// The previous minion the orbwalker was targeting. /// </summary> private Obj_AI_Minion _prevMinion; /// <summary> /// The name of the CustomMode if it is set. /// </summary> private string CustomModeName; /// <summary> /// Initializes a new instance of the <see cref="Orbwalker" /> class. /// </summary> /// <param name="attachToMenu">The menu the orbwalker should attach to.</param> public Orbwalker(Menu attachToMenu) { _config = attachToMenu; /* Drawings submenu */ var drawings = new Menu("Drawings", "drawings"); drawings.AddItem( new MenuItem("AACircle", "AACircle").SetShared() .SetValue(new Circle(true, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem( new MenuItem("AACircle2", "Enemy AA circle").SetShared() .SetValue(new Circle(false, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem( new MenuItem("HoldZone", "HoldZone").SetShared() .SetValue(new Circle(false, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem(new MenuItem("AALineWidth", "Line Width")).SetShared().SetValue(new Slider(2, 1, 6)); drawings.AddItem(new MenuItem("LastHitHelper", "Last Hit Helper").SetShared().SetValue(false)); _config.AddSubMenu(drawings); /* Misc options */ var misc = new Menu("Misc", "Misc"); misc.AddItem( new MenuItem("HoldPosRadius", "Hold Position Radius").SetShared().SetValue(new Slider(50, 50, 250))); misc.AddItem(new MenuItem("PriorizeFarm", "Priorize farm over harass").SetShared().SetValue(true)); misc.AddItem(new MenuItem("AttackWards", "Auto attack wards").SetShared().SetValue(false)); misc.AddItem(new MenuItem("AttackPetsnTraps", "Auto attack pets & traps").SetShared().SetValue(true)); misc.AddItem(new MenuItem("AttackGPBarrel", "Auto attack gangplank barrel").SetShared().SetValue(new StringList(new[] { "Combo and Farming", "Farming", "No" }, 1))); misc.AddItem(new MenuItem("Smallminionsprio", "Jungle clear small first").SetShared().SetValue(false)); misc.AddItem( new MenuItem("LimitAttackSpeed", "Don't kite if Attack Speed > 2.5").SetShared().SetValue(false)); misc.AddItem( new MenuItem("FocusMinionsOverTurrets", "Focus minions over objectives").SetShared() .SetValue(new KeyBind('M', KeyBindType.Toggle))); _config.AddSubMenu(misc); /* Missile check */ _config.AddItem(new MenuItem("MissileCheck", "Use Missile Check").SetShared().SetValue(true)); /* Delay sliders */ _config.AddItem( new MenuItem("ExtraWindup", "Extra windup time").SetShared().SetValue(new Slider(80, 0, 200))); _config.AddItem(new MenuItem("FarmDelay", "Farm delay").SetShared().SetValue(new Slider(0, 0, 200))); /*Load the menu*/ _config.AddItem( new MenuItem("LastHit", "Last hit").SetShared().SetValue(new KeyBind('X', KeyBindType.Press))); _config.AddItem(new MenuItem("Farm", "Mixed").SetShared().SetValue(new KeyBind('C', KeyBindType.Press))); _config.AddItem( new MenuItem("Freeze", "Freeze").SetShared().SetValue(new KeyBind('N', KeyBindType.Press))); _config.AddItem( new MenuItem("LaneClear", "LaneClear").SetShared().SetValue(new KeyBind('V', KeyBindType.Press))); _config.AddItem( new MenuItem("Orbwalk", "Combo").SetShared().SetValue(new KeyBind(32, KeyBindType.Press))); _config.AddItem( new MenuItem("StillCombo", "Combo without moving").SetShared() .SetValue(new KeyBind('N', KeyBindType.Press))); _config.Item("StillCombo").ValueChanged += (sender, args) => { Move = !args.GetNewValue<KeyBind>().Active; }; this.Player = ObjectManager.Player; Game.OnUpdate += this.GameOnOnGameUpdate; Drawing.OnDraw += this.DrawingOnOnDraw; Instances.Add(this); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Menu.Remove(_config); Game.OnUpdate -= this.GameOnOnGameUpdate; Drawing.OnDraw -= this.DrawingOnOnDraw; Instances.Remove(this); } /// <summary> /// Gets the farm delay. /// </summary> /// <value>The farm delay.</value> private int FarmDelay { get { return _config.Item("FarmDelay").GetValue<Slider>().Value; } } /// <summary> /// Gets a value indicating whether the orbwalker is orbwalking by checking the missiles. /// </summary> /// <value><c>true</c> if the orbwalker is orbwalking by checking the missiles; otherwise, <c>false</c>.</value> public static bool MissileCheck { get { return _config.Item("MissileCheck").GetValue<bool>(); } } public static bool LimitAttackSpeed { get { return _config.Item("LimitAttackSpeed").GetValue<bool>(); } } /// <summary> /// Gets or sets the active mode. /// </summary> /// <value>The active mode.</value> public OrbwalkingMode ActiveMode { get { if (_mode != OrbwalkingMode.None) { return _mode; } if (_config.Item("Orbwalk").GetValue<KeyBind>().Active) { return OrbwalkingMode.Combo; } if (_config.Item("StillCombo").GetValue<KeyBind>().Active) { return OrbwalkingMode.Combo; } if (_config.Item("LaneClear").GetValue<KeyBind>().Active) { return OrbwalkingMode.LaneClear; } if (_config.Item("Farm").GetValue<KeyBind>().Active) { return OrbwalkingMode.Mixed; } if (_config.Item("Freeze").GetValue<KeyBind>().Active) { return OrbwalkingMode.Freeze; } if (_config.Item("LastHit").GetValue<KeyBind>().Active) { return OrbwalkingMode.LastHit; } if (_config.Item(CustomModeName) != null && _config.Item(CustomModeName).GetValue<KeyBind>().Active) { return OrbwalkingMode.CustomMode; } return OrbwalkingMode.None; } set { _mode = value; } } /// <summary> /// Determines if a target is in auto attack range. /// </summary> /// <param name="target">The target.</param> /// <returns><c>true</c> if a target is in auto attack range, <c>false</c> otherwise.</returns> public virtual bool InAutoAttackRange(AttackableUnit target) { return Orbwalking.InAutoAttackRange(target); } /// <summary> /// Registers the Custom Mode of the Orbwalker. Useful for adding a flee mode and such. /// </summary> /// <param name="name">The name of the mode Ex. "Myassembly.FleeMode" </param> /// <param name="displayname">The name of the mode in the menu. Ex. Flee</param> /// <param name="key">The default key for this mode.</param> public virtual void RegisterCustomMode(string name, string displayname, uint key) { CustomModeName = name; if (_config.Item(name) == null) { _config.AddItem( new MenuItem(name, displayname).SetShared().SetValue(new KeyBind(key, KeyBindType.Press))); } } /// <summary> /// Enables or disables the auto-attacks. /// </summary> /// <param name="b">if set to <c>true</c> the orbwalker will attack units.</param> public void SetAttack(bool b) { Attack = b; } /// <summary> /// Enables or disables the movement. /// </summary> /// <param name="b">if set to <c>true</c> the orbwalker will move.</param> public void SetMovement(bool b) { Move = b; } /// <summary> /// Forces the orbwalker to attack the set target if valid and in range. /// </summary> /// <param name="target">The target.</param> public void ForceTarget(Obj_AI_Base target) { _forcedTarget = target; } /// <summary> /// Forces the orbwalker to move to that point while orbwalking (Game.CursorPos by default). /// </summary> /// <param name="point">The point.</param> public void SetOrbwalkingPoint(Vector3 point) { _orbwalkingPoint = point; } /// <summary> /// Determines if the orbwalker should wait before attacking a minion. /// </summary> /// <returns><c>true</c> if the orbwalker should wait before attacking a minion, <c>false</c> otherwise.</returns> public bool ShouldWait() { return ObjectManager.Get<Obj_AI_Minion>() .Any( minion => minion.IsValidTarget() && minion.Team != GameObjectTeam.Neutral && InAutoAttackRange(minion) && MinionManager.IsMinion(minion, false) && HealthPrediction.LaneClearHealthPrediction( minion, (int)(Player.AttackDelay * 1000 * LaneClearWaitTimeMod), FarmDelay) <= Player.GetAutoAttackDamage(minion)); } private bool ShouldWaitUnderTurret(Obj_AI_Minion noneKillableMinion) { return ObjectManager.Get<Obj_AI_Minion>() .Any( minion => (noneKillableMinion != null ? noneKillableMinion.NetworkId != minion.NetworkId : true) && minion.IsValidTarget() && minion.Team != GameObjectTeam.Neutral && InAutoAttackRange(minion) && MinionManager.IsMinion(minion, false) && HealthPrediction.LaneClearHealthPrediction( minion, (int) (Player.AttackDelay * 1000 + (Player.IsMelee ? Player.AttackCastDelay * 1000 : Player.AttackCastDelay * 1000 + 1000 * (Player.AttackRange + 2 * Player.BoundingRadius) / Player.BasicAttack.MissileSpeed)), FarmDelay) <= Player.GetAutoAttackDamage(minion)); } /// <summary> /// Gets the target. /// </summary> /// <returns>AttackableUnit.</returns> public virtual AttackableUnit GetTarget() { AttackableUnit result = null; var mode = ActiveMode; if ((mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LaneClear) && !_config.Item("PriorizeFarm").GetValue<bool>()) { var target = TargetSelector.GetTarget(-1, TargetSelector.DamageType.Physical); if (target != null && InAutoAttackRange(target)) { return target; } } //GankPlank barrels var attackGankPlankBarrels = _config.Item("AttackGPBarrel").GetValue<StringList>().SelectedIndex; if (attackGankPlankBarrels != 2 && (attackGankPlankBarrels == 0 || (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LastHit || mode == OrbwalkingMode.Freeze))) { var enemyGangPlank = HeroManager.Enemies.FirstOrDefault(e => e.ChampionName.Equals("gangplank", StringComparison.InvariantCultureIgnoreCase)); if (enemyGangPlank != null) { var barrels = ObjectManager.Get<Obj_AI_Minion>() .Where(minion => minion.Team == GameObjectTeam.Neutral && minion.CharData.BaseSkinName == "gangplankbarrel" && minion.IsHPBarRendered && minion.IsValidTarget() && InAutoAttackRange(minion)); foreach (var barrel in barrels) { if (barrel.Health <= 1f) { return barrel; } var t = (int)(Player.AttackCastDelay * 1000) + Game.Ping / 2 + 1000 * (int)Math.Max(0, Player.Distance(barrel) - Player.BoundingRadius) / (int)GetMyProjectileSpeed(); var barrelBuff = barrel.Buffs.FirstOrDefault( b => b.Name.Equals( "gangplankebarrelactive", StringComparison.InvariantCultureIgnoreCase)); if (barrelBuff != null && barrel.Health <= 2f) { var healthDecayRate = enemyGangPlank.Level >= 13 ? 0.5f : (enemyGangPlank.Level >= 7 ? 1f : 2f); var nextHealthDecayTime = Game.Time < barrelBuff.StartTime + healthDecayRate ? barrelBuff.StartTime + healthDecayRate : barrelBuff.StartTime + healthDecayRate * 2; if (nextHealthDecayTime <= Game.Time + t / 1000f) { return barrel; } } } if (barrels.Any()) { return null; } } } /*Killable Minion*/ if (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LastHit || mode == OrbwalkingMode.Freeze) { var MinionList = ObjectManager.Get<Obj_AI_Minion>() .Where(minion => minion.IsValidTarget() && InAutoAttackRange(minion)) .OrderByDescending(minion => minion.CharData.BaseSkinName.Contains("Siege")) .ThenBy(minion => minion.CharData.BaseSkinName.Contains("Super")) .ThenBy(minion => minion.Health) .ThenByDescending(minion => minion.MaxHealth); foreach (var minion in MinionList) { var t = (int)(Player.AttackCastDelay * 1000) - 100 + Game.Ping / 2 + 1000 * (int)Math.Max(0, Player.Distance(minion) - Player.BoundingRadius) / (int)GetMyProjectileSpeed(); if (mode == OrbwalkingMode.Freeze) { t += 200 + Game.Ping / 2; } var predHealth = HealthPrediction.GetHealthPrediction(minion, t, FarmDelay); if (minion.Team != GameObjectTeam.Neutral && ShouldAttackMinion(minion)) { var damage = Player.GetAutoAttackDamage(minion, true); var killable = predHealth <= damage; if (mode == OrbwalkingMode.Freeze) { if (minion.Health < 50 || predHealth <= 50) { return minion; } } else { if (predHealth <= 0) { FireOnNonKillableMinion(minion); } if (killable) { return minion; } } } } } //Forced target if (_forcedTarget.IsValidTarget() && InAutoAttackRange(_forcedTarget)) { return _forcedTarget; } /* turrets / inhibitors / nexus */ if (mode == OrbwalkingMode.LaneClear && (!_config.Item("FocusMinionsOverTurrets").GetValue<KeyBind>().Active || !MinionManager.GetMinions( ObjectManager.Player.Position, GetRealAutoAttackRange(ObjectManager.Player)).Any())) { /* turrets */ foreach (var turret in ObjectManager.Get<Obj_AI_Turret>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return turret; } /* inhibitor */ foreach (var turret in ObjectManager.Get<Obj_BarracksDampener>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return turret; } /* nexus */ foreach (var nexus in ObjectManager.Get<Obj_HQ>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return nexus; } } /*Champions*/ if (mode != OrbwalkingMode.LastHit) { if (mode != OrbwalkingMode.LaneClear || !ShouldWait()) { var target = TargetSelector.GetTarget(-1, TargetSelector.DamageType.Physical); if (target.IsValidTarget() && InAutoAttackRange(target)) { return target; } } } /*Jungle minions*/ if (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed) { var jminions = ObjectManager.Get<Obj_AI_Minion>() .Where( mob => mob.IsValidTarget() && mob.Team == GameObjectTeam.Neutral && InAutoAttackRange(mob) && mob.CharData.BaseSkinName != "gangplankbarrel" && mob.Name != "WardCorpse"); result = _config.Item("Smallminionsprio").GetValue<bool>() ? jminions.MinOrDefault(mob => mob.MaxHealth) : jminions.MaxOrDefault(mob => mob.MaxHealth); if (result != null) { return result; } } /* UnderTurret Farming */ if (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LastHit || mode == OrbwalkingMode.Freeze) { var closestTower = ObjectManager.Get<Obj_AI_Turret>() .MinOrDefault(t => t.IsAlly && !t.IsDead ? Player.Distance(t, true) : float.MaxValue); if (closestTower != null && Player.Distance(closestTower, true) < 1500 * 1500) { Obj_AI_Minion farmUnderTurretMinion = null; Obj_AI_Minion noneKillableMinion = null; // return all the minions underturret in auto attack range var minions = MinionManager.GetMinions(Player.Position, Player.AttackRange + 200) .Where( minion => InAutoAttackRange(minion) && closestTower.Distance(minion, true) < 900 * 900) .OrderByDescending(minion => minion.CharData.BaseSkinName.Contains("Siege")) .ThenBy(minion => minion.CharData.BaseSkinName.Contains("Super")) .ThenByDescending(minion => minion.MaxHealth) .ThenByDescending(minion => minion.Health); if (minions.Any()) { // get the turret aggro minion var turretMinion = minions.FirstOrDefault( minion => minion is Obj_AI_Minion && HealthPrediction.HasTurretAggro(minion as Obj_AI_Minion)); if (turretMinion != null) { var hpLeftBeforeDie = 0; var hpLeft = 0; var turretAttackCount = 0; var turretStarTick = HealthPrediction.TurretAggroStartTick( turretMinion as Obj_AI_Minion); // from healthprediction (don't blame me :S) var turretLandTick = turretStarTick + (int)(closestTower.AttackCastDelay * 1000) + 1000 * Math.Max( 0, (int) (turretMinion.Distance(closestTower) - closestTower.BoundingRadius)) / (int)(closestTower.BasicAttack.MissileSpeed + 70); // calculate the HP before try to balance it for (float i = turretLandTick + 50; i < turretLandTick + 10 * closestTower.AttackDelay * 1000 + 50; i = i + closestTower.AttackDelay * 1000) { var time = (int)i - Utils.GameTimeTickCount + Game.Ping / 2; var predHP = (int) HealthPrediction.LaneClearHealthPrediction( turretMinion, time > 0 ? time : 0); if (predHP > 0) { hpLeft = predHP; turretAttackCount += 1; continue; } hpLeftBeforeDie = hpLeft; hpLeft = 0; break; } // calculate the hits is needed and possibilty to balance if (hpLeft == 0 && turretAttackCount != 0 && hpLeftBeforeDie != 0) { var damage = (int)Player.GetAutoAttackDamage(turretMinion, true); var hits = hpLeftBeforeDie / damage; var timeBeforeDie = turretLandTick + (turretAttackCount + 1) * (int)(closestTower.AttackDelay * 1000) - Utils.GameTimeTickCount; var timeUntilAttackReady = LastAATick + (int)(Player.AttackDelay * 1000) > Utils.GameTimeTickCount + Game.Ping / 2 + 25 ? LastAATick + (int)(Player.AttackDelay * 1000) - (Utils.GameTimeTickCount + Game.Ping / 2 + 25) : 0; var timeToLandAttack = Player.IsMelee ? Player.AttackCastDelay * 1000 : Player.AttackCastDelay * 1000 + 1000 * Math.Max(0, turretMinion.Distance(Player) - Player.BoundingRadius) / Player.BasicAttack.MissileSpeed; if (hits >= 1 && hits * Player.AttackDelay * 1000 + timeUntilAttackReady + timeToLandAttack < timeBeforeDie) { farmUnderTurretMinion = turretMinion as Obj_AI_Minion; } else if (hits >= 1 && hits * Player.AttackDelay * 1000 + timeUntilAttackReady + timeToLandAttack > timeBeforeDie) { noneKillableMinion = turretMinion as Obj_AI_Minion; } } else if (hpLeft == 0 && turretAttackCount == 0 && hpLeftBeforeDie == 0) { noneKillableMinion = turretMinion as Obj_AI_Minion; } // should wait before attacking a minion. if (ShouldWaitUnderTurret(noneKillableMinion)) { return null; } if (farmUnderTurretMinion != null) { return farmUnderTurretMinion; } // balance other minions foreach (var minion in minions.Where( x => x.NetworkId != turretMinion.NetworkId && x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion))) { var playerDamage = (int)Player.GetAutoAttackDamage(minion); var turretDamage = (int)closestTower.GetAutoAttackDamage(minion, true); var leftHP = (int)minion.Health % turretDamage; if (leftHP > playerDamage) { return minion; } } // late game var lastminion = minions.LastOrDefault(x => x.NetworkId != turretMinion.NetworkId && x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion)); if (lastminion != null && minions.Count() >= 2) { if (1f / Player.AttackDelay >= 1f && (int)(turretAttackCount * closestTower.AttackDelay / Player.AttackDelay) * Player.GetAutoAttackDamage(lastminion) > lastminion.Health) { return lastminion; } if (minions.Count() >= 5 && 1f / Player.AttackDelay >= 1.2) { return lastminion; } } } else { if (ShouldWaitUnderTurret(noneKillableMinion)) { return null; } // balance other minions foreach (var minion in minions.Where( x => x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion)) ) { if (closestTower != null) { var playerDamage = (int)Player.GetAutoAttackDamage(minion); var turretDamage = (int)closestTower.GetAutoAttackDamage(minion, true); var leftHP = (int)minion.Health % turretDamage; if (leftHP > playerDamage) { return minion; } } } //late game var lastminion = minions .LastOrDefault(x => x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion)); if (lastminion != null && minions.Count() >= 2) { if (minions.Count() >= 5 && 1f / Player.AttackDelay >= 1.2) { return lastminion; } } } return null; } } } /*Lane Clear minions*/ if (mode == OrbwalkingMode.LaneClear) { if (!ShouldWait()) { if (_prevMinion.IsValidTarget() && InAutoAttackRange(_prevMinion)) { var predHealth = HealthPrediction.LaneClearHealthPrediction( _prevMinion, (int)(Player.AttackDelay * 1000 * LaneClearWaitTimeMod), FarmDelay); if (predHealth >= 2 * Player.GetAutoAttackDamage(_prevMinion) || Math.Abs(predHealth - _prevMinion.Health) < float.Epsilon) { return _prevMinion; } } result = (from minion in ObjectManager.Get<Obj_AI_Minion>() .Where( minion => minion.IsValidTarget() && InAutoAttackRange(minion) && ShouldAttackMinion(minion)) let predHealth = HealthPrediction.LaneClearHealthPrediction( minion, (int)(Player.AttackDelay * 1000 * LaneClearWaitTimeMod), FarmDelay) where predHealth >= 2 * Player.GetAutoAttackDamage(minion) || Math.Abs(predHealth - minion.Health) < float.Epsilon select minion).MaxOrDefault( m => !MinionManager.IsMinion(m, true) ? float.MaxValue : m.Health); if (result != null) { _prevMinion = (Obj_AI_Minion)result; } } } return result; } /// <summary> /// Returns if a minion should be attacked /// </summary> /// <param name="minion">The <see cref="Obj_AI_Minion" /></param> /// <param name="includeBarrel">Include Gangplank Barrel</param> /// <returns><c>true</c> if the minion should be attacked; otherwise, <c>false</c>.</returns> private bool ShouldAttackMinion(Obj_AI_Minion minion) { if (minion.Name == "WardCorpse" || minion.CharData.BaseSkinName == "jarvanivstandard") { return false; } if (MinionManager.IsWard(minion)) { return _config.Item("AttackWards").IsActive(); } return (_config.Item("AttackPetsnTraps").GetValue<bool>() || MinionManager.IsMinion(minion)) && minion.CharData.BaseSkinName != "gangplankbarrel"; } /// <summary> /// Fired when the game is updated. /// </summary> /// <param name="args">The <see cref="EventArgs" /> instance containing the event data.</param> private void GameOnOnGameUpdate(EventArgs args) { try { if (ActiveMode == OrbwalkingMode.None) { return; } //Prevent canceling important spells if (Player.IsCastingInterruptableSpell(true)) { return; } var target = GetTarget(); Orbwalk( target, _orbwalkingPoint.To2D().IsValid() ? _orbwalkingPoint : Game.CursorPos, _config.Item("ExtraWindup").GetValue<Slider>().Value, Math.Max(_config.Item("HoldPosRadius").GetValue<Slider>().Value, 30)); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// Fired when the game is drawn. /// </summary> /// <param name="args">The <see cref="EventArgs" /> instance containing the event data.</param> private void DrawingOnOnDraw(EventArgs args) { if (_config.Item("AACircle").GetValue<Circle>().Active) { Render.Circle.DrawCircle( Player.Position, GetRealAutoAttackRange(null) + 65, _config.Item("AACircle").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value); } if (_config.Item("AACircle2").GetValue<Circle>().Active) { foreach (var target in HeroManager.Enemies.FindAll(target => target.IsValidTarget(1175))) { Render.Circle.DrawCircle( target.Position, GetAttackRange(target), _config.Item("AACircle2").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value); } } if (_config.Item("HoldZone").GetValue<Circle>().Active) { Render.Circle.DrawCircle( Player.Position, _config.Item("HoldPosRadius").GetValue<Slider>().Value, _config.Item("HoldZone").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value, true); } _config.Item("FocusMinionsOverTurrets") .Permashow(_config.Item("FocusMinionsOverTurrets").GetValue<KeyBind>().Active); if (_config.Item("LastHitHelper").GetValue<bool>()) { foreach (var minion in ObjectManager.Get<Obj_AI_Minion>() .Where( x => x.Name.ToLower().Contains("minion") && x.IsHPBarRendered && x.IsValidTarget(1000))) { if (minion.Health < ObjectManager.Player.GetAutoAttackDamage(minion, true)) { Render.Circle.DrawCircle(minion.Position, 50, Color.LimeGreen); } } } } } } }
SephLeague/LeagueSharp
YasuoPro/Orbwalking.cs
C#
gpl-3.0
70,413
function failure () { } function create_msg(){ //alert(document.getElementById('intraweb').value); if (document.getElementById('intraweb').value == '') { jQuery('#intraweb').focus(); } } function enableTopicListSort(){ if (jQuery( "#EnDisSort" ).hasClass( "disabled" )) { jQuery('.handle').removeClass('hide'); jQuery('#EnDisSort').removeClass('disabled'); jQuery('#divEDSort').attr('data-original-title',Zikula.__('Disable topics list reorder','module_iwforums_js')); } else { jQuery('.handle').addClass('hide'); jQuery('#EnDisSort').addClass('disabled'); jQuery('#divEDSort').attr('data-original-title',Zikula.__('Enable topics list reorder','module_iwforums_js')); } } // Delete selected topic and its messages function deleteTopic(){ var fid = jQuery('#fid').val(); var ftid = jQuery('#ftid').val(); var p = { fid : fid, ftid: ftid, deleteTopic: true } if (typeof(fid) != 'undefined') new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=reorderTopics", { parameters: p, onComplete: deleteTopic_reponse, onFailure: failure }); } function deleteTopic_reponse(req) { if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('topicsList').update(b.content); } function reorderTopics(fid, ftid){ var tList = jQuery("#topicsTableBody").sortable("serialize"); var p = { fid : fid, ftid : ftid, ordre : tList } new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=reorderTopics", { parameters: p, onComplete: reorderTopics_reponse, onFailure: failure }); } function reorderTopics_reponse(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('topicsList').update(b.content); jQuery('#divEDSort').attr('title',Zikula.__('Disable topics list reorder','module_iwforums_js')); enableTopicListSort(); } /* * Deleta message attached file * @returns {} */ function delAttachment(){ var p = { fid : document.new_msg["fid"].value, fmid : document.new_msg["fmid"].value } new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=delAttachment", { parameters: p, onComplete: delAttachment_reponse, onFailure: failure }); } function delAttachment_reponse(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('attachment').update(b.content); // Reload filestyle jQuery(":file").filestyle({ buttonText : b.btnMsg , buttonBefore: true, iconName : "glyphicon-paperclip" }); jQuery(":file").filestyle('clear'); } /* * Apply introduction forum changes * @returns {} */ function updateForumIntro(){ var fid = document.feditform["fid"].value; var nom_forum = document.feditform["titol"].value; var descriu = document.feditform["descriu"].value; var longDescriu = document.feditform["lDesc"].value; var observacions = document.feditform["observacions"].value; var topicsPage = document.feditform["topicsPage"].value; /*if (typeof tinyMCE != "undefined") { tinyMCE.execCommand('mceRemoveEditor', true, 'lDesc'); } */ //Scribite.destroyEditor('lDesc'); var p = { fid : fid, nom_forum : nom_forum, descriu : descriu, longDescriu : longDescriu, topicsPage : topicsPage, observacions: observacions }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=setForum", { parameters: p, onComplete: updateForumIntro_reponse, onFailure: failure }); } function updateForumIntro_reponse(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('forumDescription').update(b.content); jQuery("#btnNewTopic").toggle(); if (b.moduleSc){ if (b.moduleSc == 'new') Scribite.createEditors(); if (b.moduleSc == 'old') document.location.reload(true); } /*if (typeof tinyMCE != "undefined") { tinyMCE.execCommand('mceAddEditor', true, 'lDesc'); } */ } // Get selected image icon in edit, create and reply message forms function selectedIcon(){ var file= jQuery("#iconset input[type='radio']:checked").val(); if (file != "") { var src = document.getElementById(file).src; jQuery('#currentIcon').attr("src", src); jQuery('#currentIcon').show(); } else { jQuery('#currentIcon').hide(); } } function checkName(){ if (jQuery('#titol').val().length < 1) { jQuery('#btnSend').hide(); jQuery('#inputName').addClass('has-error'); } else { jQuery('#btnSend').show(); jQuery('#inputName').removeClass('has-error'); jQuery('#titol').focus(); } } // Show/hide forum information edition form function showEditForumForm(){ jQuery("#forumIntroduction").toggle(); jQuery("#forumEdition").toggle(); jQuery("#btnNewTopic").toggle(); } function getTopic(fid, ftid){ var p = { fid : fid, ftid: ftid }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=getTopic", { parameters: p, onComplete: getTopic_response, onFailure: failure }); } function getTopic_response(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('row_'+b.id).update(b.content); } function editTopic(fid, ftid){ var p = { fid : fid, ftid: ftid }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=editTopic", { parameters: p, onComplete: editTopic_response, onFailure: failure }); } function editTopic_response(req) { if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('row_'+b.id).update(b.content); } // Save topic with new values function setTopic(){ var fid = document.feditTopic["fid"].value; var ftid = document.feditTopic["ftid"].value; var titol = document.feditTopic["titol"].value; var descriu = document.feditTopic["descriu"].value; var p = { fid : fid, ftid: ftid, titol: titol, descriu: descriu }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=setTopic", { parameters: p, onComplete: setTopic_response, onFailure: failure }); } function setTopic_response(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('row_'+b.id).update(b.content); // Show or hide sortable list if (jQuery( "#EnDisSort" ).hasClass( "disabled" )) { jQuery('.handle').addClass('hide'); } else { jQuery('.handle').removeClass('hide'); } } function chgUsers(a){ show_info(); var b={ gid:a }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=chgUsers",{ parameters: b, onComplete: chgUsers_response, onFailure: chgUsers_failure }); } function chgUsers_failure(){ show_info(); $("uid").update(''); } function chgUsers_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); show_info(); $("uid").update(b.content); } function show_info() { var info = ''; if(!Element.hasClassName(info, 'z-hide')) { $("chgInfo").update('&nbsp;'); Element.addClassName("chgInfo", 'z-hide'); } else { $("chgInfo").update('<img src="'+Zikula.Config.baseURL+'images/ajax/circle-ball-dark-antialiased.gif">'); Element.removeClassName("chgInfo", 'z-hide'); } } function modifyField(a,aa){ showfieldinfo(a, modifyingfield); var b={ fid:a, character:aa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=modifyForum",{ parameters: b, onComplete: modifyField_response, onFailure: failure }); } function modifyField_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); changeContent(b.fid); } function showfieldinfo(fndid, infotext){ if(fndid) { if(!Element.hasClassName('foruminfo_' + fndid, 'z-hide')) { $('foruminfo_' + fndid).update('&nbsp;'); Element.addClassName('foruminfo_' + fndid, 'z-hide'); } else { $('foruminfo_' + fndid).update(infotext); Element.removeClassName('foruminfo_' + fndid, 'z-hide'); } } } function changeContent(a){ var b={ fid:a }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=changeContent",{ parameters: b, onComplete: changeContent_response, onFailure: failure }); } function changeContent_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('forumChars_' + b.fid).update(b.content); } // Check or uncheck forum message function of_mark(fid,msgId){ var b={ fid:fid, fmid:msgId }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=mark",{ parameters: b, onComplete: of_mark_response, onFailure: failure }); } function of_mark_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); var icon = '<span data-toggle="tooltip" class="glyphicon glyphicon-flag" title="'+b.ofMarkText+'"></span>'; if(b.m == 1){ Element.removeClassName(b.fmid, 'disabled'); //Element.writeAttribute(b.fmid,'title',b.ofMarkText); }else{ Element.addClassName(b.fmid, 'disabled'); //Element.writeAttribute(b.fmid,'title',b.ofMarkText); } $(b.fmid).update(icon); if (b.reloadFlags) { reloadFlaggedBlock(); } } function mark(a,aa){ var b={ fid:a, fmid:aa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=mark",{ parameters: b, onComplete: mark_response, onFailure: failure }); } function mark_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); if(b.m == 1){ $(b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/marcat.gif"; $("msgMark" + b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/marcat.gif"; $('msgMark' + b.fmid).update(b.fmid); }else{ $(b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/res.gif"; $("msgMark" + b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/res.gif"; $('msgMark' + b.fmid).update(b.fmid); } if (b.reloadFlags) { reloadFlaggedBlock(); } } function deleteGroup(a,aa){ var response = confirm(deleteConfirmation); if(response){ $('groupId_' + a + '_' + aa).update('<img src="'+Zikula.Config.baseURL+'images/ajax/circle-ball-dark-antialiased.gif">'); var b={ gid:a, fid:aa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=deleteGroup",{ parameters: b, onComplete: deleteGroup_response, onFailure: failure }); } } function deleteGroup_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('groupId_' + b.gid + '_' + b.fid).toggle() } function deleteModerator(a,aa){ var response = confirm(deleteModConfirmation); if(response){ var b={ fid:a, id:aa }; $('mod_' + a + '_' + aa).update('<img src="'+Zikula.Config.baseURL+'images/ajax/circle-ball-dark-antialiased.gif">'); var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=deleteModerator",{ parameters: b, onComplete: deleteModerador_response, onFailure: failure }); } } function deleteModerador_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('mod_' + b.fid + '_' +b.id).toggle() } function openMsg(a,aa,aaa,aaaa,aaaaa,aaaaaa){ $('openMsgIcon_' + a).src=Zikula.Config.baseURL+"images/ajax/circle-ball-dark-antialiased.gif"; var b={ fmid:a, fid:aa, ftid:aaa, u:aaaa, oid:aaaaa, inici:aaaaaa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=openMsg",{ parameters: b, onComplete: openMsg_response, onFailure: failure }); } function openMsg_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('openMsgRow_' + b.fmid).update(b.content); $('openMsgIcon_' + b.fmid).toggle(); $('msgImage_' + b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/msg.gif"; } function closeMsg(fmid){ $('openMsgRow_' + fmid).update(''); $('openMsgIcon_' + fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/msgopen.gif"; $('openMsgIcon_' + fmid).toggle(); }
projectestac/intraweb
intranet/modules/IWforums/javascript/IWforums.js
JavaScript
gpl-3.0
14,075
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.12.18 at 12:06:30 PM EST // package com.devtechnology.api.jaxb; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for dataType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="dataType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="location" type="{}locationType" maxOccurs="unbounded"/> * &lt;element name="moreWeatherInformation" type="{}moreWeatherInformationType" maxOccurs="unbounded"/> * &lt;element name="time-layout" type="{}time-layoutElementType" maxOccurs="unbounded"/> * &lt;element name="parameters" type="{}parametersType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;attribute name="type"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="forecast"/> * &lt;enumeration value="current observations"/> * &lt;enumeration value="analysis"/> * &lt;enumeration value="guidance"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "dataType", propOrder = { "location", "moreWeatherInformation", "timeLayout", "parameters" }) public class DataType { @XmlElement(required = true) protected List<LocationType> location; @XmlElement(required = true) protected List<MoreWeatherInformationType> moreWeatherInformation; @XmlElement(name = "time-layout", required = true) protected List<TimeLayoutElementType> timeLayout; @XmlElement(required = true) protected List<ParametersType> parameters; @XmlAttribute(name = "type") protected String type; /** * Gets the value of the location property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the location property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLocation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link LocationType } * * */ public List<LocationType> getLocation() { if (location == null) { location = new ArrayList<LocationType>(); } return this.location; } /** * Gets the value of the moreWeatherInformation property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the moreWeatherInformation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMoreWeatherInformation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MoreWeatherInformationType } * * */ public List<MoreWeatherInformationType> getMoreWeatherInformation() { if (moreWeatherInformation == null) { moreWeatherInformation = new ArrayList<MoreWeatherInformationType>(); } return this.moreWeatherInformation; } /** * Gets the value of the timeLayout property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the timeLayout property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTimeLayout().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TimeLayoutElementType } * * */ public List<TimeLayoutElementType> getTimeLayout() { if (timeLayout == null) { timeLayout = new ArrayList<TimeLayoutElementType>(); } return this.timeLayout; } /** * Gets the value of the parameters property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the parameters property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParameters().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ParametersType } * * */ public List<ParametersType> getParameters() { if (parameters == null) { parameters = new ArrayList<ParametersType>(); } return this.parameters; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } }
DevTechnology/DTGEPA
epa-api-webapp/src/main/java/com/devtechnology/api/jaxb/DataType.java
Java
gpl-3.0
6,435
package com.dotcms.content.elasticsearch.business; import java.io.File; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import com.dotcms.repackage.elasticsearch.org.elasticsearch.ElasticSearchException; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.admin.indices.status.IndexStatus; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.bulk.BulkRequestBuilder; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.index.IndexRequest; import com.dotcms.repackage.elasticsearch.org.elasticsearch.client.Client; import com.dotcms.repackage.elasticsearch.org.elasticsearch.client.IndicesAdminClient; import com.dotcms.repackage.elasticsearch.org.elasticsearch.index.query.QueryBuilders; import com.dotcms.content.business.DotMappingException; import com.dotcms.content.elasticsearch.business.IndiciesAPI.IndiciesInfo; import com.dotcms.content.elasticsearch.util.ESClient; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.DotStateException; import com.dotmarketing.cache.StructureCache; import com.dotmarketing.common.db.DotConnect; import com.dotmarketing.db.DbConnectionFactory; import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotHibernateException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.structure.factories.RelationshipFactory; import com.dotmarketing.portlets.structure.model.Relationship; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.dotcms.repackage.tika_app_1_3.com.google.gson.Gson; public class ESContentletIndexAPI implements ContentletIndexAPI{ private static final ESIndexAPI iapi = new ESIndexAPI(); private static final ESMappingAPIImpl mappingAPI = new ESMappingAPIImpl(); public static final SimpleDateFormat timestampFormatter=new SimpleDateFormat("yyyyMMddHHmmss"); public synchronized void getRidOfOldIndex() throws DotDataException { IndiciesInfo idxs=APILocator.getIndiciesAPI().loadIndicies(); if(idxs.working!=null) delete(idxs.working); if(idxs.live!=null) delete(idxs.live); if(idxs.reindex_working!=null) delete(idxs.reindex_working); if(idxs.reindex_live!=null) delete(idxs.reindex_live); } /** * Tells if at least we have a "working_XXXXXX" index * @return * @throws DotDataException */ private synchronized boolean indexReady() throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); return info.working!=null && info.live!=null; } /** * Inits the indexs */ public synchronized void checkAndInitialiazeIndex() { new ESClient().getClient(); // this will call initNode try { // if we don't have a working index, create it if (!indexReady()) initIndex(); } catch (Exception e) { Logger.fatal("ESUil.checkAndInitialiazeIndex", e.getMessage()); } } public synchronized boolean createContentIndex(String indexName) throws ElasticSearchException, IOException { return createContentIndex(indexName, 0); } @Override public synchronized boolean createContentIndex(String indexName, int shards) throws ElasticSearchException, IOException { CreateIndexResponse cir = iapi.createIndex(indexName, null, shards); int i = 0; while(!cir.isAcknowledged()){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(i++ > 300){ throw new ElasticSearchException("index timed out creating"); } } ClassLoader classLoader = null; URL url = null; classLoader = Thread.currentThread().getContextClassLoader(); url = classLoader.getResource("es-content-mapping.json"); // create actual index String mapping = new String(com.liferay.util.FileUtil.getBytes(new File(url.getPath()))); mappingAPI.putMapping(indexName, "content", mapping); return true; } /** * Creates new indexes /working_TIMESTAMP (aliases working_read, working_write and workinglive) * and /live_TIMESTAMP with (aliases live_read, live_write, workinglive) * * @return the timestamp string used as suffix for indices * @throws ElasticSearchException if Murphy comes arround * @throws DotDataException */ private synchronized String initIndex() throws ElasticSearchException, DotDataException { if(indexReady()) return ""; try { final String timeStamp=timestampFormatter.format(new Date()); final String workingIndex=ES_WORKING_INDEX_NAME+"_"+timeStamp; final String liveIndex=ES_LIVE_INDEX_NAME+ "_" + timeStamp; final IndicesAdminClient iac = new ESClient().getClient().admin().indices(); createContentIndex(workingIndex,0); createContentIndex(liveIndex,0); IndiciesInfo info=new IndiciesInfo(); info.working=workingIndex; info.live=liveIndex; APILocator.getIndiciesAPI().point(info); return timeStamp; } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } /** * creates new working and live indexes with reading aliases pointing to old index * and write aliases pointing to both old and new indexes * @return the timestamp string used as suffix for indices * @throws DotDataException * @throws ElasticSearchException */ public synchronized String setUpFullReindex() throws ElasticSearchException, DotDataException { if(indexReady()) { try { final String timeStamp=timestampFormatter.format(new Date()); // index names for new index final String workingIndex=ES_WORKING_INDEX_NAME + "_" + timeStamp; final String liveIndex=ES_LIVE_INDEX_NAME + "_" + timeStamp; final IndicesAdminClient iac = new ESClient().getClient().admin().indices(); createContentIndex(workingIndex); createContentIndex(liveIndex); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; newinfo.reindex_working=workingIndex; newinfo.reindex_live=liveIndex; APILocator.getIndiciesAPI().point(newinfo); iapi.moveIndexToLocalNode(workingIndex); iapi.moveIndexToLocalNode(liveIndex); return timeStamp; } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } else return initIndex(); } public boolean isInFullReindex() throws DotDataException { return isInFullReindex(DbConnectionFactory.getConnection()); } public boolean isInFullReindex(Connection conn) throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(conn); return info.reindex_working!=null && info.reindex_live!=null; } public synchronized void fullReindexSwitchover() { fullReindexSwitchover(DbConnectionFactory.getConnection()); } /** * This will drop old index and will point read aliases to new index. * This method should be called after call to {@link #setUpFullReindex()} * @return */ public synchronized void fullReindexSwitchover(Connection conn) { try { if(!isInFullReindex()) return; IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(conn); Logger.info(this, "Executing switchover from old index [" +info.working+","+info.live+"] and new index [" +info.reindex_working+","+info.reindex_live+"]"); final String oldw=info.working; final String oldl=info.live; IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.reindex_working; newinfo.live=info.reindex_live; APILocator.getIndiciesAPI().point(conn,newinfo); iapi.moveIndexBackToCluster(newinfo.working); iapi.moveIndexBackToCluster(newinfo.live); ArrayList<String> list=new ArrayList<String>(); list.add(newinfo.working); list.add(newinfo.live); optimize(list); } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } public boolean delete(String indexName) { return iapi.delete(indexName); } public boolean optimize(List<String> indexNames) { return iapi.optimize(indexNames); } public void addContentToIndex(final Contentlet content) throws DotHibernateException { addContentToIndex(content, true); } public void addContentToIndex(final Contentlet content, final boolean deps) throws DotHibernateException { addContentToIndex(content,deps,false); } public void addContentToIndex(final Contentlet content, final boolean deps, boolean indexBeforeCommit) throws DotHibernateException { addContentToIndex(content,deps,indexBeforeCommit,false); } public void addContentToIndex(final Contentlet content, final boolean deps, boolean indexBeforeCommit, final boolean reindexOnly) throws DotHibernateException { addContentToIndex(content,deps,indexBeforeCommit,reindexOnly,null); } public void addContentToIndex(final Contentlet content, final boolean deps, boolean indexBeforeCommit, final boolean reindexOnly, final BulkRequestBuilder bulk) throws DotHibernateException { if(content==null || !UtilMethods.isSet(content.getIdentifier())) return; Runnable indexAction=new Runnable() { public void run() { try { Client client=new ESClient().getClient(); BulkRequestBuilder req = (bulk==null) ? client.prepareBulk() : bulk; // http://jira.dotmarketing.net/browse/DOTCMS-6886 // check for related content to reindex List<Contentlet> contentToIndex=new ArrayList<Contentlet>(); contentToIndex.add(content); if(deps) contentToIndex.addAll(loadDeps(content)); indexContentletList(req, contentToIndex,reindexOnly); if(bulk==null && req.numberOfActions()>0) req.execute().actionGet(); } catch (Exception e) { Logger.error(ESContentFactoryImpl.class, e.getMessage(), e); } } }; if(bulk!=null || indexBeforeCommit) { indexAction.run(); } else { // add a commit listener to index the contentlet if the entire // transaction finish clean HibernateUtil.addCommitListener(content.getInode(),indexAction); } } private void indexContentletList(BulkRequestBuilder req, List<Contentlet> contentToIndex, boolean reindexOnly) throws DotStateException, DotDataException, DotSecurityException, DotMappingException { for(Contentlet con : contentToIndex) { String id=con.getIdentifier()+"_"+con.getLanguageId(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); Gson gson=new Gson(); String mapping=null; if(con.isWorking()) { mapping=gson.toJson(mappingAPI.toMap(con)); if(!reindexOnly) req.add(new IndexRequest(info.working, "content", id) .source(mapping)); if(info.reindex_working!=null) req.add(new IndexRequest(info.reindex_working, "content", id) .source(mapping)); } if(con.isLive()) { if(mapping==null) mapping=gson.toJson(mappingAPI.toMap(con)); if(!reindexOnly) req.add(new IndexRequest(info.live, "content", id) .source(mapping)); if(info.reindex_live!=null) req.add(new IndexRequest(info.reindex_live, "content", id) .source(mapping)); } } } @SuppressWarnings("unchecked") private List<Contentlet> loadDeps(Contentlet content) throws DotDataException, DotSecurityException { List<Contentlet> contentToIndex=new ArrayList<Contentlet>(); List<String> depsIdentifiers=mappingAPI.dependenciesLeftToReindex(content); for(String ident : depsIdentifiers) { // get working and live version for all languages based on the identifier // String sql = "select distinct inode from contentlet join contentlet_version_info " + // " on (inode=live_inode or inode=working_inode) and contentlet.identifier=?"; String sql = "select working_inode,live_inode from contentlet_version_info where identifier=?"; DotConnect dc = new DotConnect(); dc.setSQL(sql); dc.addParam(ident); List<Map<String,String>> ret = dc.loadResults(); List<String> inodes = new ArrayList<String>(); for(Map<String,String> m : ret) { String workingInode = m.get("working_inode"); String liveInode = m.get("live_inode"); inodes.add(workingInode); if(UtilMethods.isSet(liveInode) && !workingInode.equals(liveInode)){ inodes.add(liveInode); } } for(String inode : inodes) { Contentlet con=APILocator.getContentletAPI().find(inode, APILocator.getUserAPI().getSystemUser(), false); contentToIndex.add(con); } } return contentToIndex; } public void removeContentFromIndex(final Contentlet content) throws DotHibernateException { removeContentFromIndex(content, false); } private void removeContentFromIndex(final Contentlet content, final boolean onlyLive, final List<Relationship> relationships) throws DotHibernateException { Runnable indexRunner = new Runnable() { public void run() { try { String id=content.getIdentifier()+"_"+content.getLanguageId(); Client client=new ESClient().getClient(); BulkRequestBuilder bulk=client.prepareBulk(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); bulk.add(client.prepareDelete(info.live, "content", id)); if(info.reindex_live!=null) bulk.add(client.prepareDelete(info.reindex_live, "content", id)); if(!onlyLive) { // here we search for relationship fields pointing to this // content to be deleted. Those contentlets are reindexed // to avoid left those fields making noise in the index for(Relationship rel : relationships) { String q = ""; boolean isSameStructRelationship = rel.getParentStructureInode().equalsIgnoreCase(rel.getChildStructureInode()); if(isSameStructRelationship) q = "+type:content +(" + rel.getRelationTypeValue() + "-parent:" + content.getIdentifier() + " " + rel.getRelationTypeValue() + "-child:" + content.getIdentifier() + ") "; else q = "+type:content +" + rel.getRelationTypeValue() + ":" + content.getIdentifier(); List<Contentlet> related = APILocator.getContentletAPI().search(q, -1, 0, null, APILocator.getUserAPI().getSystemUser(), false); indexContentletList(bulk, related, false); } bulk.add(client.prepareDelete(info.working, "content", id)); if(info.reindex_working!=null) bulk.add(client.prepareDelete(info.reindex_working, "content", id)); } bulk.execute().actionGet(); } catch(Exception ex) { throw new ElasticSearchException(ex.getMessage(),ex); } } }; HibernateUtil.addCommitListener(content.getIdentifier(),indexRunner); } public void removeContentFromIndex(final Contentlet content, final boolean onlyLive) throws DotHibernateException { if(content==null || !UtilMethods.isSet(content.getIdentifier())) return; List<Relationship> relationships = RelationshipFactory.getAllRelationshipsByStructure(content.getStructure()); // add a commit listener to index the contentlet if the entire // transaction finish clean removeContentFromIndex(content, onlyLive, relationships); } public void removeContentFromLiveIndex(final Contentlet content) throws DotHibernateException { removeContentFromIndex(content, true); } public void removeContentFromIndexByStructureInode(String structureInode) throws DotDataException { String structureName=StructureCache.getStructureByInode(structureInode).getVelocityVarName(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); // collecting indexes List<String> idxs=new ArrayList<String>(); idxs.add(info.working); idxs.add(info.live); if(info.reindex_working!=null) idxs.add(info.reindex_working); if(info.reindex_live!=null) idxs.add(info.reindex_live); String[] idxsArr=new String[idxs.size()]; idxsArr=idxs.toArray(idxsArr); // deleting those with the specified structure inode new ESClient().getClient().prepareDeleteByQuery() .setIndices(idxsArr) .setQuery(QueryBuilders.queryString("+structurename:"+structureName)) .execute().actionGet(); } public void fullReindexAbort() { try { if(!isInFullReindex()) return; IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); final String rew=info.reindex_working; final String rel=info.reindex_live; IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; APILocator.getIndiciesAPI().point(newinfo); iapi.moveIndexBackToCluster(rew); iapi.moveIndexBackToCluster(rel); } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } public boolean isDotCMSIndexName(String indexName) { return indexName.startsWith(ES_WORKING_INDEX_NAME+"_") || indexName.startsWith(ES_LIVE_INDEX_NAME+"_"); } public List<String> listDotCMSClosedIndices() { List<String> indexNames=new ArrayList<String>(); List<String> list=APILocator.getESIndexAPI().getClosedIndexes(); for(String idx : list) if(isDotCMSIndexName(idx)) indexNames.add(idx); return indexNames; } /** * Returns a list of dotcms working and live indices. * @return */ public List<String> listDotCMSIndices() { Client client=new ESClient().getClient(); Map<String,IndexStatus> indices=APILocator.getESIndexAPI().getIndicesAndStatus(); List<String> indexNames=new ArrayList<String>(); for(String idx : indices.keySet()) if(isDotCMSIndexName(idx)) indexNames.add(idx); List<String> existingIndex=new ArrayList<String>(); for(String idx : indexNames) if(client.admin().indices().exists(new IndicesExistsRequest(idx)).actionGet().isExists()) existingIndex.add(idx); indexNames=existingIndex; List<String> indexes = new ArrayList<String>(); indexes.addAll(indexNames); Collections.sort(indexes, new IndexSortByDate()); return indexes; } public void activateIndex(String indexName) throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; newinfo.reindex_working=info.reindex_working; newinfo.reindex_live=info.reindex_live; newinfo.site_search=info.site_search; if(indexName.startsWith(ES_WORKING_INDEX_NAME)) { newinfo.working=indexName; } else if(indexName.startsWith(ES_LIVE_INDEX_NAME)) { newinfo.live=indexName; } APILocator.getIndiciesAPI().point(newinfo); } public void deactivateIndex(String indexName) throws DotDataException, IOException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; newinfo.reindex_working=info.reindex_working; newinfo.reindex_live=info.reindex_live; newinfo.site_search=info.site_search; if(indexName.equals(info.working)) { newinfo.working=null; } else if(indexName.equals(info.live)) { newinfo.live=null; } else if(indexName.equals(info.reindex_working)) { iapi.moveIndexBackToCluster(info.reindex_working); newinfo.reindex_working=null; } else if(indexName.equals(info.reindex_live)) { iapi.moveIndexBackToCluster(info.reindex_live); newinfo.reindex_live=null; } APILocator.getIndiciesAPI().point(newinfo); } public synchronized List<String> getCurrentIndex() throws DotDataException { List<String> newIdx = new ArrayList<String>(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); newIdx.add(info.working); newIdx.add(info.live); return newIdx; } public synchronized List<String> getNewIndex() throws DotDataException { List<String> newIdx = new ArrayList<String>(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); if(info.reindex_working!=null) newIdx.add(info.reindex_working); if(info.reindex_live!=null) newIdx.add(info.reindex_live); return newIdx; } private class IndexSortByDate implements Comparator<String> { public int compare(String o1, String o2) { if(o1 == null || o2==null ){ return 0; } if(o1.indexOf("_") <0 ){ return 1; } if(o2.indexOf("_") <0 ){ return -1; } String one = o1.split("_")[1]; String two = o2.split("_")[1]; return two.compareTo(one); } } public String getActiveIndexName(String type) throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); if(type.equalsIgnoreCase(ES_WORKING_INDEX_NAME)) { return info.working; } else if(type.equalsIgnoreCase(ES_LIVE_INDEX_NAME)) { return info.live; } return null; } }
austindlawless/dotCMS
src/com/dotcms/content/elasticsearch/business/ESContentletIndexAPI.java
Java
gpl-3.0
23,993
""" Copied from https://bitcointalk.org/index.php?topic=1026.0 (public domain) """ from hashlib import sha256 if str != bytes: def ord(c): # Python 3.x return c def chr(n): return bytes((n,)) __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' __b58base = len(__b58chars) def b58encode(v): """ encode v, which is a string of bytes, to base58. """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += (256 ** i) * ord(c) result = '' while long_value >= __b58base: div, mod = divmod(long_value, __b58base) result = __b58chars[mod] + result long_value = div result = __b58chars[long_value] + result # Bitcoin does a little leading-zero-compression: # leading 0-bytes in the input become leading-1s nPad = 0 for c in v: if c == '\0': nPad += 1 else: break return (__b58chars[0]*nPad) + result def b58decode(v, length): """ decode v into a string of len bytes """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += __b58chars.find(c) * (__b58base**i) result = bytes() while long_value >= 256: div, mod = divmod(long_value, 256) result = chr(mod) + result long_value = div result = chr(long_value) + result nPad = 0 for c in v: if c == __b58chars[0]: nPad += 1 else: break result = chr(0) * nPad + result if length is not None and len(result) != length: return None return result def _parse_address(str_address): raw = b58decode(str_address, 25) if raw is None: raise AttributeError("'{}' is invalid base58 of decoded length 25" .format(str_address)) version = raw[0] checksum = raw[-4:] vh160 = raw[:-4] # Version plus hash160 is what is checksummed h3 = sha256(sha256(vh160).digest()).digest() if h3[0:4] != checksum: raise AttributeError("'{}' has an invalid address checksum" .format(str_address)) return ord(version), raw[1:-4] def get_bcaddress_version(str_address): """ Reverse compatibility non-python implementation """ try: return _parse_address(str_address)[0] except AttributeError: return None def get_bcaddress(str_address): """ Reverse compatibility non-python implementation """ try: return _parse_address(str_address)[1] except AttributeError: return None def address_version(str_address): return _parse_address(str_address)[0] def address_bytes(str_address): return _parse_address(str_address)[1]
simplecrypto/cryptokit
cryptokit/base58.py
Python
gpl-3.0
2,723
// For ntohX / htonX #ifdef _WIN32 #include <winsock2.h> #else #include <arpa/inet.h> #endif #include "byte_order.h" namespace net { uint16_t ntoh( const uint16_t& src ) { return ntohs(src); } uint32_t ntoh( const uint32_t& src ) { return ntohl(src); } uint16_t hton( const uint16_t& src ) { return htons(src); } uint32_t hton( const uint32_t& src ) { return htonl(src); } } // namespace net
IronSavior/phlegethon
src/net/byte_order.cpp
C++
gpl-3.0
411
// ----------- General Utility Functions ----------- function get_answer_div(answer_id) { return dom_lookup("answer-", answer_id) } function get_answer_div_desc_div(answer_div) { return dom_lookup("desc-", answer_div.id) } function get_question_desc_div(question_id) { return dom_lookup("question-desc-", question_id) } function get_question_selected_div(question_id) { return dom_lookup("question-selected-", question_id) } function get_question_unselected_div(question_id) { return dom_lookup("question-unselected-", question_id) } function get_verify_ballot_div() { return dom_lookup("verify-ballot-area", "") } function get_submit_button() { return dom_lookup("submit-btn", "") } function dom_lookup(prefix, id) { return document.getElementById("" + prefix + id) } function filter_visible(arr) { /* Take an array-like object containing DOM elements, and use j-query * to filter out the visible ones * * Param arr - array-like object containing DOM elements * * Returns - array containing only visible elements */ return Array.prototype.filter.call(arr, function(test_element) { return $(test_element).is(":visible");} ) } function is_selected(answer_id, question_id) { /* Return true if an answer belonging to a question is selected */ var sel_div = get_question_selected_div(question_id) return get_answer_div(answer_id).parentNode == sel_div } // ----------- Less-General Helper Functions ----------- function build_tutorial_block(next_to_element, tut_text) { /* Display a tutorial block */ if($(next_to_element).is(":visible")) { var max_tut_width = "150" // Just a magic number for look var tut_border_add = 10 // In css, border is about this width... var tut_div = document.createElement("div") // The class is used to style the object, and to remove it later tut_div.className = "tutorial_child" // Attach event listeners so it can disappear on mouseover tut_div.addEventListener("mouseenter", function () { this.style.opacity=0; }, false) tut_div.addEventListener("mouseleave", function () { this.style.opacity=1; }, false) tut_div.innerHTML = tut_text var src_loc = next_to_element.getBoundingClientRect() tut_div.style.top = (src_loc.top + window.pageYOffset) + "px" var tut_width = src_loc.left - window.pageXOffset - tut_border_add if(tut_width > max_tut_width) { tut_width = max_tut_width } tut_div.style.width = tut_width + "px" tut_div.style.left = (src_loc.left - tut_width - tut_border_add) + "px" document.body.appendChild(tut_div) } } function ballot_change_made(func_after) { /* Handle visual changes necessary after a change on the ballot */ $("#check-ballot-btn").slideDown("fast", function() { $("#form").slideUp("fast", function() { $("#verify-ballot-area").slideUp("fast", function() { handle_tutorial() if(func_after !== undefined) { func_after() } }) }) }) } function number_ballot(question_id) { /* Number the selected ballot options for a given question */ var sel_div = get_question_selected_div(question_id) var unsel_div = get_question_unselected_div(question_id) for( var i = 0; i < sel_div.childNodes.length; i++ ) { var selected_ans_node = sel_div.childNodes[i] var ans_rank = document.getElementById("rank-"+selected_ans_node.id) ans_rank.innerHTML = i + 1 } for( var i = 0; i < unsel_div.childNodes.length; i++ ) { var unselected_ans_node = unsel_div.childNodes[i] var ans_rank = document.getElementById("rank-"+unselected_ans_node.id) ans_rank.innerHTML = "&nbsp;" } } // ----------- Tutorial Functions ----------- function handle_tutorial() { /* Display the tutorial blocks */ remove_tutorial_blocks() var TutorialQuestionState = Object.freeze( {ADD:0, REORDER:1, VERIFY:2, SUBMIT:3, NONE:4}) var add_help = "Drag one or more options into the &quot;selected&quot; area to vote for them." var reorder_help = "Reorder options to match your preferences, or remove items you no longer wish to vote for." var nochoices_help = "Make voting selections above before verifying your ballot." var submit_help = "Verify your preferences. Make changes above if necessary. Submit when you&apos;re ready." var state_text_map = [add_help, reorder_help, nochoices_help, submit_help] // Display one tutorial block per question for( var question in question_list ) { var question_id = question_list[question] var sel_div = get_question_selected_div(question_id) var unsel_div = get_question_unselected_div(question_id) var q_state = 0; var next_to = sel_div; if( sel_div.childNodes.length < 2 ) { q_state = TutorialQuestionState.ADD next_to = unsel_div } else { q_state = TutorialQuestionState.REORDER next_to = sel_div } build_tutorial_block(next_to, state_text_map[q_state]) } var verify_ballot_div = get_verify_ballot_div() var submit_btn = get_submit_button() // Default these two to the verify state - if it's not visible, // build_tutorial_block won't display it... var ver_state = TutorialQuestionState.VERIFY var ver_next_to = verify_ballot_div if( $(submit_btn).is(":visible") ) { ver_state = TutorialQuestionState.SUBMIT } build_tutorial_block(ver_next_to, state_text_map[ver_state]) } function remove_tutorial_blocks() { /* Clear all tutorial blocks from the screen */ var element_list = [] do { for(var i = 0; i < element_list.length; i++) { document.body.removeChild(element_list[i]) } element_list = document.body.getElementsByClassName("tutorial_child") } while( element_list.length > 0 ) } $(document).ready( function() { // Run handle_tutorial as soon as the DOM is ready handle_tutorial() // Make the questions sortable, but don't allow sorting between questions for( var question in question_list ) { var question_id = question_list[question] var sel_div = get_question_selected_div(question_id) var unsel_div = get_question_unselected_div(question_id) var desc_div = get_question_desc_div(question_id) // What I do with update down there is weird - I create a function // that returns a function then call it. That results in creating // a new scoping specifically for local_question_id $(sel_div).sortable({ placeholder: "poll_answer_placeholder", connectWith: "#" + unsel_div.id, update: function() { var local_question_id = question_id return function(event, ui) { number_ballot(local_question_id) ballot_change_made() } }(), // Whenever receive happense on the selected div, // update happens too. No need to duplicate things... /*receive: function(event, ui) { ballot_change_made() },*/ }) $(unsel_div).sortable({ placeholder: "poll_answer_placeholder", connectWith: "#" + sel_div.id, receive: function(event, ui) { ballot_change_made() }, }) } } ) // ----------- Functions Referenced In HTML ----------- function validate_ballot() { /* Occurs when the "validate ballot" button is pressed */ var form_entries = document.getElementById("constructed-form-entries") var validate = document.getElementById("verify-ballot-div-area") var some_answers = false form_entries.innerHTML = "" validate.innerHTML = "" // Build the validation view and the response form for each question for( var question in question_list ) { var question_id = question_list[question] var sel_div = get_question_selected_div(question_id) var desc_div = get_question_desc_div(question_id) var question_validate_div = document.createElement("div") question_validate_div.className = "poll_question" var question_validate_desc = document.createElement("div") question_validate_desc.innerHTML = desc_div.innerHTML question_validate_desc.classList = desc_div.classList question_validate_div.appendChild(question_validate_desc) if( sel_div.childNodes.length == 0 ) { var new_ans = document.createElement("div") new_ans.className = "poll_answer_desc" new_ans.innerHTML = "No choices selected" question_validate_div.appendChild(new_ans) } for( var i = 0; i < sel_div.childNodes.length; i++ ) { some_answers = true var selected_ans_node = sel_div.childNodes[i] var new_input = document.createElement("input") new_input.type = "hidden" new_input.name = selected_ans_node.id new_input.value = i + 1 form_entries.appendChild(new_input) var new_ans = document.createElement("div") new_ans.className = "poll_answer_desc" new_ans.innerHTML = "" + (i+1) + ". " + get_answer_div_desc_div(selected_ans_node).innerHTML question_validate_div.appendChild(new_ans) } validate.appendChild(question_validate_div) } if( some_answers ) { $("#form").show() } else { $("#form").hide() } $("#check-ballot-btn").slideUp("fast") toggle_visible_block("verify-ballot-area", true) }
kc0bfv/RankedChoiceRestaurants
RankedChoiceRestaurants/static/voting/ranked_choice.js
JavaScript
gpl-3.0
9,999
import { QueryInterface } from "sequelize"; export default { up: (queryInterface: QueryInterface) => { return Promise.resolve() .then(() => queryInterface.bulkInsert("dimension_bridges", [ { type: "hookshot_webhook", name: "Webhooks Bridge", avatarUrl: "/assets/img/avatars/webhooks.png", isEnabled: true, isPublic: true, description: "Webhooks to Matrix", }, ])); }, down: (queryInterface: QueryInterface) => { return Promise.resolve() .then(() => queryInterface.bulkDelete("dimension_bridges", { type: "hookshot_webhook", })); } }
turt2live/matrix-dimension
src/db/migrations/20211202181745-AddHookshotWebhookBridgeRecord.ts
TypeScript
gpl-3.0
782
<?php /** * QuittanceTable * * This class has been auto-generated by the Doctrine ORM Framework */ class QuittanceTable extends Doctrine_Table { /** * Returns an instance of this class. * * @return object QuittanceTable */ public static function getInstance() { return Doctrine_Core::getTable('Quittance'); } }
MichaelMure/Ordo
lib/model/doctrine/QuittanceTable.class.php
PHP
gpl-3.0
360
package visualization.utilities; import java.util.Collection; import java.util.Collections; import java.util.HashMap; public class BidirectionalHashMap<K1,K2> { protected HashMap<K1,K2> left = new HashMap<K1, K2>(); protected HashMap<K2,K1> right= new HashMap<K2, K1>(); public void put(K1 k1, K2 k2) { left.put(k1,k2); right.put(k2,k1); } public void remove(Object key) { if (left.containsKey(key)) right.remove(left.remove(key)); else left.remove(right.remove(key)); } @SuppressWarnings("unchecked") public <T> T get(Object key) { Object ret = left.get(key); if (ret==null) ret = right.get(key); return (T)ret; } public int size() { return left.size(); } public Collection<K1> getLeftElements() { return Collections.unmodifiableSet(left.keySet()); } public Collection<K2> getRightElements() { return Collections.unmodifiableSet(right.keySet()); } public void clear() { left.clear(); right.clear(); } @SuppressWarnings("unchecked") public <T> T getRight(Object key) { Object ret = right.get(key); return (T)ret; } @SuppressWarnings("unchecked") public <T> T getLeft(Object key) { Object ret = left.get(key); return (T)ret; } }
Integrative-Transcriptomics/inPHAP
HaplotypeViewer/visualization/utilities/BidirectionalHashMap.java
Java
gpl-3.0
1,215
/** * Copyright (c) 2015 TerraFrame, Inc. All rights reserved. * * This file is part of Geoprism(tm). * * Geoprism(tm) 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. * * Geoprism(tm) 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 Geoprism(tm). If not, see <http://www.gnu.org/licenses/>. */ package net.geoprism.data.etl; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.runwaysdk.business.ontology.Term; import com.runwaysdk.dataaccess.transaction.Transaction; import com.runwaysdk.query.OIterator; import com.runwaysdk.query.QueryFactory; import com.runwaysdk.system.gis.geo.AllowedIn; import com.runwaysdk.system.gis.geo.GeoEntity; import com.runwaysdk.system.gis.geo.Universal; import com.runwaysdk.system.metadata.MdAttribute; import net.geoprism.ontology.GeoEntityUtil; public class TargetFieldGeoEntityBinding extends TargetFieldGeoEntityBindingBase { private static class UniversalAttributeBindingComparator implements Comparator<UniversalAttributeBinding> { private Map<String, Integer> indices; public UniversalAttributeBindingComparator(Collection<Term> terms) { this.indices = new HashMap<String, Integer>(); int index = 0; for (Term term : terms) { this.indices.put(term.getOid(), index++); } } @Override public int compare(UniversalAttributeBinding o1, UniversalAttributeBinding o2) { Integer i1 = this.indices.get(o1.getUniversalId()); Integer i2 = this.indices.get(o2.getUniversalId()); return i1.compareTo(i2); } } private static final long serialVersionUID = -2005836550; public TargetFieldGeoEntityBinding() { super(); } @Override @Transaction public void delete() { List<UniversalAttributeBinding> attributes = this.getUniversalAttributes(); for (UniversalAttributeBinding attribute : attributes) { attribute.delete(); } super.delete(); } public List<UniversalAttributeBinding> getUniversalAttributes() { List<UniversalAttributeBinding> list = new LinkedList<UniversalAttributeBinding>(); UniversalAttributeBindingQuery query = new UniversalAttributeBindingQuery(new QueryFactory()); query.WHERE(query.getField().EQ(this)); OIterator<? extends UniversalAttributeBinding> iterator = query.getIterator(); try { while (iterator.hasNext()) { UniversalAttributeBinding binding = iterator.next(); list.add(binding); } return list; } finally { iterator.close(); } } @Override protected void populate(TargetField field) { super.populate(field); GeoEntity root = this.getGeoEntity(); Collection<Term> descendants = GeoEntityUtil.getOrderedDescendants(root.getUniversal(), AllowedIn.CLASS); TargetFieldGeoEntity tField = (TargetFieldGeoEntity) field; tField.setRoot(root); List<UniversalAttributeBinding> attributes = this.getUniversalAttributes(); Collections.sort(attributes, new UniversalAttributeBindingComparator(descendants)); for (UniversalAttributeBinding attribute : attributes) { MdAttribute sourceAttribute = attribute.getSourceAttribute(); String attributeName = sourceAttribute.getAttributeName(); String label = sourceAttribute.getDisplayLabel().getValue(); Universal universal = attribute.getUniversal(); tField.addUniversalAttribute(attributeName, label, universal); } tField.setUseCoordinatesForLocationAssignment(this.getUseCoordinatesForLocationAssignment()); tField.setCoordinateObject(this.getLatitudeAttributeName(), this.getLongitudeAttributeName()); } @Override public TargetFieldIF getTargetField() { TargetFieldGeoEntity field = new TargetFieldGeoEntity(); populate(field); return field; } }
terraframe/geodashboard
geoprism-server/src/main/java-gen/stub/net/geoprism/data/etl/TargetFieldGeoEntityBinding.java
Java
gpl-3.0
4,444
/**=============================================================================== * * MotiQ_cropper plugin for ImageJ, Version v0.1.1 * * Copyright (C) 2014-2017 Jan Niklas Hansen * First version: December 01, 2014 * This Version: May 03, 2017 * * 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 (http://www.gnu.org/licenses/gpl.txt ) * * 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/gpl-3.0.html>. * * For any questions please feel free to contact me (jan.hansen@caesar.de). * * ==============================================================================*/ package motiQ_cr; import java.awt.*; import java.awt.Font; import java.util.*; import ij.*; import ij.gui.*; import ij.io.*; import ij.measure.*; import ij.plugin.*; import ij.plugin.frame.*; import ij.text.*; import java.text.*; public class Cropper_ implements PlugIn, Measurements { static final String PLUGINNAME = "MotiQ_cropper"; static final String PLUGINVERSION = "v0.1.1"; static final SimpleDateFormat yearOnly = new SimpleDateFormat("yyyy"); //Fonts static final Font SuperHeadingFont = new Font("Sansserif", Font.BOLD, 16); static final Font HeadingFont = new Font("Sansserif", Font.BOLD, 14); static final Font SubHeadingFont = new Font("Sansserif", Font.BOLD, 12); static final Font InstructionsFont = new Font("Sansserif", 2, 12); //variables static final String roiPrefix = "Polygon_Stack_";// //Selection variables static final String[] taskVariant = {"process the active, open image","manually open image to be processed"}; String selectedTaskVariant = taskVariant[0]; static final String[] stackVariants = {"consecutive order (recommended for time-lapse 2D images)", "user-defined order (recommended for time-lapse and non-time-lapse 3D images)"}; String selectedStackVariant = stackVariants [0]; public void run(String arg) { //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //-------------------------GenericDialog-------------------------------------- //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& GenericDialog gd = new GenericDialog(PLUGINNAME + " - settings"); //show Dialog----------------------------------------------------------------- gd.setInsets(0,0,0); gd.addMessage(PLUGINNAME + ", version " + PLUGINVERSION + " (\u00a9 2014 - " + yearOnly.format(new Date()) + ", Jan Niklas Hansen)", SuperHeadingFont); gd.setInsets(0,0,0); gd.addChoice("Image:", taskVariant, selectedTaskVariant); gd.setInsets(5,0,0); gd.addChoice("Process stack in ", stackVariants, selectedStackVariant); gd.setInsets(10,0,0); gd.addCheckbox("Post processing, crop image to selected region", true); gd.setInsets(10,0,0); gd.showDialog(); //show Dialog----------------------------------------------------------------- //read and process variables-------------------------------------------------- String selectedTaskVariant = gd.getNextChoice(); selectedStackVariant = gd.getNextChoice(); boolean freeStackOrder = true; if(selectedStackVariant.equals(stackVariants[0])) freeStackOrder = false; boolean cropImage = gd.getNextBoolean(); //read and process variables-------------------------------------------------- if (gd.wasCanceled()) return; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //---------------------end-GenericDialog-end---------------------------------- //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& ImagePlus imp = new ImagePlus(); String name = new String(); String dir = new String(); //get folder and file name if (selectedTaskVariant.equals(taskVariant[1])){ OpenDialog od = new OpenDialog("List Opener", null); name = od.getFileName(); dir = od.getDirectory(); imp = IJ.openImage(""+dir+name+""); imp.show(); }else if (selectedTaskVariant.equals(taskVariant[0])){ imp = WindowManager.getCurrentImage(); FileInfo info = imp.getOriginalFileInfo(); name = info.fileName; //get name dir = info.directory; //get directory } final ImagePlus impSave = imp.duplicate(); impSave.hide(); final String impTitle = imp.getTitle(); //Get Image Properties int width = imp.getWidth(), height = imp.getHeight(), stacksize = imp.getStackSize(), slices = imp.getNSlices(), frames = imp.getNFrames(), channels = imp.getNChannels(); //check for hyperstack boolean hyperStack = true; if(channels == stacksize || frames == stacksize || slices == stacksize) hyperStack = false; //Generate backup image array double backupImage [][][] = new double [width][height][stacksize]; for(int z = 0; z < stacksize; z++){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ backupImage [x][y][z] = imp.getStack().getVoxel(x,y,z); } } } //Init ROI Manager RoiManager rm = RoiManager.getInstance(); if (rm==null) rm = new RoiManager(); rm.runCommand("reset"); running: while(true){ //Process Saving Name SimpleDateFormat NameDateFormatter = new SimpleDateFormat("yyMMdd_HHmmss"); Date currentDate = new Date(); String namewithoutending = name; if(name.contains(".")){ namewithoutending = name.substring(0,name.lastIndexOf("."));//Remove Datatype-Ending from name } String Dataname = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + "_Info.txt"; String DatanameImp = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + ".tif"; //Process Saving Name Roi roi; // imp.deleteRoi(); int aMaxX [] = new int [stacksize], aMaxY [] = new int [stacksize], aMinX [] = new int [stacksize], aMinY [] = new int [stacksize], aMaxZ = 0, aMinZ = (stacksize-1); for(int i = 0; i < stacksize; i++){ aMaxX [i] = 0; aMaxY [i] = 0; aMinX [i] = width-1; aMinY [i] = height-1; } rm.runCommand("reset"); int startStacking = 0; if(freeStackOrder==false){ SettingRois: while(true){ Stacking: for (int stack = startStacking; stack < stacksize; stack++){ IJ.selectWindow(imp.getID()); IJ.setTool("polygon"); imp.setPosition(stack+1); new WaitForUserDialog("Draw a ROI containing the cell of interest for stack image " + (stack+1) + "!").show(); //start Generic Dialog for navigation //Initialize variables for continue cutting dialog String [] continueVariants = new String [stack + 2 + 4]; continueVariants [0] = "remove remaining stack images, save, and finish"; continueVariants [1] = "apply the current ROI in all remaining stack images, save, and finish"; continueVariants [2] = "keep remaining stack images as is, save, and finish"; continueVariants [3] = "CONTINUE setting ROIs in next stack image (" + (stack+2) + ")"; for (int i = stack+1; i > 0; i--){ continueVariants [3 + (stack+2 - i)] = "restart setting ROIs from stack image " + i; } continueVariants [stack + 2 + 3] = "abort plugin"; //show Dialog GenericDialog gd2 = new GenericDialog(PLUGINNAME + ", version " + PLUGINVERSION); gd2.hideCancelButton(); gd2.setInsets(0,0,0); gd2.addMessage(PLUGINNAME + ", version " + PLUGINVERSION + " (\u00a9 2014 - " + yearOnly.format(new Date()) + ", Jan Niklas Hansen)", SuperHeadingFont); gd2.setInsets(5,0,0); gd2.addMessage("You currently have cropped image " + (stack+1) + "/" + stacksize + ".", InstructionsFont); gd2.setInsets(5,0,0); gd2.addMessage((stacksize - stack - 1) + " stack images remaining to process.", InstructionsFont); gd2.setInsets(5,0,0); gd2.addChoice("", continueVariants, continueVariants [3]); gd2.setInsets(5,0,0); gd2.addMessage("Note: if you restart in a previous stack image, all following stack images are reset.", InstructionsFont); gd2.showDialog(); //get Selections int continueVariantIndex = gd2.getNextChoiceIndex(); //end GenericDialog for navigation roi = imp.getRoi(); if(continueVariantIndex == continueVariants.length-1){ //abort break running; }else if(continueVariantIndex > 3){ //restart from previous frame int continueNr = (stack+2-(continueVariantIndex-3)); if(continueNr == stack+1){ imp.setPosition(stack+1); }else{ for(int z = (continueNr-1); z < stack; z++){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,z,backupImage[x][y][z]); } } //Reset of parameters aMaxX [z] = 0; aMaxY [z] = 0; aMinX [z] = width-1; aMinY [z] = height-1; //RoiManager resetten for(int r = (rm.getCount()-1); r >= 0; r--){ String roiName = rm.getName(r); if(roiName.equals(roiPrefix + (z+1) + "")){ rm.runCommand(imp,"Deselect"); rm.select(r); rm.runCommand(imp,"Delete"); } } } } aMaxZ = continueNr-2; if(roi!=null){ imp.setRoi(new PolygonRoi(roi.getPolygon(),Roi.POLYGON)); } startStacking = (continueNr-1); break Stacking; } //----------------------Extract Imagepart--------------------------- if(roi!=null){ Polygon p = roi.getPolygon(); for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ double pxintensity = imp.getStack().getVoxel(x,y,stack); if(p.contains(x,y)==false&&pxintensity!=0){ imp.getStack().setVoxel( x, y, stack, 0.0); }else if(p.contains(x,y)){ if(aMinX [stack] > x){aMinX[stack]=x;} if(aMaxX [stack] < x){aMaxX[stack]=x;} if(aMinY [stack] > y){aMinY[stack]=y;} if(aMaxY [stack] < y){aMaxY[stack]=y;} } } } if(aMinZ > stack){aMinZ=stack;} if(aMaxZ < stack){aMaxZ=stack;} }else{ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel( x, y, stack, 0.0); } } // IJ.log("No ROI was selected in image " + stack); } //----------------------Extract Imagepart--------------------------- if(roi!=null){ rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (stack+1) + ""); } if(stack == stacksize-1){ //stop setting ROIs, if all images are processed break SettingRois; } if(continueVariantIndex == 1 && roi!=null){ //Finish and apply current ROI to all remaining stack images Polygon p = roi.getPolygon(); for (int stackRoi = stack+1; stackRoi < stacksize; stackRoi++){ if(roi!=null){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ double pxintensity = imp.getStack().getVoxel(x,y,stackRoi); if(p.contains(x,y)==false&&pxintensity!=0){ imp.getStack().setVoxel( x, y, stackRoi, 0.0); }else if(p.contains(x,y)){ if(aMinX [stackRoi] > x){aMinX[stackRoi]=x;} if(aMaxX [stackRoi] < x){aMaxX[stackRoi]=x;} if(aMinY [stackRoi] > y){aMinY[stackRoi]=y;} if(aMaxY [stackRoi] < y){aMaxY[stackRoi]=y;} } } } if(aMinZ > stackRoi){aMinZ=stackRoi;} if(aMaxZ < stackRoi){aMaxZ=stackRoi;} rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (stackRoi+1) + ""); }else{ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel( x, y, stackRoi, 0.0); } } // IJ.log("No ROI was selected in image " + stackRoi); } } break SettingRois; }else if(continueVariantIndex == 0 || (continueVariantIndex == 1 && roi==null)){ //Finish and remove remaining stack images if(cropImage==false){ for(int z = stack+1; z < stacksize; z++){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,z,0.0); } } } } break SettingRois; }else if(continueVariantIndex == 2){ //Keep remaining stack images and finish for (int stackRoi = stack+1; stackRoi < stacksize; stackRoi++){ aMinX[stackRoi]=0; aMaxX[stackRoi]=imp.getWidth()-1; aMinY[stackRoi]=0; aMaxY[stackRoi]=imp.getHeight()-1; if(aMinZ > stackRoi){aMinZ=stackRoi;} aMaxZ=stackRoi; } break SettingRois; } imp.updateImage(); } } }else{ //list of processed images boolean imageCropped [] = new boolean [stacksize]; for(int i = 0; i < stacksize; i++){ imageCropped [i] = false; } //Variables for intermediate dialog int continueIndex = 5; String [] continueVariants; if(hyperStack){ continueVariants = new String [7]; continueVariants [5] = "CONTINUE setting ROIs in closest remaining slice"; continueVariants [6] = "CONTINUE setting ROIs in closest remaining frame"; }else{ continueVariants = new String [6]; continueVariants [5] = "CONTINUE setting ROIs in closest remaining stack image"; } continueVariants [0] = "abort plugin"; continueVariants [1] = "clear remaining stack images, save, and finish"; continueVariants [2] = "apply the current ROI in all remaining stack images, save, and finish"; continueVariants [3] = "keep remaining stack images as is, save, and finish"; continueVariants [4] = "CONTINUE setting ROIs but stay at current stack position"; SettingRois: while(true){ IJ.setTool("polygon"); IJ.selectWindow(imp.getID()); int stack = 0; int cSlice = imp.getSlice()-1, cFrame = imp.getFrame()-1, cChannel = imp.getChannel()-1; waitingDialog: while(true){ new WaitForUserDialog("Draw a ROI in your preferred slice!").show(); cSlice = imp.getSlice()-1; cFrame = imp.getFrame()-1; cChannel = imp.getChannel()-1; roi = imp.getRoi(); stack = imp.getCurrentSlice()-1; if(imageCropped[stack]==true){ YesNoCancelDialog confirm = new YesNoCancelDialog(IJ.getInstance(),"Action required", "Previously, you had already set a ROI for stack image " + (stack+1) + ". Do you want to reset the image using the new ROI?"); if (confirm.yesPressed()){ imageCropped[stack] = false; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,stack,backupImage[x][y][stack]); } } //Reset of parameters aMaxX [stack] = 0; aMaxY [stack] = 0; aMinX [stack] = width-1; aMinY [stack] = height-1; //Reset RoiManager for(int z = 0; z < rm.getCount(); z++){ String roiName = rm.getName(z); if(roiName.contains(roiPrefix)){ int stackRoiNr = Integer.parseInt(roiName.substring(roiPrefix.length())); if(stackRoiNr==(stack+1)){ rm.runCommand(imp,"Deselect"); rm.select(z); rm.runCommand(imp,"Delete"); } } } break waitingDialog; } }else{ break waitingDialog; } } imageCropped [stack] = true; //----------------------Extract Imagepart--------------------------- if(roi!=null){ Polygon p = roi.getPolygon(); for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ double pxintensity = imp.getStack().getVoxel(x,y,stack); if(p.contains(x,y)==false&&pxintensity!=0.0){ imp.getStack().setVoxel(x, y, stack, 0.0); }else if(p.contains(x,y)){ if(aMinX [stack] > x){aMinX[stack]=x;} if(aMaxX [stack] < x){aMaxX[stack]=x;} if(aMinY [stack] > y){aMinY[stack]=y;} if(aMaxY [stack] < y){aMaxY[stack]=y;} } } } }else{ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x, y, stack, 0.0); } } // IJ.log("No ROI was selected in image " + (stack+1)); } //----------------------Extract Imagepart--------------------------- if(roi!=null){ rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (stack+1) + ""); } // Generic Dialog for navigation //Initialize variables for continue cutting dialog //Count remaining frames int cutImgCt = 0; for(int i = 0; i<stacksize; i++){ if(imageCropped[i]){ cutImgCt++; } } //Finish analysis if all images have been cut if(cutImgCt == stacksize) break SettingRois; //generate list of cut images String [] croppedImagesOverview = new String [cutImgCt]; int cutImgCt2 = 0; for(int i = 1; i <= stacksize; i++){ if(imageCropped[i-1]){ croppedImagesOverview [cutImgCt2] = "" + (i); cutImgCt2++; } } //show Dialog GenericDialog gd2 = new GenericDialog(PLUGINNAME + ", version " + PLUGINVERSION); gd2.hideCancelButton(); gd2.setInsets(0,0,0); gd2.addMessage(PLUGINNAME + ", version " + PLUGINVERSION + " (\u00a9 2014 - " + yearOnly.format(new Date()) + ", Jan Niklas Hansen)", SuperHeadingFont); gd2.setInsets(5,0,0); gd2.addMessage("You currently cropped image " + (stack+1) + "/" + stacksize + ".", InstructionsFont); gd2.setInsets(5,0,0); gd2.addMessage((stacksize - stack - 1) + " stack images remaining to process.", InstructionsFont); gd2.setInsets(5,0,0); gd2.addChoice("", continueVariants, continueVariants [continueIndex]); gd2.setInsets(15,0,0); gd2.addCheckbox("Reset specific stack image", false); gd2.setInsets(-25,80,0); gd2.addChoice("", croppedImagesOverview , croppedImagesOverview[0]); gd2.showDialog(); //read and process variables continueIndex = gd2.getNextChoiceIndex(); boolean resetFrame = gd2.getNextBoolean(); int resetNr = Integer.parseInt(gd2.getNextChoice())-1; // Generic Dialog for navigation if(continueIndex == 0){ //abort break running; } if(continueIndex==1 || (continueIndex==2 && roi==null)){ //clear remaining stack images, save and finish for(int i = 0; i<stacksize; i++){ if(imageCropped[i]==false){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,i,0.0); } } } } break SettingRois; } if(continueIndex==2 && roi!=null){ //apply the current ROI in all remaining stack images, save, and finish" for(int i = 0; i < stacksize; i++){ if(imageCropped [i]==false){ Polygon p = roi.getPolygon(); for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ if(p.contains(x,y)==false){ imp.getStack().setVoxel(x, y, i, 0.0); }else if(p.contains(x,y)){ if(aMinX [i] > x){aMinX [i] = x;} if(aMaxX [i] < x){aMaxX [i] = x;} if(aMinY [i] > y){aMinY [i] = y;} if(aMaxY [i] < y){aMaxY [i] = y;} } } } imageCropped [i] = true; if(roi!=null){ rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (i+1) + ""); } } } break SettingRois; } if(continueIndex==3){ //keep remaining stack images as is, save and finish for(int i = 0; i<stacksize; i++){ if(imageCropped[i]==false){ aMinX[i]=0; aMaxX[i]=imp.getWidth(); aMinY[i]=0; aMaxY[i]=imp.getHeight(); imageCropped [i] = true; } } break SettingRois; } if(resetFrame){ imp.setPosition(resetNr+1); imageCropped[resetNr] = false; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,resetNr,backupImage[x][y][resetNr]); } } //Reset of parameters aMaxX [resetNr] = 0; aMaxY [resetNr] = 0; aMinX [resetNr] = width-1; aMinY [resetNr] = height-1; //Rest RoiManager for(int z = 0; z < rm.getCount(); z++){ String roiName = rm.getName(z); if(roiName.contains(roiPrefix)){ int stackRoiNr = Integer.parseInt(roiName.substring(roiPrefix.length())); if(stackRoiNr==(resetNr+1)){ rm.runCommand(imp,"Deselect"); rm.select(z); rm.runCommand(imp,"Delete"); } } } imp.setRoi(roi); } if(continueIndex == 5){ //Auto-moving to next remaining slice or stack image moving: for(int i = 0; i < stacksize; i++){ if(stack+i<stacksize){ if(imageCropped[stack+i]==false){ imp.setPosition(stack+i+1); break moving; } } if(stack-i>=0){ if(imageCropped[stack-i]==false){ imp.setPosition(stack-i+1); break moving; } } } }else if(continueIndex == 6){ //Auto-moving to next remaining frame boolean found = false; search: while(true){ moving: for(int i = 0; i < frames; i++){ if(stack+i*slices<stacksize){ if(imageCropped[stack+i*slices]==false){ imp.setPosition(stack+i*slices+1); found = true; break moving; } } if(stack-i*slices>=0){ if(imageCropped[stack-i*slices]==false){ imp.setPosition(stack-i*slices+1); found = true; break moving; } } } if(found){ break search; }else{ //move to next remaining stack moving: for(int i = 0; i < stacksize; i++){ if(stack+i<stacksize){ if(imageCropped[stack+i]==false){ imp.setPosition(stack+i+1); break moving; } } if(stack-i>=0){ if(imageCropped[stack-i]==false){ imp.setPosition(stack-i+1); break moving; } } } } } } //if image is a hyperstack, search for the closest frame's / slice's / channel's ROI if(hyperStack){ cFrame = imp.getFrame(); cChannel = imp.getChannel(); cSlice = imp.getSlice(); int z; searching: for(int f = 1; f+cFrame <= frames || cFrame-f > 0; f++){ for(int c = 0; cChannel + c <= channels || cChannel-c > 0; c++){ for(int j = 0; j < rm.getCount(); j++){ z = imp.getStackIndex(cChannel+c, cSlice, cFrame+f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } z = imp.getStackIndex(cChannel-c, cSlice, cFrame+f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } z = imp.getStackIndex(cChannel-c, cSlice, cFrame-f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } z = imp.getStackIndex(cChannel+c, cSlice, cFrame-f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } } } } }else{ imp.setRoi(new PolygonRoi(rm.getRoi(rm.getCount()-1).getPolygon(),Roi.POLYGON)); } imp.updateImage(); } for(int z = 0; z < stacksize; z++){ boolean zTrue = false; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ if(imp.getStack().getVoxel(x,y,z)!=0.0){ zTrue = true; } } } if(zTrue){ if(aMinZ > z){aMinZ=z;} if(aMaxZ < z){aMaxZ=z;} } } } if(cropImage){ int max_x = 0, max_y = 0, min_x = width-1, min_y = height-1, max_z = aMaxZ, min_z = aMinZ; for(int i = 0; i < stacksize; i++){ if(min_x > aMinX[i]){min_x=aMinX[i];} if(max_x < aMaxX[i]){max_x=aMaxX[i];} if(min_y > aMinY[i]){min_y=aMinY[i];} if(max_y < aMaxY[i]){max_y=aMaxY[i];} } if(min_x > 0) {min_x--;} if(max_x < (width-1)) {max_x++;} if(min_y > 0) {min_y--;} if(max_y < (height-1)) {max_y++;} imp.deleteRoi(); Roi RoiCut = new Roi(min_x, min_y, max_x-min_x+1, max_y-min_y+1); IJ.selectWindow(imp.getID()); imp.setRoi(RoiCut); IJ.run(imp, "Crop", ""); imp.getCalibration().xOrigin = imp.getCalibration().xOrigin + min_x; imp.getCalibration().yOrigin = imp.getCalibration().yOrigin + min_y; if(!hyperStack){ imp.getCalibration().zOrigin = imp.getCalibration().zOrigin + min_z; for(int stack = stacksize-1; stack >= 0; stack--){ if(stack<min_z){ IJ.selectWindow(imp.getID()); imp.setPosition(stack+1); IJ.run(imp, "Delete Slice", ""); } if(stack>max_z){ IJ.selectWindow(imp.getID()); imp.setPosition(stack+1); IJ.run(imp, "Delete Slice", ""); } } } SimpleDateFormat FullDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); TextPanel tp =new TextPanel("Metadata"); tp.append("Cropping started: " + FullDateFormatter.format(currentDate)); if(freeStackOrder){ tp.append("During cropping free stack order mode was used."); } tp.append("Image Cropping Info (Min Values have to be added to any pixel position in the new image " + "to find positions in the original image)"); tp.append(" Min X: " + min_x + " Max X: " + max_x); tp.append(" Min Y: " + min_y + " Max Y: " + max_y); if(!hyperStack){ tp.append(" Min Z: " + min_z + " Max Z: " + max_z + " (0 = smallest)"); }else{ tp.append(""); } tp.append(""); tp.append("Datafile was generated by '"+PLUGINNAME+"', \u00a9 2014 - " + yearOnly.format(new Date()) + " Jan Niklas Hansen (jan.hansen@caesar.de)."); tp.append("The plugin '"+PLUGINNAME+"' 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."); tp.append("Plugin version: "+PLUGINVERSION); tp.saveAs(Dataname); DatanameImp = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + "_X" + min_x + "_Y" + min_y + "_Z" + min_z + ".tif"; } imp.deleteRoi(); IJ.saveAsTiff(imp,DatanameImp); // Save RoiSet String Roi_Dataname = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + "_RoiSet.zip"; rm.runCommand("Save", Roi_Dataname); // Save RoiSet imp.changes = false; imp.close(); YesNoCancelDialog confirm = new YesNoCancelDialog(IJ.getInstance(),"Do it again?", "Your selection was saved. Do you want to cut out another region in the same stack?"); if (confirm.yesPressed()){ imp = impSave.duplicate(); imp.setTitle(impTitle); imp.show(); }else{break running;} } } }
hansenjn/MotiQ
Cropper/src/main/java/motiQ_cr/Cropper_.java
Java
gpl-3.0
27,906
class AddUserIdToBalances < ActiveRecord::Migration[5.0] def change add_column :balances, :user_id, :integer end end
kizzonia/TBTC
db/migrate/20170709204817_add_user_id_to_balances.rb
Ruby
gpl-3.0
125
<?php namespace common\modules\fa\models; use Yii; /** * This is the model class for table "{{%fa_asset_trasaction}}". * * @property string $fa_asset_trasaction_id * @property integer $fa_asset_id * @property integer $transaction_type_id * @property string $quantity * @property string $amount * @property string $description * @property string $status * @property string $reference * @property integer $accounted_cb * @property integer $created_by * @property string $creation_date * @property integer $last_update_by * @property string $last_update_date * @property integer $company_id */ class FaAssetTrasaction extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%fa_asset_trasaction}}'; } /** * @inheritdoc */ public function rules() { return [ [['fa_asset_id', 'created_by', 'last_update_by'], 'required'], [['fa_asset_id', 'transaction_type_id', 'accounted_cb', 'created_by', 'last_update_by', 'company_id'], 'integer'], [['quantity', 'amount'], 'number'], [['creation_date', 'last_update_date'], 'safe'], [['description'], 'string', 'max' => 256], [['status'], 'string', 'max' => 25], [['reference'], 'string', 'max' => 50], [['fa_asset_id'], 'unique'], [['transaction_type_id'], 'unique'], [['fa_asset_id', 'quantity'], 'unique', 'targetAttribute' => ['fa_asset_id', 'quantity'], 'message' => 'The combination of Fa Asset ID and Quantity has already been taken.'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'fa_asset_trasaction_id' => Yii::t('app', 'Fa Asset Trasaction ID'), 'fa_asset_id' => Yii::t('app', 'Fa Asset ID'), 'transaction_type_id' => Yii::t('app', 'Transaction Type ID'), 'quantity' => Yii::t('app', 'Quantity'), 'amount' => Yii::t('app', 'Amount'), 'description' => Yii::t('app', 'Description'), 'status' => Yii::t('app', 'Status'), 'reference' => Yii::t('app', 'Reference'), 'accounted_cb' => Yii::t('app', 'Accounted Cb'), 'created_by' => Yii::t('app', 'Created By'), 'creation_date' => Yii::t('app', 'Creation Date'), 'last_update_by' => Yii::t('app', 'Last Update By'), 'last_update_date' => Yii::t('app', 'Last Update Date'), 'company_id' => Yii::t('app', 'Company ID'), ]; } }
zeddarn/yinoerp
_protected/common/modules/fa/models/FaAssetTrasaction.php
PHP
gpl-3.0
2,611
using UnityEngine; public class PauseMenuHandler : MonoBehaviour { public void ResumeGame() { MenuSystem.instance.ResumeGame(); } public void AbortGame() { MenuSystem.instance.AbortGame(); } }
Rezmason/Gamut
Assets/UI Scripts/PauseMenuHandler.cs
C#
gpl-3.0
199
<?php /* P2P Food Lab P2P Food Lab is an open, collaborative platform to develop an alternative food value system. Copyright (C) 2013 Sony Computer Science Laboratory Paris Author: Peter Hanappe 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/>. */ if (1) { $osd = new OpenSensorData(null, null, null); $start_timestamp = date("U"); $end_timestamp = 0; $datastreams = $this->group->datastreams; for ($j = 0; $j < count($datastreams); $j++) { $datastream = $datastreams[$j]; if (isset($this->datastreams[$datastream->id])) { $interval = $osd->get_datastream_interval($datastream->id); if ($interval && (count($interval) >= 2)) { $s = strtotime($interval[0]); $e = strtotime($interval[1]); //echo "datastream " . $datastream->id . ": start " . date("Y-m-d H:i:s", $s) . ", end " . date("Y-m-d H:i:s", $e) . "<br>\n"; if ($s < $start_timestamp) $start_timestamp = $s; if ($e > $end_timestamp) $end_timestamp = $e; } } } $start_year = date("Y", $start_timestamp); $start_month = date("m", $start_timestamp); $start_day = date("d", $start_timestamp); $end_year = date("Y", $end_timestamp); $end_month = date("m", $end_timestamp); $end_day = date("d", $end_timestamp); } else { $start_year = date("Y"); $start_month = date("m"); $start_day = 1; $end_year = $start_year; $end_month = $start_month; $end_day = date("d"); } $start_date = sprintf("%04d-%02d-%02d", $start_year, $start_month, $start_day); $start_date_js = sprintf('%04d,%02d,%02d', $start_year, ($start_month-1), $start_day); $end_date = sprintf("%04d-%02d-%02d", $end_year, $end_month, $end_day); $end_date_js = sprintf('%04d,%02d,%02d', $end_year, ($end_month-1), $end_day); $range = sprintf("%04d%02d%02d/%04d%02d%02d", $start_year, $start_month, $start_day, $end_year, $end_month, $end_day); ?> <script type="text/javascript"> var startDate = new Date(<?php echo $start_date_js ?>); var endDate = new Date(<?php echo $end_date_js ?>); <?php echo "var graphs = []\n"; echo "var slideshows = []\n"; echo "var blockRedraw = false;\n"; echo "var datastreams = [ "; $n = 0; $datastreams = $this->group->datastreams; for ($j = 0; $j < count($datastreams); $j++) { $datastream = $datastreams[$j]; if (isset($this->datastreams[$datastream->id])) { if ($n > 0) echo ", "; echo $datastream->id; $n++; } } echo " ];\n"; $photostreams = $this->group->photostreams; echo "var photostreams = [ "; $n = 0; for ($j = 0; $j < count($photostreams); $j++) { $photostream = $photostreams[$j]; if ($n > 0) echo ", "; echo $photostream->id; $n++; } echo " ];\n"; ?> var timer = null; var updating = false; var osd = new OpenSensorData("<?php echo $base_url ?>/opensensordata", null); function twoDigits(n) { if (n < 10) return "0" + n; else return "" + n; } function formatDate(d) { return ("" + d.getFullYear() + twoDigits(1 + d.getMonth()) + twoDigits(d.getDate())); } function formatDate2(d) { return ("" + d.getFullYear() + "-" + twoDigits(1 + d.getMonth()) + "-" + twoDigits(d.getDate())); } function checkUpdating() { if (!updating) return; for (i = 0; i < datastreams.length; i++) if (graphs[i].updating) return; for (i = 0; i < photostreams.length; i++) if (slideshows[i].updating) return; updating = false; for (i = 0; i < datastreams.length; i++) { if (graphs[i].numRows() > 0) graphs[i].resetZoom(); } } function updateDatasets() { var range = formatDate(startDate) + "/" + formatDate(endDate); //var d = formatDate(endDate); if (updating) return; updating = true; for (i = 0; i < datastreams.length; i++) { var path = ("filter/" + datastreams[i] + "/" + range + ".json"); //var path = ("datapoints/" + datastreams[i] + "/" + range + ".json"); //var path = ("filter/" + datastreams[i] + "/" + d + ".json"); var updater = { "graph": graphs[i], "callback": function(me, data) { //alert(data); me.graph.updateOptions({ "file": data, "customBars": true, "errorBars": true }); me.graph.updating = false; checkUpdating(); } }; graphs[i].updating = true; osd.getdata(path, updater, updater.callback); } for (i = 0; i < photostreams.length; i++) { var path = ("photos/" + photostreams[i] + "/" + range + ".json"); //var path = ("photos/" + photostreams[i] + "/" + d + ".json"); var updater = { "slideshow": slideshows[i], "callback": function(me, data) { me.slideshow.setPhotos(data); me.slideshow.updating = false; checkUpdating(); } }; slideshows[i].updating = true; osd.get(path, updater, updater.callback); } } function changeStartDate(calendar, date) { var div = document.getElementById("startDate"); div.innerHTML = formatDate2(calendar.date); startDate = calendar.date; if (timer != null) { clearTimeout(timer); timer = null; } timer = setTimeout(updateDatasets, 2000); } function changeEndDate(calendar, date) { var div = document.getElementById("endDate"); div.innerHTML = formatDate2(calendar.date); endDate = calendar.date; if (timer != null) { clearTimeout(timer); timer = null; } timer = setTimeout(updateDatasets, 2000); } </script> <?php $this->host->load_sensorboxes(); if ($this->errmsg) { ?> <div class="strip"> <div class="content_box frame"> <div class="margin"> <?php echo $this->errmsg; ?> </div> </div> </div> <?php } else if (($this->visitor != NULL) && ($this->host != NULL) && ($this->visitor->id == $this->host->id) && (count($this->host->sensorbox) <= 0)) { echo " COUNT " . count($host->sensorbox) . "\n"; echo " <div class=\"strip\">\n"; echo " <div class=\"content_box frame margin\">\n"; echo " " . _s("For more information about this section, check out the help section") . " (<a href=\"" . url_s('help#sensorbox') . "\">" . _s("here") . "</a>).\n"; echo " </div>\n"; echo " </div>\n"; } else { ?> <div class="strip"> <div class="content_box frame margin"> <?php echo $this->group->name; if (isset($this->group->description) && (strlen($this->group->description) > 0)) { echo ": " . $this->group->description; } ?> </div> </div> <div class="strip"> <div class="content_box frame"> <div class="datepicker margin"> <? /* <?php _p("show data of") ?> <a href="javascript:void(0);" id="endDate" class="date"><?php _p("today") ?></a>. */ ?> <?php _p("show data from") ?> <a href="javascript:void(0);" id="startDate" class="date"><?php echo $start_date ?></a> <?php _p("to") ?> <a href="javascript:void(0);" id="endDate" class="date"><?php echo $end_date ?></a>. <script type="text/javascript"> Calendar.setup( { dateField: 'startDate', triggerElement: 'startDate', selectHandler: changeStartDate } ); <? /**/ ?> Calendar.setup( { dateField: 'endDate', triggerElement: 'endDate', selectHandler: changeEndDate } ); </script> </div> </div> </div> <?php /* if ($this->group->app != $osd_appid) */ /* continue; */ for ($j = 0; $j < count($photostreams); $j++) { $photostream = $photostreams[$j]; $id = 'photostream_' . $photostream->id; $path = "photos/" . $photostream->id . "/$range.json"; ?> <div class="strip"> <div class="content_box frame centered"> <div id="<?php echo $id ?>" class="photostreamviewer"></div> <script type="text/javascript"> var slideshow = new Photostream("<?php echo $id ?>", [], "http://opensensordata.net", ".jpg", 575, 530); slideshows.push(slideshow); </script> </div> </div> <?php } for ($j = 0; $j < count($datastreams); $j++) { $datastream = $datastreams[$j]; if (isset($this->datastreams[$datastream->id])) { $id = 'datastream_' . $datastream->id; ?> <div class="strip"> <div class="content_box frame centered datastreamviewer"> <?php echo "$datastream->name\n" ?> <div id="<?php echo $id ?>" class="datastream margin"></div> <script type="text/javascript"> var graph = new Dygraph(document.getElementById("<?php echo $id ?>"), [], { labels: [ "Date", "<?php echo $datastream->unit ?>" ], includeZero: true, showRangeSelector: false, customBars: true, errorBars: true, drawCallback: function(me, initial) { if (blockRedraw || initial) return; blockRedraw = true; var range = me.xAxisRange(); for (var j = 0; j < graphs.length; j++) { if (graphs[j] == me) continue; graphs[j].updateOptions( { dateWindow: range } ); } blockRedraw = false; } } ); graphs.push(graph); </script> </div> </div> <?php } } } ?> <script type="text/javascript"> updateDatasets(); </script>
hanappe/p2pfoodlab
https/dataset.view.php
PHP
gpl-3.0
12,733
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2019 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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 <https://www.gnu.org/licenses/>. # from __future__ import unicode_literals import gettext import re from collections import defaultdict from itertools import chain from appconf import AppConf from django.conf import settings from django.db import models, transaction from django.db.models import Q from django.db.utils import OperationalError from django.urls import reverse from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.functional import cached_property from django.utils.safestring import mark_safe from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext as _ from django.utils.translation import ugettext_lazy from weblate.lang import data from weblate.langdata import languages from weblate.logger import LOGGER from weblate.trans.util import sort_objects from weblate.utils.stats import LanguageStats from weblate.utils.validators import validate_pluraleq PLURAL_RE = re.compile( r'\s*nplurals\s*=\s*([0-9]+)\s*;\s*plural\s*=\s*([()n0-9!=|&<>+*/%\s?:-]+)' ) PLURAL_TITLE = ''' {name} <i class="fa fa-question-circle text-primary" title="{examples}"></i> ''' COPY_RE = re.compile(r'\([0-9]+\)') def get_plural_type(base_code, pluralequation): """Get correct plural type for language.""" # Remove not needed parenthesis if pluralequation[-1] == ';': pluralequation = pluralequation[:-1] # No plural if pluralequation == '0': return data.PLURAL_NONE # Standard plural equations for mapping in data.PLURAL_MAPPINGS: if pluralequation in mapping[0]: return mapping[1] # Arabic special case if base_code in ('ar',): return data.PLURAL_ARABIC # Log error in case of uknown mapping LOGGER.error( 'Can not guess type of plural for %s: %s', base_code, pluralequation ) return data.PLURAL_UNKNOWN def get_english_lang(): """Return object ID for English language""" try: return Language.objects.get_default().id except (Language.DoesNotExist, OperationalError): return 65535 class LanguageQuerySet(models.QuerySet): # pylint: disable=no-init def get_default(self): """Return default source language object.""" return self.get(code='en') def try_get(self, *args, **kwargs): """Try to get language by code.""" try: return self.get(*args, **kwargs) except (Language.DoesNotExist, Language.MultipleObjectsReturned): return None def parse_lang_country(self, code): """Parse language and country from locale code.""" # Parse private use subtag subtag_pos = code.find('-x-') if subtag_pos != -1: subtag = code[subtag_pos:] code = code[:subtag_pos] else: subtag = '' # Parse the string if '-' in code: lang, country = code.split('-', 1) # Android regional locales if len(country) > 2 and country[0] == 'r': country = country[1:] elif '_' in code: lang, country = code.split('_', 1) elif '+' in code: lang, country = code.split('+', 1) else: lang = code country = None return lang, country, subtag @staticmethod def sanitize_code(code): """Language code sanitization.""" # Strip b+ prefix from Android if code.startswith('b+'): code = code[2:] # Handle duplicate language files eg. "cs (2)" code = COPY_RE.sub('', code) # Remove some unwanted characters code = code.replace(' ', '').replace('(', '').replace(')', '') # Strip leading and trailing . code = code.strip('.') return code def aliases_get(self, code): code = code.lower() codes = ( code, code.replace('+', '_'), code.replace('-', '_'), code.replace('-r', '_'), code.replace('_r', '_') ) for newcode in codes: if newcode in languages.ALIASES: newcode = languages.ALIASES[newcode] ret = self.try_get(code=newcode) if ret is not None: return ret return None def fuzzy_get(self, code, strict=False): """Get matching language for code (the code does not have to be exactly same, cs_CZ is same as cs-CZ) or returns None It also handles Android special naming of regional locales like pt-rBR """ code = self.sanitize_code(code) lookups = [ # First try getting language as is Q(code__iexact=code), # Replace dash with underscore (for things as zh_Hant) Q(code__iexact=code.replace('-', '_')), # Try using name Q(name__iexact=code), ] for lookup in lookups: # First try getting language as is ret = self.try_get(lookup) if ret is not None: return ret # Handle aliases ret = self.aliases_get(code) if ret is not None: return ret # Parse the string lang, country, subtags = self.parse_lang_country(code) # Try "corrected" code if country is not None: if '@' in country: region, variant = country.split('@', 1) country = '{0}@{1}'.format(region.upper(), variant.lower()) elif '_' in country: # Xliff way of defining variants region, variant = country.split('_', 1) country = '{0}@{1}'.format(region.upper(), variant.lower()) else: country = country.upper() newcode = '{0}_{1}'.format(lang.lower(), country) else: newcode = lang.lower() if subtags: newcode += subtags ret = self.try_get(code__iexact=newcode) if ret is not None: return ret # Try canonical variant if (settings.SIMPLIFY_LANGUAGES and newcode.lower() in data.DEFAULT_LANGS): ret = self.try_get(code=lang.lower()) if ret is not None: return ret return None if strict else newcode def auto_get_or_create(self, code, create=True): """Try to get language using fuzzy_get and create it if that fails.""" ret = self.fuzzy_get(code) if isinstance(ret, Language): return ret # Create new one return self.auto_create(ret, create) def auto_create(self, code, create=True): """Automatically create new language based on code and best guess of parameters. """ # Create standard language name = '{0} (generated)'.format(code) if create: lang = self.get_or_create( code=code, defaults={'name': name}, )[0] else: lang = Language(code=code, name=name) baselang = None # Check for different variant if baselang is None and '@' in code: parts = code.split('@') baselang = self.fuzzy_get(code=parts[0], strict=True) # Check for different country if baselang is None and '_' in code or '-' in code: parts = code.replace('-', '_').split('_') baselang = self.fuzzy_get(code=parts[0], strict=True) if baselang is not None: lang.name = baselang.name lang.direction = baselang.direction if create: lang.save() baseplural = baselang.plural lang.plural_set.create( source=Plural.SOURCE_DEFAULT, number=baseplural.number, equation=baseplural.equation, ) elif create: lang.plural_set.create( source=Plural.SOURCE_DEFAULT, number=2, equation='n != 1', ) return lang def setup(self, update): """Create basic set of languages based on languages defined in the languages-data repo. """ # Create Weblate languages for code, name, nplurals, pluraleq in languages.LANGUAGES: lang, created = self.get_or_create( code=code, defaults={'name': name} ) # Get plural type plural_type = get_plural_type(lang.base_code, pluraleq) # Should we update existing? if update: lang.name = name lang.save() plural_data = { 'type': plural_type, 'number': nplurals, 'equation': pluraleq, } try: plural, created = lang.plural_set.get_or_create( source=Plural.SOURCE_DEFAULT, language=lang, defaults=plural_data, ) if not created: modified = False for item in plural_data: if getattr(plural, item) != plural_data[item]: modified = True setattr(plural, item, plural_data[item]) if modified: plural.save() except Plural.MultipleObjectsReturned: continue # Create addditiona plurals for code, _unused, nplurals, pluraleq in languages.EXTRAPLURALS: lang = self.get(code=code) # Get plural type plural_type = get_plural_type(lang.base_code, pluraleq) plural_data = { 'type': plural_type, } plural, created = lang.plural_set.get_or_create( source=Plural.SOURCE_GETTEXT, language=lang, number=nplurals, equation=pluraleq, defaults=plural_data, ) if not created: modified = False for item in plural_data: if getattr(plural, item) != plural_data[item]: modified = True setattr(plural, item, plural_data[item]) if modified: plural.save() def have_translation(self): """Return list of languages which have at least one translation.""" return self.filter(translation__pk__gt=0).distinct().order() def order(self): return self.order_by('name') def order_translated(self): return sort_objects(self) def setup_lang(sender, **kwargs): """Hook for creating basic set of languages on database migration.""" with transaction.atomic(): Language.objects.setup(False) @python_2_unicode_compatible class Language(models.Model): code = models.SlugField( unique=True, verbose_name=ugettext_lazy('Language code'), ) name = models.CharField( max_length=100, verbose_name=ugettext_lazy('Language name'), ) direction = models.CharField( verbose_name=ugettext_lazy('Text direction'), max_length=3, default='ltr', choices=( ('ltr', ugettext_lazy('Left to right')), ('rtl', ugettext_lazy('Right to left')) ), ) objects = LanguageQuerySet.as_manager() class Meta(object): verbose_name = ugettext_lazy('Language') verbose_name_plural = ugettext_lazy('Languages') def __init__(self, *args, **kwargs): """Constructor to initialize some cache properties.""" super(Language, self).__init__(*args, **kwargs) self._plural_examples = {} self.stats = LanguageStats(self) def __str__(self): if self.show_language_code: return '{0} ({1})'.format( _(self.name), self.code ) return _(self.name) @property def show_language_code(self): return self.code not in data.NO_CODE_LANGUAGES def get_absolute_url(self): return reverse('show_language', kwargs={'lang': self.code}) def get_html(self): """Return html attributes for markup in this language, includes language and direction. """ return mark_safe( 'lang="{0}" dir="{1}"'.format(self.code, self.direction) ) def save(self, *args, **kwargs): """Set default direction for language.""" if self.base_code in data.RTL_LANGS: self.direction = 'rtl' else: self.direction = 'ltr' return super(Language, self).save(*args, **kwargs) @cached_property def base_code(self): return self.code.replace('_', '-').split('-')[0] def uses_ngram(self): return self.base_code in ('ja', 'zh', 'ko') @cached_property def plural(self): return self.plural_set.filter(source=Plural.SOURCE_DEFAULT)[0] class PluralQuerySet(models.QuerySet): def order(self): return self.order_by('source') @python_2_unicode_compatible class Plural(models.Model): PLURAL_CHOICES = ( ( data.PLURAL_NONE, pgettext_lazy('Plural type', 'None') ), ( data.PLURAL_ONE_OTHER, pgettext_lazy('Plural type', 'One/other (classic plural)') ), ( data.PLURAL_ONE_FEW_OTHER, pgettext_lazy('Plural type', 'One/few/other (Slavic languages)') ), ( data.PLURAL_ARABIC, pgettext_lazy('Plural type', 'Arabic languages') ), ( data.PLURAL_ZERO_ONE_OTHER, pgettext_lazy('Plural type', 'Zero/one/other') ), ( data.PLURAL_ONE_TWO_OTHER, pgettext_lazy('Plural type', 'One/two/other') ), ( data.PLURAL_ONE_OTHER_TWO, pgettext_lazy('Plural type', 'One/other/two') ), ( data.PLURAL_ONE_TWO_FEW_OTHER, pgettext_lazy('Plural type', 'One/two/few/other') ), ( data.PLURAL_OTHER_ONE_TWO_FEW, pgettext_lazy('Plural type', 'Other/one/two/few') ), ( data.PLURAL_ONE_TWO_THREE_OTHER, pgettext_lazy('Plural type', 'One/two/three/other') ), ( data.PLURAL_ONE_OTHER_ZERO, pgettext_lazy('Plural type', 'One/other/zero') ), ( data.PLURAL_ONE_FEW_MANY_OTHER, pgettext_lazy('Plural type', 'One/few/many/other') ), ( data.PLURAL_TWO_OTHER, pgettext_lazy('Plural type', 'Two/other') ), ( data.PLURAL_ONE_TWO_FEW_MANY_OTHER, pgettext_lazy('Plural type', 'One/two/few/many/other') ), ( data.PLURAL_UNKNOWN, pgettext_lazy('Plural type', 'Unknown') ), ( data.PLURAL_ZERO_ONE_TWO_THREE_SIX_OTHER, pgettext_lazy('Plural type', 'Zero/one/two/three/six/other') ), ) SOURCE_DEFAULT = 0 SOURCE_GETTEXT = 1 SOURCE_MANUAL = 2 source = models.SmallIntegerField( default=SOURCE_DEFAULT, verbose_name=ugettext_lazy('Plural definition source'), choices=( (SOURCE_DEFAULT, ugettext_lazy('Default plural')), (SOURCE_GETTEXT, ugettext_lazy('Plural gettext formula')), (SOURCE_MANUAL, ugettext_lazy('Manually entered formula')), ), ) number = models.SmallIntegerField( default=2, verbose_name=ugettext_lazy('Number of plurals'), ) equation = models.CharField( max_length=400, default='n != 1', validators=[validate_pluraleq], blank=False, verbose_name=ugettext_lazy('Plural equation'), ) type = models.IntegerField( choices=PLURAL_CHOICES, default=data.PLURAL_ONE_OTHER, verbose_name=ugettext_lazy('Plural type'), editable=False, ) language = models.ForeignKey(Language, on_delete=models.deletion.CASCADE) objects = PluralQuerySet.as_manager() class Meta(object): verbose_name = ugettext_lazy('Plural form') verbose_name_plural = ugettext_lazy('Plural forms') def __str__(self): return self.get_type_display() @cached_property def plural_form(self): return 'nplurals={0:d}; plural={1};'.format( self.number, self.equation ) @cached_property def plural_function(self): return gettext.c2py( self.equation if self.equation else '0' ) @cached_property def examples(self): result = defaultdict(list) func = self.plural_function for i in chain(range(0, 10000), range(10000, 2000001, 1000)): ret = func(i) if len(result[ret]) >= 10: continue result[ret].append(str(i)) return result @staticmethod def parse_formula(plurals): matches = PLURAL_RE.match(plurals) if matches is None: raise ValueError('Failed to parse formula') number = int(matches.group(1)) formula = matches.group(2) if not formula: formula = '0' # Try to parse the formula gettext.c2py(formula) return number, formula def same_plural(self, number, equation): """Compare whether given plurals formula matches""" if number != self.number or not equation: return False # Convert formulas to functions ours = self.plural_function theirs = gettext.c2py(equation) # Compare equation results # It would be better to compare formulas, # but this was easier to implement and the performance # is still okay. for i in range(-10, 200): if ours(i) != theirs(i): return False return True def get_plural_label(self, idx): """Return label for plural form.""" return PLURAL_TITLE.format( name=self.get_plural_name(idx), # Translators: Label for plurals with example counts examples=_('For example: {0}').format( ', '.join(self.examples.get(idx, [])) ) ) def get_plural_name(self, idx): """Return name for plural form.""" try: return force_text(data.PLURAL_NAMES[self.type][idx]) except (IndexError, KeyError): if idx == 0: return _('Singular') if idx == 1: return _('Plural') return _('Plural form %d') % idx def list_plurals(self): for i in range(self.number): yield { 'index': i, 'name': self.get_plural_name(i), 'examples': ', '.join(self.examples.get(i, [])) } def save(self, *args, **kwargs): self.type = get_plural_type(self.language.base_code, self.equation) # Try to calculate based on equation if self.type == data.PLURAL_UNKNOWN: for equations, plural in data.PLURAL_MAPPINGS: for equation in equations: if self.same_plural(self.number, equation): self.type = plural break if self.type != data.PLURAL_UNKNOWN: break super(Plural, self).save(*args, **kwargs) def get_absolute_url(self): return '{}#information'.format( reverse('show_language', kwargs={'lang': self.language.code}) ) class WeblateLanguagesConf(AppConf): """Languages settings.""" # Use simple language codes for default language/country combinations SIMPLIFY_LANGUAGES = True class Meta(object): prefix = ''
dontnod/weblate
weblate/lang/models.py
Python
gpl-3.0
20,870
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * 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/>. */ /* $Id:$ */ package com.aurel.track.beans.base; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Connection; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import com.aurel.track.beans.*; /** * Hierarchical categorization of the queries * * You should not use this class directly. It should not even be * extended; all references should be to TFilterCategoryBean */ public abstract class BaseTFilterCategoryBean implements Serializable { /** * whether the bean or its underlying object has changed * since last reading from the database */ private boolean modified = true; /** * false if the underlying object has been read from the database, * true otherwise */ private boolean isNew = true; /** The value for the objectID field */ private Integer objectID; /** The value for the label field */ private String label; /** The value for the repository field */ private Integer repository; /** The value for the filterType field */ private Integer filterType; /** The value for the createdBy field */ private Integer createdBy; /** The value for the project field */ private Integer project; /** The value for the parentID field */ private Integer parentID; /** The value for the sortorder field */ private Integer sortorder; /** The value for the uuid field */ private String uuid; /** * sets whether the bean exists in the database */ public void setNew(boolean isNew) { this.isNew = isNew; } /** * returns whether the bean exists in the database */ public boolean isNew() { return this.isNew; } /** * sets whether the bean or the object it was created from * was modified since the object was last read from the database */ public void setModified(boolean isModified) { this.modified = isModified; } /** * returns whether the bean or the object it was created from * was modified since the object was last read from the database */ public boolean isModified() { return this.modified; } /** * Get the ObjectID * * @return Integer */ public Integer getObjectID () { return objectID; } /** * Set the value of ObjectID * * @param v new value */ public void setObjectID(Integer v) { this.objectID = v; setModified(true); } /** * Get the Label * * @return String */ public String getLabel () { return label; } /** * Set the value of Label * * @param v new value */ public void setLabel(String v) { this.label = v; setModified(true); } /** * Get the Repository * * @return Integer */ public Integer getRepository () { return repository; } /** * Set the value of Repository * * @param v new value */ public void setRepository(Integer v) { this.repository = v; setModified(true); } /** * Get the FilterType * * @return Integer */ public Integer getFilterType () { return filterType; } /** * Set the value of FilterType * * @param v new value */ public void setFilterType(Integer v) { this.filterType = v; setModified(true); } /** * Get the CreatedBy * * @return Integer */ public Integer getCreatedBy () { return createdBy; } /** * Set the value of CreatedBy * * @param v new value */ public void setCreatedBy(Integer v) { this.createdBy = v; setModified(true); } /** * Get the Project * * @return Integer */ public Integer getProject () { return project; } /** * Set the value of Project * * @param v new value */ public void setProject(Integer v) { this.project = v; setModified(true); } /** * Get the ParentID * * @return Integer */ public Integer getParentID () { return parentID; } /** * Set the value of ParentID * * @param v new value */ public void setParentID(Integer v) { this.parentID = v; setModified(true); } /** * Get the Sortorder * * @return Integer */ public Integer getSortorder () { return sortorder; } /** * Set the value of Sortorder * * @param v new value */ public void setSortorder(Integer v) { this.sortorder = v; setModified(true); } /** * Get the Uuid * * @return String */ public String getUuid () { return uuid; } /** * Set the value of Uuid * * @param v new value */ public void setUuid(String v) { this.uuid = v; setModified(true); } private TProjectBean aTProjectBean; /** * sets an associated TProjectBean object * * @param v TProjectBean */ public void setTProjectBean(TProjectBean v) { if (v == null) { setProject((Integer) null); } else { setProject(v.getObjectID()); } aTProjectBean = v; } /** * Get the associated TProjectBean object * * @return the associated TProjectBean object */ public TProjectBean getTProjectBean() { return aTProjectBean; } private TPersonBean aTPersonBean; /** * sets an associated TPersonBean object * * @param v TPersonBean */ public void setTPersonBean(TPersonBean v) { if (v == null) { setCreatedBy((Integer) null); } else { setCreatedBy(v.getObjectID()); } aTPersonBean = v; } /** * Get the associated TPersonBean object * * @return the associated TPersonBean object */ public TPersonBean getTPersonBean() { return aTPersonBean; } private TFilterCategoryBean aTFilterCategoryBeanRelatedByParentID; /** * sets an associated TFilterCategoryBean object * * @param v TFilterCategoryBean */ public void setTFilterCategoryBeanRelatedByParentID(TFilterCategoryBean v) { if (v == null) { setParentID((Integer) null); } else { setParentID(v.getObjectID()); } aTFilterCategoryBeanRelatedByParentID = v; } /** * Get the associated TFilterCategoryBean object * * @return the associated TFilterCategoryBean object */ public TFilterCategoryBean getTFilterCategoryBeanRelatedByParentID() { return aTFilterCategoryBeanRelatedByParentID; } /** * Collection to store aggregation of collTQueryRepositoryBeans */ protected List<TQueryRepositoryBean> collTQueryRepositoryBeans; /** * Returns the collection of TQueryRepositoryBeans */ public List<TQueryRepositoryBean> getTQueryRepositoryBeans() { return collTQueryRepositoryBeans; } /** * Sets the collection of TQueryRepositoryBeans to the specified value */ public void setTQueryRepositoryBeans(List<TQueryRepositoryBean> list) { if (list == null) { collTQueryRepositoryBeans = null; } else { collTQueryRepositoryBeans = new ArrayList<TQueryRepositoryBean>(list); } } }
trackplus/Genji
src/main/java/com/aurel/track/beans/base/BaseTFilterCategoryBean.java
Java
gpl-3.0
8,748
// // Installs the bash completion script // // Load the needed modules var fs = require('fs'); var path = require('path'); // File name constants var BASH_COMPLETION = '/etc/bash_completion.d'; var COMPLETION = path.join(__dirname, '..', 'completion.sh'); // Make sure the bash completion directory exists path.exists(BASH_COMPLETION, function(exists) { if (exists) { fs.stat(BASH_COMPLETION, function(err, stats) { if (err) {fail();} if (stats.isDirectory()) { var cruxCompletion = path.join(BASH_COMPLETION, 'crux'); path.exists(cruxCompletion, function(exists) { if (! exists) { fs.symlink(COMPLETION, cruxCompletion, function(err) { if (err) {fail();} }); } }); } }); } }); // -------------------------------------------------------- // Fail with a standard error message function fail() { console.error([ 'Could not install bash completion. If your system supports this feature, it may', 'be a permissions error (are you using sudo?). You can try installing the bash', 'completion scripts later using `[sudo] npm run-script crux install -g`.' ].join('\n')); process.exit(0); } /* End of file bash-completion.js */
kbjr/node-crux
scripts/bash-completion.js
JavaScript
gpl-3.0
1,206
<?php /** * Minimum Order Fee extension * * NOTICE OF LICENSE * * This extension 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 extension 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 file. If not, see <http://www.gnu.org/licenses/>. * * @category UnleashedTech_MinOrderFee * @package UnleashedTech_MinOrderFee * @copyright Copyright (c) 2014 Unleashed Technologies, LLC. (http://www.unleashed-technologies.com) * @license https://www.gnu.org/licenses/gpl-3.0.txt */ class UnleashedTech_MinOrderFee_Block_Sales_Order_Totals extends Mage_Sales_Block_Order_Totals { protected function _initTotals() { parent::_initTotals(); $amount = $this->getSource()->getMinOrderFeeAmount(); $baseAmount = $this->getSource()->getBaseMinOrderFeeAmount(); if ($amount > 0) { $this->addTotal(new Varien_Object(array( 'code' => 'min_order_fee', 'value' => $amount, 'base_value'=> $baseAmount, 'label' => Mage::getStoreConfig('sales/minimum_order/small_order_fee_label', $this->getSource()->getStore()) )), 'tax'); } return $this; } }
unleashedtech/min-order-fee-magento
src/code/Block/Sales/Order/Totals.php
PHP
gpl-3.0
1,683
/* * 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/>. * * Copyright (C) 2016 Mark E. Wilson * */ #include <QGraphicsItem> #include <QGraphicsScene> #include <QGraphicsObject> #include <QPainter> #include <QColor> #include <QBrush> #include <QPen> #include <QRectF> #include <QPointF> #include <QDebug> #include <libavoid/router.h> #include <libavoid/shape.h> #include "shims.h" #include "rectangleshape.h" RectangleShape::RectangleShape(const QSize &size, Avoid::Router* router, QGraphicsItem *parent) : ShapeBase(router, parent), mRect(QRectF(0, 0, size.width(), size.height())), mBorder(0.0) { setFlag(QGraphicsItem::ItemIsMovable, true); setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true); setFlag(QGraphicsItem::ItemIsSelectable, true); Avoid::Rectangle rect = convertRectangle(mRect); mShapeRef = new Avoid::ShapeRef(mRouter, rect); mPin = new Avoid::ShapeConnectionPin(mShapeRef, 1, Avoid::ATTACH_POS_CENTRE, Avoid::ATTACH_POS_CENTRE, true, 0.0, Avoid::ConnDirAll); mConnEnd = new Avoid::ConnEnd(mShapeRef, 1); setZValue(1); } QRectF RectangleShape::boundingRect() const { return QRectF(mRect); } void RectangleShape::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); QPen usePen; QBrush useBrush; if ( isSelected() ) { usePen = QPen(mPen.brush(), mPen.widthF(), Qt::DashLine); useBrush = mBrush; } else { usePen = mPen; useBrush = mBrush; } painter->setPen(usePen); painter->setBrush(useBrush); painter->drawRect(mRect); } QVariant RectangleShape::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { if ( change == ItemPositionChange ) { QPointF newPos = value.toPointF(); QRectF sceneRect = scene()->sceneRect(); qreal checkX, checkY; checkX = sceneRect.right() - mRect.width() - mBorder; checkY = sceneRect.bottom() - mRect.height() - mBorder; if ( newPos.x() > checkX ) newPos.setX(checkX); else if ( newPos.x() < sceneRect.left() + mBorder ) newPos.setX(mRect.left() + mBorder); if ( newPos.y() > checkY ) newPos.setY(checkY); else if ( newPos.y() < sceneRect.top() + mBorder ) newPos.setY(mRect.top() + mBorder); //qDebug() << "itemChange newPos:" << newPos; Avoid::Rectangle newAvoidRect = convertRectangle(QRectF(newPos.x(), newPos.y(), mRect.width(), mRect.height())); mRouter->moveShape(mShapeRef, newAvoidRect); mRouter->processTransaction(); emit shapeMoved(); return newPos; } return QGraphicsObject::itemChange(change, value); } int RectangleShape::type() const { return Type; } #if 0 void MyRectangleItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent) { qDebug() << "DOUBLE CLICK"; } void MyRectangleItem::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent) { qDebug() << "Mouse MOVE"; QGraphicsItem::mouseMoveEvent(mouseEvent); } void MyRectangleItem::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) { QGraphicsItem::mousePressEvent(mouseEvent); } void MyRectangleItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent) { QGraphicsItem::mouseReleaseEvent(mouseEvent); } #endif
MarkVTech/DiagramExample
rectangleshape.cpp
C++
gpl-3.0
4,247
package cn.ac.rcpa.bio.proteomics.utils; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptide; import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptideHit; import cn.ac.rcpa.bio.proteomics.comparison.IdentifiedPeptideComparator; import cn.ac.rcpa.bio.utils.IsoelectricPointCalculator; import cn.ac.rcpa.filter.IFilter; public class PeptideUtils { private PeptideUtils() { } private static Pattern pureSeqPattern; private static Pattern getPureSeqPattern() { if (pureSeqPattern == null) { pureSeqPattern = Pattern.compile("\\S\\.(\\S+)\\.\\S*"); } return pureSeqPattern; } public static String removeModification(String sequence) { StringBuilder result = new StringBuilder(); for (int i = 0; i < sequence.length(); i++) { char c = sequence.charAt(i); if ('-' == c || '.' == c || (c >= 'A' && c <= 'Z')) { result.append(c); } } return result.toString(); } public static String getMatchPeptideSequence(String sequence) { Matcher matcher = getPureSeqPattern().matcher(sequence); if (matcher.find()) { return matcher.group(1); } else { return sequence; } } public static String getPurePeptideSequence(String sequence) { String tmpPureSequence = getMatchPeptideSequence(sequence); StringBuffer result = new StringBuffer(); for (int i = 0; i < tmpPureSequence.length(); i++) { if (tmpPureSequence.charAt(i) >= 'A' && tmpPureSequence.charAt(i) <= 'Z') { result.append(tmpPureSequence.charAt(i)); } } return result.toString(); } /** * Get peptide sequence whose modification site corresponding to assigned * modifiedAminoacids will be set as '*' and other modification site will be * removed * * @param sequence * String * @param modifiedAminoacids * String * @return String */ public static String getSpecialModifiedPeptideSequence(String sequence, String modifiedAminoacids) { final String matchSequence = getMatchPeptideSequence(sequence); StringBuffer sb = new StringBuffer(); for (int i = 0; i < matchSequence.length(); i++) { if (Character.isLetter(matchSequence.charAt(i))) { sb.append(matchSequence.charAt(i)); } else if (sb.length() > 0 && modifiedAminoacids.indexOf(sb.charAt(sb.length() - 1)) != -1) { sb.append('*'); } } return sb.toString(); } public static double getPeptidePI(String sequence) { String pureSeq = getPurePeptideSequence(sequence); return IsoelectricPointCalculator.getPI(pureSeq); } public static boolean isModified(String sequence) { final String matchSequence = getMatchPeptideSequence(sequence); for (int j = 0; j < matchSequence.length(); j++) { final char aa = matchSequence.charAt(j); if ((aa >= 'A' && aa <= 'Z') || (aa >= 'a' && aa <= 'z')) { continue; } return true; } return false; } public static <E extends IIdentifiedPeptide, F extends IIdentifiedPeptideHit<E>> Map<String, List<E>> getScanPeptideMap( List<F> peptides) { Map<String, List<E>> result = new HashMap<String, List<E>>(); for (F peptide : peptides) { String experimentFilename = peptide.getPeakListInfo().getExperiment() + "." + peptide.getPeakListInfo().getFirstScan() + "." + peptide.getPeakListInfo().getLastScan() + "." + peptide.getPeakListInfo().getCharge(); result.put(experimentFilename, new ArrayList<E>(peptide.getPeptides())); } return result; } /** * ÒòΪIdentifiedPeptideÁбíÖУ¬»áÓжà¸öscan¼ø¶¨µ½Í¬Ò»¸öëĶΡ£ ¸Ãº¯ÊýÊÇÖ»±£Áôͬһ¸öëĶζÔÓ¦µÄÒ»¸öscan£¬ÒÔ±ãͳ¼Æ¡£ÕâÀȥ³ý * Ò»¸öscan¶ÔÓ¦µÄ¶à¸öëĶβ»ÄÜÓÃgetUnduplicatedPeptides·½Ê½¡£ * ÒòΪ¿ÉÄÜ»áÓÐscan_A¶ÔÓ¦ëĶÎX,Y£¬scan_BÖ»¶ÔÓ¦Y£¬ÕâÀXºÍYÍùÍù * Ö»ÊÇQºÍKµÄ²î±ð¡£Ëùνscan_BÖ»¶ÔÓ¦Y£¬ÊÂʵÉÏXÊÇÅÅÃûµÚ¶þ룬µ«¼ÆËã * DeltaCnʱ£¬¿¼ÂǵÄÊǵÚÒ»ºÍµÚÈýµÄDeltaCn£¬X±»ºöÂÔ¡£¶ÔÓÚunique * ëĶΣ¬Ó¦¸ÃÖ»±£ÁôY¡£Èô°´ÕÕgetUnduplicatedPeptides£¬Ôòscan_A ¶ÔÓ¦X£¬scan_B¶ÔÓ¦Y£¬¾ÍÊÇÁ½¸öunique * peptideÁË¡£ * * ÕâÀÎÒÃDzÉÓ÷½Ê½ÊÇ£¬ÏȰÑËùÓÐscan¶ÔÓ¦µÄpeptide¾ÛÔÚÒ»Æð¡£È»ºó¸ù¾Ý * ëĶÎÐòÁжÔscan½øÐÐmap£¬ÓÅÏȱ£ÁôÒ»¸öscan¶ÔÓ¦¶à¸öpeptideµÄ½á¹û¡£Õâ * Ñù£¬ÐòÁÐXºÍY¶¼»á¶ÔÓ¦µ½scan_AÉÏ£¬¶ø²»ÊÇscan_BÉÏ£¬¼´Ê¹scan_B³öÏÖÔÚ scan_AÇ°Ãæ¡£×îºó£¬Ã¿¸öscanÖ»±£ÁôÒ»¸öpeptide¡£ * * @param peptides * List * @return List */ public static <E extends IIdentifiedPeptide, F extends IIdentifiedPeptideHit<E>> List<E> getUniquePeptides( List<F> peptides) { final Map<String, List<E>> map = getScanPeptideMap(peptides); final Map<String, List<E>> sequencePeptideMap = new HashMap<String, List<E>>(); for (List<E> pepList : map.values()) { if (pepList.size() == 1 && sequencePeptideMap.containsKey(pepList.get(0).getSequence())) { continue; } for (E peptide : pepList) { sequencePeptideMap.put(peptide.getSequence(), pepList); } } ArrayList<E> result = new ArrayList<E>(); final Set<List<E>> pepSet = new HashSet<List<E>>(sequencePeptideMap .values()); for (List<E> pepList : pepSet) { result.add(pepList.get(0)); } Collections.sort(result, new IdentifiedPeptideComparator<E>()); return result; } public static <E extends IIdentifiedPeptide, F extends IIdentifiedPeptideHit<E>> List<E> getUnduplicatedPeptides( List<F> pephits) { ArrayList<E> result = new ArrayList<E>(); for (F pephit : pephits) { result.add(pephit.getPeptide(0)); } return result; } public static <E extends IIdentifiedPeptideHit> List<E> getSubset( List<E> source, IFilter<IIdentifiedPeptideHit> filter) { List<E> result = new ArrayList<E>(); for (E hit : source) { if (filter.accept(hit)) { result.add(hit); } } return result; } public static <E extends IIdentifiedPeptideHit> Set<String> getFilenames( List<E> pephits) { Set<String> result = new HashSet<String>(); for (E peptide : pephits) { result.add(peptide.getPeptide(0).getPeakListInfo().getLongFilename()); } return result; } public static boolean isModified(String matchPeptide, int index) { if (index < 0 || index >= matchPeptide.length()) { throw new IllegalArgumentException("Index " + index + " out of bound, peptide = " + matchPeptide); } return Character.isLetter(matchPeptide.charAt(index)) && (index < matchPeptide.length() - 1) && !Character.isLetter(matchPeptide.charAt(index + 1)); } public static void merge(String[] oldFilenames, String resultFilename) throws Exception { PrintWriter pw = new PrintWriter(resultFilename); try { boolean bFirst = true; for (String filename : oldFilenames) { BufferedReader br = new BufferedReader(new FileReader(filename)); String line = br.readLine(); if (bFirst) { pw.println(line); bFirst = false; } while ((line = br.readLine()) != null) { if (line.length() == 0) { break; } pw.println(line); } } } finally { pw.close(); } } }
shengqh/RcpaBioJava
src/cn/ac/rcpa/bio/proteomics/utils/PeptideUtils.java
Java
gpl-3.0
7,387
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SoftMod.Framework; using SoftMod.Framework.Solution; using SoftMod.Framework.Modules.Comparator; using SoftMod.Framework.RNG; namespace SoftMod.Framework.Modules.Operator { public class TournamentSelection : ModuleBase { /// <summary> /// Tournament selection module, provides ability to select individuals from a population, based upon dominance /// </summary> /// <summary> /// Constructor /// </summary> public TournamentSelection() { // Set tag name moduleType = "TournamentSelection"; // Initialise modules knowledge tome moduleTome = new Tome(moduleType); // Initialise is wrapped to false isWrapped = false; // Initialise default module parameters InitialiseModuleParameters(); } /// <summary> /// Execute modules specific behaviour /// </summary> public override void Execute() { /////////////////////////////////////////////////////////////////// ////////////////////// PATH 1 //////////////////// /////////////////////////////////////////////////////////////////// // Active Input Slots // Active Output Slots // Active Use Slots // //--------------------//---------------------//------------------// // Slot 1 // Slot 1 // - // /////////////////////////////////////////////////////////////////// if ((int)RequestTomeData("getExecutePath", null) == 1) { // Perform all functions associated with this path and the input, output and use module setup /////////////////////////////////////////////////////////////////////// //////////////////////////// SETUP DATA /////////////////////////// /////////////////////////////////////////////////////////////////////// // Setup local reference copies to input, and use data slot data // Set inputs ///////////////////////////////////////////////////////// // Set arguments object[] args = new object[1]; args[0] = 1; // Retrieve input slot 1 data object DataObject Input_1 = (DataObject)RequestTomeData("RequestInputData", args); // Set outputs //////////////////////////////////////////////////////// DataObject Output_1 = (DataObject)RequestTomeData("RequestOutputData", args); /////////////////////////////////////////////////////////////////////// ////////////////////// EXECUTE MAIN FUNCTION ////////////////////// /////////////////////////////////////////////////////////////////////// // Perform a binary tournament selection utilizing dominance by rank and crowding distance // Output data slot 1 holds altered data, clear all data Output_1.ClearDataCollection(); // Get tournament round count information int roundCount = (int)moduleTome.getModuleParameter("Rounds"); // Declare list to hold tournament selection round winners List<List<int>> tournamentSets = new List<List<int>>(); // Calculate the number of sets required double tournamentSetNumber = Math.Pow(2, roundCount - 1); // Get number of players for each initial tournament set int playerCount = (int)moduleTome.getModuleParameter("Player Count"); // Declare random number generator RandomNumberGenerator RNG = new RandomNumberGenerator(); // Loop through and fill output data object data collection to value of maxCount while (Output_1.getDataCollection().Count() < Output_1.MaxCount) { // Randomly select parents to fill our tournament list while (tournamentSets.Count < tournamentSetNumber) { // Fill initial tournament sets List<int> set = new List<int>(); // Loop and fill set while (set.Count < playerCount) { // Add random population member, do not allow duplicate parents in any one set (they can occur in other sets however) // Get population member index value int index = (int)RNG.NextDouble(0, Input_1.getDataCollection().Count); // Check set does not contain this parent index if (set.Contains(index)) { // Do nothing and pick again } else { set.Add(index); } } // Add set to collection tournamentSets.Add(set); } // Tournament is now set up run elimination over set number of rounds to get final single parent // Declare list to hold tournament selection root sets List<List<Root>> tournamentRootSets = new List<List<Root>>(); // Using tournament set information create a list with reference to each root member indexed foreach (List<int> set in tournamentSets) { // Declare list to hold actual root objects List<Root> rootSet = new List<Root>(); // loop through each set and get correct root object and pass to list foreach (int index in set) { // Using index get reference of root object and add to collection rootSet.Add(Input_1.getDataCollection()[index].CopyNode()); // <--- copy node, just in case in multiple sets two same parents are used and added to offspring later } // Add this set to collection tournamentRootSets.Add(rootSet); } // Clear tournament sets for selection tournamentSets.Clear(); // Declare ranking object Rank rank = new Rank(); // Declare rank comparator object RankComparator rankComparator = new RankComparator(); // Loop through each round for (int i = 0; i < roundCount; i++) { // Set temporary list to hold round winners List<Root> tempRoundRootWinners = new List<Root>(); // For each tournament set compare by rank and then if more then one winner crowding distance foreach (List<Root> set in tournamentRootSets) { // Rank set individuals rank.AssignRank(set); // Pass set to rank comparator and get set winners (non-dominated) List<Root> rankWinners = rankComparator.Compare(set); // Check whether this set has a count larger then 1 if (rankWinners.Count > 1) { // Then randomly pick a winner from the final set and pass to winners of this round tempRoundRootWinners.Add(rankWinners[(int)RNG.NextDouble(0, rankWinners.Count)]); } else { // Only one winner pass to next round tempRoundRootWinners.Add(rankWinners[0]); } } // Clear tournament root sets collection tournamentRootSets.Clear(); // Check if selection has drawn down to just one individual if (tempRoundRootWinners.Count == 1) { // Pass this individual to output data object Output_1.AddData(tempRoundRootWinners[0]); } else { // Update tournament root sets collection with new round sets while (tempRoundRootWinners.Count > 0) { // Create a new set list and add two winning individuals List<Root> set = new List<Root>(); // Add two winners and remove from collection set.Add(tempRoundRootWinners[0]); tempRoundRootWinners.RemoveAt(0); // Repeat set.Add(tempRoundRootWinners[0]); tempRoundRootWinners.RemoveAt(0); // Add new set to collection tournamentRootSets.Add(set); } } } } // Add output data to output data slot 1 moduleTome.AddOutputData(1, Output_1); } } /// <summary> /// Initialise module specific parameters, add to knowledge tome collection /// </summary> public override void InitialiseModuleParameters() { ////////////////////////////////////////////////////////////////////////// ///////////////////// SET DEFAULT PARAMETERS /////////////////// ////////////////////////////////////////////////////////////////////////// // Ranking and crowding selection is essentially tournament selection with the addition of crowding distance // Define variable to hold the number of individuals held in each tournament set, default is two int playerCount = 2; // Add to module tomes parameter collection moduleTome.AddModuleParameter("Player Count", playerCount); // Define variable to hold the number of rounds that tournament selection is to undergo, each round adds two more tournament sets int rounds = 1; // Add to module tomes parameter collection moduleTome.AddModuleParameter("Rounds", rounds); } } }
cdrwolfe/SoftMod
SoftMod.Framework/Modules/Operator/TournamentSelection.cs
C#
gpl-3.0
11,104
# -*- coding: utf-8 -*- """ HipparchiaServer: an interface to a database of Greek and Latin texts Copyright: E Gunderson 2016-21 License: GNU GENERAL PUBLIC LICENSE 3 (see LICENSE in the top level directory of the distribution) """ import re from collections import defaultdict try: from rich.progress import track except ImportError: track = None from server.formatting.miscformatting import timedecorator from server.formatting.wordformatting import stripaccents """ simple loaders called when HipparchiaServer launches these lists will contain (more or less...) globally available values the main point is to avoid constant calls to the DB for commonly used info """ def buildaugenresdict(authordict: dict) -> dict: """ build lists of author genres: [ g1, g2, ...] do this by corpus and tag it accordingly :param authordict: :return: """ gklist = list() ltlist = list() inlist = list() dplist = list() chlist = list() genresdict = {'gr': gklist, 'lt': ltlist, 'in': inlist, 'dp': dplist, 'ch': chlist} for a in authordict: if authordict[a].genres and authordict[a].genres != '': g = authordict[a].genres.split(',') l = authordict[a].universalid[0:2] genresdict[l] += g for l in ['gr', 'lt', 'in', 'dp', 'ch']: genresdict[l] = list(set(genresdict[l])) genresdict[l] = [re.sub(r'^\s|\s$', '', x) for x in genresdict[l]] genresdict[l].sort() return genresdict def buildworkgenresdict(workdict: dict) -> dict: """ load up the list of work genres: [ g1, g2, ...] this will see heavy use throughout the world of 'views.py' :param workdict: :return: """ gklist = list() ltlist = list() inlist = list() dplist = list() chlist = list() genresdict = {'gr': gklist, 'lt': ltlist, 'in': inlist, 'dp': dplist, 'ch': chlist} for w in workdict: if workdict[w].workgenre and workdict[w].workgenre != '': g = workdict[w].workgenre.split(',') lg = workdict[w].universalid[0:2] genresdict[lg] += g for lg in ['gr', 'lt', 'in', 'dp', 'ch']: genresdict[lg] = list(set(genresdict[lg])) genresdict[lg] = [re.sub(r'^\s|\s$', '', x) for x in genresdict[lg]] genresdict[lg].sort() return genresdict def buildauthorlocationdict(authordict: dict) -> dict: """ build lists of author locations: [ g1, g2, ...] do this by corpus and tag it accordingly :param authordict: :return: """ gklist = list() ltlist = list() inlist = list() dplist = list() chlist = list() locationdict = {'gr': gklist, 'lt': ltlist, 'in': inlist, 'dp': dplist, 'ch': chlist} for a in authordict: if authordict[a].location and authordict[a].location != '': # think about what happens if the location looks like 'Italy, Africa and the West [Chr.]'... loc = authordict[a].location.split(',') lg = authordict[a].universalid[0:2] locationdict[lg] += loc for lg in ['gr', 'lt', 'in', 'dp', 'ch']: locationdict[lg] = list(set(locationdict[lg])) locationdict[lg] = [re.sub(r'\[.*?\]', '', x) for x in locationdict[lg]] locationdict[lg] = [re.sub(r'^\s|\s$', '', x) for x in locationdict[lg]] locationdict[lg].sort() return locationdict def buildworkprovenancedict(workdict: dict) -> dict: """ load up the list of work provenances used in offerprovenancehints() :param workdict: :return: """ gklist = list() ltlist = list() inlist = list() dplist = list() chlist = list() locationdict = {'gr': gklist, 'lt': ltlist, 'in': inlist, 'dp': dplist, 'ch': chlist } for w in workdict: if workdict[w].provenance and workdict[w].provenance != '': loc = workdict[w].provenance.split(',') lg = workdict[w].universalid[0:2] locationdict[lg] += loc for lg in ['gr', 'lt', 'in', 'dp', 'ch']: locationdict[lg] = list(set(locationdict[lg])) locationdict[lg] = [re.sub(r'^\s|\s$', '', x) for x in locationdict[lg]] locationdict[lg].sort() return locationdict @timedecorator def buildkeyedlemmata(listofentries: list) -> defaultdict: """ a list of 140k words is too long to send to 'getlemmahint' without offering quicker access a dict with keys... :param listofentries: :return: """ invals = u'jvσς' outvals = u'iuϲϲ' keyedlemmata = defaultdict(list) if track: iterable = track(listofentries, description='building keyedlemmata', transient=True) else: print('building keyedlemmata', end=str()) iterable = listofentries for e in iterable: try: # might IndexError here... bag = e[0:2] key = stripaccents(bag.translate(str.maketrans(invals, outvals))) try: keyedlemmata[key].append(e) except KeyError: keyedlemmata[key] = [e] except IndexError: pass if track: print('building keyedlemmata', end=str()) return keyedlemmata
e-gun/HipparchiaServer
server/listsandsession/sessiondicts.py
Python
gpl-3.0
4,686
/** * */ package com.fr.design.report.share; import java.util.HashMap; import com.fr.data.impl.EmbeddedTableData; import com.fr.general.GeneralUtils; import com.fr.stable.ArrayUtils; import com.fr.stable.StringUtils; /** * 混淆传入的tabledata * * @author neil * * @date: 2015-3-10-上午10:45:41 */ public class ConfuseTabledataAction { /** * 混淆指定的内置数据集 * * @param info 混淆相关的信息 * @param tabledata 需要混淆的数据集 * */ public void confuse(ConfusionInfo info, EmbeddedTableData tabledata){ int rowCount = tabledata.getRowCount(); String[] keys = info.getConfusionKeys(); for (int j = 0, len = ArrayUtils.getLength(keys); j < len; j++) { if(StringUtils.isEmpty(keys[j])){ continue; } //缓存下已经混淆的数据, 这样相同的原始数据, 混淆出来的结果是一致的. HashMap<Object, Object> cachedValue = new HashMap<Object, Object>(); for (int k = 0; k < rowCount; k++) { Object oriValue = tabledata.getValueAt(k, j); Object newValue; if(cachedValue.containsKey(oriValue)){ newValue = cachedValue.get(oriValue); }else{ newValue = confusionValue(info, j, keys[j], cachedValue, oriValue); cachedValue.put(oriValue, newValue); } tabledata.setValueAt(newValue, k, j); } } } //混淆每一个格子的数据 private Object confusionValue(ConfusionInfo info, int colIndex, String key, HashMap<Object, Object> cachedValue, Object oriValue){ if (info.isNumberColumn(colIndex)){ //如果是数字格式的, 那么就做乘法, eg: 3 * 3, 8 *3..... Number keyValue = GeneralUtils.objectToNumber(key, false); Number oriNumber = GeneralUtils.objectToNumber(oriValue, false); return oriNumber.doubleValue() * keyValue.doubleValue(); } String oriStrValue = GeneralUtils.objectToString(oriValue); if(StringUtils.isEmpty(oriStrValue)){ //如果是空字段, 就默认不混淆. 因为有的客户他就是留了空字段来做一些过滤, 条件属性之类的. return oriStrValue; } //默认其他格式的就做加法, eg: 地区1, 地区2...... return key + cachedValue.size(); } }
fanruan/finereport-design
designer/src/com/fr/design/report/share/ConfuseTabledataAction.java
Java
gpl-3.0
2,273
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend 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. foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #ifndef outletInletFvPatchFieldsFwd_H #define outletInletFvPatchFieldsFwd_H #include "fvPatchField.H" #include "fieldTypes.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // template<class Type> class outletInletFvPatchField; makePatchTypeFieldTypedefs(outletInlet) // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/finiteVolume/fields/fvPatchFields/derived/outletInlet/outletInletFvPatchFieldsFwd.H
C++
gpl-3.0
1,891
const constants = require('./../routes/constants.json'); const logger = require('../utils/logger'); const amanda = require('amanda'); const jsonSchemaValidator = amanda('json'); const math = require('mathjs'); const calculatePopularity = popularity => { logger.debug('Calculating popularity'); if (popularity) { return math.round(popularity, 2); } return 0; }; const internalServerError = (reason, response) => { const message = `Unexpected error: ${reason}`; logger.warn(message); return response.status(500).json({ code: 500, message }); }; const unauthorizedError = (reason, response) => { const message = `Unauthorized: ${reason}`; logger.warn(message); response.status(401).json({ code: 401, message }); }; const nonExistentId = (message, response) => { logger.warn(message); response.status(400).json({ code: 400, message }); }; const validateRequestBody = (body, schema) => { logger.info('Validating request'); logger.debug(`Request "${JSON.stringify(body, null, 4)}"`); return new Promise((resolve, reject) => { jsonSchemaValidator.validate(body, schema, error => { if (error) { reject(error); } else { resolve(); } }); }); }; const invalidRequestBodyError = (reasons, response) => { const message = `Request body is invalid: ${reasons[0].message}`; logger.warn(message); return response.status(400).json({ code: 400, message }); }; const entryExists = (id, entry, response) => { logger.info(`Checking if entry ${id} exist`); logger.debug(`Entry: ${JSON.stringify(entry, null, 4)}`); if (!entry) { logger.warn(`No entry with id ${id}`); response.status(404).json({ code: 404, message: `No entry with id ${id}` }); return false; } return true; }; /* Users */ const formatUserShortJson = user => ({ id: user.id, userName: user.userName, href: user.href, images: user.images, }); const formatUserContacts = contacts => (contacts[0] === null) ? [] : contacts.map(formatUserShortJson); // eslint-disable-line const formatUserJson = user => ({ userName: user.userName, password: user.password, fb: { userId: user.facebookUserId, authToken: user.facebookAuthToken, }, firstName: user.firstName, lastName: user.lastName, country: user.country, email: user.email, birthdate: user.birthdate, images: user.images, href: user.href, contacts: formatUserContacts(user.contacts), }); const formatGetUserJson = user => ({ id: user.id, userName: user.userName, password: user.password, fb: { userId: user.facebookUserId, authToken: user.facebookAuthToken, }, firstName: user.firstName, lastName: user.lastName, country: user.country, email: user.email, birthdate: user.birthdate, images: user.images, href: user.href, contacts: formatUserContacts(user.contacts), }); const successfulUsersFetch = (users, response) => { logger.info('Successful users fetch'); return response.status(200).json({ metadata: { count: users.length, version: constants.API_VERSION, }, users: users.map(formatGetUserJson), }); }; const successfulUserFetch = (user, response) => { logger.info('Successful user fetch'); response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, user: formatGetUserJson(user), }); }; const successfulUserCreation = (user, response) => { logger.info('Successful user creation'); response.status(201).json(formatUserJson(user)); }; const successfulUserUpdate = (user, response) => { logger.info('Successful user update'); response.status(200).json(formatUserJson(user)); }; const successfulUserDeletion = response => { logger.info('Successful user deletion'); response.sendStatus(204); }; const successfulUserContactsFetch = (contacts, response) => { logger.info('Successful contacts fetch'); response.status(200).json({ metadata: { count: contacts.length, version: constants.API_VERSION, }, contacts: formatUserContacts(contacts), }); }; const successfulContactAddition = response => { logger.info('Successful contact addition'); response.sendStatus(201); }; const successfulContactDeletion = response => { logger.info('Successful contact deletion'); response.sendStatus(204); }; /* Admins */ const successfulAdminsFetch = (admins, response) => { logger.info('Successful admins fetch'); return response.status(200).json({ metadata: { count: admins.length, version: constants.API_VERSION, }, admins, }); }; const successfulAdminCreation = (admin, response) => { logger.info('Successful admin creation'); response.status(201).json(admin[0]); }; const successfulAdminDeletion = response => { logger.info('Successful admin deletion'); response.sendStatus(204); }; /* Tokens */ const nonexistentCredentials = response => { const message = 'No entry with such credentials'; logger.warn(message); response.status(400).json({ code: 400, message }); }; const inconsistentCredentials = response => { const message = 'There is more than one entry with those credentials'; logger.warn(message); response.status(500).json({ code: 500, message }); }; const successfulTokenGeneration = (result, response) => { logger.info('Successful token generation'); response.status(201).json(result); }; const successfulUserTokenGeneration = (user, token, response) => { const result = { token }; successfulTokenGeneration(result, response); }; const successfulAdminTokenGeneration = (admin, token, response) => { const result = Object.assign( {}, { token, admin: { id: admin.id, userName: admin.userName, }, }); successfulTokenGeneration(result, response); }; /* Artists */ const formatArtistShortJson = artist => ({ id: artist.id, name: artist.name, href: artist.href, images: artist.images, }); const formatArtistJson = artist => ({ id: artist.id, name: artist.name, description: artist.description, href: artist.href, images: artist.images, genres: artist.genres, albums: artist.albums[0] ? artist.albums.map(formatAlbumShortJson) : [], popularity: calculatePopularity(artist.popularity), }); const successfulArtistsFetch = (artists, response) => { logger.info('Successful artists fetch'); return response.status(200).json({ metadata: { count: artists.length, version: constants.API_VERSION, }, artists: artists.map(formatArtistJson), }); }; const successfulArtistCreation = (artist, response) => { logger.info('Successful artist creation'); response.status(201).json(formatArtistJson(artist)); }; const successfulArtistFetch = (artist, response) => { logger.info('Successful artist fetch'); return response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, artist: (formatArtistJson(artist)), }); }; const successfulArtistUpdate = (artist, response) => { logger.info('Successful artist update'); response.status(200).json(formatArtistJson(artist)); }; const successfulArtistDeletion = response => { logger.info('Successful artist deletion'); response.sendStatus(204); }; const successfulArtistFollow = (artist, response) => { logger.info('Successful artist follow'); response.status(201).json(formatArtistJson(artist)); }; const successfulArtistUnfollow = (artist, response) => { logger.info('Successful artist unfollow'); response.status(204).json(formatArtistJson(artist)); }; const successfulArtistTracksFetch = (tracks, response) => { logger.info('Successful tracks fetch'); response.status(200).json({ metadata: { count: tracks.length, version: constants.API_VERSION, }, tracks: tracks.map(formatTrackJson), }); }; /* Albums */ const formatAlbumShortJson = album => ({ id: album.id, name: album.name, href: album.href, images: album.images, }); const formatAlbumJson = album => ({ id: album.id, name: album.name, release_date: album.release_date, href: album.href, popularity: calculatePopularity(album.popularity), artists: album.artists[0] ? album.artists.map(artist => formatArtistShortJson(artist)) : [], tracks: album.tracks[0] ? album.tracks.map(track => formatTrackShortJson(track)) : [], genres: album.genres, images: album.images, }); const successfulAlbumsFetch = (albums, response) => { logger.info('Successful albums fetch'); return response.status(200).json({ metadata: { count: albums.length, version: constants.API_VERSION, }, albums: albums.map(formatAlbumJson), }); }; const successfulAlbumCreation = (album, response) => { logger.info('Successful album creation'); response.status(201).json(formatAlbumJson(album)); }; const successfulAlbumFetch = (album, response) => { logger.info('Successful album fetch'); response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, album: formatAlbumJson(album), }); }; const successfulAlbumUpdate = (album, response) => { logger.info('Successful album update'); response.status(200).json(formatAlbumJson(album)); }; const successfulAlbumDeletion = response => { logger.info('Successful album deletion'); response.sendStatus(204); }; const invalidTrackDeletionFromAlbum = (trackId, albumId, response) => { const message = `Track (id: ${trackId}) does not belong to album (id: ${albumId})`; logger.info(message); response.status(400).json({ code: 400, message }); }; const successfulTrackDeletionFromAlbum = (trackId, albumId, response) => { logger.info(`Successful track (id: ${trackId}) deletion from album (id: ${albumId})`); response.sendStatus(204); }; const successfulTrackAdditionToAlbum = (trackId, album, response) => { logger.info(`Track (id: ${trackId}) now belongs to album (id: ${album.id})`); response.status(200).json(formatAlbumJson(album)); }; /* Tracks */ const formatTrackShortJson = track => ({ id: track.id, name: track.name, href: track.href, }); const formatTrackJson = track => ({ id: track.id, name: track.name, href: track.href, duration: track.duration, popularity: calculatePopularity(track.popularity), externalId: track.external_id, album: track.album ? formatAlbumShortJson(track.album) : {}, artists: track.artists ? track.artists.map(artist => formatArtistShortJson(artist)) : [], }); const successfulTracksFetch = (tracks, response) => { logger.info('Successful tracks fetch'); logger.debug(`Tracks: ${JSON.stringify(tracks, null, 4)}`); return response.status(200).json({ metadata: { count: tracks.length, version: constants.API_VERSION, }, tracks: tracks.map(formatTrackJson), }); }; const successfulTrackCreation = (track, response) => { logger.info('Successful track creation'); logger.debug(`Track: ${JSON.stringify(track, null, 4)}`); response.status(201).json(formatTrackJson(track)); }; const successfulTrackFetch = (track, response) => { logger.info('Successful track fetch'); logger.debug(`Track: ${JSON.stringify(track, null, 4)}`); response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, track: formatTrackJson(track), }); }; const successfulTrackUpdate = (track, response) => { logger.info('Successful track update'); response.status(200).json(formatTrackJson(track)); }; const successfulTrackDeletion = response => { logger.info('Successful track deletion'); response.sendStatus(204); }; const successfulTrackLike = (track, response) => { logger.info('Successful track like'); response.status(201).json(formatTrackJson(track)); }; const successfulTrackDislike = (track, response) => { logger.info('Successful track dislike'); response.status(204).json(formatTrackJson(track)); }; const successfulTrackPopularityCalculation = (rating, response) => { logger.info(`Successful track popularity calculation (rate: ${rating})`); response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, popularity: { rate: rating, }, }); }; const successfulTrackRate = (rate, response) => { logger.info(`Successful track rate: ${rate}`); response.status(201).json({ rate, }); }; /* Playlist */ const formatPlaylistJson = playlist => ({ id: playlist.id, name: playlist.name, href: playlist.href, description: playlist.description, owner: playlist.owner ? formatUserShortJson(playlist.owner) : {}, songs: playlist.tracks ? _formatTracks(playlist.tracks) : [], images: playlist.images ? playlist.images : [], }); const _formatTracks = tracks => { if (tracks.length === 1 && tracks[0] === null) { return []; } return tracks.map(track => formatTrackShortJson(track)); }; const formatPlaylistCreationJson = playlist => ({ id: playlist.id, name: playlist.name, href: playlist.href, description: playlist.description, owner: playlist.owner ? formatUserShortJson(playlist.owner) : {}, }); const successfulPlaylistsFetch = (playlists, response) => { logger.info('Successful playlists fetch'); logger.debug(`Playlists: ${JSON.stringify(playlists, null, 4)}`); return response.status(200).json({ metadata: { count: playlists.length, version: constants.API_VERSION, }, playlists: playlists.map(formatPlaylistJson), }); }; const successfulPlaylistCreation = (playlist, response) => { logger.info('Successful playlist creation'); logger.debug(`Playlist: ${JSON.stringify(playlist, null, 4)}`); response.status(201).json(formatPlaylistCreationJson(playlist)); }; const successfulPlaylistFetch = (playlist, response) => { logger.info('Successful playlist fetch'); response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, playlist: formatPlaylistJson(playlist), }); }; const successfulPlaylistUpdate = (playlist, response) => { logger.info('Successful playlist update'); response.status(200).json(formatPlaylistJson(playlist)); }; const successfulPlaylistDeletion = response => { logger.info('Successful playlist deletion'); response.sendStatus(204); }; const successfulTrackDeletionFromPlaylist = (trackId, playlist, response) => { logger.info(`Successful track (id: ${trackId}) deletion from playlist (id: ${playlist.id})`); response.sendStatus(204); }; const successfulTrackAdditionToPlaylist = (trackId, playlist, response) => { logger.info(`Track (id: ${trackId}) now belongs to playlist (id: ${playlist.id})`); response.status(200).json(formatPlaylistJson(playlist)); }; const successfulAlbumDeletionFromPlaylist = (albumId, playlist, response) => { logger.info(`Successful album (id: ${albumId}) deletion from playlist (id: ${playlist.id})`); response.sendStatus(204); }; const successfulAlbumAdditionToPlaylist = (albumId, playlist, response) => { logger.info(`Album (id: ${albumId}) now belongs to playlist (id: ${playlist.id})`); response.status(200).json(formatPlaylistJson(playlist)); }; module.exports = { internalServerError, unauthorizedError, nonExistentId, validateRequestBody, entryExists, invalidRequestBodyError, successfulUsersFetch, successfulUserFetch, successfulUserCreation, successfulUserUpdate, successfulUserDeletion, successfulUserContactsFetch, successfulContactAddition, successfulContactDeletion, successfulAdminsFetch, successfulAdminCreation, successfulAdminDeletion, nonexistentCredentials, inconsistentCredentials, successfulUserTokenGeneration, successfulAdminTokenGeneration, successfulArtistsFetch, successfulArtistCreation, successfulArtistFetch, successfulArtistUpdate, successfulArtistDeletion, successfulArtistFollow, successfulArtistUnfollow, successfulArtistTracksFetch, successfulAlbumsFetch, successfulAlbumCreation, successfulAlbumFetch, successfulAlbumUpdate, successfulAlbumDeletion, invalidTrackDeletionFromAlbum, successfulTrackDeletionFromAlbum, successfulTrackAdditionToAlbum, successfulTracksFetch, successfulTrackCreation, successfulTrackFetch, successfulTrackUpdate, successfulTrackDeletion, successfulTrackLike, successfulTrackDislike, successfulTrackPopularityCalculation, successfulTrackRate, successfulPlaylistsFetch, successfulPlaylistCreation, successfulPlaylistFetch, successfulPlaylistUpdate, successfulPlaylistDeletion, successfulTrackDeletionFromPlaylist, successfulTrackAdditionToPlaylist, successfulAlbumDeletionFromPlaylist, successfulAlbumAdditionToPlaylist, };
tallerify/shared-server
src/handlers/response.js
JavaScript
gpl-3.0
16,674
<?php // Heading $_['heading_title'] = 'Paskyra'; // Text $_['text_register'] = 'Registruotis'; $_['text_login'] = 'Prisijungti'; $_['text_logout'] = 'Atsijungti'; $_['text_forgotten'] = 'Priminti slaptažodį'; $_['text_account'] = 'Mano paskyra'; $_['text_edit'] = 'Mano duomenys'; $_['text_password'] = 'Keisti slaptažodį'; $_['text_address'] = 'Mano adresai'; $_['text_wishlist'] = 'Prekių sąrašas'; $_['text_order'] = 'Užsakymų istorija'; $_['text_download'] = 'Detalių schemos ir dokumentai'; $_['text_return'] = 'Grąžinimų istorija'; $_['text_transaction'] = 'Kreditų valdymas'; $_['text_newsletter'] = 'Naujienlaiškis'; $_['text_recurring'] = 'Pasikartojantys mokėjimai'; ?>
zilgrg/opencart
upload/catalog/language/lithuanian/module/account.php
PHP
gpl-3.0
756
#region header // ======================================================================== // Copyright (c) 2018 - Julien Caillon (julien.caillon@gmail.com) // This file (ProgressCopy.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; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Net; namespace _3PA.Lib { /// <summary> /// This class allows to copy a file or a folder asynchronously, with the possibility to cancel and see the progress /// </summary> internal class ProgressCopy { /// <summary> /// Copies the file asynchronously, you can cancel it by using the returns object and its method cancel /// </summary> public static ProgressCopy CopyAsync(string source, string destination, EventHandler<EndEventArgs> completed, EventHandler<ProgressEventArgs> progressChanged) { var stack = new Stack<FileToCopy>(); stack.Push(new FileToCopy(source, destination)); return new ProgressCopy(stack, completed, progressChanged); } /// <summary> /// Copies the folder asynchronously, you can cancel it by using the returns object and its method cancel /// </summary> public static ProgressCopy CopyDirectory(string source, string target, EventHandler<EndEventArgs> completed, EventHandler<ProgressEventArgs> progressChanged) { var fileStack = new Stack<FileToCopy>(); var folderStack = new Stack<FolderToCopy>(); try { folderStack.Push(new FolderToCopy(source, target)); while (folderStack.Count > 0) { var folders = folderStack.Pop(); Directory.CreateDirectory(folders.Target); foreach (var file in Directory.GetFiles(folders.Source, "*.*")) { fileStack.Push(new FileToCopy(file, Path.Combine(folders.Target, Path.GetFileName(file)))); } foreach (var folder in Directory.GetDirectories(folders.Source)) { folderStack.Push(new FolderToCopy(folder, Path.Combine(folders.Target, Path.GetFileName(folder)))); } } } catch (Exception e) { if (completed != null) completed(null, new EndEventArgs(CopyCompletedType.Exception, e)); } return new ProgressCopy(fileStack, completed, progressChanged); } private long _total; private WebClient _wc; private Stack<FileToCopy> _filesToCopy; private ProgressCopy(Stack<FileToCopy> stack, EventHandler<EndEventArgs> completed, EventHandler<ProgressEventArgs> progressChanged) { _filesToCopy = stack; Completed += completed; ProgressChanged += progressChanged; _total = _filesToCopy.Count; _wc = new WebClient(); _wc.DownloadProgressChanged += WebClientOnDownloadProgressChanged; _wc.DownloadFileCompleted += WcOnDownloadFileCompleted; // start treating the next file Next(); } /// <summary> /// Aborts the copy asynchronously and throws Completed event when done /// </summary> public void AbortCopyAsync() { _wc.CancelAsync(); } /// <summary> /// Event which will notify the subscribers if the copy gets completed /// There are three scenarios in which completed event will be thrown when /// 1.Copy succeeded /// 2.Copy aborted /// 3.Any exception occurred /// </summary> private event EventHandler<EndEventArgs> Completed; /// <summary> /// Event which will notify the subscribers if there is any progress change while copying /// </summary> private event EventHandler<ProgressEventArgs> ProgressChanged; /// <summary> /// Copies the next file in the stack /// </summary> private void Next() { if (_filesToCopy.Count > 0) { var currentFile = _filesToCopy.Pop(); _wc.DownloadFileAsync(new Uri(currentFile.Source), currentFile.Target); } else { if (Completed != null) Completed(this, new EndEventArgs(CopyCompletedType.Succeeded, null)); } } private void WcOnDownloadFileCompleted(object sender, AsyncCompletedEventArgs args) { if (args.Cancelled || args.Error != null) { if (Completed != null) { Completed(this, new EndEventArgs(args.Cancelled ? CopyCompletedType.Aborted : CopyCompletedType.Exception, args.Error)); } } else { Next(); } } private void WebClientOnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs downloadProgressChangedEventArgs) { if (ProgressChanged != null) ProgressChanged(this, new ProgressEventArgs((_total - _filesToCopy.Count) / (double)_total * 100.0, downloadProgressChangedEventArgs.ProgressPercentage)); } private class FolderToCopy { public string Source { get; private set; } public string Target { get; private set; } public FolderToCopy(string source, string target) { Source = source; Target = target; } } private class FileToCopy { public string Source { get; private set; } public string Target { get; private set; } public FileToCopy(string source, string target) { Source = source; Target = target; } } /// <summary> /// Type indicates how the copy gets completed /// </summary> internal enum CopyCompletedType { Succeeded, Aborted, Exception } /// <summary> /// Event arguments for file copy /// </summary> internal class EndEventArgs : EventArgs { /// <summary> /// Constructor /// </summary> public EndEventArgs(CopyCompletedType type, Exception exception) { Type = type; Exception = exception; } /// <summary> /// Type of the copy completed type /// </summary> public CopyCompletedType Type { get; private set; } /// <summary> /// Exception if any happened during copy /// </summary> public Exception Exception { get; private set; } } /// <summary> /// Event arguments for file copy /// </summary> internal class ProgressEventArgs : EventArgs { /// <summary> /// Constructor /// </summary> public ProgressEventArgs(double total, double current) { TotalFiles = total; CurrentFile = current; } /// <summary> /// Percent of total files done /// </summary> public double TotalFiles { get; private set; } /// <summary> /// Percent done for current file /// </summary> public double CurrentFile { get; private set; } } } }
jcaillon/3P
3PA/Lib/ProgressCopy.cs
C#
gpl-3.0
8,184
var searchData= [ ['network',['Network',['../classNetwork.html',1,'Network&lt; Vertex, Edge &gt;'],['../classNetwork.html#a5041dbbc6de74dfee903edb066476ddb',1,'Network::Network()'],['../classNetwork.html#ae591a151ac8f3fbfb800b282f1d11ea7',1,'Network::Network(NetworkInfo i)']]], ['networkinfo',['NetworkInfo',['../structNetworkInfo.html',1,'']]] ];
leoandeol/network-coverage-computation
docs/search/all_8.js
JavaScript
gpl-3.0
353
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file import copy,re,os from waflib import Task,Utils,Logs,Errors,ConfigSet,Node feats=Utils.defaultdict(set) class task_gen(object): mappings={} prec=Utils.defaultdict(list) def __init__(self,*k,**kw): self.source='' self.target='' self.meths=[] self.prec=Utils.defaultdict(list) self.mappings={} self.features=[] self.tasks=[] if not'bld'in kw: self.env=ConfigSet.ConfigSet() self.idx=0 self.path=None else: self.bld=kw['bld'] self.env=self.bld.env.derive() self.path=self.bld.path try: self.idx=self.bld.idx[id(self.path)]=self.bld.idx.get(id(self.path),0)+1 except AttributeError: self.bld.idx={} self.idx=self.bld.idx[id(self.path)]=1 for key,val in kw.items(): setattr(self,key,val) def __str__(self): return"<task_gen %r declared in %s>"%(self.name,self.path.abspath()) def __repr__(self): lst=[] for x in self.__dict__.keys(): if x not in['env','bld','compiled_tasks','tasks']: lst.append("%s=%s"%(x,repr(getattr(self,x)))) return"bld(%s) in %s"%(", ".join(lst),self.path.abspath()) def get_name(self): try: return self._name except AttributeError: if isinstance(self.target,list): lst=[str(x)for x in self.target] name=self._name=','.join(lst) else: name=self._name=str(self.target) return name def set_name(self,name): self._name=name name=property(get_name,set_name) def to_list(self,val): if isinstance(val,str):return val.split() else:return val def post(self): if getattr(self,'posted',None): return False self.posted=True keys=set(self.meths) self.features=Utils.to_list(self.features) for x in self.features+['*']: st=feats[x] if not st: if not x in Task.classes: Logs.warn('feature %r does not exist - bind at least one method to it'%x) keys.update(list(st)) prec={} prec_tbl=self.prec or task_gen.prec for x in prec_tbl: if x in keys: prec[x]=prec_tbl[x] tmp=[] for a in keys: for x in prec.values(): if a in x:break else: tmp.append(a) tmp.sort() out=[] while tmp: e=tmp.pop() if e in keys:out.append(e) try: nlst=prec[e] except KeyError: pass else: del prec[e] for x in nlst: for y in prec: if x in prec[y]: break else: tmp.append(x) if prec: raise Errors.WafError('Cycle detected in the method execution %r'%prec) out.reverse() self.meths=out Logs.debug('task_gen: posting %s %d'%(self,id(self))) for x in out: try: v=getattr(self,x) except AttributeError: raise Errors.WafError('%r is not a valid task generator method'%x) Logs.debug('task_gen: -> %s (%d)'%(x,id(self))) v() Logs.debug('task_gen: posted %s'%self.name) return True def get_hook(self,node): name=node.name for k in self.mappings: if name.endswith(k): return self.mappings[k] for k in task_gen.mappings: if name.endswith(k): return task_gen.mappings[k] raise Errors.WafError("File %r has no mapping in %r (did you forget to load a waf tool?)"%(node,task_gen.mappings.keys())) def create_task(self,name,src=None,tgt=None): task=Task.classes[name](env=self.env.derive(),generator=self) if src: task.set_inputs(src) if tgt: task.set_outputs(tgt) self.tasks.append(task) return task def clone(self,env): newobj=self.bld() for x in self.__dict__: if x in['env','bld']: continue elif x in['path','features']: setattr(newobj,x,getattr(self,x)) else: setattr(newobj,x,copy.copy(getattr(self,x))) newobj.posted=False if isinstance(env,str): newobj.env=self.bld.all_envs[env].derive() else: newobj.env=env.derive() return newobj def declare_chain(name='',rule=None,reentrant=None,color='BLUE',ext_in=[],ext_out=[],before=[],after=[],decider=None,scan=None,install_path=None,shell=False): ext_in=Utils.to_list(ext_in) ext_out=Utils.to_list(ext_out) if not name: name=rule cls=Task.task_factory(name,rule,color=color,ext_in=ext_in,ext_out=ext_out,before=before,after=after,scan=scan,shell=shell) def x_file(self,node): ext=decider and decider(self,node)or cls.ext_out if ext_in: _ext_in=ext_in[0] tsk=self.create_task(name,node) cnt=0 keys=list(self.mappings.keys())+list(self.__class__.mappings.keys()) for x in ext: k=node.change_ext(x,ext_in=_ext_in) tsk.outputs.append(k) if reentrant!=None: if cnt<int(reentrant): self.source.append(k) else: for y in keys: if k.name.endswith(y): self.source.append(k) break cnt+=1 if install_path: self.bld.install_files(install_path,tsk.outputs) return tsk for x in cls.ext_in: task_gen.mappings[x]=x_file return x_file def taskgen_method(func): setattr(task_gen,func.__name__,func) return func def feature(*k): def deco(func): setattr(task_gen,func.__name__,func) for name in k: feats[name].update([func.__name__]) return func return deco def before_method(*k): def deco(func): setattr(task_gen,func.__name__,func) for fun_name in k: if not func.__name__ in task_gen.prec[fun_name]: task_gen.prec[fun_name].append(func.__name__) return func return deco before=before_method def after_method(*k): def deco(func): setattr(task_gen,func.__name__,func) for fun_name in k: if not fun_name in task_gen.prec[func.__name__]: task_gen.prec[func.__name__].append(fun_name) return func return deco after=after_method def extension(*k): def deco(func): setattr(task_gen,func.__name__,func) for x in k: task_gen.mappings[x]=func return func return deco @taskgen_method def to_nodes(self,lst,path=None): tmp=[] path=path or self.path find=path.find_resource if isinstance(lst,self.path.__class__): lst=[lst] for x in Utils.to_list(lst): if isinstance(x,str): node=find(x) else: node=x if not node: raise Errors.WafError("source not found: %r in %r"%(x,self)) tmp.append(node) return tmp @feature('*') def process_source(self): self.source=self.to_nodes(getattr(self,'source',[])) for node in self.source: self.get_hook(node)(self,node) @feature('*') @before_method('process_source') def process_rule(self): if not getattr(self,'rule',None): return name=str(getattr(self,'name',None)or self.target or self.rule) try: cache=self.bld.cache_rule_attr except AttributeError: cache=self.bld.cache_rule_attr={} cls=None if getattr(self,'cache_rule','True'): try: cls=cache[(name,self.rule)] except KeyError: pass if not cls: cls=Task.task_factory(name,self.rule,getattr(self,'vars',[]),shell=getattr(self,'shell',True),color=getattr(self,'color','BLUE'),scan=getattr(self,'scan',None)) if getattr(self,'scan',None): cls.scan=self.scan elif getattr(self,'deps',None): def scan(self): nodes=[] for x in self.generator.to_list(getattr(self.generator,'deps',None)): node=self.generator.path.find_resource(x) if not node: self.generator.bld.fatal('Could not find %r (was it declared?)'%x) nodes.append(node) return[nodes,[]] cls.scan=scan if getattr(self,'update_outputs',None): Task.update_outputs(cls) if getattr(self,'always',None): Task.always_run(cls) for x in['after','before','ext_in','ext_out']: setattr(cls,x,getattr(self,x,[])) if getattr(self,'cache_rule','True'): cache[(name,self.rule)]=cls tsk=self.create_task(name) if getattr(self,'target',None): if isinstance(self.target,str): self.target=self.target.split() if not isinstance(self.target,list): self.target=[self.target] for x in self.target: if isinstance(x,str): tsk.outputs.append(self.path.find_or_declare(x)) else: x.parent.mkdir() tsk.outputs.append(x) if getattr(self,'install_path',None): self.bld.install_files(self.install_path,tsk.outputs) if getattr(self,'source',None): tsk.inputs=self.to_nodes(self.source) self.source=[] if getattr(self,'cwd',None): tsk.cwd=self.cwd @feature('seq') def sequence_order(self): if self.meths and self.meths[-1]!='sequence_order': self.meths.append('sequence_order') return if getattr(self,'seq_start',None): return if getattr(self.bld,'prev',None): self.bld.prev.post() for x in self.bld.prev.tasks: for y in self.tasks: y.set_run_after(x) self.bld.prev=self re_m4=re.compile('@(\w+)@',re.M) class subst_pc(Task.Task): def run(self): if getattr(self.generator,'is_copy',None): self.outputs[0].write(self.inputs[0].read('rb'),'wb') if getattr(self.generator,'chmod',None): os.chmod(self.outputs[0].abspath(),self.generator.chmod) return code=self.inputs[0].read(encoding=getattr(self.generator,'encoding','ISO8859-1')) code=code.replace('%','%%') lst=[] def repl(match): g=match.group if g(1): lst.append(g(1)) return"%%(%s)s"%g(1) return'' code=re_m4.sub(repl,code) try: d=self.generator.dct except AttributeError: d={} for x in lst: tmp=getattr(self.generator,x,'')or self.env.get_flat(x)or self.env.get_flat(x.upper()) d[x]=str(tmp) code=code%d self.outputs[0].write(code,encoding=getattr(self.generator,'encoding','ISO8859-1')) self.generator.bld.raw_deps[self.uid()]=self.dep_vars=lst try:delattr(self,'cache_sig') except AttributeError:pass if getattr(self.generator,'chmod',None): os.chmod(self.outputs[0].abspath(),self.generator.chmod) def sig_vars(self): bld=self.generator.bld env=self.env upd=self.m.update vars=self.generator.bld.raw_deps.get(self.uid(),[]) act_sig=bld.hash_env_vars(env,vars) upd(act_sig) lst=[getattr(self.generator,x,'')for x in vars] upd(Utils.h_list(lst)) return self.m.digest() @extension('.pc.in') def add_pcfile(self,node): tsk=self.create_task('subst_pc',node,node.change_ext('.pc','.pc.in')) self.bld.install_files(getattr(self,'install_path','${LIBDIR}/pkgconfig/'),tsk.outputs) class subst(subst_pc): pass @feature('subst') @before_method('process_source','process_rule') def process_subst(self): src=Utils.to_list(getattr(self,'source',[])) if isinstance(src,Node.Node): src=[src] tgt=Utils.to_list(getattr(self,'target',[])) if isinstance(tgt,Node.Node): tgt=[tgt] if len(src)!=len(tgt): raise Errors.WafError('invalid number of source/target for %r'%self) for x,y in zip(src,tgt): if not x or not y: raise Errors.WafError('null source or target for %r'%self) a,b=None,None if isinstance(x,str)and isinstance(y,str)and x==y: a=self.path.find_node(x) b=self.path.get_bld().make_node(y) if not os.path.isfile(b.abspath()): b.sig=None b.parent.mkdir() else: if isinstance(x,str): a=self.path.find_resource(x) elif isinstance(x,Node.Node): a=x if isinstance(y,str): b=self.path.find_or_declare(y) elif isinstance(y,Node.Node): b=y if not a: raise Errors.WafError('cound not find %r for %r'%(x,self)) has_constraints=False tsk=self.create_task('subst',a,b) for k in('after','before','ext_in','ext_out'): val=getattr(self,k,None) if val: has_constraints=True setattr(tsk,k,val) if not has_constraints and b.name.endswith('.h'): tsk.before=[k for k in('c','cxx')if k in Task.classes] inst_to=getattr(self,'install_path',None) if inst_to: self.bld.install_files(inst_to,b,chmod=getattr(self,'chmod',Utils.O644)) self.source=[]
arnov-sinha/sFFT-OpenACC-Library
tools/.waf-1.7.5-47d5afdb5e7e2856f7f46a7101914026/waflib/TaskGen.py
Python
gpl-3.0
11,393
from umlfri2.ufl.components.base.componenttype import ComponentType from umlfri2.types.image import Image from .componentloader import ComponentLoader from ....constants import ADDON_NAMESPACE, ADDON_SCHEMA from .structureloader import UflStructureLoader from umlfri2.ufl.components.valueproviders import ConstantValueProvider, DynamicValueProvider from umlfri2.ufl.components.text import TextContainerComponent from umlfri2.metamodel import DiagramType class DiagramTypeLoader: def __init__(self, storage, xmlroot, file_name, elements, connections): self.__storage = storage self.__xmlroot = xmlroot self.__file_name = file_name if not ADDON_SCHEMA.validate(xmlroot): raise Exception("Cannot load diagram type: {0}".format(ADDON_SCHEMA.error_log.last_error)) self.__elements = elements self.__connections = connections def load(self): id = self.__xmlroot.attrib["id"] icon = None ufl_type = None display_name = None background = None connections = [] elements = [] for child in self.__xmlroot: if child.tag == "{{{0}}}Icon".format(ADDON_NAMESPACE): icon_path = child.attrib["path"] if not self.__storage.exists(icon_path): raise Exception("Unknown icon {0}".format(icon_path)) icon = Image(self.__storage, icon_path) elif child.tag == "{{{0}}}Structure".format(ADDON_NAMESPACE): ufl_type = UflStructureLoader(child, self.__file_name).load() elif child.tag == "{{{0}}}DisplayName".format(ADDON_NAMESPACE): display_name = TextContainerComponent( ComponentLoader(child, ComponentType.text, self.__file_name).load() ) elif child.tag == "{{{0}}}Connections".format(ADDON_NAMESPACE): for childchild in child: connections.append(childchild.attrib["id"]) elif child.tag == "{{{0}}}Elements".format(ADDON_NAMESPACE): for childchild in child: elements.append(childchild.attrib["id"]) elif child.tag == "{{{0}}}Appearance".format(ADDON_NAMESPACE): for childchild in child: if childchild.tag == "{{{0}}}Background".format(ADDON_NAMESPACE): attrvalue = childchild.attrib["color"] if attrvalue.startswith("##"): background = ConstantValueProvider(attrvalue[1:]) elif attrvalue.startswith("#"): background = DynamicValueProvider(attrvalue[1:]) else: background = ConstantValueProvider(attrvalue) else: raise Exception elements = tuple(self.__elements[id] for id in elements) connections = tuple(self.__connections[id] for id in connections) return DiagramType(id, icon, ufl_type, display_name, elements, connections, background)
umlfri/umlfri2
umlfri2/datalayer/loaders/addon/metamodel/diagramtypeloader.py
Python
gpl-3.0
3,129
<?php /* * Copyright (C) 2017 Yang Ming <yangming0116@163.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace App\Model; use Org\Snje\Minifw as FW; use Org\Snje\Minifw\Exception; use App; /** * Description of BookPage * * @author Yang Ming <yangming0116@163.com> */ class BookFile extends BookNode { public function __construct($book, $path) { parent::__construct($book, $path); $path = $this->get_path(); if (FW\File::call( 'is_file' , $this->root . 'file/' . $path , $this->fsencoding)) { $this->type = self::TYPE_FILE; } else if (FW\File::call( 'is_dir' , $this->root . 'file/' . $path , $this->fsencoding)) { $this->dir = trim($path, '/'); $this->file = ''; $this->type = self::TYPE_DIR; } } public function get_real_path() { $path = $this->get_path(); return $this->root . 'file/' . $path; } public function is_image() { $path = $this->get_real_path(); $types = '.gif|.jpeg|.png|.bmp|.jpg|.svg'; //定义检查的图片类型 if (file_exists($path)) { $ext = pathinfo($path, PATHINFO_EXTENSION); return stripos($types, $ext); } else { return false; } } public function upload($file, $msg) { if (empty($file)) { return false; } if ($file['error'] != 0) { return false; } $path = $this->get_real_path(); FW\File::mkdir(dirname($path), $this->fsencoding); $path = FW\File::conv_to($path, $this->fsencoding); if (\move_uploaded_file($file['tmp_name'], $path)) { if ($msg !== null) { return $this->book_obj->git_cmd('commit', $msg); } return true; } else { return false; } } }
snje1987/webnote
src/Model/BookFile.php
PHP
gpl-3.0
2,631
<?php /** * Skeleton subclass for representing a row from the 'proveedor' table. * * * * This class was autogenerated by Propel 1.4.2 on: * * Thu Aug 16 14:42:09 2012 * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * * @package lib.model */ class Proveedor extends BaseProveedor { } // Proveedor
linuxska/sii-ibfdf
lib/model/Proveedor.php
PHP
gpl-3.0
460
#include "pieces.hpp" int W_PAWN = 100; int W_KNIGHT = 275; int W_BISHOP = 325; int W_ROOK = 465; int W_QUEEN = 900; int W_KING = 10000; int B_PAWN = -100; int B_KNIGHT = -275; int B_BISHOP = -325; int B_ROOK = -465; int B_QUEEN = -900; int B_KING = -10000; long MOVES = 0; int REQUIRED_CAPTURES = -3; int DEEPNESS=1; int LAST_VALUATION=0; int MOVE_COUNTER=1;
tsoj/jht-chess
src/pieces.cpp
C++
gpl-3.0
377
package com.majorpotato.febridge.commands; import com.forgeessentials.api.APIRegistry; import com.forgeessentials.commands.util.FEcmdModuleCommands; import com.forgeessentials.economy.ModuleEconomy; import com.forgeessentials.util.output.ChatOutputHandler; import com.majorpotato.febridge.FEBridge; import com.majorpotato.febridge.handler.GuiHandler; import com.majorpotato.febridge.init.ModPermissions; import com.majorpotato.febridge.network.PacketBuilder; import com.majorpotato.febridge.tileentity.ICurrencyService; import com.majorpotato.febridge.util.FormatHelper; import cpw.mods.fml.common.network.internal.FMLNetworkHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.permission.PermissionLevel; import java.util.ArrayList; import java.util.List; @SideOnly(Side.SERVER) public class CommandPermEditor extends FEcmdModuleCommands { @Override public boolean canConsoleUseCommand() { return false; } @Override public PermissionLevel getPermissionLevel() { return PermissionLevel.TRUE; } @Override public String getCommandName() { return "permgui"; } @Override public String getCommandUsage(ICommandSender sender) { return "/pg"; } @Override public String[] getDefaultAliases() { return new String[] { "permgui", "pgui", "pg" }; } @Override public String getPermissionNode() { return ModuleEconomy.PERM_COMMAND + "." + getCommandName(); } @Override public void processCommandPlayer(EntityPlayerMP player, String[] args) { PacketBuilder.instance().commandClientToOpenGui(player, GuiHandler.GUI_PERM_EDITOR); } }
debroejm/FEBridge
src/main/java/com/majorpotato/febridge/commands/CommandPermEditor.java
Java
gpl-3.0
1,898
namespace PKHeX.Core { /// <summary> Ribbons introduced in Generation 4 for Special Events </summary> public interface IRibbonSetEvent4 { bool RibbonClassic { get; set; } bool RibbonWishing { get; set; } bool RibbonPremier { get; set; } bool RibbonEvent { get; set; } bool RibbonBirthday { get; set; } bool RibbonSpecial { get; set; } bool RibbonWorld { get; set; } bool RibbonChampionWorld { get; set; } bool RibbonSouvenir { get; set; } } internal static partial class RibbonExtensions { private static readonly string[] RibbonSetNamesEvent4 = { nameof(IRibbonSetEvent4.RibbonClassic), nameof(IRibbonSetEvent4.RibbonWishing), nameof(IRibbonSetEvent4.RibbonPremier), nameof(IRibbonSetEvent4.RibbonEvent), nameof(IRibbonSetEvent4.RibbonBirthday), nameof(IRibbonSetEvent4.RibbonSpecial), nameof(IRibbonSetEvent4.RibbonWorld), nameof(IRibbonSetEvent4.RibbonChampionWorld), nameof(IRibbonSetEvent4.RibbonSouvenir) }; internal static bool[] RibbonBits(this IRibbonSetEvent4 set) { if (set == null) return new bool[9]; return new[] { set.RibbonClassic, set.RibbonWishing, set.RibbonPremier, set.RibbonEvent, set.RibbonBirthday, set.RibbonSpecial, set.RibbonWorld, set.RibbonChampionWorld, set.RibbonSouvenir, }; } internal static string[] RibbonNames(this IRibbonSetEvent4 _) => RibbonSetNamesEvent4; } }
jotebe/PKHeX
PKHeX.Core/Ribbons/IRibbonSetEvent4.cs
C#
gpl-3.0
1,706
""" sample AWS SQS enqueue an item """ import boto3 # AWS API python module import json # open a connection to the SQS service # (using ~/.aws/credentials for access info) sqs = boto3.resource('sqs') # print queues in existence #for queue in sqs.queues.all(): # print(queue.url) # create (or return existing) queue of this name try: queue = sqs.get_queue_by_name(QueueName='sample_queue') except: try: queue = sqs.create_queue(QueueName='sample_queue', Attributes={'DelaySeconds': '5'}) except: # print exception in case sqs could not create the queue import sys, traceback, uuid, datetime # API is "exc_traceback = sys.exc_info(out exc_type, out exc_value)" # next stmt: out parameters come before equal return variable exc_type, exc_value, exc_traceback = sys.exc_info() e = traceback.format_exception(exc_type, exc_value, exc_traceback) e = ''.join(e) uniqueErrorId = uuid.uuid4() data = {'status': 'E', 'uuid': uniqueErrorId, 'exception': str(e), 'now': datetime.datetime.utcnow()} print("Exception caught during SQS.create_queue: '{0}'".format(data)) sys.exit(0) # forces script exit without a traceback printed # print queue url for diagnostics print(queue.url) # on a real program, one would not purge the queue, but here is how to do it try: queue.purge() except: # only purge once every 60 seconds allowed in SQS... pass # <<== this is a noop stmt in python; this will "eat" the exception and continue execution # format the message to be sent msgBody = """ { "verb": "SCAN", "TCPIP": "97.80.230.155" } """ print ('orignal msg: "{0}"'.format(msgBody)) body = json.loads(msgBody) print('msg body after json.loads: "{0}"'.format(json.dumps(body))) # send the message string_msg = json.dumps(body) string_msgAttributes = { 'Author': { 'StringValue': __file__, # <== "sample_post_sqs.py" 'DataType': 'String' } } try: queue.send_message(MessageBody=string_msg, MessageAttributes=string_msgAttributes) except: import sys, traceback, uuid, datetime # API is "exc_traceback = sys.exc_info(out exc_type, out exc_value)" # next stmt: out parameters come before equal return variable exc_type, exc_value, exc_traceback = sys.exc_info() e = traceback.format_exception(exc_type, exc_value, exc_traceback) e = ''.join(e) uniqueErrorId = uuid.uuid4() data = {'status': 'E', 'uuid': uniqueErrorId, 'exception': str(e), 'now': datetime.datetime.utcnow()} print("Exception caught during SQS.create_queue: '{0}'".format(data)) sys.exit(0) # forces script exit without a traceback printed
opedroso/aws-python-examples
sqs/sample_post_sqs.py
Python
gpl-3.0
2,736
package com.encens.khipus.service.fixedassets; import com.encens.khipus.framework.service.GenericServiceBean; import com.encens.khipus.model.finances.FinancesCurrencyType; import com.encens.khipus.model.fixedassets.FixedAsset; import com.encens.khipus.model.fixedassets.FixedAssetDepreciationRecord; import com.encens.khipus.model.fixedassets.FixedAssetGroupPk; import com.encens.khipus.model.fixedassets.FixedAssetSubGroupPk; import com.encens.khipus.util.BigDecimalUtil; import com.encens.khipus.util.CurrencyValuesContainer; import com.encens.khipus.util.DateUtils; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.Name; import javax.ejb.Stateless; import javax.persistence.NoResultException; import javax.persistence.Query; import java.math.BigDecimal; import java.util.Calendar; import java.util.Date; /** * FixedAssetDepreciationRecordService implementation * * @author * @version 2.21 */ @Stateless @AutoCreate @Name("fixedAssetDepreciationRecordService") public class FixedAssetDepreciationRecordServiceBean extends GenericServiceBean implements FixedAssetDepreciationRecordService { public void createFixedAssetDepreciationRecord(FixedAsset fixedAsset, Date lastDayOfCurrentProcessMonth, BigDecimal lastDayOfMonthUfvExchangeRate) { Calendar currentDate = Calendar.getInstance(); FixedAssetDepreciationRecord fixedAssetDepreciationRecord = new FixedAssetDepreciationRecord(); fixedAssetDepreciationRecord.setFixedAsset(fixedAsset); fixedAssetDepreciationRecord.setCurrency(FinancesCurrencyType.U); fixedAssetDepreciationRecord.setAcumulatedDepreciation(fixedAsset.getAcumulatedDepreciation()); fixedAssetDepreciationRecord.setBsAccumulatedDepreciation( BigDecimalUtil.multiply( fixedAsset.getAcumulatedDepreciation(), lastDayOfMonthUfvExchangeRate ) ); fixedAssetDepreciationRecord.setCostCenterCode(fixedAsset.getCostCenterCode()); fixedAssetDepreciationRecord.setCustodian(fixedAsset.getCustodianJobContract().getContract().getEmployee()); fixedAssetDepreciationRecord.setDepreciation(fixedAsset.getDepreciation()); fixedAssetDepreciationRecord.setBsDepreciation( BigDecimalUtil.multiply( fixedAsset.getDepreciation(), lastDayOfMonthUfvExchangeRate ) ); fixedAssetDepreciationRecord.setDepreciationRate(fixedAsset.getDepreciationRate()); fixedAssetDepreciationRecord.setBusinessUnit(fixedAsset.getBusinessUnit()); fixedAssetDepreciationRecord.setTotalValue( BigDecimalUtil.sum( fixedAsset.getUfvOriginalValue(), fixedAsset.getImprovement() ) ); Calendar lastDay = DateUtils.toDateCalendar(lastDayOfCurrentProcessMonth); fixedAssetDepreciationRecord.setProcessDate(lastDay.getTime()); fixedAssetDepreciationRecord.setDepreciationDate(currentDate.getTime()); fixedAssetDepreciationRecord.setBsUfvRate(lastDayOfMonthUfvExchangeRate); getEntityManager().persist(fixedAssetDepreciationRecord); getEntityManager().flush(); } /** * Gets the depreciation sum for fixedAssets int he group and in the date range * * @param fixedAssetGroupId fixedAssetGroup * @param dateRange The date range start * @return The sum of depreciation amounts */ public CurrencyValuesContainer getDepreciationAmountForGroupUpTo(FixedAssetGroupPk fixedAssetGroupId, Date dateRange) { CurrencyValuesContainer res = new CurrencyValuesContainer(); try { Query query = getEntityManager().createNamedQuery("FixedAssetDepreciationRecord.findDepreciationAmountForGroupUpTo"); query.setParameter("fixedAssetGroupId", fixedAssetGroupId); query.setParameter("dateRange", dateRange); res = (CurrencyValuesContainer) query.getSingleResult(); } catch (NoResultException nrex) { log.debug("No result in the query getting depreciation amount for group."); } catch (Exception e) { log.error("Error when getting depreciation amount for group.. ", e); } return (res); } /** * Gets the depreciation sum for a group, subgroup and date range * @param fixedAssetSubGroupId fixedAssetSubGroupId * @param fixedAssetGroupId fixedAssetGroup * @param dateRange The date range start * @return The sum of depreciation amounts */ public CurrencyValuesContainer getDepreciationAmountForGroupAndSubGroupUpTo(FixedAssetGroupPk fixedAssetGroupId, FixedAssetSubGroupPk fixedAssetSubGroupId, Date dateRange) { CurrencyValuesContainer res = new CurrencyValuesContainer(); try { Query query = getEntityManager().createNamedQuery("FixedAssetDepreciationRecord.findDepreciationAmountForGroupAndSubGroupUpTo"); query.setParameter("fixedAssetGroupId", fixedAssetGroupId); query.setParameter("fixedAssetSubGroupId", fixedAssetSubGroupId); query.setParameter("dateRange", dateRange); res = (CurrencyValuesContainer) query.getSingleResult(); } catch (NoResultException nrex) { log.debug("No result in the query getting depreciation amount for group."); } catch (Exception e) { log.error("Error when getting depreciation amount for group.. ", e); } return (res); } /** * Gets the depreciation sum for fixedAssets in the group, subgroup and date range * @param fixedAssetSubGroupId fixedAssetSubGroupId * @param fixedAssetGroupId fixedAssetGroup * @param fixedAssetId fixedAssetId * @param dateRange The date range start * @return The sum of depreciation amounts */ public CurrencyValuesContainer getDepreciationAmountForFixedAssetUpTo(FixedAssetGroupPk fixedAssetGroupId, FixedAssetSubGroupPk fixedAssetSubGroupId, Long fixedAssetId, Date dateRange) { CurrencyValuesContainer res = new CurrencyValuesContainer(); try { Query query = getEntityManager().createNamedQuery("FixedAssetDepreciationRecord.findDepreciationAmountForFixedAssetUpTo"); query.setParameter("fixedAssetGroupId", fixedAssetGroupId); query.setParameter("fixedAssetSubGroupId", fixedAssetSubGroupId); query.setParameter("dateRange", dateRange); query.setParameter("fixedAssetId", fixedAssetId); res = (CurrencyValuesContainer) query.getSingleResult(); } catch (NoResultException nrex) { log.debug("No result in the query getting depreciation amount for group."); } catch (Exception e) { log.error("Error when getting depreciation amount for group.. ", e); } return (res); } /** * Get the sum of the depreciations for a FixedAsset (in Bs) * @param fixedAsset The fixedAsset * @return The sum */ public Double getBsDepreciationsSum(FixedAsset fixedAsset) { Double res=null; try { Query query = getEntityManager().createNamedQuery("FixedAssetDepreciationRecord.getBsDepreciationsSum"); query.setParameter("fixedAsset", fixedAsset); BigDecimal queryResult=(BigDecimal) query.getSingleResult(); if(queryResult!=null){ res = queryResult.doubleValue(); } } catch (NoResultException nrex) { log.debug("No result in the query getting depreciations SUM.", nrex); } catch (Exception e) { log.error("Error when getting depreciations SUM. ", e); } return (res); } }
arielsiles/sisk1
src/main/com/encens/khipus/service/fixedassets/FixedAssetDepreciationRecordServiceBean.java
Java
gpl-3.0
8,197
/*===========================================================================*\ * * * OpenFlipper * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openflipper.org * * * *--------------------------------------------------------------------------- * * This file is part of OpenFlipper. * * * * OpenFlipper 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 with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenFlipper 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 LesserGeneral Public * * License along with OpenFlipper. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision: 15658 $ * * $LastChangedBy: moebius $ * * $Date: 2012-10-15 22:19:10 +0800 (Mon, 15 Oct 2012) $ * * * \*===========================================================================*/ #include <QtGui> #include <QFileInfo> #include <QSettings> #include "FileOfv.hh" #include <iostream> #include <ACG/GL/GLState.hh> #include "OpenFlipper/BasePlugin/PluginFunctions.hh" #include "OpenFlipper/common/GlobalOptions.hh" #include <OpenMesh/Core/IO/IOManager.hh> #include <OpenFlipper/ACGHelper/DrawModeConverter.hh> void FileViewPlugin::initializePlugin() { } QString FileViewPlugin::getLoadFilters() { return QString( tr("View definition files ( *.ofv )") ); }; QString FileViewPlugin::getSaveFilters() { return QString( tr("View definition files ( *.ofv )") ); }; DataType FileViewPlugin::supportedType() { return DataType(); } int FileViewPlugin::loadObject(QString _filename) { // Declare variables int width = 1; int height = 1; ACG::Vec3d eye(1.0,1.0,1.0); ACG::Vec3d center(0.0,0.0,0.0); ACG::Vec3d up(1.0,0.0,0.0); // float fovy = 0; ACG::Vec4f background; //bool e_widthAndHeight = false; bool e_eye = false; bool e_center = false; bool e_up = false; // bool e_fovy = false; bool e_background = false; QSettings settings(_filename, QSettings::IniFormat); settings.beginGroup("VIEW"); if(settings.contains("Width") && settings.contains("Height")) { width = settings.value("Width").toInt(); height = settings.value("Height").toInt(); std::cerr << "Setting new viewport to " << width << "x" << height << std::endl; //e_widthAndHeight = true; } if(settings.contains("EyeX")) { eye[0] = settings.value("EyeX").toDouble(); eye[1] = settings.value("EyeY").toDouble(); eye[2] = settings.value("EyeZ").toDouble(); std::cerr << "Setting new eye position to " << eye << std::endl; e_eye = true; } if(settings.contains("CenterX")) { center[0] = settings.value("CenterX").toDouble(); center[1] = settings.value("CenterY").toDouble(); center[2] = settings.value("CenterZ").toDouble(); std::cerr << "Setting new scene center to " << center << std::endl; e_center = true; } if(settings.contains("UpX")) { up[0] = settings.value("UpX").toDouble(); up[1] = settings.value("UpY").toDouble(); up[2] = settings.value("UpZ").toDouble(); std::cerr << "Setting new up vector to " << up << std::endl; e_up = true; } // if(settings.contains("Fovy")) { // fovy = settings.value("Fovy").toDouble(); // std::cerr << "Setting fovy to " << fovy << std::endl; // e_fovy = true; // } if(settings.contains("BackgroundR")) { background[0] = settings.value("BackgroundR").toDouble(); background[1] = settings.value("BackgroundG").toDouble(); background[2] = settings.value("BackgroundB").toDouble(); background[3] = settings.value("BackgroundA").toDouble(); std::cerr << "Setting new background color to " << background << std::endl; e_background = true; } settings.endGroup(); // Now set new projection and view // Get number of viewers int viewers = PluginFunctions::viewers(); for(int i = 0; i < viewers; ++i) { Viewer::ViewerProperties& props = PluginFunctions::viewerProperties(i); ACG::GLState& state = props.glState(); // // Perspective update // double aspect = 0.0; // if(e_widthAndHeight) aspect = width / height; // else aspect = state.aspect(); // Set projection matrix //if(e_fovy) // state.perspective(fovy, aspect, near, far); // Viewport //if(e_widthAndHeight) // state.viewport(0, 0, width, height); //std::cerr << "Fovy: " << state.fovy() << std::endl; } // LookAt ACG::Vec3d new_eye = e_eye ? eye : PluginFunctions::eyePos(); ACG::Vec3d new_center = e_center ? center : PluginFunctions::sceneCenter(); ACG::Vec3d new_up = e_up ? up : PluginFunctions::upVector(); PluginFunctions::lookAt(new_eye, new_center, new_up); // Background color if(e_background) { PluginFunctions::setBackColor(background); } emit updateView(); return 0; }; bool FileViewPlugin::saveObject(int /*_id*/, QString /*_filename*/) { return true; } Q_EXPORT_PLUGIN2( fileviewplugin , FileViewPlugin );
softwarekid/OpenFlipper
PluginCollection-FilePlugins/Plugin-FileOfv/FileOfv.cc
C++
gpl-3.0
7,632
<?php /* * This file is part of WebKeyPass. * * Copyright © 2013 Université Catholique de Louvain * * WebKeyPass 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. * * WebKeyPass 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 WebKeyPass. If not, see <http://www.gnu.org/licenses/>. * * Author: Sébastien Wilmet */ namespace UCL\WebKeyPassBundle\Controller; use UCL\WebKeyPassBundle\Form\CategoryForm; class AddSubCategoryAction extends FormAddAction { protected $fullname = 'Add Sub-category'; protected $success_msg = 'Sub-category added successfully.'; protected function getForm () { $form = new CategoryForm (); $form->setNodeRepository ($this->controller->getNodeRepo ()); return $form; } protected function getFormData () { return array ('list_name' => '', 'other_name' => '', 'icon' => '', 'comment' => '', '_node' => $this->node); } protected function saveData ($db_manager, $form) { $data = $form->getData (); $node = $data['_node']; if ($data['other_name'] != '') { $node->setName ($data['other_name']); } else { $node->setName ($data['list_name']); } $node->setIcon ($data['icon']); $node->setComment ($data['comment']); $node->setType (0); $db_manager->persist ($node); } }
UCL-SIPR/WebKeyPass
Controller/AddSubCategoryAction.php
PHP
gpl-3.0
1,948
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class gameuiTutorialBracketHideEvent : redEvent { [Ordinal(0)] [RED("bracketID")] public CName BracketID { get; set; } public gameuiTutorialBracketHideEvent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/gameuiTutorialBracketHideEvent.cs
C#
gpl-3.0
375
using UnityEngine; using System.Collections.Generic; using System.Collections; public class Director : MonoBehaviour { private List<GameObject> levelElements = new List<GameObject>(); private List<float> elementTimes = new List<float>(); private float right = 17.0f; private float left = -19.0f; public float levelSpeed = 0.5f; public GameObject BG1, BG2, floor; public GameObject dashable; public GameObject GUIbg; public CameraController cam; public CharController pony; public GUIText textBlob; public enum Element{ CHANGER, MEANNICE, EVENTS }; public static float normalSpeed = 0.5f; public void SetSpeed(float speed) { if (speed == 0) levelSpeed = normalSpeed; else levelSpeed = speed; floor.GetComponent<BackgroundScroller>().speed = levelSpeed; BG1.GetComponent<BackgroundScroller>().speed = levelSpeed*.15f; BG2.GetComponent<BackgroundScroller>().speed = levelSpeed*.75f; } int crashCounter = 0; int dashCounter = 0; public void ShowHitMessage(FaceController face) { string message; if ((pony.GetCurrentState() & CharController.State.BURST) == CharController.State.BURST) { message = dashEffects[dashCounter]; dashCounter = Mathf.Min (dashEffects.Length-1, ++dashCounter); GUIbg.renderer.material.SetColor("_TintColor", Color.blue); StartCoroutine(fadeToFrom(Color.black, Color.blue)); face.Explode(true); pony.Explode(); } else { message = crashEffects[crashCounter]; cam.Shake(); face.Explode(true); crashCounter = Mathf.Min (crashEffects.Length-1, ++crashCounter); StartCoroutine(fadeToFrom(Color.black, Color.red)); GUIbg.renderer.material.SetColor("_TintColor", Color.red); } if (dashCounter+crashCounter >= crashEffects.Length + dashEffects.Length - 2) { ended = true; message = "That's all I got for you, Chen! :)"; } textBlob.text = message; } private IEnumerator fadeToFrom(Color a, Color b) { float completion = 0f; while (completion < 0.8f) { completion += Time.deltaTime; Color c = Color.Lerp(a, b, completion); GUIbg.renderer.material.SetColor("_TintColor", c); yield return null; } // Return completion = 0.2f; while (completion < 1.0f) { completion += Time.deltaTime; Color c = Color.Lerp(b, a, completion); GUIbg.renderer.material.SetColor("_TintColor", c); yield return null; } yield return null; } void Start () { Init (); //print(GUIbg.renderer.material.GetColor("_TintColor") ); } public static bool gamePaused = false; public static bool ended = false; public GUIText credits; void Update () { SpawnManager(); if (Input.GetKeyUp(KeyCode.Space)) { Time.timeScale = 1.0f - Time.timeScale; gamePaused = !gamePaused; credits.text = (gamePaused||ended)?"Credits:\nAll game development: Keerthik\n" + "Inspiration for raw material: Roydan\nA friend worth doing this for: CHYENN" :"Press space to pause"; if (gamePaused) textBlob.text = "Press Space to upause the game"; else textBlob.text = "Z = Dash\nX = Jump"; } /* // Control game pacing if (time > elementTimes[(int)(elementTimes.Count/2)]) normalSpeed = 0.750f; */ } void OnGUI() { if (gamePaused) { if (GUI.Button(RelRect(0.3f, 0.7f, 0.15f, 0.05f), "Change Music")) { MusicController.NextTrack(); } if (GUI.Button(RelRect(0.55f, 0.7f, 0.15f, 0.05f), "Rewatch Intro")) { Application.LoadLevel("IntroScene"); } } } void Init() { // Set parameters levelSpeed = 0.5f; normalSpeed = 0.5f; levelElements = new List<GameObject>(); elementTimes = new List<float>(); for (int i = 0; i < crashEffects.Length+dashEffects.Length; i++) { int thisY = Random.Range(1, 3); levelElements.Add(Instantiate(dashable, new Vector3(30, floor.transform.position.y + 4 + 1.5f*thisY, pony.transform.position.z), Quaternion.identity) as GameObject); levelElements[i].GetComponent<FaceController>().director = this; elementTimes.Add(4.0f + i*(3.5f + 0.1f*i)); } } private float time = 0.0f; private void SpawnManager() { time += levelSpeed*Time.deltaTime; // Manage adding new elements for leftover if (elementTimes.Count < dashEffects.Length + crashEffects.Length - dashCounter - crashCounter) { int thisY = Random.Range(1, 3); levelElements.Add(Instantiate(dashable, new Vector3(30, floor.transform.position.y + 4 + 1.5f*thisY, pony.transform.position.z), Quaternion.identity) as GameObject); levelElements[levelElements.Count-1].GetComponent<FaceController>().director = this; elementTimes.Add(elementTimes[elementTimes.Count-1] + 5f); } // Manage spawning level Elements into game for (int i=0; i<elementTimes.Count; i++) { float timePos = time - elementTimes[i]; if (timePos > 0) { GameObject element = levelElements[i]; element.transform.position = new Vector3(Mathf.Lerp(right, left, 0.5f*timePos), element.transform.position.y, pony.transform.position.z); if (element.transform.position.x < left/2f) { // dodge-effect } if (element.transform.position.x < left+.01f) { Destroy(element); levelElements.RemoveAt(i); elementTimes.RemoveAt(i); } } } } private Rect RelRect(float left, float top, float width, float height) { return new Rect(left*Screen.width, top*Screen.height, width*Screen.width, height*Screen.height); } private string [] dashEffects = { "You have forgiven me for all the mean things\n I've said to you (right?) ^_^\n" + "[ Keep dashing through for me to not be mean ]", "You are the first person who bought me a gift\n I always wanted [Oppa Gundam Style]", "You were always a good friend to talk to \nwhen I was lonely and stuff", "You are the only person I remembered to get\n anything(Halwa) for, even when \n" + "I forgot to get anyone else stuff", "I had a blast all the time we hung out\nwinter 2012! Quality single friends' time :) Thanks!", "I just wanted to let you know, even when\nyou thought you were being whiny\n" + "and sad, I was happy to talk to and\nhang out with you, and I hope \nI made you feel better~", "You made it this far! I hope we can be\nthere for each other always!", "Congratulations!!!\n You have just experienced the \nnicest thing I've done/made for anyone :)", "This game took a total of around 75 hours for me to make\n - about 3 months of bart rides :O\n" + "I hope you enjoyed it :)\n[ Feel free to keep playing \nto see the rest of the mean stuff ]", }; private string [] crashEffects = { "I enjoyed making you throw a shoe at Roydan ^_^\n\n" + "[ Dash through these for nicer things, \n" + "otherwise I'll say mean things ]", "Mean as it was, that thing I said \ncomparing your writing papers to \n" + "making relationships work was darn straight clever,\n" + "right?", "You're a jerk with how terribly you respond on IM", "I found this on your facebook wall from me:\nYou're fugly\n -Albert", "Oh that was when QED took over your wall for a night", "Shortly before QED issued you an infraction notice teehee >:D", "You dropped comparch in sophomore year \nand we gave you much crap about it :D", "YOU'RE AS CRAZY AS ROYDAN SOMETIMES", "Damn I should have more mean things to say to you...", "Oh right. You're fat. Hehe. Moo", "Gee, stop running into them *dash* through them~", "Ok seriously, figure out the game already, and stop getting hit\n" + "...unless you already finished it and just want to read the mean stuff :D", }; }
keerthik/fluttercorn
Assets/Scripts/Director.cs
C#
gpl-3.0
7,502
from Products.CMFCore.utils import getToolByName from cStringIO import StringIO from Products.OpenPlans.Extensions.Install import installZ3Types from Products.OpenPlans.Extensions.setup import migrate_listen_member_lookup from Products.OpenPlans.Extensions.setup import reinstallSubskins def migrate_listen(self): out = StringIO() # set listen to the active property configuration portal_setup_tool = getToolByName(self, 'portal_setup') portal_setup_tool.setImportContext('profile-listen:default') out.write('updated generic setup tool properties\n') # run the listen import step portal_setup_tool.runImportStep('listen-various', True) out.write('Listen import step run\n') # remove the open mailing list fti portal_types = getToolByName(self, 'portal_types') portal_types.manage_delObjects(['Open Mailing List']) out.write('open mailing list fti removed\n') # now run the install z3types to add it back installZ3Types(self, out) out.write('z3 types installed (Open Mailing List fti)\n') # migrate the listen local utility # self, self? migrate_listen_member_lookup(self, self) out.write('listen member lookup utility migrated\n') # remove openplans skins portal_skins = getToolByName(self, 'portal_skins') skins_to_remove = ['openplans', 'openplans_images', 'openplans_patches', 'openplans_richwidget', 'openplans_styles'] portal_skins.manage_delObjects(skins_to_remove) out.write('removed openplans skins: %s\n' % ', '.join(skins_to_remove)) # reinstall openplans skins portal_quickinstaller = getToolByName(self, 'portal_quickinstaller') portal_quickinstaller.reinstallProducts(['opencore.siteui']) out.write('reinstall opencore.siteui - openplans skins\n') # reinstall subskins reinstallSubskins(self, self) out.write('subskins reinstalled\n') # run listen migration? return out.getvalue()
socialplanning/opencore
Products/OpenPlans/Extensions/migrate_listen.py
Python
gpl-3.0
1,938
package org.mindroid.impl.statemachine.properties.sensorproperties; import org.mindroid.api.statemachine.properties.IProperty; import org.mindroid.api.statemachine.properties.SimpleEV3SensorProperty; import org.mindroid.common.messages.hardware.Sensormode; import org.mindroid.impl.ev3.EV3PortID; /** * Created by Torbe on 02.05.2017. */ public class Ambient extends SimpleEV3SensorProperty { /** * * @param port brickport of the Ambient-mode running sensor */ public Ambient(EV3PortID port) { super(port); } @Override public IProperty copy() { return new Ambient(getSensorPort()); } @Override public Sensormode getSensormode() { return Sensormode.AMBIENT; } }
Echtzeitsysteme/mindroid
impl/androidApp/api/src/main/java/org/mindroid/impl/statemachine/properties/sensorproperties/Ambient.java
Java
gpl-3.0
745
jQuery(window).load( function() { if( local_data.form_id ) { var pardot_id = local_data.form_id; } else{ var pardot_id = jQuery('[id^="form-wysija-"]').attr('id'); } jQuery('.pardotform').contents().find('#pardot-form').submit(function () { var ajax_data = { action: 'pardot_capture_lead', 'firstname': jQuery("input[name='" + local_data.first_name + "']").val(), 'lastname': jQuery("input[name='" + local_data.last_name + "']").val(), 'email': jQuery("input[name='" + local_data.email + "']").val(), 'form_id': pardot_id, } jQuery.ajax( { url: local_data.url, type: 'POST', dataType: 'json', data: ajax_data, }); }); });
leadferry/lf-leads
leads/classes/vendors/js/pardot.js
JavaScript
gpl-3.0
673
package me.jezzadabomb.es2.client.renderers.tile; import static org.lwjgl.opengl.GL11.*; import java.util.Random; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import me.jezzadabomb.es2.client.utils.RenderUtils; import me.jezzadabomb.es2.common.lib.TextureMaps; import me.jezzadabomb.es2.common.tileentity.TileQuantumStateDisruptor; @SideOnly(Side.CLIENT) public class TileQuantumStateDisruptorRenderer extends TileEntitySpecialRenderer { int texture; public TileQuantumStateDisruptorRenderer() { texture = new Random().nextInt(TextureMaps.QUANTUM_TEXTURES.length); } private void renderQuantumStateDisruptor(TileQuantumStateDisruptor tileEntity, double x, double y, double z, float tick) { glPushMatrix(); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glTranslated(x - 0.75F, y - 1.60F, z + 1.75F); float translate = 1.28F; glTranslatef(translate, 0.0F, -translate); glRotatef(-(float) (720.0 * (System.currentTimeMillis() & 0x3FFFL) / 0x3FFFL), 0.0F, 1.0F, 0.0F); glTranslatef(-translate, 0.0F, translate); glRotatef(-90F, 1.0F, 0.0F, 0.0F); glColor4f(1.0F, 1.0F, 1.0F, 0.5F); float scale = 0.01F; glScalef(scale, scale, scale); RenderUtils.bindTexture(TextureMaps.QUANTUM_TEXTURES[texture]); RenderUtils.drawTexturedQuad(0, 0, 0, 0, 256, 256, 161); glEnable(GL_CULL_FACE); glDisable(GL_BLEND); glPopMatrix(); } @Override public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float tick) { if (tileEntity instanceof TileQuantumStateDisruptor) renderQuantumStateDisruptor(((TileQuantumStateDisruptor) tileEntity), x, y, z, tick); } }
Jezza/Elemental-Sciences-2
es_common/me/jezzadabomb/es2/client/renderers/tile/TileQuantumStateDisruptorRenderer.java
Java
gpl-3.0
2,037
/* * Copyright 2014 pushbit <pushbit@gmail.com> * * This file is part of Dining Out. * * Dining Out 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. * * Dining Out 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 Dining Out. If not, * see <http://www.gnu.org/licenses/>. */ package net.sf.diningout.app; import android.app.IntentService; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import net.sf.diningout.provider.Contract.Restaurants; import net.sf.sprockets.database.Cursors; import net.sf.sprockets.util.Geos; import java.io.IOException; import java.util.List; import static net.sf.sprockets.app.SprocketsApplication.context; import static net.sf.sprockets.app.SprocketsApplication.cr; import static net.sf.sprockets.gms.analytics.Trackers.exception; /** * Gets latitude and longitude of a restaurant's address and downloads a Street View image. Callers * must include {@link #EXTRA_ID} in their Intent extras. */ public class RestaurantGeocodeService extends IntentService { /** * ID of the restaurant. */ public static final String EXTRA_ID = "intent.extra.ID"; private static final String TAG = RestaurantGeocodeService.class.getSimpleName(); public RestaurantGeocodeService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { long id = intent.getLongExtra(EXTRA_ID, 0L); Uri uri = ContentUris.withAppendedId(Restaurants.CONTENT_URI, id); String[] proj = {Restaurants.ADDRESS}; String address = Cursors.firstString(cr().query(uri, proj, null, null, null)); if (!TextUtils.isEmpty(address)) { try { ContentValues vals = new ContentValues(3); if (geocode(address, vals)) { cr().update(uri, vals, null, null); RestaurantService.photo(id, vals); } } catch (IOException e) { Log.e(TAG, "geocoding address or downloading Street View image", e); exception(e); } } } /** * Put the {@link Restaurants#LATITUDE LATITUDE}, {@link Restaurants#LONGITUDE LONGITUDE}, and * {@link Restaurants#LONGITUDE_COS LONGITUDE_COS} in the values. * * @return true if coordinates were put in the values */ public static boolean geocode(String address, ContentValues vals) throws IOException { List<Address> locs = new Geocoder(context()).getFromLocationName(address, 1); if (locs != null && locs.size() > 0) { Address loc = locs.get(0); if (loc.hasLatitude() && loc.hasLongitude()) { double lat = loc.getLatitude(); vals.put(Restaurants.LATITUDE, lat); vals.put(Restaurants.LONGITUDE, loc.getLongitude()); vals.put(Restaurants.LONGITUDE_COS, Geos.cos(lat)); return true; } } return false; } }
mobilist/dining-out
src/net/sf/diningout/app/RestaurantGeocodeService.java
Java
gpl-3.0
3,609
<?php /******************************************************************************* * Copyright 2009-2016 Amazon Services. 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://aws.amazon.com/apache2.0 * This file 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. ******************************************************************************* * PHP Version 5 * @category Amazon * @package FBA Inventory Service MWS * @version 2010-10-01 * Library Version: 2014-09-30 * Generated: Wed May 04 17:14:15 UTC 2016 */ /** * @see FBAInventoryServiceMWS_Interface */ require_once (dirname(__FILE__) . '/Interface.php'); /** * FBAInventoryServiceMWS_Client is an implementation of FBAInventoryServiceMWS * */ class FBAInventoryServiceMWS_Client implements FBAInventoryServiceMWS_Interface { const SERVICE_VERSION = '2010-10-01'; const MWS_CLIENT_VERSION = '2014-09-30'; /** @var string */ private $_awsAccessKeyId = null; /** @var string */ private $_awsSecretAccessKey = null; /** @var array */ private $_config = array ('ServiceURL' => null, 'UserAgent' => 'FBAInventoryServiceMWS PHP5 Library', 'SignatureVersion' => 2, 'SignatureMethod' => 'HmacSHA256', 'ProxyHost' => null, 'ProxyPort' => -1, 'ProxyUsername' => null, 'ProxyPassword' => null, 'MaxErrorRetry' => 3, 'Headers' => array() ); /** * Get Service Status * Gets the status of the service. * Status is one of GREEN, RED representing: * GREEN: The service section is operating normally. * RED: The service section disruption. * * @param mixed $request array of parameters for FBAInventoryServiceMWS_Model_GetServiceStatus request or FBAInventoryServiceMWS_Model_GetServiceStatus object itself * @see FBAInventoryServiceMWS_Model_GetServiceStatusRequest * @return FBAInventoryServiceMWS_Model_GetServiceStatusResponse * * @throws FBAInventoryServiceMWS_Exception */ public function getServiceStatus($request) { if (!($request instanceof FBAInventoryServiceMWS_Model_GetServiceStatusRequest)) { require_once (dirname(__FILE__) . '/Model/GetServiceStatusRequest.php'); $request = new FBAInventoryServiceMWS_Model_GetServiceStatusRequest($request); } $parameters = $request->toQueryParameterArray(); $parameters['Action'] = 'GetServiceStatus'; $httpResponse = $this->_invoke($parameters); require_once (dirname(__FILE__) . '/Model/GetServiceStatusResponse.php'); $response = FBAInventoryServiceMWS_Model_GetServiceStatusResponse::fromXML($httpResponse['ResponseBody']); $response->setResponseHeaderMetadata($httpResponse['ResponseHeaderMetadata']); return $response; } /** * Convert GetServiceStatusRequest to name value pairs */ private function _convertGetServiceStatus($request) { $parameters = array(); $parameters['Action'] = 'GetServiceStatus'; if ($request->isSetSellerId()) { $parameters['SellerId'] = $request->getSellerId(); } if ($request->isSetMWSAuthToken()) { $parameters['MWSAuthToken'] = $request->getMWSAuthToken(); } if ($request->isSetMarketplace()) { $parameters['Marketplace'] = $request->getMarketplace(); } return $parameters; } /** * List Inventory Supply * Get information about the supply of seller-owned inventory in * Amazon's fulfillment network. "Supply" is inventory that is available * for fulfilling (a.k.a. Multi-Channel Fulfillment) orders. In general * this includes all sellable inventory that has been received by Amazon, * that is not reserved for existing orders or for internal FC processes, * and also inventory expected to be received from inbound shipments. * * This operation provides 2 typical usages by setting different * ListInventorySupplyRequest value: * * 1. Set value to SellerSkus and not set value to QueryStartDateTime, * this operation will return all sellable inventory that has been received * by Amazon's fulfillment network for these SellerSkus. * * 2. Not set value to SellerSkus and set value to QueryStartDateTime, * This operation will return information about the supply of all seller-owned * inventory in Amazon's fulfillment network, for inventory items that may have had * recent changes in inventory levels. It provides the most efficient mechanism * for clients to maintain local copies of inventory supply data. * * Only 1 of these 2 parameters (SellerSkus and QueryStartDateTime) can be set value for 1 request. * If both with values or neither with values, an exception will be thrown. * * This operation is used with ListInventorySupplyByNextToken * to paginate over the resultset. Begin pagination by invoking the * ListInventorySupply operation, and retrieve the first set of * results. If more results are available,continuing iteratively requesting further * pages results by invoking the ListInventorySupplyByNextToken operation (each time * passing in the NextToken value from the previous result), until the returned NextToken * is null, indicating no further results are available. * * @param mixed $request array of parameters for FBAInventoryServiceMWS_Model_ListInventorySupply request or FBAInventoryServiceMWS_Model_ListInventorySupply object itself * @see FBAInventoryServiceMWS_Model_ListInventorySupplyRequest * @return FBAInventoryServiceMWS_Model_ListInventorySupplyResponse * * @throws FBAInventoryServiceMWS_Exception */ public function listInventorySupply($request) { if (!($request instanceof FBAInventoryServiceMWS_Model_ListInventorySupplyRequest)) { require_once (dirname(__FILE__) . '/Model/ListInventorySupplyRequest.php'); $request = new FBAInventoryServiceMWS_Model_ListInventorySupplyRequest($request); } $parameters = $request->toQueryParameterArray(); $parameters['Action'] = 'ListInventorySupply'; $httpResponse = $this->_invoke($parameters); require_once (dirname(__FILE__) . '/Model/ListInventorySupplyResponse.php'); $response = FBAInventoryServiceMWS_Model_ListInventorySupplyResponse::fromXML($httpResponse['ResponseBody']); $response->setResponseHeaderMetadata($httpResponse['ResponseHeaderMetadata']); return $response; } /** * Convert ListInventorySupplyRequest to name value pairs */ private function _convertListInventorySupply($request) { $parameters = array(); $parameters['Action'] = 'ListInventorySupply'; if ($request->isSetSellerId()) { $parameters['SellerId'] = $request->getSellerId(); } if ($request->isSetMWSAuthToken()) { $parameters['MWSAuthToken'] = $request->getMWSAuthToken(); } if ($request->isSetMarketplace()) { $parameters['Marketplace'] = $request->getMarketplace(); } if ($request->isSetMarketplaceId()) { $parameters['MarketplaceId'] = $request->getMarketplaceId(); } if ($request->isSetSellerSkus()) { $SellerSkusListInventorySupplyRequest = $request->getSellerSkus(); foreach ($SellerSkusListInventorySupplyRequest->getmember() as $memberSellerSkusIndex => $memberSellerSkus) { $parameters['SellerSkus' . '.' . 'member' . '.' . ($memberSellerSkusIndex + 1)] = $memberSellerSkus; } } if ($request->isSetQueryStartDateTime()) { $parameters['QueryStartDateTime'] = $request->getQueryStartDateTime(); } if ($request->isSetResponseGroup()) { $parameters['ResponseGroup'] = $request->getResponseGroup(); } return $parameters; } /** * List Inventory Supply By Next Token * Continues pagination over a resultset of inventory data for inventory * items. * * This operation is used in conjunction with ListUpdatedInventorySupply. * Please refer to documentation for that operation for further details. * * @param mixed $request array of parameters for FBAInventoryServiceMWS_Model_ListInventorySupplyByNextToken request or FBAInventoryServiceMWS_Model_ListInventorySupplyByNextToken object itself * @see FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenRequest * @return FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenResponse * * @throws FBAInventoryServiceMWS_Exception */ public function listInventorySupplyByNextToken($request) { if (!($request instanceof FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenRequest)) { require_once (dirname(__FILE__) . '/Model/ListInventorySupplyByNextTokenRequest.php'); $request = new FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenRequest($request); } $parameters = $request->toQueryParameterArray(); $parameters['Action'] = 'ListInventorySupplyByNextToken'; $httpResponse = $this->_invoke($parameters); require_once (dirname(__FILE__) . '/Model/ListInventorySupplyByNextTokenResponse.php'); $response = FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenResponse::fromXML($httpResponse['ResponseBody']); $response->setResponseHeaderMetadata($httpResponse['ResponseHeaderMetadata']); return $response; } /** * Convert ListInventorySupplyByNextTokenRequest to name value pairs */ private function _convertListInventorySupplyByNextToken($request) { $parameters = array(); $parameters['Action'] = 'ListInventorySupplyByNextToken'; if ($request->isSetSellerId()) { $parameters['SellerId'] = $request->getSellerId(); } if ($request->isSetMWSAuthToken()) { $parameters['MWSAuthToken'] = $request->getMWSAuthToken(); } if ($request->isSetMarketplace()) { $parameters['Marketplace'] = $request->getMarketplace(); } if ($request->isSetNextToken()) { $parameters['NextToken'] = $request->getNextToken(); } return $parameters; } /** * Construct new Client * * @param string $awsAccessKeyId AWS Access Key ID * @param string $awsSecretAccessKey AWS Secret Access Key * @param array $config configuration options. * Valid configuration options are: * <ul> * <li>ServiceURL</li> * <li>UserAgent</li> * <li>SignatureVersion</li> * <li>TimesRetryOnError</li> * <li>ProxyHost</li> * <li>ProxyPort</li> * <li>ProxyUsername<li> * <li>ProxyPassword<li> * <li>MaxErrorRetry</li> * </ul> */ public function __construct( $awsAccessKeyId, $awsSecretAccessKey, $config, $applicationName, $applicationVersion, $attributes = null) { iconv_set_encoding('output_encoding', 'UTF-8'); iconv_set_encoding('input_encoding', 'UTF-8'); iconv_set_encoding('internal_encoding', 'UTF-8'); $this->_awsAccessKeyId = $awsAccessKeyId; $this->_awsSecretAccessKey = $awsSecretAccessKey; $this->_serviceVersion = $applicationVersion; if (!is_null($config)) $this->_config = array_merge($this->_config, $config); $this->setUserAgentHeader($applicationName, $applicationVersion, $attributes); } public function setUserAgentHeader( $applicationName, $applicationVersion, $attributes = null) { if (is_null($attributes)) { $attributes = array (); } $this->_config['UserAgent'] = $this->constructUserAgentHeader($applicationName, $applicationVersion, $attributes); } private function constructUserAgentHeader($applicationName, $applicationVersion, $attributes = null) { if (is_null($applicationName) || $applicationName === "") { throw new InvalidArgumentException('$applicationName cannot be null'); } if (is_null($applicationVersion) || $applicationVersion === "") { throw new InvalidArgumentException('$applicationVersion cannot be null'); } $userAgent = $this->quoteApplicationName($applicationName) . '/' . $this->quoteApplicationVersion($applicationVersion); $userAgent .= ' ('; $userAgent .= 'Language=PHP/' . phpversion(); $userAgent .= '; '; $userAgent .= 'Platform=' . php_uname('s') . '/' . php_uname('m') . '/' . php_uname('r'); $userAgent .= '; '; $userAgent .= 'MWSClientVersion=' . self::MWS_CLIENT_VERSION; foreach ($attributes as $key => $value) { if (empty($value)) { throw new InvalidArgumentException("Value for $key cannot be null or empty."); } $userAgent .= '; ' . $this->quoteAttributeName($key) . '=' . $this->quoteAttributeValue($value); } $userAgent .= ')'; return $userAgent; } /** * Collapse multiple whitespace characters into a single ' ' character. * @param $s * @return string */ private function collapseWhitespace($s) { return preg_replace('/ {2,}|\s/', ' ', $s); } /** * Collapse multiple whitespace characters into a single ' ' and backslash escape '\', * and '/' characters from a string. * @param $s * @return string */ private function quoteApplicationName($s) { $quotedString = $this->collapseWhitespace($s); $quotedString = preg_replace('/\\\\/', '\\\\\\\\', $quotedString); $quotedString = preg_replace('/\//', '\\/', $quotedString); return $quotedString; } /** * Collapse multiple whitespace characters into a single ' ' and backslash escape '\', * and '(' characters from a string. * * @param $s * @return string */ private function quoteApplicationVersion($s) { $quotedString = $this->collapseWhitespace($s); $quotedString = preg_replace('/\\\\/', '\\\\\\\\', $quotedString); $quotedString = preg_replace('/\\(/', '\\(', $quotedString); return $quotedString; } /** * Collapse multiple whitespace characters into a single ' ' and backslash escape '\', * and '=' characters from a string. * * @param $s * @return unknown_type */ private function quoteAttributeName($s) { $quotedString = $this->collapseWhitespace($s); $quotedString = preg_replace('/\\\\/', '\\\\\\\\', $quotedString); $quotedString = preg_replace('/\\=/', '\\=', $quotedString); return $quotedString; } /** * Collapse multiple whitespace characters into a single ' ' and backslash escape ';', '\', * and ')' characters from a string. * * @param $s * @return unknown_type */ private function quoteAttributeValue($s) { $quotedString = $this->collapseWhitespace($s); $quotedString = preg_replace('/\\\\/', '\\\\\\\\', $quotedString); $quotedString = preg_replace('/\\;/', '\\;', $quotedString); $quotedString = preg_replace('/\\)/', '\\)', $quotedString); return $quotedString; } // Private API ------------------------------------------------------------// /** * Invoke request and return response */ private function _invoke(array $parameters) { try { if (empty($this->_config['ServiceURL'])) { require_once (dirname(__FILE__) . '/Exception.php'); throw new FBAInventoryServiceMWS_Exception( array ('ErrorCode' => 'InvalidServiceURL', 'Message' => "Missing serviceUrl configuration value. You may obtain a list of valid MWS URLs by consulting the MWS Developer's Guide, or reviewing the sample code published along side this library.")); } $parameters = $this->_addRequiredParameters($parameters); $retries = 0; for (;;) { $response = $this->_httpPost($parameters); $status = $response['Status']; if ($status == 200) { return array('ResponseBody' => $response['ResponseBody'], 'ResponseHeaderMetadata' => $response['ResponseHeaderMetadata']); } if ($status == 500 && $this->_pauseOnRetry(++$retries)) { continue; } throw $this->_reportAnyErrors($response['ResponseBody'], $status, $response['ResponseHeaderMetadata']); } } catch (FBAInventoryServiceMWS_Exception $se) { throw $se; } catch (Exception $t) { require_once (dirname(__FILE__) . '/Exception.php'); throw new FBAInventoryServiceMWS_Exception(array('Exception' => $t, 'Message' => $t->getMessage())); } } /** * Look for additional error strings in the response and return formatted exception */ private function _reportAnyErrors($responseBody, $status, $responseHeaderMetadata, Exception $e = null) { $exProps = array(); $exProps["StatusCode"] = $status; $exProps["ResponseHeaderMetadata"] = $responseHeaderMetadata; libxml_use_internal_errors(true); // Silence XML parsing errors $xmlBody = simplexml_load_string($responseBody); if ($xmlBody !== false) { // Check XML loaded without errors $exProps["XML"] = $responseBody; $exProps["ErrorCode"] = $xmlBody->Error->Code; $exProps["Message"] = $xmlBody->Error->Message; $exProps["ErrorType"] = !empty($xmlBody->Error->Type) ? $xmlBody->Error->Type : "Unknown"; $exProps["RequestId"] = !empty($xmlBody->RequestID) ? $xmlBody->RequestID : $xmlBody->RequestId; // 'd' in RequestId is sometimes capitalized } else { // We got bad XML in response, just throw a generic exception $exProps["Message"] = "Internal Error"; } require_once (dirname(__FILE__) . '/Exception.php'); return new FBAInventoryServiceMWS_Exception($exProps); } /** * Perform HTTP post with exponential retries on error 500 and 503 * */ private function _httpPost(array $parameters) { $config = $this->_config; $query = $this->_getParametersAsString($parameters); $url = parse_url ($config['ServiceURL']); $uri = array_key_exists('path', $url) ? $url['path'] : null; if (!isset ($uri)) { $uri = "/"; } switch ($url['scheme']) { case 'https': $scheme = 'https://'; $port = isset($url['port']) ? $url['port'] : 443; break; default: $scheme = 'http://'; $port = isset($url['port']) ? $url['port'] : 80; } $allHeaders = $config['Headers']; $allHeaders['Content-Type'] = "application/x-www-form-urlencoded; charset=utf-8"; // We need to make sure to set utf-8 encoding here $allHeaders['Expect'] = null; // Don't expect 100 Continue $allHeadersStr = array(); foreach($allHeaders as $name => $val) { $str = $name . ": "; if(isset($val)) { $str = $str . $val; } $allHeadersStr[] = $str; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $scheme . $url['host'] . $uri); curl_setopt($ch, CURLOPT_PORT, $port); $this->setSSLCurlOptions($ch); curl_setopt($ch, CURLOPT_USERAGENT, $this->_config['UserAgent']); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $query); curl_setopt($ch, CURLOPT_HTTPHEADER, $allHeadersStr); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if ($config['ProxyHost'] != null && $config['ProxyPort'] != -1) { curl_setopt($ch, CURLOPT_PROXY, $config['ProxyHost'] . ':' . $config['ProxyPort']); } if ($config['ProxyUsername'] != null && $config['ProxyPassword'] != null) { curl_setopt($ch, CURLOPT_PROXYUSERPWD, $config['ProxyUsername'] . ':' . $config['ProxyPassword']); } $response = ""; $response = curl_exec($ch); if($response === false) { require_once (dirname(__FILE__) . '/Exception.php'); $exProps["Message"] = curl_error($ch); $exProps["ErrorType"] = "HTTP"; curl_close($ch); throw new FBAInventoryServiceMWS_Exception($exProps); } curl_close($ch); return $this->_extractHeadersAndBody($response); } /** * This method will attempt to extract the headers and body of our response. * We need to split the raw response string by 2 'CRLF's. 2 'CRLF's should indicate the separation of the response header * from the response body. However in our case we have some circumstances (certain client proxies) that result in * multiple responses concatenated. We could encounter a response like * * HTTP/1.1 100 Continue * * HTTP/1.1 200 OK * Date: Tue, 01 Apr 2014 13:02:51 GMT * Content-Type: text/html; charset=iso-8859-1 * Content-Length: 12605 * * ... body .. * * This method will throw away extra response status lines and attempt to find the first full response headers and body * * return [status, body, ResponseHeaderMetadata] */ private function _extractHeadersAndBody($response){ //First split by 2 'CRLF' $responseComponents = preg_split("/(?:\r?\n){2}/", $response, 2); $body = null; for ($count = 0; $count < count($responseComponents) && $body == null; $count++) { $headers = $responseComponents[$count]; $responseStatus = $this->_extractHttpStatusCode($headers); if($responseStatus != null && $this->_httpHeadersHaveContent($headers)){ $responseHeaderMetadata = $this->_extractResponseHeaderMetadata($headers); //The body will be the next item in the responseComponents array $body = $responseComponents[++$count]; } } //If the body is null here then we were unable to parse the response and will throw an exception if($body == null){ require_once (dirname(__FILE__) . '/Exception.php'); $exProps["Message"] = "Failed to parse valid HTTP response (" . $response . ")"; $exProps["ErrorType"] = "HTTP"; throw new FBAInventoryServiceMWS_Exception($exProps); } return array( 'Status' => $responseStatus, 'ResponseBody' => $body, 'ResponseHeaderMetadata' => $responseHeaderMetadata); } /** * parse the status line of a header string for the proper format and * return the status code * * Example: HTTP/1.1 200 OK * ... * returns String statusCode or null if the status line can't be parsed */ private function _extractHttpStatusCode($headers){ $statusCode = null; if (1 === preg_match("/(\\S+) +(\\d+) +([^\n\r]+)(?:\r?\n|\r)/", $headers, $matches)) { //The matches array [entireMatchString, protocol, statusCode, the rest] $statusCode = $matches[2]; } return $statusCode; } /** * Tries to determine some valid headers indicating this response * has content. In this case * return true if there is a valid "Content-Length" or "Transfer-Encoding" header */ private function _httpHeadersHaveContent($headers){ return (1 === preg_match("/[cC]ontent-[lL]ength: +(?:\\d+)(?:\\r?\\n|\\r|$)/", $headers) || 1 === preg_match("/Transfer-Encoding: +(?!identity[\r\n;= ])(?:[^\r\n]+)(?:\r?\n|\r|$)/i", $headers)); } /** * extract a ResponseHeaderMetadata object from the raw headers */ private function _extractResponseHeaderMetadata($rawHeaders){ $inputHeaders = preg_split("/\r\n|\n|\r/", $rawHeaders); $headers = array(); $headers['x-mws-request-id'] = null; $headers['x-mws-response-context'] = null; $headers['x-mws-timestamp'] = null; $headers['x-mws-quota-max'] = null; $headers['x-mws-quota-remaining'] = null; $headers['x-mws-quota-resetsOn'] = null; foreach ($inputHeaders as $currentHeader) { $keyValue = explode (': ', $currentHeader); if (isset($keyValue[1])) { list ($key, $value) = $keyValue; if (isset($headers[$key]) && $headers[$key]!==null) { $headers[$key] = $headers[$key] . "," . $value; } else { $headers[$key] = $value; } } } require_once(dirname(__FILE__) . '/Model/ResponseHeaderMetadata.php'); return new FBAInventoryServiceMWS_Model_ResponseHeaderMetadata( $headers['x-mws-request-id'], $headers['x-mws-response-context'], $headers['x-mws-timestamp'], $headers['x-mws-quota-max'], $headers['x-mws-quota-remaining'], $headers['x-mws-quota-resetsOn']); } /** * Set curl options relating to SSL. Protected to allow overriding. * @param $ch curl handle */ protected function setSSLCurlOptions($ch) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); } /** * Exponential sleep on failed request * * @param retries current retry */ private function _pauseOnRetry($retries) { if ($retries <= $this->_config['MaxErrorRetry']) { $delay = (int) (pow(4, $retries) * 100000); usleep($delay); return true; } return false; } /** * Add authentication related and version parameters */ private function _addRequiredParameters(array $parameters) { $parameters['AWSAccessKeyId'] = $this->_awsAccessKeyId; $parameters['Timestamp'] = $this->_getFormattedTimestamp(); $parameters['Version'] = self::SERVICE_VERSION; $parameters['SignatureVersion'] = $this->_config['SignatureVersion']; if ($parameters['SignatureVersion'] > 1) { $parameters['SignatureMethod'] = $this->_config['SignatureMethod']; } $parameters['Signature'] = $this->_signParameters($parameters, $this->_awsSecretAccessKey); return $parameters; } /** * Convert paremeters to Url encoded query string */ private function _getParametersAsString(array $parameters) { $queryParameters = array(); foreach ($parameters as $key => $value) { $queryParameters[] = $key . '=' . $this->_urlencode($value); } return implode('&', $queryParameters); } /** * Computes RFC 2104-compliant HMAC signature for request parameters * Implements AWS Signature, as per following spec: * * If Signature Version is 0, it signs concatenated Action and Timestamp * * If Signature Version is 1, it performs the following: * * Sorts all parameters (including SignatureVersion and excluding Signature, * the value of which is being created), ignoring case. * * Iterate over the sorted list and append the parameter name (in original case) * and then its value. It will not URL-encode the parameter values before * constructing this string. There are no separators. * * If Signature Version is 2, string to sign is based on following: * * 1. The HTTP Request Method followed by an ASCII newline (%0A) * 2. The HTTP Host header in the form of lowercase host, followed by an ASCII newline. * 3. The URL encoded HTTP absolute path component of the URI * (up to but not including the query string parameters); * if this is empty use a forward '/'. This parameter is followed by an ASCII newline. * 4. The concatenation of all query string components (names and values) * as UTF-8 characters which are URL encoded as per RFC 3986 * (hex characters MUST be uppercase), sorted using lexicographic byte ordering. * Parameter names are separated from their values by the '=' character * (ASCII character 61), even if the value is empty. * Pairs of parameter and values are separated by the '&' character (ASCII code 38). * */ private function _signParameters(array $parameters, $key) { $signatureVersion = $parameters['SignatureVersion']; $algorithm = "HmacSHA1"; $stringToSign = null; if (2 == $signatureVersion) { $algorithm = $this->_config['SignatureMethod']; $parameters['SignatureMethod'] = $algorithm; $stringToSign = $this->_calculateStringToSignV2($parameters); } else { throw new Exception("Invalid Signature Version specified"); } return $this->_sign($stringToSign, $key, $algorithm); } /** * Calculate String to Sign for SignatureVersion 2 * @param array $parameters request parameters * @return String to Sign */ private function _calculateStringToSignV2(array $parameters) { $data = 'POST'; $data .= "\n"; $endpoint = parse_url ($this->_config['ServiceURL']); $data .= $endpoint['host']; $data .= "\n"; $uri = array_key_exists('path', $endpoint) ? $endpoint['path'] : null; if (!isset ($uri)) { $uri = "/"; } $uriencoded = implode("/", array_map(array($this, "_urlencode"), explode("/", $uri))); $data .= $uriencoded; $data .= "\n"; uksort($parameters, 'strcmp'); $data .= $this->_getParametersAsString($parameters); return $data; } private function _urlencode($value) { return str_replace('%7E', '~', rawurlencode($value)); } /** * Computes RFC 2104-compliant HMAC signature. */ private function _sign($data, $key, $algorithm) { if ($algorithm === 'HmacSHA1') { $hash = 'sha1'; } else if ($algorithm === 'HmacSHA256') { $hash = 'sha256'; } else { throw new Exception ("Non-supported signing method specified"); } return base64_encode( hash_hmac($hash, $data, $key, true) ); } /** * Formats date as ISO 8601 timestamp */ private function _getFormattedTimestamp() { return gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time()); } /** * Formats date as ISO 8601 timestamp */ private function getFormattedTimestamp($dateTime) { return $dateTime->format(DATE_ISO8601); } }
davygeek/mws
mwsapi/FBAInventoryServiceMWS/Client.php
PHP
gpl-3.0
32,332
package xyz.stupidwolf.enums; /** * 定义各个操作的返回状态码 * Created by stupidwolf on 2016/8/4. */ public enum ResultCode { DELETE_SUCCESS("40"), DELETE_FAIL("41"), WRITE_SUCCESS("50"), WRITE_FAIL("51") ; private String code; ResultCode(String code) { this.code = code; } public String getCode() { return code; } }
stupidwolf/stupid-blog
src/main/java/xyz/stupidwolf/enums/ResultCode.java
Java
gpl-3.0
392
package model; /** * @author Yi Zheng * Class to represent suppliers of sushi ingredients. * */ public class Supplier{ private String name; private int distance; // assume it is in kms and manually entered. // in the real world, the distance may depends on traffic, security issues, etc. // so it would be better to enter it manually. /** * * @param name the name of supplier * @param distance the distance to the business (how far to deliver the ingredient(s)) */ public Supplier(String name, int distance) { this.setName(name); this.setDistance(distance); } /* * Setters and Getters */ public String getName() { return name; } public void setName(String name) { this.name = name; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } }
zhengyi20201/SushiSystem
src/model/Supplier.java
Java
gpl-3.0
876
/* * SLD Editor - The Open Source Java SLD Editor * * Copyright (C) 2016, SCISYS UK Limited * * 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.sldeditor.tool.mapbox; import com.sldeditor.common.NodeInterface; import com.sldeditor.common.SLDDataInterface; import com.sldeditor.common.console.ConsoleManager; import com.sldeditor.common.data.SLDUtils; import com.sldeditor.common.localisation.Localisation; import com.sldeditor.common.output.SLDOutputFormatEnum; import com.sldeditor.common.output.SLDWriterInterface; import com.sldeditor.common.output.impl.SLDWriterFactory; import com.sldeditor.common.utils.ExternalFilenames; import com.sldeditor.datasource.SLDEditorFile; import com.sldeditor.datasource.extension.filesystem.node.file.FileTreeNode; import com.sldeditor.datasource.extension.filesystem.node.file.FileTreeNodeTypeEnum; import com.sldeditor.tool.GenerateFilename; import com.sldeditor.tool.ToolButton; import com.sldeditor.tool.ToolInterface; import com.sldeditor.tool.ToolPanel; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import org.geotools.styling.StyledLayerDescriptor; /** * Tool which given a list of SLD objects saves them to SLD files. * * @author Robert Ward (SCISYS) */ public class MapBoxTool implements ToolInterface { /** The Constant PANEL_WIDTH. */ private static final int PANEL_WIDTH = 75; /** The Constant MAPBOX_FILE_EXTENSION. */ private static final String MAPBOX_FILE_EXTENSION = "json"; /** The export to sld button. */ private JButton exportToSLDButton; /** The group panel. */ private JPanel groupPanel = null; /** The sld data list. */ private List<SLDDataInterface> sldDataList; /** Instantiates a new mapbox tool. */ public MapBoxTool() { createUI(); } /* * (non-Javadoc) * * @see com.sldeditor.tool.ToolInterface#getPanel() */ @Override public JPanel getPanel() { return groupPanel; } /* * (non-Javadoc) * * @see com.sldeditor.tool.ToolInterface#setSelectedItems(java.util.List, java.util.List) */ @Override public void setSelectedItems( List<NodeInterface> nodeTypeList, List<SLDDataInterface> sldDataList) { this.sldDataList = sldDataList; if (exportToSLDButton != null) { int mapBoxFilesCount = 0; if (sldDataList != null) { for (SLDDataInterface sldData : sldDataList) { String fileExtension = ExternalFilenames.getFileExtension( sldData.getSLDFile().getAbsolutePath()); if (fileExtension.compareTo(MapBoxTool.MAPBOX_FILE_EXTENSION) == 0) { mapBoxFilesCount++; } } } exportToSLDButton.setEnabled(mapBoxFilesCount > 0); } } /** Creates the ui. */ private void createUI() { groupPanel = new JPanel(); FlowLayout flowLayout = (FlowLayout) groupPanel.getLayout(); flowLayout.setVgap(0); flowLayout.setHgap(0); TitledBorder titledBorder = BorderFactory.createTitledBorder( Localisation.getString(MapBoxTool.class, "MapBoxTool.groupTitle")); groupPanel.setBorder(titledBorder); // Export to SLD exportToSLDButton = new ToolButton( Localisation.getString(MapBoxTool.class, "MapBoxTool.exportToSLD"), "tool/exporttosld.png"); exportToSLDButton.setEnabled(false); exportToSLDButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { exportToSLD(); } }); groupPanel.setPreferredSize(new Dimension(PANEL_WIDTH, ToolPanel.TOOL_PANEL_HEIGHT)); groupPanel.add(exportToSLDButton); } /** Export to SLD. */ private void exportToSLD() { SLDWriterInterface sldWriter = SLDWriterFactory.createWriter(SLDOutputFormatEnum.SLD); for (SLDDataInterface sldData : sldDataList) { StyledLayerDescriptor sld = SLDUtils.createSLDFromString(sldData); String layerName = sldData.getLayerNameWithOutSuffix(); if (sld != null) { String sldString = sldWriter.encodeSLD(sldData.getResourceLocator(), sld); String destinationFolder = sldData.getSLDFile().getParent(); File fileToSave = GenerateFilename.findUniqueName( destinationFolder, layerName, SLDEditorFile.getSLDFileExtension()); String sldFilename = fileToSave.getName(); if (fileToSave.exists()) { ConsoleManager.getInstance() .error( this, Localisation.getField( MapBoxTool.class, "MapBoxTool.destinationAlreadyExists") + " " + sldFilename); } else { ConsoleManager.getInstance() .information( this, Localisation.getField( MapBoxTool.class, "MapBoxTool.exportToSLDMsg") + " " + sldFilename); try (BufferedWriter out = new BufferedWriter(new FileWriter(fileToSave))) { out.write(sldString); } catch (IOException e) { ConsoleManager.getInstance().exception(this, e); } } } } } /* * (non-Javadoc) * * @see com.sldeditor.tool.ToolInterface#getToolName() */ @Override public String getToolName() { return getClass().getName(); } /* * (non-Javadoc) * * @see com.sldeditor.tool.ToolInterface#supports(java.util.List, java.util.List) */ @Override public boolean supports( List<Class<?>> uniqueNodeTypeList, List<NodeInterface> nodeTypeList, List<SLDDataInterface> sldDataList) { if (nodeTypeList == null) { return false; } for (NodeInterface node : nodeTypeList) { if (node instanceof FileTreeNode) { FileTreeNode fileTreeNode = (FileTreeNode) node; if (fileTreeNode.isDir()) { // Folder for (int childIndex = 0; childIndex < fileTreeNode.getChildCount(); childIndex++) { FileTreeNode f = (FileTreeNode) fileTreeNode.getChildAt(childIndex); if (f.getFileCategory() == FileTreeNodeTypeEnum.SLD) { String fileExtension = ExternalFilenames.getFileExtension( f.getFile().getAbsolutePath()); return (fileExtension.compareTo(MapBoxTool.MAPBOX_FILE_EXTENSION) == 0); } } } else { // Single file if (fileTreeNode.getFileCategory() == FileTreeNodeTypeEnum.SLD) { String fileExtension = ExternalFilenames.getFileExtension( fileTreeNode.getFile().getAbsolutePath()); return (fileExtension.compareTo(MapBoxTool.MAPBOX_FILE_EXTENSION) == 0); } } return false; } else { return true; } } return true; } }
robward-scisys/sldeditor
modules/application/src/main/java/com/sldeditor/tool/mapbox/MapBoxTool.java
Java
gpl-3.0
9,130
$(window).load(function() { /* Seleccionar el primer radio button (Persona) */ var contr = $('#form-adhere input[type=radio]'); contr.first().prop( "checked", true ); /* Cargar lista de paises en el select */ $.ajax({ url: location.origin + location.pathname + '/assets/js/countries.json', dataType: 'text'}) .done(function( data ) { data = JSON.parse(data); var select = $('#pais-adherente-1'); $.each( data, function( key, val ) { select.append('<option value="'+key+'">'+val+'</option>') }); select.select2(); }) .fail(function( jqxhr, textStatus, error ) { var err = textStatus + ", " + error; console.log( "Request Failed: " + err ); }); /* Evento de selección de radio button para cambiar el placeholder de los textboxes */ contr.on('change', function(ev){ if($(ev.target).attr('id') == "tipo-persona-adherente") { $('#nombre-adherente-1').attr('placeholder', 'Escribe tu nombre'); $('#email-adherente-1').attr('placeholder', 'Escribe tu email'); } else if($(ev.target).attr('id') == "tipo-organizacion-adherente") { $('#nombre-adherente-1').attr('placeholder', 'Escribe el nombre de la organización'); $('#email-adherente-1').attr('placeholder', 'Escribe el email de la organización'); } }) /* Enviamos el formulario */ $( '#form-adhere' ).submit(function(e) { e.preventDefault(); e.stopImmediatePropagation(); var $this = $( this ), action = $this.attr( 'action' ); // The AJAX requrest var data = $this.serialize(); $.get( action, data ) .done(function(data) { $("#form-adhere").slideToggle('slow', function(){ $("#form-adhere-done").slideToggle('slow'); }); }) .fail(function( jqxhr, textStatus, error ) { var err = textStatus + ", " + error; console.log( "Request Failed: " + err ); }); return false; }); /* $('#submit-adhere').click(function(ev){ $("#form-adhere").slideToggle('slow', function(){ $("#form-adhere-done").slideToggle('slow'); }); }); */ });
DemocraciaEnRed/redinnovacionpolitica.org
assets/js/adhere-form.js
JavaScript
gpl-3.0
2,368
<?php function loadXMLDoc($xmlfile) { $doc = new DOMDocument(); $doc->load($xmlfile); return $doc; } function getSingleAttribValue($xmlfile,$tag,$attrib) { return getXMLAttrib(loadXMLDoc($xmlfile)->getElementsByTagName($tag)->item(0),$attrib); } function getXMLNodeList($xmldoc,$nodename) { return $xmldoc->getElementsByTagName( $nodename ); } function getXMLAttrib($xmlnode,$attrib) { return $xmlnode->getAttributeNode($attrib)->value; } ?>
PossibilitiesForLearning/pfl-wptheme
wp.custom.src/xmlfuncs.php
PHP
gpl-3.0
476
package rd.neuron.neuron; import org.jblas.FloatMatrix; import rd.neuron.neuron.Layer.Function; /** * Build a fully connected random layer with a middle and max value * @author azahar * */ public class FullyRandomLayerBuilder implements LayerBuilder { private final float mid, max; /** * * @param mid - middle value * @param max - max value */ public FullyRandomLayerBuilder(float mid, float max) { this.mid = mid; this.max = max; } /** * Default with random values between 0 and 1 */ public FullyRandomLayerBuilder() { this.mid = 0; this.max = 1; } @Override public Layer build(int numberOfInputNeurons, int numberOfOutputNeurons, Function f) { if (numberOfInputNeurons <= 0 || numberOfOutputNeurons <= 0) { throw new IllegalArgumentException("Number of neurons cannont be <=0"); } FloatMatrix weights = FloatMatrix.rand(numberOfInputNeurons, numberOfOutputNeurons); // Out // x // In FloatMatrix bias = FloatMatrix.rand(numberOfOutputNeurons, 1); // Out x // 1 if (max != 0 && mid != 0) { weights = weights.sub(mid).mul(max); bias = bias.sub(mid).mul(max); } return new Layer(weights, bias, f); } }
amachwe/NeuralNetwork
src/main/java/rd/neuron/neuron/FullyRandomLayerBuilder.java
Java
gpl-3.0
1,234
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-13 09:57 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('db', '0077_auto_20161113_2049'), ] operations = [ migrations.AlterModelOptions( name='learningresource', options={'verbose_name': 'lr', 'verbose_name_plural': 'lr'}, ), ]
caw/curriculum
db/migrations/0078_auto_20161113_2057.py
Python
gpl-3.0
444
/* * Copyright (C) 2017 Schürmann & Breitmoser GbR * * 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.sufficientlysecure.keychain.ui.base; import android.os.Bundle; import android.os.Parcelable; import org.sufficientlysecure.keychain.operations.results.OperationResult; /** CryptoOperationFragment which calls crypto operation results only while * attached to Activity. * * This subclass of CryptoOperationFragment substitutes the onCryptoOperation* * methods for onQueuedOperation* ones, which are ensured to be called while * the fragment is attached to an Activity, possibly delaying the call until * the Fragment is re-attached. * * TODO merge this functionality into CryptoOperationFragment? * * @see CryptoOperationFragment */ public abstract class QueueingCryptoOperationFragment<T extends Parcelable, S extends OperationResult> extends CryptoOperationFragment<T,S> { public static final String ARG_QUEUED_RESULT = "queued_result"; private S mQueuedResult; public QueueingCryptoOperationFragment() { super(); } public QueueingCryptoOperationFragment(Integer initialProgressMsg) { super(initialProgressMsg); } @Override public void onViewStateRestored(Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (mQueuedResult != null) { try { if (mQueuedResult.success()) { onQueuedOperationSuccess(mQueuedResult); } else { onQueuedOperationError(mQueuedResult); } } finally { mQueuedResult = null; } } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(ARG_QUEUED_RESULT, mQueuedResult); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mQueuedResult = savedInstanceState.getParcelable(ARG_QUEUED_RESULT); } } public abstract void onQueuedOperationSuccess(S result); public void onQueuedOperationError(S result) { hideKeyboard(); result.createNotify(getActivity()).show(); } @Override final public void onCryptoOperationSuccess(S result) { if (getActivity() == null) { mQueuedResult = result; return; } onQueuedOperationSuccess(result); } @Override final public void onCryptoOperationError(S result) { if (getActivity() == null) { mQueuedResult = result; return; } onQueuedOperationError(result); } }
open-keychain/open-keychain
OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/base/QueueingCryptoOperationFragment.java
Java
gpl-3.0
3,377
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-21 05:36 from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='QuizInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('quiz_title', models.CharField(max_length=100)), ('quizDate', models.DateField(default=datetime.date.today)), ('quizTime', models.TimeField(default=datetime.time)), ], ), migrations.CreateModel( name='QuizQuestions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('question', models.CharField(max_length=200)), ('isMultipleChoice', models.CharField(max_length=1)), ('choice_1', models.CharField(blank=True, max_length=10, null=True)), ('choice_2', models.CharField(blank=True, max_length=10, null=True)), ('choice_3', models.CharField(blank=True, max_length=10, null=True)), ('choice_4', models.CharField(blank=True, max_length=10, null=True)), ('answer', models.CharField(blank=True, max_length=200, null=True)), ('quiz', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.QuizInfo')), ], ), migrations.CreateModel( name='StudentProfile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('school', models.CharField(blank=True, max_length=200, null=True)), ('standard', models.PositiveSmallIntegerField(blank=True, null=True)), ('doj', models.DateField(blank=True, default=datetime.date.today, null=True)), ('student', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, to_field='username', unique=True)), ], ), migrations.CreateModel( name='StudentQuizAttempts', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('attempt_date', models.DateField(default=datetime.date.today)), ('score', models.PositiveSmallIntegerField(default=0)), ('quiz', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.QuizInfo')), ('student', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='quiz.StudentProfile', to_field='student')), ], ), migrations.CreateModel( name='StudentResponses', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('response', models.CharField(blank=True, max_length=200, null=True)), ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.QuizQuestions')), ('quiz', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.QuizInfo')), ('student', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='quiz.StudentProfile', to_field='student')), ], ), migrations.CreateModel( name='TeacherProfile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('doj', models.DateField(blank=True, default=datetime.date.today, null=True)), ('teacher', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, to_field='username')), ], ), migrations.CreateModel( name='TeacherS', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.StudentProfile')), ('teacher', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.TeacherProfile')), ], ), migrations.AlterUniqueTogether( name='teachers', unique_together=set([('teacher', 'student')]), ), migrations.AlterUniqueTogether( name='studentresponses', unique_together=set([('student', 'quiz', 'question')]), ), migrations.AlterUniqueTogether( name='studentquizattempts', unique_together=set([('student', 'quiz')]), ), ]
rubyAce71697/QMS
quiz_system/quiz/migrations/0001_initial.py
Python
gpl-3.0
5,170
package ch.cyberduck.core.onedrive; /* * Copyright (c) 2002-2020 iterate GmbH. All rights reserved. * https://cyberduck.io/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ import ch.cyberduck.core.AttributedList; import ch.cyberduck.core.ListProgressListener; import ch.cyberduck.core.ListService; import ch.cyberduck.core.Path; import ch.cyberduck.core.exception.BackgroundException; import ch.cyberduck.core.onedrive.features.GraphFileIdProvider; import ch.cyberduck.core.onedrive.features.sharepoint.SiteDrivesListService; import ch.cyberduck.core.onedrive.features.sharepoint.SitesListService; import java.util.Optional; import static ch.cyberduck.core.onedrive.SharepointListService.*; public abstract class AbstractSharepointListService implements ListService { private final AbstractSharepointSession session; private final GraphFileIdProvider fileid; public AbstractSharepointListService(final AbstractSharepointSession session, final GraphFileIdProvider fileid) { this.session = session; this.fileid = fileid; } public AbstractSharepointSession getSession() { return session; } @Override public final AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { if((!session.isSingleSite() && directory.isRoot()) || (session.isSingleSite() && session.isHome(directory))) { return getRoot(directory, listener); } final AttributedList<Path> result = processList(directory, listener); if(result != AttributedList.<Path>emptyList()) { return result; } final GraphSession.ContainerItem container = session.getContainer(directory); if(container.getCollectionPath().map(p -> container.isContainerInCollection() && SITES_CONTAINER.equals(p.getName())).orElse(false)) { return addSiteItems(directory, listener); } final Optional<ListService> collectionListService = container.getCollectionPath().map(p -> { if(SITES_CONTAINER.equals(p.getName())) { return new SitesListService(session, fileid); } else if(DRIVES_CONTAINER.equals(p.getName())) { return new SiteDrivesListService(session, fileid); } return null; }); if(collectionListService.isPresent() && (!container.isDefined() || container.isCollectionInContainer())) { return collectionListService.get().list(directory, listener); } return new GraphItemListService(session, fileid).list(directory, listener); } AttributedList<Path> addSiteItems(final Path directory, final ListProgressListener listener) throws BackgroundException { final AttributedList<Path> list = new AttributedList<>(); list.add(new Path(directory, DRIVES_NAME.getName(), DRIVES_NAME.getType(), DRIVES_NAME.attributes())); list.add(new Path(directory, SITES_NAME.getName(), SITES_NAME.getType(), SITES_NAME.attributes())); listener.chunk(directory, list); return list; } abstract AttributedList<Path> getRoot(final Path directory, final ListProgressListener listener) throws BackgroundException; AttributedList<Path> processList(final Path directory, final ListProgressListener listener) throws BackgroundException { return AttributedList.emptyList(); } }
iterate-ch/cyberduck
onedrive/src/main/java/ch/cyberduck/core/onedrive/AbstractSharepointListService.java
Java
gpl-3.0
3,894
#!/usr/bin/env python """ Copyright (C) 2015 Ivan Gregor 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/>. The master script of the Snowball gene assembler. Module version 1.2 """ import os import sys import platform import tempfile import shutil import argparse import multiprocessing as mp from algbioi.com import fq from algbioi.com import parallel from algbioi.hsim import comh from algbioi.haplo import hmain from algbioi.haplo import hio def mainSnowball(fq1Path, fq2Path, profileHmmFile, insertSize, readLen=None, outFile=None, outFormat='fna', workingDir=None, hmmsearchPath=None, pfamMinScore=None, pOverlap=None, overlapLen=None, outAnnot=False, cleanUp=False, processors=mp.cpu_count()): """ Main function, the interface of the Snowball gene assembler. @param fq1Path: FASTQ 1 file path (containing first ends of Illumina paired-end reads) @param fq2Path: FASTQ 2 file path (containing second ends) @param profileHmmFile: profile HMMs file, containing models generated by the HMMER 3 software @param insertSize: mean insert size used for the library preparation (i.e. read generation) @param readLen: read length (if None, it will be derived from the FASTQ file) @param outFile: output file (if None, it will be derived from the FASTQ 1 file) @param outFormat: output file format 'fna' or 'fq' @param workingDir: temporary files will be stored here (if None, a temporary directory will be created/deleted) @param hmmsearchPath: path to the HMMER hmmsearch command (if None, it will take version that is in the PATH) @param pfamMinScore: minimum score for the hmmsearch (if None, use default) @param pOverlap: minimum overlap probability for the Snowball algorithm @param overlapLen: minimum overlap length for the Snowball algorithm @param outAnnot: if true, additional annotation will be stored along with the resulting contigs @param cleanUp: if true, delete temporary files at the end @param processors: Number of processors (default: use all processors available) @type fq1Path: str @type fq2Path: str @type profileHmmFile: str @type insertSize: int @type readLen: str @type outFile: str @type outFormat: str @type workingDir: str @type hmmsearchPath: str @type pfamMinScore: int @type pOverlap: float @type overlapLen: float @type outAnnot: bool @type cleanUp: bool @type processors: int """ assert os.name == 'posix', 'Snowball runs only on "posix" systems, your system is: %s' % os.name # checking input parameters assert os.path.isfile(fq1Path), 'File does not exist: %s' % fq1Path assert os.path.isfile(fq2Path), 'File does not exist: %s' % fq2Path # derive the read length if readLen is None: for name, dna, p, qs in fq.ReadFqGen(fq1Path): readLen = len(dna) assert readLen == len(qs), 'File corrupted %s' % fq1Path break assert readLen is not None, 'Cannot derive read length from %s' % fq1Path assert readLen <= insertSize < 2 * readLen, 'Invalid read length (%s) and insert size (%s) combination' \ % (readLen, insertSize) assert os.path.isfile(profileHmmFile), 'File does not exist: %s' % profileHmmFile outFormat = outFormat.strip() assert outFormat == 'fna' or outFormat == 'fq', 'Invalid output format: %s' % outFormat # checking the output file if outFile is None: c = 0 while True: outFile = fq1Path + '_%s.%s.gz' % (c, outFormat) if not os.path.isfile(outFile): break c += 1 else: outFileDir = os.path.dirname(outFile) assert os.path.basename(outFile) != '', 'Output file name is empty' assert outFileDir == '' or os.path.isdir(outFileDir), 'Invalid output directory: %s' % outFileDir outFile = outFile.strip() if not outFile.endswith('.gz'): outFile += '.gz' print('The name of the output file was modified to:\n\t%s' % outFile) # Looking for the hmmsearch binaries if hmmsearchPath is None: hmmsearchPath = os.popen("which hmmsearch").read().strip() if hmmsearchPath != '': print('This hmmsearch binary will be used:\n\t%s' % hmmsearchPath) assert os.path.isfile(hmmsearchPath), 'Path for (hmmsearch) is invalid: %s' % hmmsearchPath # creates a temporary working directory if workingDir is None: workingDir = tempfile.mkdtemp(prefix='snowball_') assert os.path.isdir(workingDir), 'Cannot create temporary working directory (%s)' % workingDir cleenUpTmpWorkingDir = True print('Using temporary directory:\n\t%s' % workingDir) else: cleenUpTmpWorkingDir = False assert os.path.isdir(workingDir), 'Working directory does not exist:\n\t%s' % workingDir assert not os.listdir(workingDir), 'Working directory must be empty:\n\t%s' % workingDir # set the number of processor cores to be used comh.MAX_PROC = max(1, min(processors, mp.cpu_count())) # set assembly parameters or use defaults if pfamMinScore is not None: comh.SAMPLES_PFAM_EVAN_MIN_SCORE = pfamMinScore if pOverlap is not None: comh.ASSEMBLY_POVERLAP = (pOverlap,) if overlapLen is not None: comh.ASSEMBLY_OVERLAP_LEN = (overlapLen,) # creates a temporary directory for the sample strains strainsDir = os.path.join(workingDir, 'strains') if not os.path.isdir(strainsDir): os.mkdir(strainsDir) assert os.path.isdir(strainsDir), 'Cannot create temporary directory:\n\t%s' % strainsDir os.symlink(fq1Path, os.path.join(strainsDir, '0_pair1.fq.gz')) os.symlink(fq2Path, os.path.join(strainsDir, '0_pair2.fq.gz')) # Start of the algorithm print('Running on: %s (%s)' % (' '.join(platform.dist()), sys.platform)) print('Using %s processors' % comh.MAX_PROC) print('Settings:\n\tRead length: %s\n\tInsert size: %s\n\tMin. overlap probability: %s\n\tMin. overlap length: %s' '\n\tMin. HMM score: %s' % (readLen, insertSize, comh.ASSEMBLY_POVERLAP[0], comh.ASSEMBLY_OVERLAP_LEN[0], comh.SAMPLES_PFAM_EVAN_MIN_SCORE)) # file with joined consensus reads fqJoinPath = os.path.join(strainsDir, '0_join.fq.gz') # join paired-end reads if True: # to skip this step, set to False (e.g. resume processing after OS/HW failure) print('Joining paired-end reads into consensus reads, loading reads from:\n\t%s\n\t%s' % (fq1Path, fq2Path)) r = fq.joinPairEnd([(fq1Path, fq2Path, fqJoinPath, readLen, insertSize, None, 60)], minOverlap=comh.SAMPLES_PAIRED_END_JOIN_MIN_OVERLAP, minOverlapIdentity=comh.SAMPLES_PAIRED_END_JOIN_MIN_OVERLAP_IDENTITY, maxCpu=comh.MAX_PROC) print("Filtered out: %s %% reads" % r) # Translate consensus reads into protein sequences, run hmmsearch if True: # to skip this step, set to False (e.g. resume processing after OS/HW failure) print("Translating reads to protein sequences") # file with protein consensus read sequences joinFastaProtGzip = os.path.join(strainsDir, '0_join_prot.fna.gz') fq.readsToProt(fqJoinPath, joinFastaProtGzip, comh.TRANSLATION_TABLE) print("Running HMMER (hmmsearch)") domOut = os.path.join(strainsDir, '0_join_prot.domtblout') joinFastaProt = joinFastaProtGzip[:-3] cmd = 'zcat %s > %s;%s -o /dev/null --noali --domtblout %s -E 0.01 ' \ '--cpu %s %s %s;rm %s;gzip -f %s' % (joinFastaProtGzip, joinFastaProt, hmmsearchPath, domOut, comh.MAX_PROC, profileHmmFile, joinFastaProt, joinFastaProt, domOut) assert parallel.reportFailedCmd(parallel.runCmdSerial([parallel.TaskCmd(cmd, strainsDir)])) is None # Assign consensus reads to individual gene domains if True: # to skip this step, set to False (e.g. resume processing after OS/HW failure) print("Assigning consensus reads to gene domains") hio.partitionReads(workingDir, comh.SAMPLES_PFAM_EVAN_MIN_SCORE, comh.SAMPLES_PFAM_EVAN_MIN_ACCURACY, comh.SAMPLES_SHUFFLE_RAND_SEED, comh.SAMPLES_PFAM_PARTITIONED_DIR, True, False) partitionedDir = os.path.join(workingDir, comh.SAMPLES_PFAM_PARTITIONED_DIR) # Run Assembly if True: # to skip this step, set to False (e.g. resume processing after OS/HW failure) print("Running Snowball assembly") # collect tasks for each gene domain taskList = [] assert os.path.isdir(partitionedDir), 'Temporary directory does not exist:\n\t%s' % partitionedDir for f in os.listdir(partitionedDir): fPath = os.path.join(partitionedDir, f) if f.endswith('join.fq.gz') and os.path.isfile(fPath): base = fPath[:-6] inFq = fPath inDomtblout = '%s_prot.domtblout.gz' % base inProtFna = '%s_prot.fna.gz' % base outPath = '%s_read_rec.pkl.gz' % base taskList.append(parallel.TaskThread(hmain.buildSuperReads, (inFq, inDomtblout, inProtFna, outPath, comh.ASSEMBLY_CONSIDER_PROT_COMP, comh.ASSEMBLY_ONLY_POVERLAP, comh.ASSEMBLY_POVERLAP, comh.ASSEMBLY_OVERLAP_LEN, comh.ASSEMBLY_OVERLAP_ANNOT_LEN, comh.ASSEMBLY_STOP_OVERLAP_MISMATCH, comh.ASSEMBLY_MAX_LOOPS, comh.TRANSLATION_TABLE))) # run tasks in parallel parallel.runThreadParallel(taskList, comh.MAX_PROC, keepRetValues=False) # Creates the output file if True: # to skip this step, set to False (e.g. resume processing after OS/HW failure) print('Creating output file:\n\t%s' % outFile) counter = 0 out = fq.WriteFq(outFile) for f in os.listdir(partitionedDir): fPath = os.path.join(partitionedDir, f) if f.endswith('.pkl.gz') and os.path.isfile(fPath): domName = f[2:-23] for rec in hio.loadReadRec(fPath): counter += 1 contigName = 'contig_%s_%s' % (counter, domName) dnaSeq = rec.dnaSeq # get the quality score string if outAnnot or outFormat == 'fq': qs = rec.qsArray.getQSStr(dnaSeq) else: qs = None # get the contig annotations if outAnnot: assert qs is not None codingStart = rec.annotStart codingLen = rec.annotLen posCov = ','.join(map(lambda x: str(int(x)), rec.getPosCovArray())) annotStr = 'domName:%s|codingStart:%s|codingLen:%s|qs:%s|posCov:%s' % (domName, codingStart, codingLen, qs, posCov) else: annotStr = '' # write an entry to the output file if outFormat == 'fq': out.writeFqEntry('@' + contigName, dnaSeq, qs, annotStr) else: assert outFormat == 'fna' if outAnnot: annotStr = '|' + annotStr out.write('>%s%s\n%s\n' % (contigName, annotStr, dnaSeq)) # close output file out.close() # Clean up the working directory if cleenUpTmpWorkingDir: # clean up the temporary directory print('Cleaning up temporary directory') assert os.path.isdir(workingDir), 'Directory to be cleaned does not exist:\n%s' % workingDir shutil.rmtree(workingDir) elif cleanUp: # clean up the user defined working directory if os.path.isdir(workingDir): print('Cleaning up working directory:\n\t%s' % workingDir) shutil.rmtree(os.path.join(workingDir, comh.SAMPLES_PFAM_PARTITIONED_DIR)) shutil.rmtree(strainsDir) print('Done') def _main(): """ Main function of the master script. """ # Command line parameters parser = argparse.ArgumentParser( description = 'Snowball gene assembler for Metagenomes (version 1.2).', epilog='This software is distributed under the GNU General Public License version 3 (http://www.gnu.org/licenses/).') parser.add_argument('-f', '--fq-1-file', nargs=1, type=file, required=True, help='FASTQ 1 file path containing first read-ends of Illumina paired-end reads).', metavar='pair1.fq.gz', dest='fq1File') parser.add_argument('-s', '--fq-2-file', nargs=1, type=file, required=True, help='FASTQ 2 file path containing second read-ends of Illumina paired-end reads).', metavar='pair2.fq.gz', dest='fq2File') parser.add_argument('-m', '--profile-hmm-file', nargs=1, type=file, required=True, help='Profile HMMs file containing models of individual gene domains ' '(this file is generated by the HMMER 3.0 software).', metavar='profile.hmm', dest='profileHmmFile') parser.add_argument('-i', '--insert-size', nargs=1, type=int, required=True, help='Mean insert size used for the library preparation (i.e. read generation).', metavar='225', dest='insertSize') parser.add_argument('-r', '--read-length', nargs=1, type=int, required=False, help='Read length of the read-ends (Default: read length will be derived from the input files).', metavar='150', dest='readLen') parser.add_argument('-o', '--output-file', nargs=1, type=str, required=False, help='Output FASTA or FASTQ file containing assembled contigs ' '(Default: the file name will be derived from the input file names).', metavar='contigs.fna.gz', dest='outFile') parser.add_argument('-t', '--output-format', nargs=1, type=str, required=False, choices=['fna', 'fq'], help='Format of the output file, supported: fna, fq (Default: fna).', metavar='fna', dest='outFormat') parser.add_argument('-w', '--working-directory', nargs=1, type=str, required=False, help='Working directory (Default: a temporary working directory will be automatically ' 'created and removed).', metavar='wd', dest='workingDir') parser.add_argument('-e', '--hmmsearch-path', nargs=1, type=file, required=False, help='Path to the HMMER hmmsearch command (Default: the version in the PATH will be used).', metavar='/usr/bin/hmmsearch', dest='hmmsearchPath') parser.add_argument('-n', '--hmmsearch-min-score', nargs=1, type=int, required=False, help='Minimum score for the reads to gene domains assignments (Default: 40).', metavar='40', dest='pfamMinScore') parser.add_argument('-v', '--minimum-overlap-probability', nargs=1, type=float, required=False, help='Minimum overlap probability parameter of the Snowball algorithm (Default: 0.8).', metavar='0.8', dest='pOverlap') parser.add_argument('-l', '--min-overlap-length', nargs=1, type=float, required=False, help='Minimum overlap length parameter of the Snowball algorithm (Default: 0.5).', metavar='0.5', dest='overlapLen') parser.add_argument('-a', '--output-contig-annotation', action='store_true', required=False, help='Store additional contig annotation along with the contigs.' ' (Default: no annotation is stored).', dest='outAnnot') parser.add_argument('-c', '--clean-up', action='store_true', required=False, help='Clean up the working directory. If a temporary working directory is automatically created, ' 'it will always be cleaned up. (Default: no clean up is performed).', dest='cleanUp') parser.add_argument('-p', '--processors', nargs=1, type=int, required=False, help='Number of processors to be used (Default: all available processors will be used).', metavar='60', dest='processors') args = parser.parse_args() # Values that must be defined fq1File = None fq2File = None profileHmmFile = None insertSize = None # Default values outFormat = 'fna' pfamMinScore = 40 pOverlap = 0.8 overlapLen = 0.5 outAnnot = False cleanUp = False processors = mp.cpu_count() readLen = None outFile = None workingDir = None hmmsearchPath = None # reading arguments if args.fq1File: fq1File = normPath(args.fq1File[0].name) if args.fq2File: fq2File = normPath(args.fq2File[0].name) if args.profileHmmFile: profileHmmFile = normPath(args.profileHmmFile[0].name) if args.insertSize: insertSize = int(args.insertSize[0]) if args.readLen: readLen = int(args.readLen[0]) if args.outFile: outFile = normPath(args.outFile[0]) if args.outFormat: outFormat = args.outFormat[0] if args.workingDir: workingDir = normPath(args.workingDir[0]) if args.hmmsearchPath: hmmsearchPath = normPath(args.hmmsearchPath[0].name) if args.pfamMinScore: pfamMinScore = int(args.pfamMinScore[0]) if args.pOverlap: pOverlap = float(args.pOverlap[0]) if args.overlapLen: overlapLen = float(args.overlapLen[0]) if args.outAnnot: outAnnot = args.outAnnot if args.cleanUp: cleanUp = args.cleanUp if args.processors: processors = int(args.processors[0]) # Printing for debugging. if False: # set to True to print input parameters print('fq1File: %s' % fq1File) print('fq2File: %s' % fq2File) print('profileHmmFile: %s' % profileHmmFile) print('insertSize: %s' % insertSize) print('readLen: %s' % readLen) print('outFile: %s' % outFile) print('outFormat: %s' % outFormat) print('workingDir: %s' % workingDir) print('hmmsearchPath: %s' % hmmsearchPath) print('pfamMinScore: %s' % pfamMinScore) print('pOverlap: %s' % pOverlap) print('overlapLen: %s' % overlapLen) print('outAnnot: %s' % outAnnot) print('cleanUp: %s' % cleanUp) print('processors: %s' % processors) # Run Snowball mainSnowball(fq1File, fq2File, profileHmmFile, insertSize, readLen=readLen, outFile=outFile, outFormat=outFormat, workingDir=workingDir, hmmsearchPath=hmmsearchPath, pfamMinScore=pfamMinScore, pOverlap=pOverlap, overlapLen=overlapLen, outAnnot=outAnnot, cleanUp=cleanUp, processors=processors) def normPath(path): if os.path.isabs(path) or path.strip().startswith('~'): return path else: return os.path.abspath(path) # TESTS --------------------------------------------------- def _test(): fq1File = '/home/igregor/Documents/work/release_snow/input/10_1_NZ_AIGN00000000_p1.fq.gz' fq2File = '/home/igregor/Documents/work/release_snow/input/10_1_NZ_AIGN00000000_p2.fq.gz' profileHmmFile = '/home/igregor/Documents/work/db/pfamV27/Pfam-A_and_Amphora2.hmm' insertSize = 225 outFile = '/home/igregor/Documents/work/release_snow/out.fna' outFormat = 'fna' # or 'fq' workingDir = '/home/igregor/Documents/work/release_snow/working' hmmsearchPath = '/home/igregor/Documents/work/tools/hmmer-3.0/binaries/hmmsearch' mainSnowball(fq1File, fq2File, profileHmmFile, insertSize, readLen=None, outFile=outFile, outFormat=outFormat, workingDir=workingDir, hmmsearchPath=hmmsearchPath, pfamMinScore=None, outAnnot=False, cleanUp=False, processors=mp.cpu_count()) if __name__ == "__main__": _main() # _test()
algbioi/snowball
algbioi/ga/run.py
Python
gpl-3.0
21,873
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module ProjectManagerApi class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
alansalinas/ProjectManager-api
config/application.rb
Ruby
gpl-3.0
988
/*********************************************************************** filename: CEGUIDirect3D11GeometryBuffer.cpp created: Wed May 5 2010 *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team * * 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 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. ***************************************************************************/ #define NOMINMAX #include "CEGUIDirect3D11GeometryBuffer.h" #include "CEGUIDirect3D11Texture.h" #include "CEGUIRenderEffect.h" #include "CEGUIVertex.h" #include "CEGUIExceptions.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// Direct3D11GeometryBuffer::Direct3D11GeometryBuffer(Direct3D11Renderer& owner) : d_owner(owner), d_device(d_owner.getDirect3DDevice()), d_activeTexture(0), d_vertexBuffer(0), d_bufferSize(0), d_bufferSynched(false), d_clipRect(0, 0, 0, 0), d_translation(0, 0, 0), d_rotation(0, 0, 0), d_pivot(0, 0, 0), d_effect(0), d_matrixValid(false) { } //----------------------------------------------------------------------------// Direct3D11GeometryBuffer::~Direct3D11GeometryBuffer() { cleanupVertexBuffer(); } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::draw() const { // setup clip region D3D11_RECT clip; clip.left = static_cast<LONG>(d_clipRect.d_left); clip.top = static_cast<LONG>(d_clipRect.d_top); clip.right = static_cast<LONG>(d_clipRect.d_right); clip.bottom = static_cast<LONG>(d_clipRect.d_bottom); d_device.d_context->RSSetScissorRects(1, &clip); if (!d_bufferSynched) syncHardwareBuffer(); // apply the transformations we need to use. if (!d_matrixValid) updateMatrix(); d_owner.setWorldMatrix(d_matrix); // set our buffer as the vertex source. const UINT stride = sizeof(D3DVertex); const UINT offset = 0; d_device.d_context->IASetVertexBuffers(0, 1, &d_vertexBuffer, &stride, &offset); const int pass_count = d_effect ? d_effect->getPassCount() : 1; for (int pass = 0; pass < pass_count; ++pass) { // set up RenderEffect if (d_effect) d_effect->performPreRenderFunctions(pass); // draw the batches size_t pos = 0; BatchList::const_iterator i = d_batches.begin(); for ( ; i != d_batches.end(); ++i) { // Set Texture d_owner.setCurrentTextureShaderResource( const_cast<ID3D11ShaderResourceView*>((*i).first)); // Draw this batch d_owner.bindTechniquePass(d_blendMode); d_device.d_context->Draw((*i).second, pos); pos += (*i).second; } } // clean up RenderEffect if (d_effect) d_effect->performPostRenderFunctions(); } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::setTranslation(const Vector3& v) { d_translation = v; d_matrixValid = false; } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::setRotation(const Vector3& r) { d_rotation = r; d_matrixValid = false; } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::setPivot(const Vector3& p) { d_pivot = p; d_matrixValid = false; } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::setClippingRegion(const Rect& region) { d_clipRect.d_top = ceguimax(0.0f, PixelAligned(region.d_top)); d_clipRect.d_bottom = ceguimax(0.0f, PixelAligned(region.d_bottom)); d_clipRect.d_left = ceguimax(0.0f, PixelAligned(region.d_left)); d_clipRect.d_right = ceguimax(0.0f, PixelAligned(region.d_right)); } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::appendVertex(const Vertex& vertex) { appendGeometry(&vertex, 1); } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::appendGeometry(const Vertex* const vbuff, uint vertex_count) { const ID3D11ShaderResourceView* srv = d_activeTexture ? d_activeTexture->getDirect3DShaderResourceView() : 0; // create a new batch if there are no batches yet, or if the active texture // differs from that used by the current batch. if (d_batches.empty() || (srv != d_batches.back().first)) d_batches.push_back(BatchInfo(srv, 0)); // update size of current batch d_batches.back().second += vertex_count; // buffer these vertices D3DVertex vd; const Vertex* vs = vbuff; for (uint i = 0; i < vertex_count; ++i, ++vs) { // copy vertex info the buffer, converting from CEGUI::Vertex to // something directly usable by D3D as needed. vd.x = vs->position.d_x; vd.y = vs->position.d_y; vd.z = vs->position.d_z; vd.diffuse = vs->colour_val.getARGB(); vd.tu = vs->tex_coords.d_x; vd.tv = vs->tex_coords.d_y; d_vertices.push_back(vd); } d_bufferSynched = false; } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::setActiveTexture(Texture* texture) { d_activeTexture = static_cast<Direct3D11Texture*>(texture); } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::reset() { d_batches.clear(); d_vertices.clear(); d_activeTexture = 0; } //----------------------------------------------------------------------------// Texture* Direct3D11GeometryBuffer::getActiveTexture() const { return d_activeTexture; } //----------------------------------------------------------------------------// uint Direct3D11GeometryBuffer::getVertexCount() const { return d_vertices.size(); } //----------------------------------------------------------------------------// uint Direct3D11GeometryBuffer::getBatchCount() const { return d_batches.size(); } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::setRenderEffect(RenderEffect* effect) { d_effect = effect; } //----------------------------------------------------------------------------// RenderEffect* Direct3D11GeometryBuffer::getRenderEffect() { return d_effect; } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::updateMatrix() const { const D3DXVECTOR3 p(d_pivot.d_x, d_pivot.d_y, d_pivot.d_z); const D3DXVECTOR3 t(d_translation.d_x, d_translation.d_y, d_translation.d_z); D3DXQUATERNION r; D3DXQuaternionRotationYawPitchRoll(&r, D3DXToRadian(d_rotation.d_y), D3DXToRadian(d_rotation.d_x), D3DXToRadian(d_rotation.d_z)); D3DXMatrixTransformation(&d_matrix, 0, 0, 0, &p, &r, &t); d_matrixValid = true; } //----------------------------------------------------------------------------// const D3DXMATRIX* Direct3D11GeometryBuffer::getMatrix() const { if (!d_matrixValid) updateMatrix(); return &d_matrix; } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::syncHardwareBuffer() const { const size_t vertex_count = d_vertices.size(); if (vertex_count > d_bufferSize) { cleanupVertexBuffer(); allocateVertexBuffer(vertex_count); } if (vertex_count > 0) { void* buff; D3D11_MAPPED_SUBRESOURCE SubRes; if (FAILED(d_device.d_context->Map(d_vertexBuffer,0,D3D11_MAP_WRITE_DISCARD, 0, &SubRes))) CEGUI_THROW(RendererException( "Direct3D11GeometryBuffer::syncHardwareBuffer: " "failed to map buffer.")); buff=SubRes.pData; std::memcpy(buff, &d_vertices[0], sizeof(D3DVertex) * vertex_count); d_device.d_context->Unmap(d_vertexBuffer,0); } d_bufferSynched = true; } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::allocateVertexBuffer(const size_t count) const { D3D11_BUFFER_DESC buffer_desc; buffer_desc.Usage = D3D11_USAGE_DYNAMIC; buffer_desc.ByteWidth = count * sizeof(D3DVertex); buffer_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; buffer_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; buffer_desc.MiscFlags = 0; if (FAILED(d_device.d_device->CreateBuffer(&buffer_desc, 0, &d_vertexBuffer))) CEGUI_THROW(RendererException( "Direct3D11GeometryBuffer::allocateVertexBuffer:" " failed to allocate vertex buffer.")); d_bufferSize = count; } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::cleanupVertexBuffer() const { if (d_vertexBuffer) { d_vertexBuffer->Release(); d_vertexBuffer = 0; d_bufferSize = 0; } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
cooljeanius/CEGUI
cegui/src/RendererModules/Direct3D11/CEGUIDirect3D11GeometryBuffer.cpp
C++
gpl-3.0
10,922
# deprecated? class HostControlWrapper(object): def __init__(self): self.id = None self.idx = None self.label = None self.btn = None self.tile_bg = None self.host = None
wackerl91/luna
resources/lib/model/hostcontrolwrapper.py
Python
gpl-3.0
222
const UserAuthentication = function () { let _userPool = new AmazonCognitoIdentity.CognitoUserPool( window.auth.config.cognito ); let _cognitoUser = _userPool.getCurrentUser(); const _getUser = function (email) { if (!_cognitoUser) { _cognitoUser = new AmazonCognitoIdentity.CognitoUser({ Username: email, Pool: _userPool, }); } _cognitoUser.getSession(function () {}); return _cognitoUser; }; const _buildAttributeList = function ( givenName, familyName, country, industry, contact ) { let attributeList = []; if (givenName !== undefined) { const dataGivenName = { Name: "given_name", Value: givenName, }; attributeList.push( new AmazonCognitoIdentity.CognitoUserAttribute(dataGivenName) ); } if (familyName !== undefined) { const dataFamilyName = { Name: "family_name", Value: familyName, }; attributeList.push( new AmazonCognitoIdentity.CognitoUserAttribute(dataFamilyName) ); } const dataLocale = { Name: "locale", Value: navigator.language, }; attributeList.push( new AmazonCognitoIdentity.CognitoUserAttribute(dataLocale) ); if (country !== undefined) { const datacountry = { Name: "custom:country", Value: country, }; attributeList.push( new AmazonCognitoIdentity.CognitoUserAttribute(datacountry) ); } if (industry !== undefined) { const dataIndustry = { Name: "custom:industry", Value: industry, }; attributeList.push( new AmazonCognitoIdentity.CognitoUserAttribute(dataIndustry) ); } if (contact !== undefined) { const dataContact = { Name: "custom:contact", Value: contact, }; attributeList.push( new AmazonCognitoIdentity.CognitoUserAttribute(dataContact) ); } return attributeList; }; const _setCookie = function (name, value, expiry) { const d = new Date(); d.setTime(d.getTime() + expiry * 24 * 60 * 60 * 1000); let expires = "expires=" + d.toUTCString(); document.cookie = name + "=" + value + ";" + expires + ";path=/"; }; const _getCookie = function (cname) { let name = cname + "="; let decodedCookie = decodeURIComponent(document.cookie); let ca = decodedCookie.split(";"); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) === " ") { c = c.substring(1); } if (c.indexOf(name) === 0) { return c.substring(name.length, c.length); } } return ""; }; const _deleteCookie = function (name) { document.cookie = name + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"; }; const _setUserCookie = function (userToken) { _setCookie("aodnPortalUser", JSON.stringify(userToken), 365); }; const _setGuestCookie = function () { _setCookie("aodnPortalGuest", true, 1); }; const _getUserCookie = function () { const cookie = _getCookie("aodnPortalUser"); return cookie ? JSON.parse(cookie) : null; }; const _getGuestCookie = function () { const cookie = _getCookie("aodnPortalGuest"); return cookie ? true : null; }; const _clearCookies = function () { _deleteCookie("aodnPortalUser"); _deleteCookie("aodnPortalGuest"); }; return { isGuest: function () { return _getGuestCookie() !== null; }, setAsGuest: function (callback) { _setGuestCookie(); callback(); }, isSignedIn: function () { const cookie = _getUserCookie(); return cookie !== null && _getUser(cookie.email) !== null; }, signUp: function ( username, password, givenName, familyName, country, industry, contact, callback ) { const attributeList = _buildAttributeList( givenName, familyName, country, industry, contact ); _userPool.signUp(username, password, attributeList, null, callback); }, setDetails: function ( givenName, familyName, country, industry, contact, callback ) { if (_cognitoUser) { const attrList = _buildAttributeList( givenName, familyName, country, industry, contact ); _cognitoUser.updateAttributes(attrList, callback); } else { return {}; } }, signIn: function (email, password, callback) { _clearCookies(); const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({ Username: email, Password: password, }); _getUser(email).authenticateUser(authenticationDetails, { onSuccess: function (res) { _setUserCookie({ email, token: res.accessToken.jwtToken }); callback(null); }, onFailure: function (err) { _cognitoUser = null; callback(err); }, }); }, getDetails: function (callback) { _cognitoUser.getUserAttributes(function(err, result) { if (err) { callback(err, null); } else { // Build attrs into object let userInfo = { name: _cognitoUser.username }; for (let k = 0; k < result.length; k++) { userInfo[result[k].getName()] = result[k].getValue(); } callback(null, userInfo); } }); }, signOut: function (callback) { if (_cognitoUser && _cognitoUser.signInUserSession) { _cognitoUser.signOut(); _cognitoUser = undefined; _clearCookies(); callback(null, {}); } }, delete: function (callback) { _cognitoUser.deleteUser(function() { _clearCookies(); callback(); }); }, changeUserPassword: function (oldPassword, newPassword, callback) { if (_cognitoUser) { _cognitoUser.changePassword(oldPassword, newPassword, callback); } else { callback({ name: "Error", message: "User is not signed in" }, null); } }, sendPasswordResetCode: function (userName, callback) { _getUser(userName).forgotPassword({ onFailure: (err) => callback(err, null), onSuccess: (result) => callback(null, result), }); }, confirmPasswordReset: function (username, code, newPassword, callback) { _getUser(username).confirmPassword(code, newPassword, { onFailure: (err) => callback(err, null), onSuccess: (result) => callback(null, result), }); }, }; };
aodn/aodn-portal
web-app/js/aws-cognito/UserAuthentication.js
JavaScript
gpl-3.0
6,716
package de.unijena.bioinf.fingerid; import de.unijena.bioinf.fingerid.db.CustomDataSourceService; import de.unijena.bioinf.sirius.gui.table.ActiveElementChangedListener; import de.unijena.bioinf.sirius.gui.utils.WrapLayout; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.util.*; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; public class DBFilterPanel extends JPanel implements ActiveElementChangedListener<CompoundCandidate, Set<FingerIdData>>, CustomDataSourceService.DataSourceChangeListener { private final List<FilterChangeListener> listeners = new LinkedList<>(); protected long bitSet; protected List<JCheckBox> checkboxes; private final AtomicBoolean isRefreshing = new AtomicBoolean(false); public DBFilterPanel(CandidateList sourceList) { setLayout(new WrapLayout(FlowLayout.LEFT, 5, 1)); this.checkboxes = new ArrayList<>(CustomDataSourceService.size()); for (CustomDataSourceService.Source source : CustomDataSourceService.sources()) { checkboxes.add(new JCheckBox(source.name())); } addBoxes(); CustomDataSourceService.addListener(this); sourceList.addActiveResultChangedListener(this); } public void addFilterChangeListener(FilterChangeListener listener) { listeners.add(listener); } public void fireFilterChangeEvent() { for (FilterChangeListener listener : listeners) { listener.fireFilterChanged(bitSet); } } protected void addBoxes() { Collections.sort(checkboxes, new Comparator<JCheckBox>() { @Override public int compare(JCheckBox o1, JCheckBox o2) { return o1.getText().toUpperCase().compareTo(o2.getText().toUpperCase()); } }); this.bitSet = 0L; for (final JCheckBox box : checkboxes) { if (box.isSelected()) this.bitSet |= CustomDataSourceService.getSourceFromName(box.getText()).flag(); add(box); box.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (!isRefreshing.get()) { if (box.isSelected()) bitSet |= CustomDataSourceService.getSourceFromName(box.getText()).flag(); else bitSet &= ~CustomDataSourceService.getSourceFromName(box.getText()).flag(); fireFilterChangeEvent(); } } }); } } protected void reset() { isRefreshing.set(true); bitSet = 0; try { for (JCheckBox checkbox : checkboxes) { checkbox.setSelected(false); } } finally { fireFilterChangeEvent(); isRefreshing.set(false); } } public boolean toggle() { setVisible(!isVisible()); return isVisible(); } @Override public void resultsChanged(Set<FingerIdData> datas, CompoundCandidate sre, List<CompoundCandidate> resultElements, ListSelectionModel selections) { reset(); } @Override public void fireDataSourceChanged(Collection<String> changes) { HashSet<String> changed = new HashSet<>(changes); isRefreshing.set(true); boolean c = false; Iterator<JCheckBox> it = checkboxes.iterator(); while (it.hasNext()) { JCheckBox checkbox = it.next(); if (changed.remove(checkbox.getText())) { it.remove(); c = true; } } for (String name : changed) { checkboxes.add(new JCheckBox(name)); c = true; } if (c) { removeAll(); addBoxes(); revalidate(); repaint(); fireFilterChangeEvent(); } isRefreshing.set(false); } public interface FilterChangeListener extends EventListener { void fireFilterChanged(long filterSet); } }
boecker-lab/sirius_frontend
sirius_gui/src/main/java/de/unijena/bioinf/fingerid/DBFilterPanel.java
Java
gpl-3.0
4,224
<?php namespace DemocracyApps\CNP\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'DemocracyApps\CNP\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { parent::boot($router); // } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $router->group(['namespace' => $this->namespace], function($router) { require app_path('Http/routes.php'); }); } }
DemocracyApps/CNP
app/Providers/RouteServiceProvider.php
PHP
gpl-3.0
959
package com.ua.homework_7_2; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ua.homework_7_1.hibernate.controllers.DishController; import com.ua.homework_7_1.hibernate.controllers.EmployeeController; import com.ua.homework_7_1.hibernate.controllers.OrderController; import java.util.Arrays; public class Main { private EmployeeController employeeController; private DishController dishController; private OrderController orderController; public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml"); Main main = applicationContext.getBean(Main.class); main.start(); } public void init() { if (reInit) { preparedDishController.removeAll(); orderController.removeAll(); dishController.removeAll(); employeeController.removeAll(); storageController.removeAll(); ingredientController.removeAll(); ingredientController.initIngredients(); storageController.initStorage(); employeeController.initEmployee(); dishController.initDishes(); orderController.initOrders(); preparedDishController.initPreparedDishes(); } } private void start() { employeeController.createEmployee(); dishController.createDish(); orderController.createOrder("John", Arrays.asList("Borch", "Deer"), 1); orderController.createOrder("John", Arrays.asList("Soup", "Tekilla"), 2); orderController.createOrder("John", Arrays.asList("Plov", "Rom"), 3); orderController.printAllOrders(); } public void setEmployeeController(EmployeeController employeeController) { this.employeeController = employeeController; } public void setDishController(DishController dishController) { this.dishController = dishController; } public void setOrderController(OrderController orderController) { this.orderController = orderController; } }
andrewzagor/goit
Enterprise_7_2/Main.java
Java
gpl-3.0
2,196
/********************************************************** * Version $Id$ *********************************************************/ /////////////////////////////////////////////////////////// // // // SAGA // // // // System for Automated Geoscientific Analyses // // // // Application Programming Interface // // // // Library: SAGA_API // // // //-------------------------------------------------------// // // // table_record.cpp // // // // Copyright (C) 2005 by Olaf Conrad // // // //-------------------------------------------------------// // // // This file is part of 'SAGA - System for Automated // // Geoscientific Analyses'. // // // // 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, version 2.1 of the License. // // // // 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 program; if // // not, write to the Free Software Foundation, Inc., // // 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, // // USA. // // // //-------------------------------------------------------// // // // contact: Olaf Conrad // // Institute of Geography // // University of Goettingen // // Goldschmidtstr. 5 // // 37077 Goettingen // // Germany // // // // e-mail: oconrad@saga-gis.org // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- #include "table.h" #include "table_value.h" /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- CSG_Table_Record::CSG_Table_Record(CSG_Table *pTable, int Index) { m_pTable = pTable; m_Index = Index; m_Flags = 0; if( m_pTable && m_pTable->Get_Field_Count() > 0 ) { m_Values = (CSG_Table_Value **)SG_Malloc(m_pTable->Get_Field_Count() * sizeof(CSG_Table_Value *)); for(int iField=0; iField<m_pTable->Get_Field_Count(); iField++) { m_Values[iField] = _Create_Value(m_pTable->Get_Field_Type(iField)); } } else { m_Values = NULL; } } //--------------------------------------------------------- CSG_Table_Record::~CSG_Table_Record(void) { if( is_Selected() ) { m_pTable->Select(m_Index, true); } if( m_pTable->Get_Field_Count() > 0 ) { for(int iField=0; iField<m_pTable->Get_Field_Count(); iField++) { delete(m_Values[iField]); } SG_Free(m_Values); } } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- CSG_Table_Value * CSG_Table_Record::_Create_Value(TSG_Data_Type Type) { switch( Type ) { default: case SG_DATATYPE_String: return( new CSG_Table_Value_String() ); case SG_DATATYPE_Date : return( new CSG_Table_Value_Date () ); case SG_DATATYPE_Color : case SG_DATATYPE_Byte : case SG_DATATYPE_Char : case SG_DATATYPE_Word : case SG_DATATYPE_Short : case SG_DATATYPE_DWord : case SG_DATATYPE_Int : return( new CSG_Table_Value_Int () ); case SG_DATATYPE_ULong : case SG_DATATYPE_Long : return( new CSG_Table_Value_Long () ); case SG_DATATYPE_Float : case SG_DATATYPE_Double: return( new CSG_Table_Value_Double() ); case SG_DATATYPE_Binary: return( new CSG_Table_Value_Binary() ); } } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- bool CSG_Table_Record::_Add_Field(int add_Field) { if( add_Field < 0 ) { add_Field = 0; } else if( add_Field >= m_pTable->Get_Field_Count() ) { add_Field = m_pTable->Get_Field_Count() - 1; } m_Values = (CSG_Table_Value **)SG_Realloc(m_Values, m_pTable->Get_Field_Count() * sizeof(CSG_Table_Value *)); for(int iField=m_pTable->Get_Field_Count()-1; iField>add_Field; iField--) { m_Values[iField] = m_Values[iField - 1]; } m_Values[add_Field] = _Create_Value(m_pTable->Get_Field_Type(add_Field)); return( true ); } //--------------------------------------------------------- bool CSG_Table_Record::_Del_Field(int del_Field) { delete(m_Values[del_Field]); for(int iField=del_Field; iField<m_pTable->Get_Field_Count(); iField++) { m_Values[iField] = m_Values[iField + 1]; } m_Values = (CSG_Table_Value **)SG_Realloc(m_Values, m_pTable->Get_Field_Count() * sizeof(CSG_Table_Value *)); return( true ); } //--------------------------------------------------------- int CSG_Table_Record::_Get_Field(const CSG_String &Field) const { if( Field.Length() ) { for(int iField=0; iField<m_pTable->Get_Field_Count(); iField++) { if( !Field.Cmp(m_pTable->Get_Field_Name(iField)) ) { return( iField ); } } } return( -1 ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- void CSG_Table_Record::Set_Selected(bool bOn) { if( bOn != is_Selected() ) { if( bOn ) { m_Flags |= SG_TABLE_REC_FLAG_Selected; } else { m_Flags &= ~SG_TABLE_REC_FLAG_Selected; } } } //--------------------------------------------------------- void CSG_Table_Record::Set_Modified(bool bOn) { if( bOn != is_Modified() ) { if( bOn ) { m_Flags |= SG_TABLE_REC_FLAG_Modified; } else { m_Flags &= ~SG_TABLE_REC_FLAG_Modified; } } if( bOn ) { m_pTable->Set_Modified(); } } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- bool CSG_Table_Record::Set_Value (int iField, const CSG_Bytes &Value) { if( iField >= 0 && iField < m_pTable->Get_Field_Count() ) { if( m_Values[iField]->Set_Value(Value) ) { Set_Modified(true); m_pTable->Set_Update_Flag(); m_pTable->_Stats_Invalidate(iField); return( true ); } } return( false ); } bool CSG_Table_Record::Set_Value(const CSG_String &Field, const CSG_Bytes &Value) { return( Set_Value(_Get_Field(Field), Value) ); } //--------------------------------------------------------- bool CSG_Table_Record::Set_Value(int iField, const CSG_String &Value) { if( iField >= 0 && iField < m_pTable->Get_Field_Count() ) { if( m_Values[iField]->Set_Value(Value) ) { Set_Modified(true); m_pTable->Set_Update_Flag(); m_pTable->_Stats_Invalidate(iField); return( true ); } } return( false ); } bool CSG_Table_Record::Set_Value(const CSG_String &Field, const CSG_String &Value) { return( Set_Value(_Get_Field(Field), Value) ); } //--------------------------------------------------------- bool CSG_Table_Record::Set_Value(int iField, double Value) { if( iField >= 0 && iField < m_pTable->Get_Field_Count() ) { if( m_Values[iField]->Set_Value(Value) ) { Set_Modified(true); m_pTable->Set_Update_Flag(); m_pTable->_Stats_Invalidate(iField); return( true ); } } return( false ); } bool CSG_Table_Record::Set_Value(const CSG_String &Field, double Value) { return( Set_Value(_Get_Field(Field), Value) ); } //--------------------------------------------------------- bool CSG_Table_Record::Add_Value(int iField, double Value) { if( iField >= 0 && iField < m_pTable->Get_Field_Count() ) { return( Set_Value(iField, asDouble(iField) + Value) ); } return( false ); } bool CSG_Table_Record::Add_Value(const CSG_String &Field, double Value) { return( Add_Value(_Get_Field(Field), Value) ); } //--------------------------------------------------------- bool CSG_Table_Record::Mul_Value(int iField, double Value) { if( iField >= 0 && iField < m_pTable->Get_Field_Count() ) { return( Set_Value(iField, asDouble(iField) * Value) ); } return( false ); } bool CSG_Table_Record::Mul_Value(const CSG_String &Field, double Value) { return( Mul_Value(_Get_Field(Field), Value) ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- bool CSG_Table_Record::Set_NoData(int iField) { if( iField >= 0 && iField < m_pTable->Get_Field_Count() ) { switch( m_pTable->Get_Field_Type(iField) ) { default: case SG_DATATYPE_String: if( !m_Values[iField]->Set_Value(SG_T("")) ) return( false ); break; case SG_DATATYPE_Date: case SG_DATATYPE_Color: case SG_DATATYPE_Byte: case SG_DATATYPE_Char: case SG_DATATYPE_Word: case SG_DATATYPE_Short: case SG_DATATYPE_DWord: case SG_DATATYPE_Int: case SG_DATATYPE_ULong: case SG_DATATYPE_Long: case SG_DATATYPE_Float: case SG_DATATYPE_Double: if( !m_Values[iField]->Set_Value(m_pTable->Get_NoData_Value()) ) return( false ); break; case SG_DATATYPE_Binary: m_Values[iField]->asBinary().Destroy(); break; } Set_Modified(true); m_pTable->Set_Update_Flag(); m_pTable->_Stats_Invalidate(iField); return( true ); } return( false ); } bool CSG_Table_Record::Set_NoData(const CSG_String &Field) { return( Set_NoData(_Get_Field(Field)) ); } //--------------------------------------------------------- bool CSG_Table_Record::is_NoData(int iField) const { if( iField >= 0 && iField < m_pTable->Get_Field_Count() ) { switch( m_pTable->Get_Field_Type(iField) ) { default: case SG_DATATYPE_String: return( m_Values[iField]->asString() == NULL ); case SG_DATATYPE_Date: case SG_DATATYPE_Color: case SG_DATATYPE_Byte: case SG_DATATYPE_Char: case SG_DATATYPE_Word: case SG_DATATYPE_Short: case SG_DATATYPE_DWord: case SG_DATATYPE_Int: case SG_DATATYPE_ULong: case SG_DATATYPE_Long: return( m_pTable->is_NoData_Value(m_Values[iField]->asInt()) ); case SG_DATATYPE_Float: case SG_DATATYPE_Double: return( m_pTable->is_NoData_Value(m_Values[iField]->asDouble()) ); case SG_DATATYPE_Binary: return( m_Values[iField]->asBinary().Get_Count() == 0 ); } } return( true ); } bool CSG_Table_Record::is_NoData(const CSG_String &Field) const { return( is_NoData(_Get_Field(Field)) ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- const SG_Char * CSG_Table_Record::asString(int iField, int Decimals) const { return( iField >= 0 && iField < m_pTable->Get_Field_Count() ? m_Values[iField]->asString(Decimals) : NULL ); } const SG_Char * CSG_Table_Record::asString(const CSG_String &Field, int Decimals) const { return( asString(_Get_Field(Field), Decimals) ); } //--------------------------------------------------------- int CSG_Table_Record::asInt(int iField) const { return( iField >= 0 && iField < m_pTable->Get_Field_Count() ? m_Values[iField]->asInt() : 0 ); } int CSG_Table_Record::asInt(const CSG_String &Field) const { return( asInt(_Get_Field(Field)) ); } //--------------------------------------------------------- sLong CSG_Table_Record::asLong(int iField) const { return( iField >= 0 && iField < m_pTable->Get_Field_Count() ? m_Values[iField]->asLong() : 0 ); } sLong CSG_Table_Record::asLong(const CSG_String &Field) const { return( asLong(_Get_Field(Field)) ); } //--------------------------------------------------------- double CSG_Table_Record::asDouble(int iField) const { return( iField >= 0 && iField < m_pTable->Get_Field_Count() ? m_Values[iField]->asDouble() : 0.0 ); } double CSG_Table_Record::asDouble(const CSG_String &Field) const { return( asDouble(_Get_Field(Field)) ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- bool CSG_Table_Record::Assign(CSG_Table_Record *pRecord) { if( pRecord ) { int nFields = m_pTable->Get_Field_Count() < pRecord->m_pTable->Get_Field_Count() ? m_pTable->Get_Field_Count() : pRecord->m_pTable->Get_Field_Count(); for(int iField=0; iField<nFields; iField++) { *(m_Values[iField]) = *(pRecord->m_Values[iField]); } Set_Modified(); return( true ); } return( false ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //---------------------------------------------------------
UoA-eResearch/saga-gis
saga-gis/src/saga_core/saga_api/table_record.cpp
C++
gpl-3.0
14,927
Simpla CMS 2.3.8 = afa50d5f661d65b6c67ec7f0e80eee7d
gohdan/DFC
known_files/hashes/simpla/design/js/codemirror/addon/hint/css-hint.js
JavaScript
gpl-3.0
52
import requests from requests.auth import HTTPDigestAuth import time import json import sys class IMT550C(): def __init__(self): params = self.configure() self.uri = params["uri"] self.ip = params["IP"] self.user = params["username"] self.password = params["password"] self.sample_rate = params["sample_rate"] self.points = [ {"name": "cooling_setpoint", "unit": "F", "data_type": "double", "OID": "4.1.6", "range": (45.0,95.0), "access": 6, "devtosmap": lambda x: x/10, "smaptodev": lambda x: x*10}, #thermSetbackCool {"name": "fan_state", "unit": "Mode", "data_type": "long", "OID": "4.1.4", "range": [0,1], "access": 4, "devtosmap": lambda x: {0:0, 1:0, 2:1}[x], "smaptodev": lambda x: {x:x}[x]}, # thermFanState {"name": "heating_setpoint", "unit": "F", "data_type": "double", "OID": "4.1.5", "range": (45.0,95.0), "access": 6, "devtosmap": lambda x: x/10, "smaptodev": lambda x: x*10}, #thermSetbackHeat {"name": "mode", "unit": "Mode", "data_type": "long", "OID": "4.1.1", "range": [0,1,2,3], "access": 6, "devtosmap": lambda x: x-1, "smaptodev": lambda x: x+1}, # thermHvacMode {"name": "override", "unit": "Mode", "data_type": "long", "OID": "4.1.9", "range": [0,1], "access": 6, "devtosmap": lambda x: {1:0, 3:1, 2:0}[x], "smaptodev": lambda x: {0:1, 1:3}[x]}, # hold/override {"name": "relative_humidity", "unit": "%RH", "data_type": "double", "OID": "4.1.14", "range": (0,95), "access": 0, "devtosmap": lambda x: x, "smaptodev": lambda x: x}, #thermRelativeHumidity {"name": "state", "unit": "Mode", "data_type": "long", "OID": "4.1.2", "range": [0,1,2], "access": 4, "devtosmap": lambda x: {1:0, 2:0, 3:1, 4:1, 5:1, 6:2, 7:2, 8:0, 9:0}[x], "smaptodev": lambda x: {x:x}[x]}, # thermHvacState {"name": "temperature", "unit": "F", "data_type": "double", "OID": "4.1.13", "range": (-30.0,200.0), "access": 4, "devtosmap": lambda x: x/10, "smaptodev": lambda x: x*10}, # thermAverageTemp {"name": "fan_mode", "unit": "Mode", "data_type": "long", "OID": "4.1.3", "range": [1,2,3], "access": 6, "devtosmap": lambda x: x, "smaptodev": lambda x: x} # thermFanMode ] def get_state(self): data = {} for p in self.points: url = "http://%s/get?OID%s" % (self.ip, p["OID"]) r = requests.get(url, auth=HTTPDigestAuth(self.user, self.password)) val = r.content.split('=')[-1] if p["data_type"] == "long": data[p["name"]] = p["devtosmap"](long(val)) else: data[p["name"]] = p["devtosmap"](float(val)) data["time"] = int(time.time()*1e9) return data def set_state(self, request): for p in self.points: key = p["name"] if key in request: payload = {"OID"+p["OID"]: int(p["smaptodev"](request[key])), "submit": "Submit"} r = requests.get('http://'+self.ip+"/pdp/", auth=HTTPDigestAuth(self.user, self.password), params=payload) if not r.ok: print r.content def configure(self): params = None with open("params.json") as f: try: params = json.loads(f.read()) except ValueError as e: print "Invalid parameter file" sys.exit(1) return dict(params) if __name__ == '__main__': thermostat = IMT550C() while True: print thermostat.get_state() print
SoftwareDefinedBuildings/bw2-contrib
driver/imt550c/smap.py
Python
gpl-3.0
3,893
# nnmware(c)2012-2020 from __future__ import unicode_literals from django import forms from django.contrib.admin.widgets import AdminTimeWidget from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.utils.timezone import now from django.utils.translation import gettext as _, get_language from nnmware.apps.booking.models import Hotel, Room, Booking, Discount, DISCOUNT_SPECIAL from nnmware.apps.booking.models import RequestAddHotel, DISCOUNT_NOREFUND, DISCOUNT_CREDITCARD, \ DISCOUNT_EARLY, DISCOUNT_LATER, DISCOUNT_PERIOD, DISCOUNT_PACKAGE, DISCOUNT_NORMAL, DISCOUNT_HOLIDAY, \ DISCOUNT_LAST_MINUTE from nnmware.apps.money.models import Bill from nnmware.core.fields import ReCaptchaField from nnmware.core.forms import UserFromRequestForm class LocaleNamedForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(LocaleNamedForm, self).__init__(*args, **kwargs) if get_language() == 'ru': name = self.instance.name description = self.instance.description else: name = self.instance.name_en description = self.instance.description_en self.fields['name'] = forms.CharField(widget=forms.TextInput(attrs={'size': '25'}), initial=name) self.fields['description'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'wide', 'rows': '5'}), initial=description) def save(self, commit=True): if get_language() == 'ru': self.instance.name = self.cleaned_data['name'] self.instance.description = self.cleaned_data['description'] else: self.instance.name_en = self.cleaned_data['name'] self.instance.description_en = self.cleaned_data['description'] return super(LocaleNamedForm, self).save(commit=commit) class CabinetInfoForm(UserFromRequestForm, LocaleNamedForm): time_on = forms.CharField(widget=AdminTimeWidget(), required=False) time_off = forms.CharField(widget=AdminTimeWidget(), required=False) class Meta: model = Hotel fields = ('option', 'time_on', 'time_off') def __init__(self, *args, **kwargs): super(CabinetInfoForm, self).__init__(*args, **kwargs) if get_language() == 'ru': schema_transit = self.instance.schema_transit paid_services = self.instance.paid_services else: schema_transit = self.instance.schema_transit_en paid_services = self.instance.paid_services_en self.fields['schema_transit'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'wide', 'rows': '5'}), initial=schema_transit) self.fields['paid_services'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'wide', 'rows': '5'}), initial=paid_services) if not self._user.is_superuser: self.fields['name'].widget.attrs['readonly'] = True def clean_name(self): if self._user.is_superuser: return self.cleaned_data['name'] if get_language() == 'ru': return self.instance.name else: return self.instance.name_en def save(self, commit=True): if get_language() == 'ru': self.instance.schema_transit = self.cleaned_data['schema_transit'] self.instance.paid_services = self.cleaned_data['paid_services'] else: self.instance.schema_transit_en = self.cleaned_data['schema_transit'] self.instance.paid_services_en = self.cleaned_data['paid_services'] return super(CabinetInfoForm, self).save(commit=commit) class CabinetRoomForm(LocaleNamedForm): class Meta: model = Room fields = ('option', 'typefood', 'surface_area') widgets = { 'typefood': forms.RadioSelect(), } class CabinetEditBillForm(forms.ModelForm): class Meta: model = Bill fields = ('date_billed', 'status', 'description_small', 'invoice_number', 'amount') class RequestAddHotelForm(forms.ModelForm): city = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'})) address = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'})) name = forms.CharField(widget=forms.TextInput(attrs={'size': '35'})) email = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'})) phone = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'})) fax = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'})) contact_email = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'})) website = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'})) rooms_count = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'})) class Meta: model = RequestAddHotel fields = ('city', 'address', 'name', 'email', 'phone', 'fax', 'contact_email', 'website', 'rooms_count', 'starcount') def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(RequestAddHotelForm, self).__init__(*args, **kwargs) if not user.is_authenticated: self.fields['recaptcha'] = ReCaptchaField(error_messages={'required': _('This field is required'), 'invalid': _('Answer is wrong')}) class UserCabinetInfoForm(UserFromRequestForm): class Meta: model = get_user_model() fields = ('first_name', 'last_name', 'subscribe') class BookingAddForm(UserFromRequestForm): room_id = forms.CharField(max_length=30, required=False) settlement = forms.CharField(max_length=30, required=False) hid_method = forms.CharField(max_length=30, required=False) class Meta: model = Booking fields = ( 'from_date', 'to_date', 'first_name', 'middle_name', 'last_name', 'phone', 'email', 'guests', 'comment') def clean_hid_method(self): m = self.cleaned_data.get('hid_method') if m: raise forms.ValidationError(_("Spam.")) return None def clean_phone(self): phone = self.cleaned_data.get('phone') if not phone: raise forms.ValidationError(_("Phone is required")) return phone def clean_email(self): email = self.cleaned_data.get('email') if not email: raise forms.ValidationError(_("Email is required")) try: validate_email(email) except ValidationError as verr: raise forms.ValidationError(_("Email is wrong")) return email def clean(self): cleaned_data = super(BookingAddForm, self).clean() if not self._user.is_authenticated: email = cleaned_data.get('email') if get_user_model().objects.filter(email=email).exists(): raise forms.ValidationError(_("Email already registered, please sign-in.")) return cleaned_data class AddDiscountForm(LocaleNamedForm): # TODO - Not used now(future) class Meta: model = Discount fields = ('name', 'choice', 'time_on', 'time_off', 'days', 'at_price_days', 'percentage', 'apply_norefund', 'apply_creditcard', 'apply_package', 'apply_period') def __init__(self, *args, **kwargs): super(AddDiscountForm, self).__init__(*args, **kwargs) self.fields['name'].required = False def clean_choice(self): choice = self.cleaned_data.get('choice') if choice == 0: raise forms.ValidationError(_("Discount not set")) return choice def clean_name(self): name = self.cleaned_data.get('name') if len(name.strip()) is 0: name = _("New discount from ") + now().strftime("%d.%m.%Y") return name def clean(self): cleaned_data = super(AddDiscountForm, self).clean() choice = cleaned_data.get("choice") need_del = [] if choice == DISCOUNT_NOREFUND or choice == DISCOUNT_CREDITCARD: need_del = ['time_on', 'time_off', 'days', 'at_price_days', 'apply_norefund', 'apply_creditcard', 'apply_package', 'apply_period'] elif choice == DISCOUNT_EARLY: need_del = ['time_on', 'time_off', 'at_price_days', 'apply_creditcard'] elif choice == DISCOUNT_LATER: need_del = ['time_off', 'at_price_days'] elif choice == DISCOUNT_PERIOD: need_del = ['time_on', 'time_off', 'at_price_days', 'apply_package', 'apply_period'] elif choice == DISCOUNT_PACKAGE: need_del = ['time_on', 'time_off', 'apply_norefund', 'apply_creditcard'] elif choice == DISCOUNT_HOLIDAY or choice == DISCOUNT_SPECIAL or choice == DISCOUNT_NORMAL: need_del = ['time_on', 'time_off', 'days', 'at_price_days', 'apply_package', 'apply_period'] elif choice == DISCOUNT_LAST_MINUTE: need_del = ['days', 'at_price_days', 'apply_norefund', 'apply_creditcard', 'apply_package', 'apply_period'] for i in need_del: del cleaned_data[i]
nnmware/nnmware
apps/booking/forms.py
Python
gpl-3.0
9,755
/* * Copyright (C) 2014 Hector Espert Pardo * * 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 utilidades; import java.util.Random; /** * * @author Hector Espert * */ public class Aleatorios { /** * Genera un numero aleatorio entre dos numeros. * @param min * @param max * @return int */ public static int entre(int min, int max) { //Ordenar if (min > max) { int aux = min; min = max; max = aux; } Random aleatorio = new Random(); int numale; do { numale = aleatorio.nextInt(max); if (aleatorio.nextBoolean()) { numale = -numale; } } while (numale < min); return numale; } /** * Genera un numero aleatorio entre dos numeros. * @param min * @param max * @return double */ public static double entre(double min, double max) { //Ordenar if (min > max) { double aux = min; min = max; max = aux; } Random aleatorio = new Random(); int numale; do { numale = aleatorio.nextInt(); if (aleatorio.nextBoolean()) { numale = -numale; } } while (numale < min && numale > max); return numale; } /** * Devuelve una matrix de enteros aleatorios. * num es el tamaño de la matriz * @param num * @return */ public static int[] toMatriz(int num) { int[] numeros = new int[num]; Random aleatorio = new Random(); for (int i = 0; i < numeros.length; i++) { int numero = aleatorio.nextInt(); numeros[i] = numero; } return numeros; } /** * Devuelve una matrix de enteros aleatorios de 0 a un valor. * num es el tamaño de la matriz * max es el valor maximo de los aleatorios. * @param num * @param max * @return */ public static int[] toMatriz(int num, int max) { int[] numeros = new int[num]; Random aleatorio = new Random(); for (int i = 0; i < numeros.length; i++) { int numero = aleatorio.nextInt(max); numeros[i] = numero; } return numeros; } /** * Devuelve una matrix de enteros aleatorios entre dos valores. * @param num * @param min * @param max * @return */ public static int[] toMatrizEntre (int num, int min, int max) { int[] numeros = new int[num]; //Ordenar if (min > max) { int aux = min; min = max; max = aux; } for (int i = 0; i < numeros.length; i++) { numeros[i] = entre(min, max); } return numeros; } /** * Devuelve una matriz multiplie con numeros aleatorios. * @param num * @return */ public static int[][] toMatrizMulti(int num) { int[][] numeros = new int[num][num]; Random aleatorio = new Random(); for (int[] matriz : numeros) { for (int i = 0; i < matriz.length; i++) { matriz[i] = aleatorio.nextInt(); } } return numeros; } /** * Devuelve una matriz * @param num * @param max * @return */ public static int[][] toMatrizMulti(int num, int max) { int[][] numeros = new int[num][num]; Random aleatorio = new Random(); for (int[] matriz : numeros) { for (int i = 0; i < matriz.length; i++) { matriz[i] = aleatorio.nextInt(max); } } return numeros; } /** * * @param num * @param min * @param max * @return */ public static int[][] toMatrizMultiEntre (int num, int min, int max) { int[][] numeros = new int[num][num]; //Ordenar if (min > max) { int aux = min; min = max; max = aux; } for (int[] matriz : numeros) { for (int i = 0; i < matriz.length; i++) { matriz[i] = entre(min, max); } } return numeros; } /** * Devuelve un boolean aleatorio. * @return */ public static boolean getBoolean() { Random aleatorio = new Random(); return aleatorio.nextBoolean(); } /** * Devuelve un int aleatorio. * @return */ public static int getInt() { Random aleatorio = new Random(); return aleatorio.nextInt(); } }
cheste1/LibDAM
LibDAM/src/utilidades/Aleatorios.java
Java
gpl-3.0
6,150
// Copyright (C) 2009--2011, 2013, 2014 Jed Brown and Ed Bueler and Constantine Khroulev and David Maxwell // // This file is part of PISM. // // PISM 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. // // PISM 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 PISM; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // The following are macros (instead of inline functions) so that error handling // is less cluttered. They should be replaced with empty macros when in // optimized mode. #ifndef _FETOOLS_H_ #define _FETOOLS_H_ #include <petscmat.h> #include "iceModelVec.hh" // to get PISMVector2 //! \file //! \brief Classes for implementing the Finite Element Method on an IceGrid. /*! \file We assume that the reader has a basic understanding of the finite element method. The following is a reminder of the method that also gives the background for the how to implement it on an IceGrid with the tools in this module. The IceGrid domain \f$\Omega\f$ is decomposed into a grid of rectangular physical elements indexed by indices (i,j): \verbatim (0,1) (1,1) --------- | | | --------- | | | --------- (0,0) (1,0) \endverbatim The index of an element corresponds with the index of its lower-left vertex in the grid. The reference element is the square \f$[-1,1]\times[-1,1]\f$. For each physical element \f$E_{ij}\f$, there is an map \f$F_{ij}\f$ from the reference element \f$R\f$ to \f$E_{ij}\f$. In this implementation, the rectangles in the domain are all congruent, and the maps F_{ij} are all the same up to a translation. On the reference element, vertices are ordered as follows: \verbatim 3 o---------o 2 | | | | | | 0 o---------o 1 \endverbatim For each vertex \f$k\f$ there is an element basis function \f$\phi_k\f$ that is bilinear, equals 1 at vertex \f$k\f$, and equals 0 at the remaining vertices. For each node \f$(i',j')\f$ in the physical domain there is a basis function that equals 1 at vertex \f$(i',j')\f$, equals zero at all other vertices, and that on element \f$(i,j)\f$ can be written as \f$\phi_k\circ F_{i,j}^{-1}\f$ for some index \f$k\f$. A (scalar) finite element function \f$f\f$ on the domain is then a linear combination \f[ f_h = \sum_{i,j} c_{ij}\psi_{ij}. \f] Let \f$G(w,\psi)\f$ denote the weak form of the PDE under consideration. For example, for the scalar Poisson equation \f$-\Delta w = f\f$, \f[ G(w,\psi) = \int_\Omega \nabla w \cdot \nabla \psi -f\psi\;dx. \f] In the continuous problem we seek to find a trial function \f$w\f$ such that \f$G(w,\psi)=0\f$ for all suitable test functions \f$\psi\f$. In the discrete problem, we seek a finite element function \f$w_h\f$ such that \f$G(w_h,\psi_{ij})=0\f$ for all suitable indices \f$(i,j)\f$. For realistice problems, the integral given by \f$G\f$ cannot be evaluated exactly, but is approximated with some \f$G_h\f$ that arises from numerical quadrature quadrature rule: integration on an element \f$E\f$ is approximated with \f[ \int_E f dx \approx \sum_{q} f(x_q) w_q \f] for certain points \f$x_q\f$ and weights \f$j_q\f$ (specific details are found in FEQuadrature). The unknown \f$w_h\f$ is represented by an IceVec, \f$w_h=\sum_{ij} c_{ij} \psi_{ij}\f$ where \f$c_{ij}\f$ are the coefficients of the vector. The solution of the finite element problem requires the following computations: -# Evaluation of the residuals \f$r_{ij} = G_h(w_h,\psi_{ij})\f$ -# Evaluation of the Jacobian matrix \f[ J_{(ij)\;(kl)}=\frac{d}{dc_{kl}} G_h(w_h,\psi_{ij}). \f] Computations of these 'integrals' are done by adding up the contributions from each element (an FEElementMap helps with iterating over the elements). For a fixed element, there is a locally defined trial function \f$\hat w_h\f$ (with 4 degrees of freedom in the scalar case) and 4 local test functions \f$\hat\psi_k\f$, one for each vertex. The contribution to the integrals proceeds as follows (for concreteness in the case of computing the residual): - Extract from the global degrees of freedom \f$c\f$ defining \f$w_h\f$ the local degrees of freedom \f$d\f$ defining \f$\hat w_h\f$. (FEDOFMap) - Evaluate the local trial function \f$w_h\f$ (values and derivatives as needed) at the quadrature points \f$x_q\f$ (FEQuadrature) - Evaluate the local test functions (again values and derivatives) at the quadrature points. (FEQuadrature) - Obtain the quadrature weights $j_q$ for the element (FEQuadrature) - Compute the values of the integrand \f$g(\hat w_h,\psi_k)\f$ at each quadrature point (call these \f$g_{qk}\f$) and form the weighted sums \f$y_k=\sum_{q} j_q g_{qk}\f$. - Each sum \f$y_k\f$ is the contribution of the current element to a residual entry \f$r_{ij}\f$, where local degree of freedom \f$k\f$ corresponds with global degree of freedom \f$(i,j)\f$. The local contibutions now need to be added to the global residual vector (FEDOFMap). Computation of the Jacobian is similar, except that there are now multiple integrals per element (one for each local degree of freedom of \f$\hat w_h\f$). All of the above is a simplified description of what happens in practice. The complications below treated by the following classes, and discussed in their documentation: - Ghost elements (as well as periodic boundary conditions): FEElementMap - Dirichlet data: FEDOFMap - Vector valued functions: (FEDOFMap, FEQuadrature) The classes in this module are not intended to be a fancy finite element package. Their purpose is to clarify the steps that occur in the computation of residuals and Jacobians in SSAFEM, and to isolate and consolodate the hard steps so that they are not scattered about the code. */ //! Struct for gathering the value and derivative of a function at a point. /*! Germ in meant in the mathematical sense, sort of. */ struct FEFunctionGerm { double val, //!< Function value. dx, //!< Function deriviative with respect to x. dy; //!< Function derivative with respect to y. }; //! Struct for gathering the value and derivative of a vector valued function at a point. /*! Germ in meant in the mathematical sense, sort of. */ struct FEVector2Germ { PISMVector2 val, //!< Function value. dx, //!< Function deriviative with respect to x. dy; //!< Function derivative with respect to y. }; //! Computation of Q1 shape function values. /*! The Q1 shape functions are bilinear functions. On a rectangular element, there are four (FEShapeQ1::Nk) basis functions, each equal to 1 at one vertex and equal to zero at the remainder. The FEShapeQ1 class consolodates the computation of the values and derivatives of these basis functions. */ class FEShapeQ1 { public: virtual ~FEShapeQ1() {} //! Compute values and derivatives of the shape function supported at node 0 static void shape0(double x, double y, FEFunctionGerm *value) { value->val = (1-x)*(1-y)/4.; value->dx = -(1-y)/4.; value->dy = -(1-x)/4; } //! Compute values and derivatives of the shape function supported at node 1 static void shape1(double x, double y, FEFunctionGerm *value) { value->val = (1+x)*(1-y)/4.; value->dx = (1-y)/4.; value->dy = -(1+x)/4; } //! Compute values and derivatives of the shape function supported at node 2 static void shape2(double x, double y, FEFunctionGerm *value) { value->val = (1+x)*(1+y)/4.; value->dx = (1+y)/4.; value->dy = (1+x)/4; } //! Compute values and derivatives of the shape function supported at node 3 static void shape3(double x, double y, FEFunctionGerm *value) { value->val = (1-x)*(1+y)/4.; value->dx = -(1+y)/4.; value->dy = (1-x)/4; } //! The number of basis shape functions. static const int Nk = 4; //! A table of function pointers, one for each shape function. typedef void (*ShapeFunctionSpec)(double,double,FEFunctionGerm*); static const ShapeFunctionSpec shapeFunction[Nk]; //! Evaluate shape function \a k at (\a x,\a y) with values returned in \a germ. virtual void eval(int k, double x, double y,FEFunctionGerm*germ){ shapeFunction[k](x,y,germ); } }; //! The mapping from global to local degrees of freedom. /*! Computations of residual and Jacobian entries in the finite element method are done by iterating of the elements and adding the various contributions from each element. To do this, degrees of freedom from the global vector of unknowns must be remapped to element-local degrees of freedom for the purposes of local computation, (and the results added back again to the global residual and Jacobian arrays). An FEDOFMap mediates the transfer between element-local and global degrees of freedom. In this very concrete implementation, the global degrees of freedom are either scalars (double's) or vectors (PISMVector2's), one per node in the IceGrid, and the local degrees of freedom on the element are FEDOFMap::Nk (%i.e. four) scalars or vectors, one for each vertex of the element. The FEDOFMap is also (perhaps awkwardly) overloaded to also mediate transfering locally computed contributions to residual and Jacobian matricies to their global counterparts. See also: \link FETools.hh FiniteElement/IceGrid background material\endlink. */ class FEDOFMap { public: FEDOFMap() { m_i = m_j = 0; PetscMemzero(m_row, Nk*sizeof(MatStencil)); PetscMemzero(m_col, Nk*sizeof(MatStencil)); }; virtual ~FEDOFMap() {}; virtual void extractLocalDOFs(int i, int j, double const*const*xg, double *x) const; virtual void extractLocalDOFs(int i, int j, PISMVector2 const*const*xg, PISMVector2 *x) const; virtual void extractLocalDOFs(double const*const*xg, double *x) const; virtual void extractLocalDOFs(PISMVector2 const*const*xg, PISMVector2 *x) const; virtual void reset(int i, int j, const IceGrid &g); virtual void markRowInvalid(int k); virtual void markColInvalid(int k); void localToGlobal(int k, int *i, int *j); virtual void addLocalResidualBlock(const PISMVector2 *y, PISMVector2 **yg); virtual void addLocalResidualBlock(const double *y, double **yg); virtual PetscErrorCode addLocalJacobianBlock(const double *K, Mat J); virtual PetscErrorCode setJacobianDiag(int i, int j, const double *K, Mat J); static const int Nk = 4; //<! The number of test functions defined on an element. protected: static const int kDofInvalid = PETSC_MIN_INT / 8; //!< Constant for marking invalid row/columns. static const int kIOffset[Nk]; static const int kJOffset[Nk]; //! Indices of the current element (for updating residual/Jacobian). int m_i, m_j; //! Stencils for updating entries of the Jacobian matrix. MatStencil m_row[Nk], m_col[Nk]; }; //! Manages iterating over element indices. /*! When computing residuals and Jacobians, there is a loop over all the elements in the IceGrid, and computations are done on each element. The IceGrid has an underlying Petsc DA, and our processor does not own all of the nodes in the grid. Therefore we should not perform computation on all of the elements. In general, an element will have ghost (o) and real (*) vertices: \verbatim o---*---*---*---o | | | | | o---*---*---*---o | | | | | o---o---o---o---o \endverbatim The strategy is to do computations on this processor on every element that has a vertex that is owned by this processor. But we only update entries in the global residual and Jacobian matrices if the corresponding row corresponds to a vertex that we own. In the worst case, where each vertex of an element is owned by a different processor, the computations for that element will be repeated four times, once for each processor. This same strategy also correctly deals with periodic boundary conditions. The way Petsc deals with periodic boundaries can be thought of as using a kind of ghost. So the rule still works: compute on all elements containg a real vertex, but only update rows corresponding to that real vertex. The calculation of what elements to index over needs to account for ghosts and the presence or absense of periodic boundary conditions in the IceGrid. The FEElementMap performs that computation for you (see FEElementMap::xs and friends). See also: \link FETools.hh FiniteElement/IceGrid background material\endlink. */ class FEElementMap { public: FEElementMap(const IceGrid &g); /*!\brief The total number of elements to be iterated over. Useful for creating per-element storage.*/ int element_count() { return xm*ym; } /*!\brief Convert an element index (\a i,\a j) into a flattened (1-d) array index, with the first element (\a i, \a j) to be iterated over corresponding to flattened index 0. */ int flatten(int i, int j) { return (i-xs)*ym+(j-ys); } int xs, //!< x-coordinate of the first element to loop over. xm, //!< total number of elements to loop over in the x-direction. ys, //!< y-coordinate of the first element to loop over. ym, //!< total number of elements to loop over in the y-direction. lxs, //!< x-index of the first local element. lxm, //!< total number local elements in x direction. lys, //!< y-index of the first local element. lym; //!< total number local elements in y direction. }; //! Numerical integration of finite element functions. /*! The core of the finite element method is the computation of integrals over elements. For nonlinear problems, or problems with non-constant coefficients (%i.e. any real problem) the integration has to be done approximately: \f[ \int_E f(x)\; dx \approx \sum_q f(x_q) w_q \f] for certain quadrature points \f$x_q\f$ and weights \f$w_q\f$. An FEQuadrature is used to evaluate finite element functions at quadrature points, and to compute weights \f$w_q\f$ for a given element. In this concrete implementation, the reference element \f$R\f$ is the square \f$[-1,1]\times[-1,1]\f$. On a given element, nodes (o) and quadrature points (*) are ordered as follows: \verbatim 3 o------------------o 2 | 3 2 | | * * | | | | | | * * | | 0 1 | 0 o------------------o 1 \endverbatim So there are four quad points per element, which occur at \f$x,y=\pm 1/\sqrt{3}\f$. This corresponds to the tensor product of Gaussian integration on an interval that is exact for cubic functions on the interval. Integration on a physical element can be thought of as being done by change of variables. The quadrature weights need to be modified, and the FEQuadrature takes care of this for you. Because all elements in an IceGrid are congruent, the quadrature weights are the same for each element, and are computed upon initialization with an IceGrid. See also: \link FETools.hh FiniteElement/IceGrid background material\endlink. */ class FEQuadrature { public: static const int Nq = 4; //!< Number of quadrature points. static const int Nk = 4; //!< Number of test functions on the element. FEQuadrature(); void init(const IceGrid &g,double L=1.); // FIXME Allow a length scale to be specified. const FEFunctionGerm (*testFunctionValues())[Nq]; const FEFunctionGerm *testFunctionValues(int q); const FEFunctionGerm *testFunctionValues(int q,int k); void computeTrialFunctionValues( const double *x, double *vals); void computeTrialFunctionValues( const double *x, double *vals, double *dx, double *dy); void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, double const*const*xg, double *vals); void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, double const*const*xg, double *vals, double *dx, double *dy); void computeTrialFunctionValues( const PISMVector2 *x, PISMVector2 *vals); void computeTrialFunctionValues( const PISMVector2 *x, PISMVector2 *vals, double (*Dv)[3]); void computeTrialFunctionValues( const PISMVector2 *x, PISMVector2 *vals, PISMVector2 *dx, PISMVector2 *dy); void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, PISMVector2 const*const*xg, PISMVector2 *vals); void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, PISMVector2 const*const*xg, PISMVector2 *vals, double (*Dv)[3]); void getWeightedJacobian(double *jxw); //! The coordinates of the quadrature points on the reference element. static const double quadPoints[Nq][2]; //! The weights for quadrature on the reference element. static const double quadWeights[Nq]; protected: //! The Jacobian determinant of the map from the reference element to the physical element. double m_jacobianDet; //! Shape function values (for each of \a Nq quadrature points, and each of \a Nk shape function ) FEFunctionGerm m_germs[Nq][Nk]; double m_tmpScalar[Nk]; PISMVector2 m_tmpVector[Nk]; }; class DirichletData { public: DirichletData(); ~DirichletData(); PetscErrorCode init( IceModelVec2Int *indices, IceModelVec2V *values, double weight); PetscErrorCode init( IceModelVec2Int *indices, IceModelVec2S *values, double weight); PetscErrorCode init( IceModelVec2Int *indices); void constrain( FEDOFMap &dofmap ); void update( FEDOFMap &dofmap, PISMVector2* x_e ); void update( FEDOFMap &dofmap, double* x_e ); void updateHomogeneous( FEDOFMap &dofmap, PISMVector2* x_e ); void updateHomogeneous( FEDOFMap &dofmap, double* x_e ); void fixResidual( PISMVector2 **x, PISMVector2 **r); void fixResidual( double **x, double **r); void fixResidualHomogeneous( PISMVector2 **r); void fixResidualHomogeneous( double **r); PetscErrorCode fixJacobian2V( Mat J); PetscErrorCode fixJacobian2S( Mat J); operator bool() { return m_indices != NULL; } PetscErrorCode finish(); protected: double m_indices_e[FEQuadrature::Nk]; IceModelVec2Int *m_indices; IceModelVec *m_values; double **m_pIndices; void **m_pValues; double m_weight; }; #endif/* _FETOOLS_H_*/
talbrecht/pism_pik06
src/base/stressbalance/ssa/FETools.hh
C++
gpl-3.0
18,810
/* * Copyright (c) 2010-2014 Clark & Parsia, LLC. <http://www.clarkparsia.com> * * 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.complexible.stardog.plan.aggregates; import java.io.File; import com.complexible.common.protocols.server.Server; import com.complexible.common.rdf.query.resultio.TextTableQueryResultWriter; import com.complexible.stardog.Stardog; import com.complexible.stardog.api.Connection; import com.complexible.stardog.api.ConnectionConfiguration; import com.complexible.stardog.api.admin.AdminConnection; import com.complexible.stardog.api.admin.AdminConnectionConfiguration; import com.complexible.stardog.protocols.snarl.SNARLProtocolConstants; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openrdf.query.TupleQueryResult; import org.openrdf.query.resultio.QueryResultIO; /** * <p></p> * * @author Albert Meroño-Peñuela * @since 1.0 * @version 1.0 */ public class TestRAggregates { private static Server SERVER = null; private static final String DB = "testRAggregates"; @BeforeClass public static void beforeClass() throws Exception { SERVER = Stardog.buildServer() .bind(SNARLProtocolConstants.EMBEDDED_ADDRESS) .start(); final AdminConnection aConn = AdminConnectionConfiguration.toEmbeddedServer() .credentials("admin", "admin") .connect(); try { if (aConn.list().contains(DB)) { aConn.drop(DB); } aConn.memory(DB).create(new File("/Users/Albert/src/linked-edit-rules/data/people.ttl")); } finally { aConn.close(); } } @AfterClass public static void afterClass() { if (SERVER != null) { SERVER.stop(); } } @Test public void TestMean() throws Exception { final Connection aConn = ConnectionConfiguration.to(DB) .credentials("admin", "admin") .connect(); try { final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + "PREFIX agg: <urn:aggregate> " + "SELECT (agg:stardog:mean(?o) AS ?c) " + "WHERE { ?s leri:height ?o } "; System.out.println("Executing query: " + aQuery); final TupleQueryResult aResult = aConn.select(aQuery).execute(); try { System.out.println("Query result:"); while (aResult.hasNext()) { System.out.println(aResult.next().getValue("c").stringValue()); } } finally { aResult.close(); } } finally { aConn.close(); } } // @Test // public void TestMedian() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "PREFIX agg: <urn:aggregate> " + // "SELECT (agg:stardog:median(?o) AS ?c) " + // "WHERE { ?s leri:height ?o } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestMaxAggregate() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "PREFIX agg: <urn:aggregate> " + // "SELECT (agg:stardog:max(?o) AS ?c) " + // "WHERE { ?s leri:height ?o } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestMinAggregate() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "PREFIX agg: <urn:aggregate> " + // "SELECT (agg:stardog:min(?o) AS ?c) " + // "WHERE { ?s leri:height ?o } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestSd() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "PREFIX agg: <urn:aggregate> " + // "SELECT (agg:stardog:sd(?o) AS ?c) " + // "WHERE { ?s leri:height ?o } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestVar() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "PREFIX agg: <urn:aggregate> " + // "SELECT (agg:stardog:var(?o) AS ?c) " + // "WHERE { ?s leri:height ?o } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestAbs() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:abs(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestSqrt() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:sqrt(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestCeiling() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:ceiling(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestFloor() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:floor(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestTrunc() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:trunc(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestLog() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:log(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestLog10() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:log10(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestExp() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:exp(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestRound() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:round(stardog:sin(?o), 4) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestSignif() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:signif(stardog:sin(?o), 4) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestCos() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:cos(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestSin() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:sin(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestTan() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT ?c " + // "WHERE { ?s leri:height ?o . BIND (stardog:tan(?o) AS ?c) } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } // // @Test // public void TestCov() throws Exception { // final Connection aConn = ConnectionConfiguration.to(DB) // .credentials("admin", "admin") // .connect(); // try { // // final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + // "PREFIX sdmx-dimension: <http://purl.org/linked-data/sdmx/2009/dimension#> " + // "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + // "SELECT (stardog:cov(?height, ?age) AS ?c) " + // "WHERE { ?s leri:height ?height ; sdmx-dimension:age ?age } "; // System.out.println("Executing query: " + aQuery); // // final TupleQueryResult aResult = aConn.select(aQuery).execute(); // // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // System.out.println(aResult.next().getValue("c").stringValue()); // } // } // finally { // aResult.close(); // } // } // finally { // aConn.close(); // } // } @Test public void TestPredict() throws Exception { final Connection aConn = ConnectionConfiguration.to(DB) .credentials("admin", "admin") .connect(); try { final String aQuery = "PREFIX stardog: <tag:stardog:api:> " + "PREFIX sdmx-dimension: <http://purl.org/linked-data/sdmx/2009/dimension#> " + "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " + "SELECT (stardog:predict(?age) AS ?page) " + "WHERE { ?s leri:height ?height . } "; System.out.println("Executing query: " + aQuery); final TupleQueryResult aResult = aConn.select(aQuery).execute(); //QueryResultIO.write(aResult, TextTableQueryResultWriter.FORMAT, System.out); // try { // System.out.println("Query result:"); // while (aResult.hasNext()) { // try { // System.out.println(aResult.next().getValue("page").stringValue()); // } catch (NullPointerException e) { // System.out.println("NA"); // } // } // } catch (NullPointerException e) { // System.err.println(e.getMessage()); // } // finally { // aResult.close(); // } } finally { aConn.close(); } } }
albertmeronyo/stardog-r
aggregates/test/src/com/complexible/stardog/plan/aggregates/TestRAggregates.java
Java
gpl-3.0
22,803
/* * HelpCommand.java * * Copyright (C) 2002-2013 Takis Diakoumis * * 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 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.executequery.gui.console.commands; import org.executequery.gui.console.Console; import org.underworldlabs.util.SystemProperties; /* ---------------------------------------------------------- * CVS NOTE: Changes to the CVS repository prior to the * release of version 3.0.0beta1 has meant a * resetting of CVS revision numbers. * ---------------------------------------------------------- */ /** * This command displays command help. * @author Romain Guy */ /** * @author Takis Diakoumis * @version $Revision: 160 $ * @date $Date: 2013-02-08 17:15:04 +0400 (Пт, 08 фев 2013) $ */ public class HelpCommand extends Command { private static final String COMMAND_NAME = "help"; public String getCommandName() { return COMMAND_NAME; } public String getCommandSummary() { return SystemProperties.getProperty("console", "console.help.command.help"); } public boolean handleCommand(Console console, String command) { if (command.equals(COMMAND_NAME)) { console.help(); return true; } return false; } }
Black-millenium/rdb-executequery
java/src/org/executequery/gui/console/commands/HelpCommand.java
Java
gpl-3.0
1,823
/* * Copyright 2010 kk-electronic a/s. * * This file is part of KKPortal. * * KKPortal 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. * * KKPortal 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 KKPortal. If not, see <http://www.gnu.org/licenses/>. * */ package com.kk_electronic.kkportal.core.rpc.jsonformat; @SuppressWarnings("serial") public class UnableToDeserialize extends Exception { public UnableToDeserialize(String string) { super(string); } }
kk-electronic/KKPortal
src/com/kk_electronic/kkportal/core/rpc/jsonformat/UnableToDeserialize.java
Java
gpl-3.0
950
/** * Copyright 2015 Poznań Supercomputing and Networking Center * * Licensed under the GNU General Public License, Version 3.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.gnu.org/licenses/gpl-3.0.txt * * 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 pl.psnc.synat.wrdz.ms.stats; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ejb.EJB; import pl.psnc.synat.wrdz.ms.entity.stats.DataFileFormatStat; import pl.psnc.synat.wrdz.zmd.dto.format.DataFileFormatDto; import pl.psnc.synat.wrdz.zmd.format.DataFileFormatBrowser; /** * Bean that handles data file format statistics. */ @SuppressWarnings("serial") public abstract class DataFileFormatBean implements Serializable { /** Data file format statistics. */ private List<DataFileFormatStat> stats; /** Data file format information. */ private Map<String, DataFileFormatDto> formats; /** Data file format browser. */ @EJB(name = "DataFileFormatBrowser") private transient DataFileFormatBrowser formatBrowser; /** When the statistics were computed. */ private Date computedOn; /** * Refreshes the currently cached statistics. */ public void refresh() { stats = fetchStatistics(); computedOn = !stats.isEmpty() ? stats.get(0).getComputedOn() : null; formats = new HashMap<String, DataFileFormatDto>(); for (DataFileFormatDto format : formatBrowser.getFormats()) { formats.put(format.getPuid(), format); } } /** * Returns the currently cached statistics, refreshing them if necessary. * * @return statistics */ public List<DataFileFormatStat> getStatistics() { if (stats == null) { refresh(); } return stats; } public Date getComputedOn() { return computedOn; } /** * Returns the map with format puids and their data. * * @return a <format puid, format data> map */ public Map<String, DataFileFormatDto> getFormats() { if (formats == null) { refresh(); } return formats; } /** * Fetches the statistics from database. * * @return the statistics */ protected abstract List<DataFileFormatStat> fetchStatistics(); }
psnc-dl/darceo
wrdz/wrdz-ms/web/src/main/java/pl/psnc/synat/wrdz/ms/stats/DataFileFormatBean.java
Java
gpl-3.0
2,754
<?php /* Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). This 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 later. Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>. */ //! Legacy mode enabler class F3 { public static $fw; /** * Forward function calls to framework * * @return mixed * @param $func callback * @param $args array **/ public static function __callstatic($func, array $args) { if (!self::$fw) { self::$fw=Base::instance(); } return call_user_func_array([self::$fw,$func], $args); } }
vijinho/fatfree-core-psr2
f3.php
PHP
gpl-3.0
1,213
#include "pointconversor.h" #include "invalidconversorinput.h" // TODO: implement human notation WIHTOUT double float (or any float). // With float, there are some 64 bits numbers which cannot be represented // because double float only really has 52 bits for mantissa. PointConversor::PointConversor(): bits(0), exponent(0), sign(false), normality(PointConversor::NORMAL) { } // Raw input functions PointConversor& PointConversor::inputHalfFloatRaw(uint16_t number) { return this->inputGenericFloatRaw(number, 10, 5); } PointConversor& PointConversor::inputSingleFloatRaw(float number) { union { float number; uint32_t bits; } bitCast { number }; return this->inputGenericFloatRaw(bitCast.bits, 23, 8); } PointConversor& PointConversor::inputDoubleFloatRaw(double number) { union { double number; uint64_t bits; } bitCast { number }; return this->inputGenericFloatRaw(bitCast.bits, 52, 11); } PointConversor& PointConversor::inputFixed8Raw(uint8_t number, int16_t pointPos, Signedness signedness) { return this->inputGenericFixedRaw(number, 8, pointPos, signedness); } PointConversor& PointConversor::inputFixed16Raw(uint16_t number, int16_t pointPos, Signedness signedness) { return this->inputGenericFixedRaw(number, 16, pointPos, signedness); } PointConversor& PointConversor::inputFixed32Raw(uint32_t number, int16_t pointPos, Signedness signedness) { return this->inputGenericFixedRaw(number, 32, pointPos, signedness); } PointConversor& PointConversor::inputFixed64Raw(uint64_t number, int16_t pointPos, Signedness signedness) { return this->inputGenericFixedRaw(number, 64, pointPos, signedness); } // String input functions PointConversor& PointConversor::inputHalfFloat(QString const& number) { return this->inputGenericFloat(number, 10, 5); } PointConversor& PointConversor::inputSingleFloat(QString const& number) { return this->inputGenericFloat(number, 23, 8); } PointConversor& PointConversor::inputDoubleFloat(QString const& number) { return this->inputGenericFloat(number, 52, 11); } PointConversor& PointConversor::inputFixed8(QString const& number, Signedness signedness) { return this->inputGenericFixed(number, 8, signedness); } PointConversor& PointConversor::inputFixed16(QString const& number, Signedness signedness) { return this->inputGenericFixed(number, 16, signedness); } PointConversor& PointConversor::inputFixed32(QString const& number, Signedness signedness) { return this->inputGenericFixed(number, 32, signedness); } PointConversor& PointConversor::inputFixed64(QString const& number, Signedness signedness) { return this->inputGenericFixed(number, 64, signedness); } PointConversor& PointConversor::inputHumanNotation(QString const& number) { // For now, we are decoding human notation via double float. This means we // are losing some precision, since double has only 52 bits of significant // digits, and our class stores 64 bits of significant digits, but that's // perhaps acceptable. bool ok = true; double asDoubleFloat = number.toDouble(&ok); if (!ok) { throw InvalidConversorInput("Número não está na notação humana adequada"); } return this->inputDoubleFloatRaw(asDoubleFloat); } // Raw output functions uint16_t PointConversor::outputHalfFloatRaw() const { return this->outputGenericFloatRaw(10, 5); } float PointConversor::outputSingleFloatRaw() const { uint32_t number = this->outputGenericFloatRaw(23, 8); union { uint32_t bits; float number; } bitCast { number }; return bitCast.number; } double PointConversor::outputDoubleFloatRaw() const { uint64_t number = this->outputGenericFloatRaw(52, 11); union { uint64_t bits; double number; } bitCast { number }; return bitCast.number; } uint8_t PointConversor::outputFixed8Raw(int16_t pointPos, Signedness signedness) const { return this->outputGenericFixedRaw(8, pointPos, signedness); } uint16_t PointConversor::outputFixed16Raw(int16_t pointPos, Signedness signedness) const { return this->outputGenericFixedRaw(16, pointPos, signedness); } uint32_t PointConversor::outputFixed32Raw(int16_t pointPos, Signedness signedness) const { return this->outputGenericFixedRaw(32, pointPos, signedness); } uint64_t PointConversor::outputFixed64Raw(int16_t pointPos, Signedness signedness) const { return this->outputGenericFixedRaw(64, pointPos, signedness); } QString PointConversor::outputHalfFloat() const { return this->outputGenericFloat(10, 5); } QString PointConversor::outputSingleFloat() const { return this->outputGenericFloat(23, 8); } QString PointConversor::outputDoubleFloat() const { return this->outputGenericFloat(52, 11); } // String output function QString PointConversor::outputFixed8(int16_t pointPos, Signedness signedness) const { return this->outputGenericFixed(8, pointPos, signedness); } QString PointConversor::outputFixed16(int16_t pointPos, Signedness signedness) const { return this->outputGenericFixed(16, pointPos, signedness); } QString PointConversor::outputFixed32(int16_t pointPos, Signedness signedness) const { return this->outputGenericFixed(32, pointPos, signedness); } QString PointConversor::outputFixed64(int16_t pointPos, Signedness signedness) const { return this->outputGenericFixed(64, pointPos, signedness); } QString PointConversor::outputHumanNotation() const { double asDoubleFloat = this->outputDoubleFloatRaw(); QString rendered = QString::number(asDoubleFloat, 'f', 50); if (rendered.contains('.')) { int trailingPos = rendered.length() - 1; while (trailingPos > 2 && rendered[trailingPos] == '0') { trailingPos--; } rendered.truncate(trailingPos + 1); } return rendered; } // Generic input functions PointConversor& PointConversor::inputGenericFloatRaw(uint64_t number, uint16_t mantissaSize, uint16_t exponentSize) { uint64_t mantissaMask = 0; int16_t exponentMask = 0; uint64_t finalBit = 0; validateFloatSpec(mantissaSize, exponentSize); // Initialize here because mantissa size or exponent size might be invalid. mantissaMask = ((uint64_t) 1 << mantissaSize) - 1; exponentMask = ((uint64_t) 1 << exponentSize) - 1; finalBit = ((uint64_t) 1 << mantissaSize); // Sign is the last bit. this->sign = number >> (exponentSize + mantissaSize); // We store the mantissa bits (lower bits) as the significant bits. this->bits = number & mantissaMask; // Exponent is between the mantissa and the sign. this->exponent = (number >> mantissaSize) & exponentMask; if (this->exponent != exponentMask) { // Exponent being `< maximum` exponent means it is normal. if (this->exponent == 0) { // But if the exponent is zero, it is actually subnormal. this->exponent++; } else { // Otherwise, `0 < exponent < max` means it is really normal. // // There is an extra high bit, because a normal number is in this // format: // // 1.xxxxxxx... * 2**e // // And this "1" is not stored, only the xxxxxx... // // So, we need to introduce it. this->bits |= finalBit; } this->normality = PointConversor::NORMAL; // The exponent uses an encoding which we need to translate to C++'s signed numbers. this->exponent -= mantissaSize + (exponentMask >> 1); } else if (this->bits == 0) { // exponent == MAX and bits are zeroed, therefore, Infinity. this->normality = PointConversor::INFINITY_NAN; } else { // exponent == MAX and bits not zeroed, therefore, regular NAN. this->normality = PointConversor::NOT_A_NUMBER; } return *this; } PointConversor& PointConversor::inputGenericFixedRaw(uint64_t number, int16_t width, int16_t pointPos, Signedness signedness) { uint64_t signMask = 0; uint64_t extendMask = 0; validateFixedSpec(width, pointPos, signedness); // Initialize here because width might be invalid. // // Last bit. signMask = (uint64_t) 1 << (width - 1); // Cut off extension mask, 0000....011111...1111 extendMask = ~((uint64_t) 0) >> (MAX_WIDTH - width); // Fixed point is always normal. this->normality = PointConversor::NORMAL; switch (signedness) { case UNSIGNED: this->sign = false; break; case TWOS_COMPL: this->sign = (number & signMask) != 0; break; } // Bits b with point p means the number is b * 2**(-p) this->exponent = -pointPos; this->bits = number; if (this->sign) { // Complementing negativeness. this->bits = (~this->bits + 1) & extendMask; } return *this; } PointConversor& PointConversor::inputGenericFloat(QString const &number, uint16_t mantissaSize, uint16_t exponentSize) { uint64_t numBits = 0; bool hasChars = false; int count = 0; for (QChar numChar : number) { if (numChar == '0' || numChar == '1') { numBits <<= 1; // By now we know it is zero or one. numBits |= numChar.digitValue(); if (numBits != 0) { // Only start to count when bits not zero because leading zeros are ignored. count++; } if (count > mantissaSize + exponentSize + 1) { // Note that count ignores leading zeros. throw InvalidConversorInput("Entrada é muito grande"); } hasChars = true; } else if (numChar != ' ') { // Space is ignored, but other chars are an error! throw InvalidConversorInput("Entrada precisa conter apenas 0 ou 1"); } } if (!hasChars) { throw InvalidConversorInput("Entrada não pode ser vazia"); } return this->inputGenericFloatRaw(numBits, mantissaSize, exponentSize); } PointConversor& PointConversor::inputGenericFixed(QString const &number, int16_t width, Signedness signedness) { uint64_t numBits = 0; bool hasChars = false; bool pointFound = false; int16_t pointPos = 0; int count = 0; for (QChar numChar : number) { if (numChar == '0' || numChar == '1') { numBits <<= 1; // By now we know it is zero or one. numBits |= numChar.digitValue(); if (numBits != 0 || pointFound) { // Only start to count when bits not zero because leading zeros are ignored. // // However, once a point has been found, we cannot ignore anymore. count++; } if (count > width && numChar != '0') { // Note that count ignores leading zeros (before point!). throw InvalidConversorInput("Entrada é muito grande"); } hasChars = true; } else if (numChar == '.') { if (pointFound) { throw InvalidConversorInput("Entrada pode conter apenas um ponto"); } pointFound = true; // Saves point position, because count still has to be incremented for overflow checks, // and for knowing the total width. pointPos = count; } else if (numChar != ' ') { // Space is ignored, but other chars are an error! throw InvalidConversorInput("Entrada precisa conter apenas 0 ou 1 (ou ponto)"); } } if (!hasChars) { throw InvalidConversorInput("Entrada não pode ser vazia"); } if (!pointFound) { throw InvalidConversorInput("O número em ponto fixo deve conter um ponto."); } if (pointPos > width || count - pointPos > width) { throw InvalidConversorInput("O ponto não pode estar fora dos limites."); } // Actual point position is reversed because humans usually write numbers in big-endian: // complement it with the found width to reverse it back.. return this->inputGenericFixedRaw(numBits, width, count - pointPos, signedness); } // Generic output functions uint64_t PointConversor::outputGenericFloatRaw(uint16_t mantissaSize, uint16_t exponentSize) const { int16_t numExponent = 0; uint64_t numBits = 0; uint64_t number = 0; uint64_t mantissaMask = 0; int16_t exponentMask = 0; uint64_t finalBit = 0; bool subnormal = false; uint64_t roundRight = 0; // Initialize here because mantissa size or exponent size might be invalid. validateFloatSpec(mantissaSize, exponentSize); mantissaMask = ((uint64_t) 1 << mantissaSize) - 1; exponentMask = ((uint64_t) 1 << exponentSize) - 1; finalBit = (uint64_t) 1 << mantissaSize; switch (this->normality) { case PointConversor::NORMAL: // Converts the C++'s signed integer representation of the exponent into float's one. numExponent = this->exponent + (exponentMask >> 1) + mantissaSize; numBits = this->bits; // Try to normalize the number if too small. Remember "really" normal floats have an implicit bit, // and that the significant bits they store are `xxxxx...` in the number `1.xxxxx... * 2**e`. // This makes that 1 be in the correct position. while (numBits < finalBit && numBits != 0) { numBits <<= 1; // Remember making an equivalent exponent. numExponent -= 1; } // Same as the loop above, but in this case the number is too big. while (numBits >= (finalBit << 1)) { // If the last eliminated bit was 1, we might round the number later. roundRight = numBits & 1; numBits >>= 1; // Remember making an equivalent exponent. numExponent += 1; } if (numExponent <= 0) { // In case the exponent is below zero, this will be subnormal... while (numExponent < 0) { numBits >>= 1; numExponent += 1; } roundRight = numBits & 1; // Subnormal numbers have an extra step on the exponent, so we must // get rid off an extra bit to compensate. numBits >>= 1; } // If it does not have final bit, it is subnormal. Important for below. subnormal = (numBits & finalBit) == 0; // Getting rid of that implicit "1". numBits &= ~finalBit; // Potentially rounding in the right. numBits += roundRight; // Tries to fit the exponent. Might fail and end up with infinity below. while (numExponent > exponentMask && numBits < (finalBit >> 1)) { numBits <<= 1; numExponent -= 1; } if (subnormal && numBits == 0) { // No final bit => subnormal. numExponent = 0; } else if (numExponent >= exponentMask) { // Exponent too big? Then infinity. numExponent = exponentMask; numBits = 0; } break; case PointConversor::INFINITY_NAN: numExponent = exponentMask; numBits = 0; break; case PointConversor::NOT_A_NUMBER: numExponent = exponentMask; // Could be any non-zero value. numBits = 1; break; } number = numBits & mantissaMask; number |= (uint64_t) (numExponent & exponentMask) << mantissaSize; number |= (uint64_t) this->sign << (mantissaSize + exponentSize); return number; } uint64_t PointConversor::outputGenericFixedRaw(int16_t width, int16_t pointPos, Signedness signedness) const { uint64_t number = this->bits; int16_t numExponent = this->exponent; uint64_t finalBit = 0; uint64_t mantissaMask = 0; uint64_t digitsMask = 0; uint64_t roundLeft = 0; uint64_t roundRight = 0; validateFixedSpec(width, pointPos, signedness); // Initialize here because width might be invalid. // // 0000...01111..111111 digitsMask = ~((uint64_t) 0) >> (MAX_WIDTH - width); // Gets final significant bit (except for sign). switch (signedness) { case UNSIGNED: finalBit = (uint64_t) 1 << (width - 1); break; case TWOS_COMPL: finalBit = (uint64_t) 1 << (width - 2); break; } // Significant bits mask. mantissaMask = (finalBit << 1) - 1; switch (this->normality) { case NORMAL: // We need to normalize the exponent to the point position. while (numExponent > -pointPos) { // We might need to round the number in the left. if (number >= finalBit) { roundLeft = finalBit; } numExponent -= 1; number <<= 1; } // If the exponent was not too big, it could be too small. while (numExponent < -pointPos) { // In this case, we might need to round by the right. roundRight = (number & 1) != 0; numExponent += 1; number >>= 1; } if (number > mantissaMask) { roundLeft = finalBit; } // Potential rounding at left position (most significant). number |= roundLeft; // Truncating the number. number &= mantissaMask; if (digitsMask != number) { // But that's ok because we will round right (less significant) it here if required. number += roundRight; } if (this->sign) { switch (signedness) { case UNSIGNED: throw InvalidConversorInput("Formato de saída é sem sinal, mas entrada é negativa."); case TWOS_COMPL: // Complementing via 2's complement. number = (~number + 1) & digitsMask; break; } } break; case INFINITY_NAN: // If infinity, let's just assign it to the greatest value (in magnitude). number = mantissaMask; if (this->sign) { switch (signedness) { case UNSIGNED: throw InvalidConversorInput("Formato de saída é sem sinal, mas entrada é negativa."); case TWOS_COMPL: // Negative "infinity". number = ((~number + 1) & digitsMask) - 1; break; } } break; case NOT_A_NUMBER: // NAN is invalid for fixed points. No way to represent? throw InvalidConversorInput("Entrada é um NAN (Not A Number)"); } return number; } QString PointConversor::outputGenericFloat(uint16_t mantissaSize, uint16_t exponentSize) const { uint64_t number = this->outputGenericFloatRaw(mantissaSize, exponentSize); QString output; // Simple dummy binary conversion loop :P for (uint64_t i = mantissaSize + exponentSize + 1; i > 0; i--) { uint64_t mask = (uint64_t) 1 << (i - 1); output.append(number & mask ? '1' : '0'); } return output; } QString PointConversor::outputGenericFixed(int16_t width, int16_t pointPos, Signedness signedness) const { uint64_t number = this->outputGenericFixedRaw(width, pointPos, signedness); QString output; // Before the point. for (int i = width - 1; i >= pointPos; i--) { if (i >= 0) { // Regular bit conversion. uint64_t mask = (uint64_t) 1 << (uint64_t) i; output.append(number & mask ? '1' : '0'); } else { // Append a trailing zero. output.append('0'); } } // Point required because fixed-point format. output.append('.'); // After the point. for (int i = pointPos - 1; i >= 0; i--) { if (i < width) { // Regular bit conversion. uint64_t mask = (uint64_t) 1 << (uint64_t) i; output.append(number & mask ? '1' : '0'); } else { // Append a trailing zero. output.append('0'); } } return output; } // Validation functions void PointConversor::validateFloatSpec(uint16_t mantissaSize, uint16_t exponentSize) const { if (mantissaSize < MIN_MANTISSA_SIZE) { throw InvalidConversorInput(QString("Tamanho da mantissa não pode ser menor que ") + QString::number(MIN_MANTISSA_SIZE)); } if (exponentSize < MIN_EXPONENT_SIZE) { throw InvalidConversorInput(QString("Tamanho do expoente não pode ser menor que ") + QString::number(MIN_EXPONENT_SIZE)); } if (mantissaSize + exponentSize > MAX_WIDTH - 1) { throw InvalidConversorInput( QString("É necessário um bit de sinal, mantissa e expoente juntos devem ser menor que ") + QString::number(MAX_WIDTH - 1)); } } void PointConversor::validateFixedSpec(int16_t width, int16_t pointPos, Signedness signedness) const { if (width < MIN_FIXED_WIDTH) { throw InvalidConversorInput(QString("Largura não pode ser menor que ") + QString::number(MIN_FIXED_WIDTH)); } if (width > MAX_WIDTH) { throw InvalidConversorInput(QString("Largura não pode ser maior que ") + QString::number(MAX_WIDTH)); } if (pointPos > width || pointPos < 0) { throw InvalidConversorInput("Ponto fora da quantidade de bits disponíveis."); } if (pointPos > width || pointPos < 0) { throw InvalidConversorInput("Ponto fora da quantidade de bits disponíveis."); } }
petcomputacaoufrgs/hidracpp
src/core/pointconversor.cpp
C++
gpl-3.0
21,532
import java.util.ArrayList; /** * Write a description of class StrengthPotion here. * * @author Jarom Kraus * @version 2.23.16 */ @SuppressWarnings("unchecked") public class StrengthPotion extends Potion{ private ArrayList stats; public StrengthPotion(String Name){ super(Name); } public void drinkStrengthPotion(){ System.out.println("You drink the strength potion and your strength is increased."); }public ArrayList getStats(){ stats = new ArrayList(); stats.addAll(super.getStats()); return stats; } }
jaromkraus/RPG
RPG/StrengthPotion.java
Java
gpl-3.0
577
package centralapp.views; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import centralapp.controlers.CentralApp; /** * The main window containing all the sub-views */ @SuppressWarnings("serial") public class MainView extends JFrame { private JTabbedPane tabbedPane; /** * Constructor of MainView * * @param controler The controlers associated to this view */ public MainView(CentralApp controler) { //GTK theme /*try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (Exception e) { }*/ //Ensure to exit the program and not only the window setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(800, 600); tabbedPane = new JTabbedPane(); getContentPane().add(tabbedPane); //Just to test //openCheckInOutTab(); //Set up events addWindowListener(controler.new ExitEvent()); } /** * Add the panel in parameter as a tab of the main window * * @param name The tab's name * @param tab The panel to add */ public void addTab(String name, JPanel tab){ tabbedPane.addTab(name, tab); CentralApp.nbTab++; } /** * Close a tab * * @param tabNb The tab id */ public void closeTab(int tabNb) { tabbedPane.remove(tabNb); } }
Edroxis/DI3_Projet4_Pointeuse
src/centralapp/views/MainView.java
Java
gpl-3.0
1,273
from __future__ import print_function, division INLINE_LABEL_STYLE = { 'display': 'inline-block', } GRAPH_GLOBAL_CONFIG = { 'displaylogo': False, 'modeBarButtonsToRemove': ['sendDataToCloud'], } AXIS_OPTIONS = ({ 'label': 'linear', 'value': 'linear', }, { 'label': 'log', 'value': 'log', }) ERRORBAR_OPTIONS = ({ 'label': 'True', 'value': True, }, { 'label': 'False', 'value': False, }) LINE_STYLE = { 'width': 1.0, } XLABEL = { 'linear': r'Scattering Vector, $q$ $(\text{\AA}^{-1})$', 'log': r'Scattering Vector, $q$ $(\text{\AA}^{-1}) (log scale)$', 'guinier': r'$q^2$ $(\text{\AA}^{-2})$', 'kratky': r'Scattering Vector, $q$ $(\text{\AA}^{-1})$', 'porod': r'$q^4$ $(\text{\AA}^{-4})$', 'pdf': r'pair distance ($\text{\AA}$)', } YLABEL = { 'linear': 'Intensity (arb. units.)', 'log': r'$\log(I)$', 'guinier': r'$\ln(I(q))$', 'kratky': r'$I(q) \cdot q^2$', 'porod': r'$I(q) \cdot q^4$', 'relative_diff': 'Relative Ratio (%)', 'absolute_diff': 'Absolute Difference (arb. units.)', 'error': 'Error', 'error_relative_diff': 'Error Relative Ratio (%)', 'pdf': 'P(r)', } TITLE = { 'sasprofile': 'Subtracted Profiles', 'guinier': 'Guinier Profiles', 'kratky': 'Kratky Profiles', 'porod': 'Porod Profiles', 'relative_diff': 'Relative Difference Profiles', 'absolute_diff': 'Absolute Difference Profiles', 'error': 'Error Profile', 'error_relative_diff': 'Error Relative Difference Profile', 'pdf': 'Pair-wise Distribution', 'fitting': 'P(r) Distribution Fitting', }
lqhuang/SAXS-tools
dashboard/layouts/style.py
Python
gpl-3.0
1,620
/* * Copyright (C) 2020 <mark@makr.zone> * inspired and based on work * Copyright (C) 2011 Jason von Nieda <jason@vonnieda.org> * * This file is part of OpenPnP. * * OpenPnP 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. * * OpenPnP 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 OpenPnP. If not, see * <http://www.gnu.org/licenses/>. * * For more information about OpenPnP visit http://openpnp.org */ package org.openpnp.machine.reference.axis.wizards; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.TitledBorder; import org.openpnp.gui.components.ComponentDecorators; import org.openpnp.gui.support.AbstractConfigurationWizard; import org.openpnp.spi.Axis; import org.openpnp.spi.base.AbstractAxis; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.FormSpecs; import com.jgoodies.forms.layout.RowSpec; @SuppressWarnings("serial") public abstract class AbstractAxisConfigurationWizard extends AbstractConfigurationWizard { protected final AbstractAxis axis; protected JPanel panelProperties; protected JLabel lblName; protected JTextField name; protected JLabel lblType; protected JComboBox type; public AbstractAxisConfigurationWizard(AbstractAxis axis) { super(); this.axis = axis; panelProperties = new JPanel(); panelProperties.setBorder(new TitledBorder(null, "Properties", TitledBorder.LEADING, TitledBorder.TOP, null, null)); contentPanel.add(panelProperties); panelProperties.setLayout(new FormLayout(new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(70dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,}, new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,})); lblType = new JLabel("Type"); panelProperties.add(lblType, "2, 2, right, default"); type = new JComboBox(Axis.Type.values()); panelProperties.add(type, "4, 2, fill, default"); lblName = new JLabel("Name"); panelProperties.add(lblName, "2, 4, right, default"); name = new JTextField(); panelProperties.add(name, "4, 4, fill, default"); name.setColumns(20); } protected AbstractAxis getAxis() { return axis; } @Override public void createBindings() { addWrappedBinding(axis, "type", type, "selectedItem"); addWrappedBinding(axis, "name", name, "text"); ComponentDecorators.decorateWithAutoSelect(name); } }
openpnp/openpnp
src/main/java/org/openpnp/machine/reference/axis/wizards/AbstractAxisConfigurationWizard.java
Java
gpl-3.0
3,328
package com.github.alexaegis.plane.poligons; import com.github.alexaegis.plane.Point; public abstract class RegularPolygon implements Polygon { protected RegularPolygons type = null; protected Point center = new Point(0, 0); protected double edgeLength = 0; // length of the edges protected double radius = 0; // the radius of the circumscribed circle protected double apothem = 0; // the radius of the inscribed circle protected double perimeter = 0; RegularPolygon() { } @Override public double getArea() { return 0.5d * apothem * perimeter; } @Override public double getPerimeter() { return perimeter; } @Override public Point getCenter() { return new Point(center); } @Override public double diffInPerimArea() { return Math.abs(getArea() - getPerimeter()); } @Override public void show() { System.out.println(toString()); } @Override public String toString() { return "Regular Polygon{" + "type = " + type.getName() + ", vertices = " + Integer.toString(type.getVertices() - 1) + ", center = " + center.toString() + ", edgeLength = " + edgeLength + ", radius = " + radius + ", apothem = " + apothem + ", area = " + getArea() + ", perimeter = " + perimeter + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RegularPolygon that = (RegularPolygon) o; if (Double.compare(that.edgeLength, edgeLength) != 0) return false; if (Double.compare(that.radius, radius) != 0) return false; if (Double.compare(that.apothem, apothem) != 0) return false; if (Double.compare(that.perimeter, perimeter) != 0) return false; if (type != that.type) return false; if (center != null ? !center.equals(that.center) : that.center != null) return false; return true; } @Override public int hashCode() { int result; long temp; result = type != null ? type.hashCode() : 0; result = 31 * result + (center != null ? center.hashCode() : 0); temp = Double.doubleToLongBits(edgeLength); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(radius); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(apothem); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(perimeter); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } }
AlexAegis/elte-progtech-1
submission1/src/main/java/com/github/alexaegis/plane/poligons/RegularPolygon.java
Java
gpl-3.0
2,838
/******************************************************************************* * HellFirePvP / Astral Sorcery 2017 * * This project is licensed under GNU GENERAL PUBLIC LICENSE Version 3. * The source code is available on github: https://github.com/HellFirePvP/AstralSorcery * For further details, see the License file there. ******************************************************************************/ package hellfirepvp.astralsorcery.common.base; import hellfirepvp.astralsorcery.common.constellation.effect.GenListEntries; import hellfirepvp.astralsorcery.common.util.BlockStateCheck; import hellfirepvp.astralsorcery.common.util.ItemUtils; import hellfirepvp.astralsorcery.common.util.MiscUtils; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.World; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * This class is part of the Astral Sorcery Mod * The complete source code for this mod can be found on github. * Class: WorldMeltables * Created by HellFirePvP * Date: 31.10.2016 / 22:49 */ public enum WorldMeltables implements MeltInteraction { COBBLE( new BlockStateCheck.Block(Blocks.COBBLESTONE), Blocks.FLOWING_LAVA.getDefaultState(), 180), STONE( new BlockStateCheck.Block(Blocks.STONE), Blocks.FLOWING_LAVA.getDefaultState(), 100), OBSIDIAN( new BlockStateCheck.Block(Blocks.OBSIDIAN), Blocks.FLOWING_LAVA.getDefaultState(), 75), NETHERRACK( new BlockStateCheck.Block(Blocks.NETHERRACK), Blocks.FLOWING_LAVA.getDefaultState(), 40), NETHERBRICK(new BlockStateCheck.Block(Blocks.NETHER_BRICK), Blocks.FLOWING_LAVA.getDefaultState(), 60), MAGMA( new BlockStateCheck.Block(Blocks.MAGMA), Blocks.FLOWING_LAVA.getDefaultState(), 1), ICE( new BlockStateCheck.Block(Blocks.ICE), Blocks.FLOWING_WATER.getDefaultState(), 1), FROSTED_ICE(new BlockStateCheck.Block(Blocks.FROSTED_ICE), Blocks.FLOWING_WATER.getDefaultState(), 1), PACKED_ICE( new BlockStateCheck.Block(Blocks.PACKED_ICE), Blocks.FLOWING_WATER.getDefaultState(), 2); private final BlockStateCheck meltableCheck; private final IBlockState meltResult; private final int meltDuration; private WorldMeltables(BlockStateCheck meltableCheck, IBlockState meltResult, int meltDuration) { this.meltableCheck = meltableCheck; this.meltResult = meltResult; this.meltDuration = meltDuration; } @Override public boolean isMeltable(World world, BlockPos pos, IBlockState worldState) { return meltableCheck.isStateValid(world, pos, worldState); } @Override @Nullable public IBlockState getMeltResultState() { return meltResult; } @Override @Nonnull public ItemStack getMeltResultStack() { return ItemStack.EMPTY; } @Override public int getMeltTickDuration() { return meltDuration; } @Nullable public static MeltInteraction getMeltable(World world, BlockPos pos) { IBlockState state = world.getBlockState(pos); for (WorldMeltables melt : values()) { if(melt.isMeltable(world, pos, state)) return melt; } ItemStack stack = ItemUtils.createBlockStack(state); if(!stack.isEmpty()) { ItemStack out = FurnaceRecipes.instance().getSmeltingResult(stack); if(!out.isEmpty()) { return new FurnaceRecipeInteraction(state, out); } } return null; } public static class ActiveMeltableEntry extends GenListEntries.CounterListEntry { public ActiveMeltableEntry(BlockPos pos) { super(pos); } public boolean isValid(World world, boolean forceLoad) { if(!forceLoad && !MiscUtils.isChunkLoaded(world, new ChunkPos(getPos()))) return true; return getMeltable(world) != null; } public MeltInteraction getMeltable(World world) { return WorldMeltables.getMeltable(world, getPos()); } } public static class FurnaceRecipeInteraction implements MeltInteraction { private final ItemStack out; private final BlockStateCheck.Meta matchInState; public FurnaceRecipeInteraction(IBlockState inState, ItemStack outStack) { this.matchInState = new BlockStateCheck.Meta(inState.getBlock(), inState.getBlock().getMetaFromState(inState)); this.out = outStack; } @Override public boolean isMeltable(World world, BlockPos pos, IBlockState state) { return matchInState.isStateValid(world, pos, state); } @Nullable @Override public IBlockState getMeltResultState() { return ItemUtils.createBlockState(out); } @Nonnull @Override public ItemStack getMeltResultStack() { return out; } } }
Saereth/AstralSorcery
src/main/java/hellfirepvp/astralsorcery/common/base/WorldMeltables.java
Java
gpl-3.0
5,184
# -*- coding: utf-8 -*- # Generated by Django 1.9.3 on 2016-07-01 17:09 from __future__ import unicode_literals from django.db import migrations import django_fsm class Migration(migrations.Migration): dependencies = [ ('invoice', '0002_billordering'), ] operations = [ migrations.AlterField( model_name='bill', name='status', field=django_fsm.FSMIntegerField(choices=[(0, 'building'), (1, 'valid'), (2, 'cancel'), (3, 'archive')], db_index=True, default=0, verbose_name='status'), ), ]
Diacamma2/financial
diacamma/invoice/migrations/0003_bill_status.py
Python
gpl-3.0
568
package com.taobao.api.domain; import java.util.List; import com.taobao.api.TaobaoObject; import com.taobao.api.internal.mapping.ApiField; import com.taobao.api.internal.mapping.ApiListField; /** * 评价信息 * * @author auto create * @since 1.0, null */ public class RateInfo extends TaobaoObject { private static final long serialVersionUID = 7494752753378247845L; /** * 评价信息 */ @ApiListField("rate_list") @ApiField("rate_item") private List<RateItem> rateList; public List<RateItem> getRateList() { return this.rateList; } public void setRateList(List<RateItem> rateList) { this.rateList = rateList; } }
kuiwang/my-dev
src/main/java/com/taobao/api/domain/RateInfo.java
Java
gpl-3.0
692