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
// sparkly effect for xmas stuff // a blue icey glow with occasional sparkles // sparkles led.led_rnd(0, led.leds); led.color(255, 255, 255); led.fade_mode(2); led.fade_speed(20); led.draw(); //blue glow led.repeat_begin_rnd(0,100); led.led_rnd(0, led.leds); led.color_rnd(0, 0, 0, 0, 100, 250); led.fade_mode(1); led.fade_speed(1); led.draw(); led.delay(0); led.repeat_end();
psy0rz/ledanim
web/repo/xmas/sparkle.js
JavaScript
gpl-3.0
390
<?php /** * Ini manipulation */ class Ini { var $m_ini; function Ini() { $this->m_ini = Array(); } function load($fn) { $this->m_ini = Array(); $fh = fopen($fn, "r"); if (!$fh) return false; $section = ""; while (($line = fgets($fh)) !== false) { $line = trim($line); // ignore blank lines if (strlen($line) == 0) continue; if (substr($line, 0, 1) == "[") { if (substr($line, -1) != "]") { fclose($fh); return false; } $section = substr($line, 1, -1); continue; } list($name, $value) = explode("=", $line, 2); $name = trim($name); // TODO: comma separated values? $value = trim($value); if (!$this->add($section, $name, $value)) { fclose($fh); return false; } } fclose($fh); return true; } function validate($section, $name) { return $section != "" && $name != ""; } function get($section, $name) { if (!$this->validate($section, $name)) return false; return $this->m_ini[$section][$name]; } function set($section, $name, $value) { if (!$this->validate($section, $name)) return false; $this->m_ini[$section][$name] = $value; return true; } function add($section, $name, $value) { if (!$this->validate($section, $name)) return false; if (isset($this->m_ini[$section][$name])) { if (!is_array($this->m_ini[$section][$name])) { $ovalue = $this->m_ini[$section][$name]; $this->m_ini[$section][$name] = array(); $this->m_ini[$section][$name][] = $ovalue; } $this->m_ini[$section][$name][] = $value; } else { $this->m_ini[$section][$name] = $value; } return true; } function dump($fn) { $fh = fopen($fn, "w"); if (!$fh) return false; foreach (array_keys($this->m_ini) as $section) { fwrite($fh, "[$section]\n"); foreach (array_keys($this->m_ini[$section]) as $name) { if (is_array($this->m_ini[$section][$name])) { foreach ($this->m_ini[$section][$name] as $value) fwrite($fh, "$name=$value\n"); } else { fwrite($fh, "$name=" . $this->m_ini[$section][$name] . "\n"); } } fwrite($fh, "\n"); } fclose($fh); } function sections() { return array_keys($this->m_ini); } function deleteSection($section) { if ($section != "") unset($this->m_ini[$section]); } } /* $ini = new Ini(); $ini->load("data/sip.conf"); var_dump($ini->get("general", "allow")); var_dump($ini->get("general", "bindport")); $ini->dump("sip.conf"); */ ?>
xiaosuo/voipconf
lib/ini.php
PHP
gpl-3.0
2,462
/* * This file is part of CRISIS, an economics simulator. * * Copyright (C) 2015 AITIA International, Inc. * Copyright (C) 2015 John Kieran Phillips * Copyright (C) 2015 Ariel Y. Hoffman * * CRISIS 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. * * CRISIS 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 CRISIS. If not, see <http://www.gnu.org/licenses/>. */ package eu.crisis_economics.abm.dashboard; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Map.Entry; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import org.apache.log4j.Logger; import ai.aitia.meme.gui.Wizard; import ai.aitia.meme.gui.Wizard.Button; import ai.aitia.meme.gui.Wizard.IWizardPage; import aurelienribon.ui.css.Style; import com.jgoodies.forms.builder.DefaultFormBuilder; import com.jgoodies.forms.layout.CellConstraints; import eu.crisis_economics.utilities.Pair; /** * @author Tamás Máhr * */ public class Page_Model implements IWizardPage, IIconsInHeader { private static final String CSS_CLASS_COMMON_PANEL = ".commonPanel"; private static final int DECORATION_IMAGE_WIDTH = 600; private static final String DECORATION_IMAGE = "Decisions.png"; private static final String TITLE = "Model"; private static final String INFO_TEXT = "Please select the model to run!"; private static final int STARTBUTTON_HEIGHT = 50; private static final int STARTBUTTON_WIDTH = 350; private Wizard wizard; private Dashboard dashboard; private Container container; public Page_Model(Wizard wizard, final Dashboard dashboard) { this.wizard = wizard; this.dashboard = dashboard; container = initContainer(); } @Override public String getInfoText(Wizard wizard) { return wizard.getArrowsHeader(INFO_TEXT); } @Override public Icon getIcon() { return new ImageIcon(getClass().getResource("icons/bank.png")); } @Override public Container getPanel() { // ImageIcon buttonIcon = new ImageIcon(getClass().getResource("white-background-gold-button-hi.png")); // buttonIcon = new ImageIcon(buttonIcon.getImage().getScaledInstance(STARTBUTTON_WIDTH, -STARTBUTTON_HEIGHT, java.awt.Image.SCALE_SMOOTH)); // // int buttonHeight = buttonIcon.getIconHeight(); // int buttonWidth = buttonIcon.getIconWidth(); return container; } private Container initContainer() { // BufferedImage image = null; // try { // image = ImageIO.read(getClass().getResource(DECORATION_IMAGE)); // } catch (IOException e) { // throw new IllegalStateException(e); // } // // ImageIcon imageIcon = new ImageIcon(image.getScaledInstance(DECORATION_IMAGE_WIDTH, -1, BufferedImage.SCALE_SMOOTH)); JLabel label = null; label = new JLabel(new ImageIcon(new ImageIcon(getClass().getResource(DECORATION_IMAGE)).getImage().getScaledInstance(DECORATION_IMAGE_WIDTH, -1, Image.SCALE_SMOOTH))); // label = new JLabel(imageIcon); // label.setOpaque(true); final DefaultFormBuilder buttonFormBuilder = FormsUtils.build("p ~ p", ""); for (final Entry<String, Pair<String, Color>> record : Dashboard.availableModels.entrySet()) { final String modelURI = record.getKey(), modelName = record.getValue().getFirst(); final Color buttonColor = record.getValue().getSecond(); JButton button = new JButton( "<html><p align='center'>" + modelName + "</html>"); button.setPreferredSize(new Dimension(STARTBUTTON_WIDTH, STARTBUTTON_HEIGHT)); button.setBackground(buttonColor); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { IModelHandler modelHandler = null; try { modelHandler = dashboard.createModelHandler(modelURI); } catch (ClassNotFoundException e) { Logger log = Logger.getLogger(getClass()); log.error("Could not load the model class!", e); } try { modelHandler.getRecorderAnnotationValue(); } catch (Exception e) { ErrorDialog errorDialog = new ErrorDialog(wizard, "No recorder specified", "The model does not have '@RecorderSource' annotation"); errorDialog.show(); return; } dashboard.setTitle(modelName.substring(modelName.lastIndexOf('.') + 1)); wizard.gotoPage(1); } }); } }); buttonFormBuilder.append(button); } final JButton loadButton = new JButton("<html><p align='center'>Load model configuration..." + "</html>"); loadButton.setPreferredSize(new Dimension(STARTBUTTON_WIDTH, STARTBUTTON_HEIGHT)); loadButton.setBackground(new Color(60, 193, 250)); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent _) { dashboard.loadConfiguration(); } }); buttonFormBuilder.append(loadButton); JPanel buttonPanel = buttonFormBuilder.getPanel(); Style.registerCssClasses(buttonPanel, CSS_CLASS_COMMON_PANEL); JPanel panel = FormsUtils.build("p ~ f:p:g", "01 f:p:g", label, buttonPanel, CellConstraints.CENTER).getPanel(); // panel.setBackground(Color.WHITE); Style.registerCssClasses(panel, CSS_CLASS_COMMON_PANEL); final JScrollPane pageScrollPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); pageScrollPane.setBorder(null); pageScrollPane.setViewportBorder(null); pageScrollPane.setViewportView(panel); return pageScrollPane; } @Override public boolean isEnabled(Button button) { switch (button){ case BACK: return false; case NEXT: return false; case CANCEL: // this is the charts page return true; case FINISH: return false; case CUSTOM: return false; } return false; } @Override public boolean onButtonPress(Button button) { return true; } @Override public void onPageChange(boolean show) { if (show){ dashboard.getSaveConfigMenuItem().setEnabled(false); dashboard.setTitle(null); } else { IModelHandler modelHandler = dashboard.getModelHandler(); if (modelHandler != null){ dashboard.setTitle(modelHandler.getModelClassSimpleName()); } } } @Override public String getTitle() { return TITLE; } }
crisis-economics/CRISIS
CRISIS/src/eu/crisis_economics/abm/dashboard/Page_Model.java
Java
gpl-3.0
7,152
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package SQL; import java.util.ArrayList; /** * * @author adam279 */ public interface CustomerDAO { public Customer getCustomer(int id); public ArrayList<Customer> getCustomers(); public void addCustomer(Customer customer); public void deleteCustomer(int id); public void updateCustomer(Customer customer); }
mda747/dtu_elec2_prog2_semester_project
Serial/src/SQL/CustomerDAO.java
Java
gpl-3.0
529
//------------------------------------------------------------------------------ // // This file is part of AnandamideEditor // // copyright: (c) 2010 - 2016 // authors: Alexey Egorov (FadeToBlack aka EvilSpirit) // Zakhar Shelkovnikov // Georgiy Kostarev // // mailto: anandamide@mail.ru // anandamide.script@gmail.com // // AnandamideEditor 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. // // AnandamideEditor 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 AnandamideEditor. If not, see <http://www.gnu.org/licenses/>. // //------------------------------------------------------------------------------ #include "AnandamideWorkspaceTree.h" #include "MainWindow.h" #include "Anandamide.h" #include "AnandamideLibrary.h" #include "AnandamideViewport.h" #include "XmlSettings.h" #include "AnandamideViewport.h" #include "AnandamideLibraryWidget.h" #include <QFileInfo> #include <QDir> //------------------------------------------------------------------------------ // // TreeItemWorkspace // //------------------------------------------------------------------------------ void TreeItemWorkspace::setChanged(bool changed) { changeFlag = changed; QString text = "Default workspace"; if(fileName != QString()) { text = QFileInfo(fileName).baseName(); } if(changeFlag) text.append('*'); setText(text.toLocal8Bit().constData()); } TreeItemWorkspace::TreeItemWorkspace(QTreeWidget *parent, MainWindow *main_window) : TreeItemBase(parent, main_window) { setIcon(0, QIcon(":/icons/folder2.png")); setExpanded(true); setChanged(false); } bool TreeItemWorkspace::addScriptItem(Anandamide::Script *script, const QString& fileName, int tabIndex, EditorWidgetsCollection *collection) { if(getScriptWorkspaceIndex(script) >= 0) return false; clearSelection(); TreeItemDepProject* project = new TreeItemDepProject(script, fileName, tabIndex, this); project->setCollection(collection); project->setSelected(true); setChanged(true); return true; } bool TreeItemWorkspace::removeScriptItem(Anandamide::Script *script) { int idx = getScriptWorkspaceIndex(script); if(idx < 0) return false; QTreeWidgetItem* child = this->child(idx); TreeItemDepProject* project = dynamic_cast<TreeItemDepProject*>(child); if(project) { QList<int> tabs = project->getChildsTabs(); qSort(tabs); while(tabs.size()) main_window->on_tabWidgetViewports_tabCloseRequested(tabs.takeLast()); } this->removeChild(child); delete child; setChanged(true); return true; } bool TreeItemWorkspace::removeScriptProjectByIndex(int tabIndex) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(proj == NULL) continue; if(proj->getTabIndex() == tabIndex) { QTreeWidgetItem* child = this->child(i); this->removeChild(child); delete child; setChanged(true); return true; } } return false; } int TreeItemWorkspace::getScriptWorkspaceIndex(Anandamide::Script *script) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(proj == NULL) continue; if(proj->getScript() == script /*|| Anandamide::Str(proj->script->getName()) == Anandamide::Str(script->getName())*/) return i; } return -1; } bool TreeItemWorkspace::updateProject(Anandamide::Script *script) { // int idx = getScriptWorkspaceIndex(script); // if(idx < 0) return false; // TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(idx)); // if(proj == NULL) return false; // proj->updateChildren(); // return true; bool res = false; for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(proj == NULL) continue; if(proj->updateProject(script)) res = true; } return res; } TreeItemDepProject *TreeItemWorkspace::getScriptProject(Anandamide::Script *script) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(proj == NULL) continue; TreeItemDepProject* res = proj->getScriptProject(script); if(res != NULL) return res; } return NULL; } TreeItemDepProject *TreeItemWorkspace::getTabIndexProject(int tabIndex) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(proj == NULL) continue; TreeItemDepProject* res = proj->getTabIndexProject(tabIndex); if(res != NULL) return res; } return NULL; } TreeItemDepProject *TreeItemWorkspace::getProjectByFilename(const QString &filename) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(proj == NULL) continue; if(filename == proj->info.fileName) return proj; } return NULL; } void TreeItemWorkspace::updateChildren() { for(int i = 0; i < this->childCount(); ++i) { TreeItemBase* item = dynamic_cast<TreeItemBase*>(this->child(i)); if(item == NULL) continue; item->updateChildren(); } } EditorWidgetsCollection *TreeItemWorkspace::getCollection(int tabIndex) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; EditorWidgetsCollection* res = child->getCollection(tabIndex); if(res != NULL) return res; } return NULL; } Anandamide::Script *TreeItemWorkspace::getScript(int tabIndex) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; Anandamide::Script* res = child->getScript(tabIndex); if(res != NULL) return res; } return NULL; } void TreeItemWorkspace::selectByTabIndex(int tabIndex) { clearSelection(); for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; if(child->selectByTabIndex(tabIndex)) return; } } void TreeItemWorkspace::tabMoved(int from, int to) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->tabMoved(from, to); } } void TreeItemWorkspace::resetTabIndex(int tabIndex) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->resetTabIndex(tabIndex); } } QString TreeItemWorkspace::getFileName(int tabIndex) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; QString res = child->getFileName(tabIndex); if(res != QString()) return res; } return QString(); } bool TreeItemWorkspace::setFileName(const QString &filename, int tabIndex) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; if(child->setFileName(filename, tabIndex)) return true; } return false; } void TreeItemWorkspace::setShiftOnWheel(bool shift) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->setShiftOnWheel(shift); } } void TreeItemWorkspace::clearSelection() { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->setSelected(false); } } bool TreeItemWorkspace::saveWorkspace() { if(fileName == QString()) return false; return saveWorkspace(fileName); } bool TreeItemWorkspace::saveWorkspace(const QString &filename) { if(filename == QString()) return false; CXml_Settings sets; sets.beginGroup("WorkSpace"); sets.beginGroup("Scripts"); int cntr = 0; for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; sets.beginGroup(QString("Script_%1").arg(cntr)); sets.setValue("filename", QFileInfo(filename).absoluteDir().relativeFilePath(child->info.fileName)); sets.endGroup(); child->setSelected(false); cntr++; } sets.endGroup(); sets.setValue("ScriptsCount", cntr); sets.endGroup(); QFile file( filename ); if ( !file.open(QIODevice::WriteOnly) ) return false; sets.saveToIO(&file); file.close(); fileName = filename; setChanged(false); return true; } bool TreeItemWorkspace::loadWorkspace(const QString &filename) { QFile file( filename ); if ( !file.open(QIODevice::ReadOnly) ) return false; CXml_Settings sets; if(!sets.loadFromIO(&file)) { file.close(); return false; } file.close(); main_window->closeAllTabs(true, -1); this->clearChildren(); sets.beginGroup("WorkSpace"); int n = sets.value("ScriptsCount").toInt(); sets.beginGroup("Scripts"); for(int i = 0; i < n; ++i) { sets.beginGroup(QString("Script_%1").arg(i)); QString fn = sets.value("filename").toString(); sets.endGroup(); if(fn != QString()) { fn = QFileInfo(filename).absoluteDir().absoluteFilePath(fn); Anandamide::Script* scr = main_window->createScript(); EditorWidgetsCollection* coll = new EditorWidgetsCollection(main_window); main_window->currentCollection = coll; coll->createCollection(main_window); coll->viewport->shiftFlag = main_window->getShiftFlag(); main_window->setMessangerView(coll); scr->load(fn.toLocal8Bit().constData()); if(scr->getLogicsCount() <= 0) { scr->destroy(); continue; } // main_window->createTestLibraryForScript(scr); addScriptItem(scr, fn, -1, coll); } } sets.endGroup(); sets.endGroup(); fileName = filename; setChanged(false); selectByTabIndex(-1); return true; } bool TreeItemWorkspace::isWorkspaceChanged() { return changeFlag; } QTreeWidgetItem *TreeItemWorkspace::getLibraryItem(const QString &libraryName) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; QTreeWidgetItem* item = child->getLibraryItem(libraryName, main_window->currentCollection); if(item != NULL) return item; } return NULL; } void TreeItemWorkspace::onStopExecuting() { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->onStopExecuting(); } } //------------------------------------------------------------------------------ // // TreeItemDepProject // //------------------------------------------------------------------------------ void TreeItemDepProject::clearCache() { while(cache.size()) delete cache.takeFirst(); } int TreeItemDepProject::getCacheIndex(Anandamide::Script *script) { for(int i = 0; i < cache.size(); ++i) if(cache[i]->script == script) return i; return -1; } void TreeItemDepProject::saveToCache() { clearCache(); for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->saveToCache(); cache.append(new DepProjectInfo()); cache.last()->script = child->info.script; cache.last()->fileName = child->info.fileName; cache.last()->tabIndex = child->info.tabIndex; foreach (DepProjectInfo* cc, child->cache) { cache.last()->childInfo.append(new DepProjectInfo(cc)); } cache.last()->collection = child->getCollection(); cache.last()->selected = child->info.selected; } } QList<int> TreeItemDepProject::restoreFromCache() { QSet<int> unused; QList<int> tabIndexes; for(int i = 0; i < cache.size(); ++i) unused.insert(i); for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; int idx = getCacheIndex(child->info.script); if(idx < 0) continue; unused.remove(idx); child->info.fileName = cache[idx]->fileName; child->info.tabIndex = cache[idx]->tabIndex; child->clearCache(); foreach (DepProjectInfo* cc, cache[idx]->childInfo) { child->cache.append(new DepProjectInfo(cc)); } child->setCollection(cache[idx]->collection); child->setSelected(cache[idx]->selected); child->restoreFromCache(); } QList<int> unusedList = unused.toList(); foreach (int i, unusedList) { if(cache[i]->tabIndex >= 0) tabIndexes.append(cache[i]->tabIndex); tabIndexes.append( cache[i]->getChildsTabs() ); } clearCache(); return tabIndexes; } TreeItemDepProject::TreeItemDepProject(Anandamide::Script *script, const QString& fileName, int tabIndex, TreeItemBase *parent) : TreeItemBase(parent) { info.script = script; info.fileName = fileName; info.tabIndex = tabIndex; setIcon(0, QIcon(isTopLevelProject() ? ":/icons/blocks.png" : ":/icons/library.png")); setExpanded(true); updateChildren(); } TreeItemDepProject::~TreeItemDepProject() { clearCache(); } bool TreeItemDepProject::isTopLevelProject() { TreeItemDepProject* prg = dynamic_cast<TreeItemDepProject*>(this->parent()); return prg == NULL; } void TreeItemDepProject::updateChildren() { if(Anandamide::Str(info.script->getName()) == Anandamide::Str()) setText("Unnamed Script"); else setText(info.script->getName()); saveToCache(); clearChildren(); for(int i = 0; i < info.script->getLibraries()->getLibrariesCount(); ++i) { Anandamide::ScriptLibrary* script_lib = dynamic_cast<Anandamide::ScriptLibrary*>(const_cast<Anandamide::Library*>(info.script->getLibraries()->getLibrary(i))); if(script_lib == NULL) continue; if(isScriptUsed(script_lib->getScript())) continue; /*TreeItemDepProject *item = */new TreeItemDepProject(script_lib->getScript(), QString::fromLocal8Bit(script_lib->getFileName()), -1, this); } QList<int> tabIndexes = restoreFromCache(); qSort(tabIndexes); while(tabIndexes.size()) { main_window->on_tabWidgetViewports_tabCloseRequested(tabIndexes.takeLast()); } } bool TreeItemDepProject::isScriptUsed(Anandamide::Script *script) { if(info.script == script/* || Anandamide::Str(info.script->getName()) == Anandamide::Str(script->getName())*/) return true; TreeItemDepProject* parent = dynamic_cast<TreeItemDepProject*>(this->parent()); if(parent == NULL) return false; return parent->isScriptUsed(script); } Anandamide::Script *TreeItemDepProject::getScript() {return info.script;} Anandamide::Script *TreeItemDepProject::getScript(int tabIndex) { if(info.tabIndex == tabIndex && tabIndex >= 0) return info.script; for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; Anandamide::Script* res = child->getScript(tabIndex); if(res != NULL) return res; } return NULL; } int TreeItemDepProject::getScriptIndex(Anandamide::Script *script) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; if(script = child->getScript()) return i; } return -1; } bool TreeItemDepProject::updateProject(Anandamide::Script *script) { bool res = false; if(script == info.script) { res = true; updateChildren(); } for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; if(child->updateProject(script)) res = true; } return res; } EditorWidgetsCollection *TreeItemDepProject::getCollection() {return info.collection;} EditorWidgetsCollection *TreeItemDepProject::getCollection(int tabIndex) { if(info.tabIndex == tabIndex && tabIndex >= 0) return info.collection; for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; EditorWidgetsCollection* res = child->getCollection(tabIndex); if(res != NULL) return res; } return NULL; } void TreeItemDepProject::setCollection(EditorWidgetsCollection *collection) { info.collection = collection; } int TreeItemDepProject::getTabIndex() { return info.tabIndex; } void TreeItemDepProject::setTabIndex(int tabIndex) { info.tabIndex = tabIndex; } void TreeItemDepProject::tabMoved(int from, int to) { if(info.tabIndex == from) info.tabIndex = to; else if(info.tabIndex == to) info.tabIndex = from; for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->tabMoved(from, to); } } void TreeItemDepProject::resetTabIndex(int tabIndex) { if(tabIndex >= 0) { if(info.tabIndex == tabIndex) info.tabIndex = -1; else if(info.tabIndex > tabIndex) info.tabIndex--; } for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->resetTabIndex(tabIndex); } } void TreeItemDepProject::setShiftOnWheel(bool shift) { if(info.collection != NULL) if(info.collection->isCreated()) info.collection->viewport->shiftFlag = shift; for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->setShiftOnWheel(shift); } } void TreeItemDepProject::setSelected(bool selected) { info.selected = selected; QFont f; if(selected) f.setBold(true); this->setFont(0, f); this->setBackground(0, selected ? QBrush(QColor(230, 193, 193)) : QBrush()); for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->setSelected(false); } } bool TreeItemDepProject::selectByTabIndex(int tabIndex) { if(info.tabIndex == tabIndex && tabIndex >= 0) { setSelected(true); return true; } for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; if(child->selectByTabIndex(tabIndex)) return true; } return false; } void TreeItemDepProject::createNewTab() { if(info.collection == NULL) info.collection = new EditorWidgetsCollection(main_window); main_window->currentCollection = info.collection; if(!info.collection->isCreated()) info.collection->createCollection(main_window); info.tabIndex = main_window->getTabsCount(); main_window->addCollection(info.collection, info.script->getName(), isTopLevelProject()); Anandamide::Logic *logic = info.script->getLogic(0); info.collection->editor->setLogic(logic); info.collection->editor->reset(); info.collection->project_tree->clear(); TreeItemScript *script_item = new TreeItemScript(info.collection->project_tree, main_window, info.script); info.collection->project_tree->addTopLevelItem(script_item); script_item->setExpanded(true); info.collection->library_widget->invalidate(); info.collection->viewport->repaint(); } QString TreeItemDepProject::getFileName(int tabIndex) { if(info.tabIndex == tabIndex && tabIndex >= 0) return info.fileName; for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; QString res = child->getFileName(tabIndex); if(res != QString()) return res; } return QString(); } bool TreeItemDepProject::setFileName(const QString &filename, int tabIndex) { if(info.tabIndex == tabIndex && tabIndex >= 0) { info.fileName = filename; return true; } for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; if(child->setFileName(filename, tabIndex)) return true; } return false; } QList<int> TreeItemDepProject::getChildsTabs() { QList<int> res; if(info.tabIndex >= 0) res << info.tabIndex; for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; res << child->getChildsTabs(); } return res; } QTreeWidgetItem *TreeItemDepProject::getLibraryItem(const QString &libraryName, EditorWidgetsCollection *collection) { if(info.collection == collection) { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; if(QString::fromLocal8Bit( child->info.script->getName() ) == libraryName) return child; } } else { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; QTreeWidgetItem* item = child->getLibraryItem(libraryName, collection); if(item != NULL) return item; } } return NULL; } TreeItemDepProject *TreeItemDepProject::getChildByName(const QString &name) { return dynamic_cast<TreeItemDepProject*>(this->getChildByText(name)); } void TreeItemDepProject::onStopExecuting() { for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; child->onStopExecuting(); } } TreeItemDepProject *TreeItemDepProject::getScriptProject(Anandamide::Script *script) { if(info.script == script) return this; for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; TreeItemDepProject* res = child->getScriptProject(script); if(res != NULL) return res; } return NULL; } TreeItemDepProject *TreeItemDepProject::getTabIndexProject(int tabIndex) { if(info.tabIndex == tabIndex && tabIndex >= 0) return this; for(int i = 0; i < this->childCount(); ++i) { TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i)); if(child == NULL) continue; TreeItemDepProject* res = child->getTabIndexProject(tabIndex); if(res != NULL) return res; } return NULL; } //------------------------------------------------------------------------------ // // AnandamideWorkspaceTree // //------------------------------------------------------------------------------ AnandamideWorkspaceTree::AnandamideWorkspaceTree(QWidget *parent) : QTreeWidget(parent) { root = new TreeItemWorkspace(this, main_window); connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), SLOT(onItemDoubleClicked(QTreeWidgetItem*, int))); } bool AnandamideWorkspaceTree::addScriptProject(Anandamide::Script *script, const QString &fileName, int tabIndex, EditorWidgetsCollection *collection) { return root->addScriptItem(script, fileName, tabIndex, collection); } bool AnandamideWorkspaceTree::removeScriptProject(Anandamide::Script *script) { return root->removeScriptItem(script); } bool AnandamideWorkspaceTree::removeScriptProjectByIndex(int tabIndex) { return root->removeScriptProjectByIndex(tabIndex); } bool AnandamideWorkspaceTree::isScriptProject(Anandamide::Script *script) { return root->getScriptWorkspaceIndex(script) >= 0; } bool AnandamideWorkspaceTree::setScriptProject(const QString &fileName) { TreeItemDepProject* project = root->getProjectByFilename(fileName); if(project == NULL) return false; onItemDoubleClicked(project, 0); return true; } bool AnandamideWorkspaceTree::updateProject(Anandamide::Script *script) { return root->updateProject(script); } void AnandamideWorkspaceTree::update() { root->updateChildren(); } EditorWidgetsCollection *AnandamideWorkspaceTree::getCollection(int tabIndex) { return root->getCollection(tabIndex); } Anandamide::Script *AnandamideWorkspaceTree::getScript(int tabIndex) { return root->getScript(tabIndex); } QString AnandamideWorkspaceTree::getFileName(int tabIndex) { return root->getFileName(tabIndex); } bool AnandamideWorkspaceTree::setFileName(const QString &filename, int tabIndex) { return root->setFileName(filename, tabIndex); } void AnandamideWorkspaceTree::newWorkspace() { main_window->closeAllTabs(true, -1); delete root; root = new TreeItemWorkspace(this, main_window); } bool AnandamideWorkspaceTree::saveWorkspace() { return root->saveWorkspace(); } bool AnandamideWorkspaceTree::saveWorkspace(const QString &filename) { return root->saveWorkspace(filename); } bool AnandamideWorkspaceTree::loadWorkspace(const QString &filename) { main_window->setCursorShape(Qt::WaitCursor); bool res = root->loadWorkspace(filename); main_window->setCursorShape(Qt::ArrowCursor); return res; } bool AnandamideWorkspaceTree::isWorkspaceChanged() { return root->isWorkspaceChanged(); } void AnandamideWorkspaceTree::clearChanges() { root->setChanged(false); } bool AnandamideWorkspaceTree::openLibrary(const QString &libraryName) { QTreeWidgetItem* item = root->getLibraryItem(libraryName); if(item == NULL) return false; onItemDoubleClicked(item, 0); return true; } void AnandamideWorkspaceTree::onStopExecuting() { root->clearSelection(); root->onStopExecuting(); } void AnandamideWorkspaceTree::setCurrentScript(QStringList &logicLibList) {/* if(logicLibList.takeLast() != QString()) return; while(logicLibList.size() && project != NULL) { project = project->getChildByName(logicLibList.takeLast()); } onItemDoubleClicked(project, 0); */ } void AnandamideWorkspaceTree::openScriptView(Anandamide::Script *script) { TreeItemDepProject* project = root->getScriptProject(script); if(project == NULL) return; if(project->getTabIndex() >= 0) { main_window->setTabIndex(project->getTabIndex()); } else { project->createNewTab(); } } bool AnandamideWorkspaceTree::isProjectRunning(int tabIndex) { if(tabIndex < 0) return false; TreeItemDepProject* project = root->getTabIndexProject(tabIndex); while(project != NULL) { project = dynamic_cast<TreeItemDepProject*>(project->parent()); } return false; } void AnandamideWorkspaceTree::selectByTabIndex(int tabIndex) { root->selectByTabIndex(tabIndex); } void AnandamideWorkspaceTree::tabMoved(int from, int to) { root->tabMoved(from, to); } void AnandamideWorkspaceTree::resetTabIndex(int tabIndex) { root->resetTabIndex(tabIndex); } void AnandamideWorkspaceTree::setShiftOnWheel(bool shift) { root->setShiftOnWheel(shift); } void AnandamideWorkspaceTree::onItemDoubleClicked(QTreeWidgetItem *tree_item, int column) { Q_UNUSED(column); TreeItemDepProject* project = dynamic_cast<TreeItemDepProject*>(tree_item); if(project == NULL) return; root->clearSelection(); project->setSelected(true); if(project->getTabIndex() >= 0) { main_window->setTabIndex(project->getTabIndex()); } else { project->createNewTab(); } } TreeItemDepProject::DepProjectInfo::DepProjectInfo() { collection = NULL; selected = false; } TreeItemDepProject::DepProjectInfo::DepProjectInfo(TreeItemDepProject::DepProjectInfo *other) { script = other->script; fileName = other->fileName; tabIndex = other->tabIndex; collection = other->collection; selected = other->selected; childCopy(other); } void TreeItemDepProject::DepProjectInfo::clear() { while(childInfo.size()) { delete childInfo.takeFirst(); } } void TreeItemDepProject::DepProjectInfo::childCopy(TreeItemDepProject::DepProjectInfo *other) { clear(); foreach (DepProjectInfo* cc, other->childInfo) { childInfo.append(new DepProjectInfo(cc)); } } QList<int> TreeItemDepProject::DepProjectInfo::getChildsTabs() { QList<int> res; foreach (DepProjectInfo* ci, childInfo) { if(ci->tabIndex >= 0) res.append(ci->tabIndex); res.append( ci->getChildsTabs() ); } return res; }
Evil-Spirit/AnandamideEditor
src/AnandamideWorkspaceTree.cpp
C++
gpl-3.0
29,220
/** Unused, mostly useless, code. */ /// Computes circumcentre and circumradius of a [tetrahedron](@ref Tet). /** NOTE: The tetrahedron's jacobian (2*volume) should be stored in [elem.D](&ref D) beforehand. * The center and radius of the circumsphere are calculated as follows. The circumcenter is * \f[ \mathbf{O} = \frac{|\mathbf{a}^2(\mathbf{b}\times \mathbf{c}) + \mathbf{b}^2(\mathbf{c}\times \mathbf{a}) + \mathbf{c}^2(\mathbf{a}\times \mathbf{b})|}{12 V} \f] * and the radius \f$ R = |\mathbf{O}|\f$. */ void Delaunay3d::compute_circumsphere2(Tet& elem) { vector<double> a(ndim), b(ndim), c(ndim), n1(ndim), n2(ndim), n3(ndim), fin(ndim); for(int idim = 0; idim < ndim; idim++) { a[idim] = nodes[elem.p[0]][idim]-nodes[elem.p[3]][idim]; b[idim] = nodes[elem.p[1]][idim]-nodes[elem.p[3]][idim]; c[idim] = nodes[elem.p[2]][idim]-nodes[elem.p[3]][idim]; } cross_product3(n1,b,c); cross_product3(n2,c,a); cross_product3(n3,a,b); for(int idim = 0; idim < ndim; idim++) { fin[idim] = dot(a,a)*n1[idim] + dot(b,b)*n2[idim] + dot(c,c)*n3[idim]; fin[idim] /= 2.0*elem.D; elem.centre[idim] = fin[idim]; } elem.radius = l2norm(fin); cout << "Circumsphere data: centre " << elem.centre[0] << "," << elem.centre[1] << "," << elem.centre[2] << ", radius " << elem.radius << ", elem jacobian " << elem.D << endl; } /// Computes circumcentre and circumradius of a [tetrahedron](@ref Tet). /** NOTE: The tetrahedron's jacobian (6*volume) should be stored in [elem.D](@ref elem::D) beforehand. * Reference: [Weisstein, Eric W. "Circumsphere." From MathWorld--A Wolfram Web Resource.](@ref http://mathworld.wolfram.com/Circumsphere.html) * \note Probably wrong! */ void Delaunay3d::compute_circumsphere3(Tet& elem) { Matrix<double> dx(nnode,nnode), dy(nnode,nnode), dz(nnode,nnode), cc(nnode,nnode); double a = elem.D, c, d_x, d_y, d_z; #if DEBUGW==1 if(fabs(a) < ZERO_TOL) cout << "Delaunay3d: compute_circumcircle(): ! Jacobian of the element is zero!!" << endl; #endif dx(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2]; dx(0,1) = nodes[elem.p[0]][1]; dx(0,2) = nodes[elem.p[0]][2]; dx(0,3) = 1; dx(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2]; dx(1,1) = nodes[elem.p[1]][1]; dx(1,2) = nodes[elem.p[1]][2]; dx(1,3) = 1; dx(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2]; dx(2,1) = nodes[elem.p[2]][1]; dx(2,2) = nodes[elem.p[2]][2]; dx(2,3) = 1; dx(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2]; dx(3,1) = nodes[elem.p[3]][1]; dx(3,2) = nodes[elem.p[3]][2]; dx(3,3) = 1; dy(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2]; dy(0,1) = nodes[elem.p[0]][0]; dy(0,2) = nodes[elem.p[0]][2]; dy(0,3) = 1; dy(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2]; dy(1,1) = nodes[elem.p[1]][0]; dy(1,2) = nodes[elem.p[1]][2]; dy(1,3) = 1; dy(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2]; dy(2,1) = nodes[elem.p[2]][0]; dy(2,2) = nodes[elem.p[2]][2]; dy(2,3) = 1; dy(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2]; dy(3,1) = nodes[elem.p[3]][0]; dy(3,2) = nodes[elem.p[3]][2]; dy(3,3) = 1; dz(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2]; dz(0,1) = nodes[elem.p[0]][0]; dz(0,2) = nodes[elem.p[0]][1]; dz(0,3) = 1; dz(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2]; dz(1,1) = nodes[elem.p[1]][0]; dz(1,2) = nodes[elem.p[1]][1]; dz(1,3) = 1; dz(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2]; dz(2,1) = nodes[elem.p[2]][0]; dz(2,2) = nodes[elem.p[2]][1]; dz(2,3) = 1; dz(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2]; dz(3,1) = nodes[elem.p[3]][0]; dz(3,2) = nodes[elem.p[3]][1]; dz(3,3) = 1; cc(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2]; cc(0,1) = nodes[elem.p[0]][0]; cc(0,2) = nodes[elem.p[0]][1]; cc(0,3) = nodes[elem.p[0]][2]; cc(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2]; cc(1,1) = nodes[elem.p[1]][0]; cc(1,2) = nodes[elem.p[1]][1]; cc(1,3) = nodes[elem.p[1]][2]; cc(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2]; cc(2,1) = nodes[elem.p[2]][0]; cc(2,2) = nodes[elem.p[2]][1]; cc(2,3) = nodes[elem.p[2]][2]; cc(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2]; cc(3,1) = nodes[elem.p[3]][0]; cc(3,2) = nodes[elem.p[3]][1]; cc(3,3) = nodes[elem.p[3]][2]; d_x = determinant(dx); d_y = determinant(dy); d_z = determinant(dz); c = determinant(cc); elem.centre[0] = d_x/a*0.5; elem.centre[1] = d_y/a*0.5; elem.centre[2] = d_z/a*0.5; elem.radius = sqrt(d_x*d_x + d_y*d_y + d_z*d_z - 4.0*a*c)/2*fabs(a); cout << "Circumcircle data: centre " << elem.centre[0] << "," << elem.centre[1] << "," << elem.centre[2] << ", radius " << elem.radius << ", elem jacobian " << a << endl; } /// Calculates the jacobian of the tetrahedron formed by point r and a face of tetrahedron ielem. /** The face is selected by i between 0 and 3. Face i is the face opposite to local node i of the tetrahedron. */ double Delaunay3d::det4(int ielem, int i, const vector<double>& r) const { #if DEBUGW==1 if(i > 3) { std::cout << "Delaunay3D: det4(): ! Second argument is greater than 3!" << std::endl; return 0; } #endif Tet elem = elems[ielem]; double ret = 0; switch(i) { case(0): ret = r[0] * ( nodes[elem.p[1]][1]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) + nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] ); ret -= r[1] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] ); ret += r[2] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) -nodes[elem.p[1]][1]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] ); ret -= nodes[elem.p[1]][0]*( nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] ) -nodes[elem.p[1]][1]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] ) +nodes[elem.p[1]][2]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] ); break; case(1): ret = nodes[elem.p[0]][0] * ( r[1]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -r[2]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) + nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] ); ret -= nodes[elem.p[0]][1] * (r[0]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -r[2]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] ); ret += nodes[elem.p[0]][2] * (r[0]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) -r[1]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] ); ret -= r[0]*( nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] ) -r[1]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] ) +r[2]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] ); break; case(2): ret = nodes[elem.p[0]][0] * ( nodes[elem.p[1]][1]*(r[2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(r[1]-nodes[elem.p[3]][1]) + r[1]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][1] ); ret -= nodes[elem.p[0]][1] * (nodes[elem.p[1]][0]*(r[2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(r[0]-nodes[elem.p[3]][0]) + r[0]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][0] ); ret += nodes[elem.p[0]][2] * (nodes[elem.p[1]][0]*(r[1]-nodes[elem.p[3]][1]) -nodes[elem.p[1]][1]*(r[0]-nodes[elem.p[3]][0]) + r[0]*nodes[elem.p[3]][1] - r[1]*nodes[elem.p[3]][0] ); ret -= nodes[elem.p[1]][0]*( r[1]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][1] ) -nodes[elem.p[1]][1]*( r[0]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][0] ) +nodes[elem.p[1]][2]*( r[0]*nodes[elem.p[3]][1] - r[1]*nodes[elem.p[3]][0] ); break; case(3): ret = nodes[elem.p[0]][0] * ( nodes[elem.p[1]][1]*(nodes[elem.p[2]][2]-r[2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][1]-r[1]) + nodes[elem.p[2]][1]*r[2] - nodes[elem.p[2]][2]*r[1] ); ret -= nodes[elem.p[0]][1] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][2]-r[2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][0]-r[0]) + nodes[elem.p[2]][0]*r[2] - nodes[elem.p[2]][2]*r[0] ); ret += nodes[elem.p[0]][2] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][1]-r[1]) -nodes[elem.p[1]][1]*(nodes[elem.p[2]][0]-r[0]) + nodes[elem.p[2]][0]*r[1] - nodes[elem.p[2]][1]*r[0] ); ret -= nodes[elem.p[1]][0] *( nodes[elem.p[2]][1]*r[2] - nodes[elem.p[2]][2]*r[1] ) -nodes[elem.p[1]][1]*( nodes[elem.p[2]][0]*r[2] - nodes[elem.p[2]][2]*r[0] ) + nodes[elem.p[1]][2]*( nodes[elem.p[2]][0]*r[1] - nodes[elem.p[2]][1]*r[0] ); break; default: cout << "Delaunay3D: det4(): ! Invalid argument i! Should be between 0 and 3 inclusive." << endl; ret = -1; } return ret; }
Slaedr/amovemesh
src/unused/extra_code.hpp
C++
gpl-3.0
10,133
//package org.aksw.autosparql.tbsl.algorithm.util; // //import java.util.Comparator; //import java.util.HashMap; //import java.util.Map; // //import org.dllearner.common.index.IndexResultItem; // //public class IndexResultItemComparator implements Comparator<IndexResultItem>{ // private String s; // private Map<String, Double> cache; // // public IndexResultItemComparator(String s) { // this.s = s; // cache = new HashMap<String, Double>(); // } // // @Override // public int compare(IndexResultItem item1, IndexResultItem item2) { // // double sim1 = 0; // if(cache.containsKey(item1.getLabel())){ // sim1 = cache.get(item1.getLabel()); // } else { // sim1 = Similarity.getSimilarity(s, item1.getLabel()); // cache.put(item1.getLabel(), sim1); // } // double sim2 = 0; // if(cache.containsKey(item2.getLabel())){ // sim2 = cache.get(item2.getLabel()); // } else { // sim2 = Similarity.getSimilarity(s, item2.getLabel()); // cache.put(item2.getLabel(), sim2); // } // // if(sim1 < sim2){ // return 1; // } else if(sim1 > sim2){ // return -1; // } else { // int val = item1.getLabel().compareTo(item2.getLabel()); // if(val == 0){ // return item1.getUri().compareTo(item2.getUri()); // } // return val; // } // } //}
AKSW/AutoSPARQL
algorithm-tbsl/src/main/java/org/aksw/autosparql/tbsl/algorithm/util/IndexResultItemComparator.java
Java
gpl-3.0
1,260
import {Logger, getLogger} from '../utils/logger'; import fs = require('fs'); import {Observable} from 'rxjs/Observable'; import {Subscriber} from 'rxjs/Subscriber'; import {Direction, AbstractAIN, AbstractGPIO, AbstractLED} from './abstract-ports'; export class GPIO extends AbstractGPIO { public static readonly VALID_IDS: number[] = [2, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 20, 26, 27, 44, 45, 46, 47, 48, 49, 60, 61, 65, 66, 69, 115]; private static readonly logger: Logger = getLogger('GPIO'); private static readonly ROOT = '/sys/class/gpio/'; private static readonly UNEXPORT = GPIO.ROOT + 'unexport'; private static readonly EXPORT = GPIO.ROOT + 'export'; private static readonly BASE_NAME = 'gpio'; private outputObs: Observable<boolean> = null; private intervalId: any = null; private prevValue: number = 48; // ascii 0 constructor(protected id: number, private direction: Direction) { super(id); if (GPIO.VALID_IDS.filter(vid => vid != id).length === 0) { throw new Error(`GPIO id ${id} is not valid!`); } let portName: string = this.getName(); // activate port if not yet done if (!fs.existsSync(portName)) { let cmd: string = `${GPIO.EXPORT}`; fs.writeFileSync(cmd, id); GPIO.logger.debug(`enable port id ${id}`); } // set port direction let cmd = `${portName}/direction`; fs.writeFileSync(cmd, this.directionVerb()); GPIO.logger.debug(`port ${id} direction ${this.directionVerb()}`); // if output then set mode to edge if (this.direction === Direction.INPUT) { cmd = `${portName}/edge`; fs.writeFileSync(cmd, 'none'); GPIO.logger.debug(`port ${id} edge on both`); } else { this.setState(false); } } getName(): string { return `${GPIO.ROOT}${GPIO.BASE_NAME}${this.id}`; } directionVerb(): string { switch (this.direction) { case Direction.INPUT: return 'in'; case Direction.OUTPUT: return 'out'; default: return null; } } setState(on: boolean): void { if (this.direction === Direction.OUTPUT) { let cmd: string = `${this.getName()}/value`; let state: number = on ? 0 : 1; // on = 0, off = 1, i.e. inverted GPIO.logger.debug(`setState ${cmd} to ${state}`); if (fs.existsSync(cmd)) { fs.writeFileSync(cmd, state); GPIO.logger.debug('done'); } else { GPIO.logger.error(`setState failed: ${cmd} does not exit`); } } else { GPIO.logger.error(`setState ${this.getName()} not allowed for input pin`); } } watch(): Observable<boolean> { if (this.direction === Direction.INPUT) { if (this.outputObs === null) { this.outputObs = Observable.create((subscriber: Subscriber<boolean>) => { let cmd: string = `${this.getName()}/value`; GPIO.logger.debug(`watch ${cmd}`); if (fs.existsSync(cmd)) { this.read(subscriber, cmd); } else { subscriber.error(`watch failed: ${cmd} does not exist`); subscriber.complete(); } }); } return this.outputObs; } else { GPIO.logger.error(`watch ${this.getName()} not allowed for output pin`); } } private read(subscriber: Subscriber<boolean>, cmd: string, value?: boolean): void { this.intervalId = setInterval(() => { let data: Buffer = fs.readFileSync(cmd); if (data) { let val: number = data.readUInt8(0); // ascii value of 0 = 48, of 1 = 49 if (val !== this.prevValue) { GPIO.logger.debug(`${this.getName()} input is ${val !== 48}`); subscriber.next(val !== 48); this.prevValue = val; } } else { let errStr: string = `read ${cmd} failed with no data`; GPIO.logger.error(errStr); subscriber.error(errStr); subscriber.complete(); clearInterval(this.intervalId); } }, 100); } reset(): void { GPIO.logger.debug(`reset ${this.getName()} --> ${GPIO.UNEXPORT} for gpio${this.id}`); if (fs.existsSync(this.getName())) { if (this.intervalId !== null) { clearInterval(this.intervalId); } fs.writeFileSync(GPIO.UNEXPORT, this.id); GPIO.logger.debug('done'); } else { GPIO.logger.error(`Reset failed: ${this.getName()} does not exit`); } } toString(): string { let portName: string = `${this.getName()}`; if (fs.existsSync(portName)) { let direction = fs.readFileSync(`${portName}}/direction`); let edge = fs.readFileSync(`${portName}}/edge`); let str = `${portName}: direction ${direction} [${this.directionVerb()}]`; if (this.direction === Direction.OUTPUT) { str += `, edge on ${edge} [none]`; } return str; } else { return `Unexpected: ${portName} does not exist!`; } } } export class AIN extends AbstractAIN { public static readonly VALID_IDS: number[] = [0, 1, 2, 3, 4, 5, 6]; public static readonly MAX_VALUE: number = 4096; private static readonly logger: Logger = getLogger('AIN'); private static readonly ROOT = '/sys/bus/iio/devices/iio:device0/'; private static readonly BASE_NAME = 'in_voltage'; private static readonly POST_FIX = '_raw'; private outputObs: Observable<number> = null; private intervalId: any = null; private doPoll: boolean = true; constructor(protected id: number) { super(id); if (AIN.VALID_IDS.filter(vid => vid != id).length === 0) { throw new Error(`AIN id ${id} is not valid!`); } } getName(): string { return `${AIN.ROOT}${AIN.BASE_NAME}${this.id}${AIN.POST_FIX}`; } poll(intervalSeconds: number): Observable<number> { if (this.outputObs === null) { this.outputObs = Observable.create((subscriber: Subscriber<number>) => { AIN.logger.debug(`poll ${this.getName()} every ${intervalSeconds} second(s)`); if (fs.existsSync(this.getName())) { this.readInitialValue(subscriber); this.doPoll = true; this.intervalId = setInterval(() => { if (this.doPoll) { this.subscribeReadValue(subscriber); } else { subscriber.complete(); } }, intervalSeconds * 1000); } else { subscriber.error(`poll failed: ${this.getName()} does not exist`); subscriber.complete(); } }); } return this.outputObs; } private readInitialValue(subscriber: Subscriber<number>) { this.subscribeReadValue(subscriber); } private subscribeReadValue(subscriber: Subscriber<number>) { fs.readFile(this.getName(), (err, data) => { if (err) { subscriber.error(`read ${this.getName()} failed with ${err}`); } else { let val: number = Number(data.toString()); AIN.logger.debug(`${this.getName()}: value ${val}`); subscriber.next(val); } }); } stopPolling(): void { AIN.logger.debug(`stopPolling ${this.getName()}`); clearInterval(this.intervalId); this.doPoll = false; } } export class LED extends AbstractLED { public static readonly VALID_IDS: number[] = [0, 1, 2, 3]; private static readonly logger: Logger = getLogger('SimulatedGPIO'); private static readonly ROOT = '/sys/class/leds/'; private static readonly BASE_NAME = 'beaglebone:green:usr'; constructor(protected id: number) { super(id); if (LED.VALID_IDS.filter(vid => vid != id).length === 0) { throw new Error(`LED id ${id} is not valid!`); } this.setState(0); } getName(): string { return `${LED.ROOT}${LED.BASE_NAME}${this.id}`; } setState(state: number): void { let cmd: string = `${this.getName()}/brightness`; LED.logger.debug(`setState ${cmd} to ${state}`); if (fs.existsSync(cmd)) { fs.writeFileSync(cmd, state); } else { LED.logger.error(`setState ${state} failed: ${cmd} does not exist`); } } blink(delayOn: number, delayOff: number): void { let cmdTimer: string = `${this.getName()}/trigger`; let cmdOn: string = `${this.getName()}/delay_on`; let cmdOff: string = `${this.getName()}/delay_off`; LED.logger.debug(`blink ${cmdTimer} with ${delayOn}-${delayOff}`); if (fs.existsSync(cmdTimer)) { fs.writeFileSync(cmdTimer, 'timer'); fs.writeFileSync(cmdOn, delayOn); fs.writeFileSync(cmdOff, delayOff); } else { LED.logger.error(`blink ${delayOn}-${delayOff} failed: ${cmdTimer} does not exist`); } } heartbeat(): void { let cmd: string = `${this.getName()}/trigger`; let value: string = 'heartbeat'; LED.logger.debug(`heartbeat ${cmd} to ${value}`); if (fs.existsSync(cmd)) { fs.writeFileSync(cmd, value); } else { LED.logger.error(`heatbeat ${value} failed: ${cmd} does not exist`); } } }
dleuenbe/project2
server/hardware/beaglebone-ports.ts
TypeScript
gpl-3.0
8,864
//============================================================================ // Name : closure-test.cc // Author : ronaflx // Version : 1.0 // Copyright : GNU GPL // Description : //============================================================================ #include <iostream> using namespace std; #include <google/protobuf/stubs/common.h> #include <gtest/gtest.h> #include "person.pb.h" using google::protobuf::NewCallback; using google::protobuf::Closure; class ClosureTestFixture : public ::testing::Test { protected: string name; string email; int id; vector<string> phonenumber; void SetUp() { name = "ronaflx"; id = 195936; email = "900831flx@gmail.com"; phonenumber.push_back("18945918324"); phonenumber.push_back("13354599597"); } }; // all call function should use void as return value void PrintInfo() { EXPECT_TRUE(true); return; } // callback function can only call once // it will delete it self after call. TEST_F(ClosureTestFixture, SimpleCallBack) { Closure* closure = NewCallback(&PrintInfo); closure->Run(); // DO NOT call it again. // closure->Run(); EXPECT_EQ(name, "ronaflx"); EXPECT_EQ(email, "900831flx@gmail.com"); // DO NOT delete it again. // delete closure; } // for this kind callback funtion, we // use pointer instead of reference. void PrintInfo(string* name, string* email) { *name = "flx.rona"; *email = "ronaflx@google.com"; } // callback function can also have args. // but protobuf only provide 5 args besides // funcion itself. TEST_F(ClosureTestFixture, ArguementCallBack) { Closure* closure = NewCallback(&PrintInfo, &name, &email); closure->Run(); EXPECT_EQ(name, "flx.rona"); EXPECT_EQ(email, "ronaflx@google.com"); } // use const type pointer. void ConstPrintInfo(const string* name, const string* email) { EXPECT_EQ(*name, "ronaflx"); EXPECT_EQ(*email, "900831flx@gmail.com"); } // for a non-const value, if we want to pass it // to const type we use const_cast operator. TEST_F(ClosureTestFixture, ConstArguement) { Closure* closure = NewCallback(&ConstPrintInfo, const_cast<const string*>(&name), const_cast<const string*>(&email)); closure->Run(); EXPECT_EQ(name, "ronaflx"); EXPECT_EQ(email, "900831flx@gmail.com"); } template<class T> void SimpleFunction(T* instance) { EXPECT_TRUE(true); } // fo template function, use function<type> as argument. TEST_F(ClosureTestFixture, TemplateCallBack) { Closure* closure = NewCallback(&SimpleFunction<string>, &name); closure->Run(); EXPECT_EQ(name, "ronaflx"); } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
ronaflx/opensource-tutorial
protobuf/closure-test.cc
C++
gpl-3.0
2,640
/* Copyright (C) 2003-2013 Runtime Revolution Ltd. This file is part of LiveCode. LiveCode is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License v3 as published by the Free Software Foundation. LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */ #include <foundation.h> #include <foundation-auto.h> #include "foundation-private.h" //////////////////////////////////////////////////////////////////////////////// // This method ensures there is 'count' bytes of empty space starting at 'at' // in 'r_data'. It returns false if allocation fails. static bool __MCDataExpandAt(MCDataRef r_data, uindex_t at, uindex_t count); // This method removes 'count' bytes from byte sequence starting at 'at'. static void __MCDataShrinkAt(MCDataRef r_data, uindex_t at, uindex_t count); // This method clamps the given range to the valid limits for the byte sequence. static void __MCDataClampRange(MCDataRef r_data, MCRange& x_range); static bool __MCDataMakeImmutable(__MCData *self); //////////////////////////////////////////////////////////////////////////////// bool MCDataCreateWithBytes(const byte_t *p_bytes, uindex_t p_byte_count, MCDataRef& r_data) { bool t_success; t_success = true; __MCData *self; self = nil; if (t_success) t_success = __MCValueCreate(kMCValueTypeCodeData, self); if (t_success) t_success = MCMemoryNewArray(p_byte_count, self -> bytes); if (t_success) { MCMemoryCopy(self -> bytes, p_bytes, p_byte_count); self -> byte_count = p_byte_count; r_data = self; } else { if (self != nil) MCMemoryDeleteArray(self -> bytes); MCMemoryDelete(self); } return t_success; } bool MCDataCreateWithBytesAndRelease(byte_t *p_bytes, uindex_t p_byte_count, MCDataRef& r_data) { if (MCDataCreateWithBytes(p_bytes, p_byte_count, r_data)) { MCMemoryDeallocate(p_bytes); return true; } return false; } bool MCDataIsEmpty(MCDataRef p_data) { return p_data -> byte_count == 0; } uindex_t MCDataGetLength(MCDataRef p_data) { return p_data->byte_count; } const byte_t *MCDataGetBytePtr(MCDataRef p_data) { return p_data->bytes; } byte_t MCDataGetByteAtIndex(MCDataRef p_data, uindex_t p_index) { return p_data->bytes[p_index]; } hash_t MCDataHash(MCDataRef p_data); bool MCDataIsEqualTo(MCDataRef p_left, MCDataRef p_right) { if (p_left -> byte_count != p_right -> byte_count) return false; return MCMemoryCompare(p_left -> bytes, p_right -> bytes, p_left -> byte_count) == 0; } compare_t MCDataCompareTo(MCDataRef p_left, MCDataRef p_right); // Mutable data methods bool MCDataCreateMutable(uindex_t p_initial_capacity, MCDataRef& r_data) { bool t_success; t_success = true; __MCData *self; self = nil; if (t_success) t_success = __MCValueCreate(kMCValueTypeCodeData, self); if (t_success) t_success = __MCDataExpandAt(self, 0, p_initial_capacity); if (t_success) { self->flags |= kMCDataFlagIsMutable; r_data = self; } return t_success; } bool MCDataCopy(MCDataRef p_data, MCDataRef& r_new_data) { if (!MCDataIsMutable(p_data)) { MCValueRetain(p_data); r_new_data = p_data; return true; } return MCDataCreateWithBytes(p_data->bytes, p_data->byte_count, r_new_data); } bool MCDataCopyAndRelease(MCDataRef p_data, MCDataRef& r_new_data) { // If the MCData is immutable we just pass it through (as we are releasing it). if (!MCDataIsMutable(p_data)) { r_new_data = p_data; return true; } // If the reference is 1, convert it to an immutable MCData if (p_data->references == 1) { __MCDataMakeImmutable(p_data); p_data->flags &= ~kMCDataFlagIsMutable; r_new_data = p_data; return true; } // Otherwise make a copy of the data and then release the original bool t_success; t_success = MCDataCreateWithBytes(p_data->bytes, p_data->byte_count, r_new_data); MCValueRelease(p_data); return t_success; } bool MCDataMutableCopy(MCDataRef p_data, MCDataRef& r_mutable_data) { MCDataRef t_mutable_data; if (!MCDataCreateMutable(p_data->byte_count, t_mutable_data)) return false; MCMemoryCopy(t_mutable_data->bytes, p_data->bytes, p_data->byte_count); t_mutable_data->byte_count = p_data->byte_count; r_mutable_data = t_mutable_data; return true; } bool MCDataMutableCopyAndRelease(MCDataRef p_data, MCDataRef& r_mutable_data) { if (MCDataMutableCopy(p_data, r_mutable_data)) { MCValueRelease(p_data); return true; } return false; } bool MCDataCopyRange(MCDataRef self, MCRange p_range, MCDataRef& r_new_data) { __MCDataClampRange(self, p_range); return MCDataCreateWithBytes(self -> bytes + p_range . offset, p_range . length, r_new_data); } bool MCDataCopyRangeAndRelease(MCDataRef self, MCRange p_range, MCDataRef& r_new_data) { if (MCDataCopyRange(self, p_range, r_new_data)) { MCValueRelease(self); return true; } return false; } bool MCDataIsMutable(const MCDataRef p_data) { return (p_data->flags & kMCDataFlagIsMutable) != 0; } bool MCDataAppend(MCDataRef r_data, MCDataRef p_suffix) { MCAssert(MCDataIsMutable(r_data)); if (r_data == p_suffix) { // Must copy first the suffix MCDataRef t_suffix_copy; if(!MCDataCopy(r_data, t_suffix_copy)) return false; // Copy succeeded: can process recursively the appending, and then release the newly created suffix. bool t_success = MCDataAppend(r_data, t_suffix_copy); MCValueRelease(t_suffix_copy); return t_success; } if (!__MCDataExpandAt(r_data, r_data->byte_count, p_suffix->byte_count)) return false; MCMemoryCopy(r_data->bytes + r_data->byte_count - p_suffix->byte_count, p_suffix->bytes, p_suffix->byte_count); return true; } bool MCDataAppendBytes(MCDataRef r_data, const byte_t *p_bytes, uindex_t p_byte_count) { MCAssert(MCDataIsMutable(r_data)); // Expand the capacity if necessary if (!__MCDataExpandAt(r_data, r_data->byte_count, p_byte_count)) return false; MCMemoryCopy(r_data->bytes + r_data->byte_count - p_byte_count, p_bytes, p_byte_count); return true; } bool MCDataAppendByte(MCDataRef r_data, byte_t p_byte) { MCAssert(MCDataIsMutable(r_data)); return MCDataAppendBytes(r_data, &p_byte, 1); } bool MCDataPrepend(MCDataRef r_data, MCDataRef p_prefix) { MCAssert(MCDataIsMutable(r_data)); if (r_data == p_prefix) { // Must copy first the prefix MCDataRef t_prefix_copy; if(!MCDataCopy(r_data, t_prefix_copy)) return false; // Copy succeeded: can process recursively the appending, and then release the newly created suffix. bool t_success = MCDataPrepend(r_data, t_prefix_copy); MCValueRelease(t_prefix_copy); return t_success; } // Ensure there is room enough to copy the prefix if (!__MCDataExpandAt(r_data, 0, p_prefix->byte_count)) return false; MCMemoryCopy(r_data->bytes, p_prefix->bytes, p_prefix->byte_count); return true; } bool MCDataPrependBytes(MCDataRef r_data, const byte_t *p_bytes, uindex_t p_byte_count) { MCAssert(MCDataIsMutable(r_data)); // Ensure there is room enough to copy the prefix if (!__MCDataExpandAt(r_data, 0, p_byte_count)) return false; MCMemoryCopy(r_data->bytes, p_bytes, p_byte_count); return true; } bool MCDataPrependByte(MCDataRef r_data, byte_t p_byte) { return MCDataPrependBytes(r_data, &p_byte, 1); } bool MCDataInsert(MCDataRef r_data, uindex_t p_at, MCDataRef p_new_data) { MCAssert(MCDataIsMutable(r_data)); if (r_data == p_new_data) { // Must copy first the prefix MCDataRef t_new_data_copy; if(!MCDataCopy(r_data, t_new_data_copy)) return false; // Copy succeeded: can process recursively the appending, and then release the newly created suffix. bool t_success = MCDataPrepend(r_data, t_new_data_copy); MCValueRelease(t_new_data_copy); return t_success; } // Ensure there is room enough to copy the prefix if (!__MCDataExpandAt(r_data, p_at, p_new_data->byte_count)) return false; MCMemoryCopy(r_data->bytes, p_new_data->bytes, p_new_data->byte_count); return true; } bool MCDataRemove(MCDataRef r_data, MCRange p_range) { MCAssert(MCDataIsMutable(r_data)); __MCDataClampRange(r_data, p_range); // Copy down the bytes above __MCDataShrinkAt(r_data, p_range.offset, p_range.length); // We succeeded. return true; } bool MCDataReplace(MCDataRef r_data, MCRange p_range, MCDataRef p_new_data) { MCAssert(MCDataIsMutable(r_data)); if (r_data == p_new_data) { MCDataRef t_new_data; if (!MCDataCopy(p_new_data, t_new_data)) return false; bool t_success = MCDataReplace(r_data, p_range, t_new_data); MCValueRelease(t_new_data); return t_success; } __MCDataClampRange(r_data, p_range); // Work out the new size of the string. uindex_t t_new_char_count; t_new_char_count = r_data->byte_count - p_range.length + p_new_data->byte_count; if (t_new_char_count > r_data->byte_count) { // Expand the string at the end of the range by the amount extra we // need. if (!__MCDataExpandAt(r_data, p_range.offset + p_range.length, t_new_char_count - r_data->byte_count)) return false; } else if (t_new_char_count < r_data->byte_count) { // Shrink the last part of the range by the amount less we need. __MCDataShrinkAt(r_data, p_range.offset + (p_range.length - (r_data->byte_count - t_new_char_count)), (r_data->byte_count - t_new_char_count)); } // Copy across the replacement chars. MCMemoryCopy(r_data->bytes + p_range.offset, p_new_data->bytes, p_new_data->byte_count); // We succeeded. return true; } bool MCDataPad(MCDataRef p_data, byte_t p_byte, uindex_t p_count) { if (!__MCDataExpandAt(p_data, p_data -> byte_count, p_count)) return false; memset(p_data -> bytes + p_data -> byte_count - p_count, p_byte, p_count); return true; } compare_t MCDataCompareTo(MCDataRef p_left, MCDataRef p_right) { compare_t t_result; t_result = memcmp(p_left -> bytes, p_right -> bytes, MCMin(p_left -> byte_count, p_right -> byte_count)); if (t_result != 0) return t_result; return p_left -> byte_count - p_right -> byte_count; } #if defined(__MAC__) || defined (__IOS__) bool MCDataConvertToCFDataRef(MCDataRef p_data, CFDataRef& r_cfdata) { r_cfdata = CFDataCreate(nil, MCDataGetBytePtr(p_data), MCDataGetLength(p_data)); return r_cfdata != nil; } #endif static void __MCDataClampRange(MCDataRef p_data, MCRange& x_range) { uindex_t t_left, t_right; t_left = MCMin(x_range . offset, p_data -> byte_count); t_right = MCMin(x_range . offset + MCMin(x_range . length, UINDEX_MAX - x_range . offset), p_data->byte_count); x_range . offset = t_left; x_range . length = t_right - t_left; } static void __MCDataShrinkAt(MCDataRef r_data, uindex_t p_at, uindex_t p_count) { // Shift the bytes above 'at' down to remove 'count' MCMemoryMove(r_data->bytes + p_at, r_data->bytes + (p_at + p_count), r_data->byte_count - (p_at + p_count)); // Now adjust the length of the string. r_data->byte_count -= p_count; // TODO: Shrink the buffer if its too big. } static bool __MCDataExpandAt(MCDataRef r_data, uindex_t p_at, uindex_t p_count) { // Fetch the capacity. uindex_t t_capacity; t_capacity = r_data->capacity; // The capacity field stores the total number of chars that could fit not // including the implicit NUL, so if we fit, we can fast-track. if (t_capacity != 0 && r_data->byte_count + p_count <= t_capacity) { // Shift up the bytes above MCMemoryMove(r_data->bytes + p_at + p_count,r_data->bytes + p_at, r_data->byte_count - p_at); // Increase the byte_count. r_data->byte_count += p_count; // We succeeded. return true; } // If we get here then we need to reallocate first. // Base capacity - current length + inserted length uindex_t t_new_capacity; t_new_capacity = r_data->byte_count + p_count; // Capacity rounded up to a suitable boundary (at some point this should // be a function of the string's size). t_new_capacity = (t_new_capacity + 63) & ~63; // Reallocate. if (!MCMemoryReallocate(r_data->bytes, t_new_capacity, r_data->bytes)) return false; // Shift up the bytes above MCMemoryMove(r_data->bytes + p_at + p_count, r_data->bytes + p_at, r_data->byte_count - p_at); // Increase the byte_count. r_data->byte_count += p_count; // Update the capacity r_data -> capacity = t_new_capacity; // We succeeded. return true; } static bool __MCDataMakeImmutable(__MCData *self) { if (!MCMemoryResizeArray(self -> byte_count, self -> bytes, self -> byte_count)) return false; return true; } //////////////////////////////////////////////////////////////////////////////// MCDataRef kMCEmptyData; bool __MCDataInitialize(void) { if (!MCDataCreateWithBytes(nil, 0, kMCEmptyData)) return false; return true; } void __MCDataFinalize(void) { MCValueRelease(kMCEmptyData); } void __MCDataDestroy(__MCData *self) { if (self -> bytes != nil) MCMemoryDeleteArray(self -> bytes); } bool __MCDataImmutableCopy(__MCData *self, bool p_release, __MCData *&r_immutable_value) { if (!p_release) return MCDataCopy(self, r_immutable_value); return MCDataCopyAndRelease(self, r_immutable_value); } bool __MCDataIsEqualTo(__MCData *self, __MCData *p_other_data) { return MCDataIsEqualTo(self, p_other_data); } hash_t __MCDataHash(__MCData *self) { return MCHashBytes(self -> bytes, self -> byte_count); } bool __MCDataCopyDescription(__MCData *self, MCStringRef &r_description) { return false; }
livecodefraser/livecode
libfoundation/src/foundation-data.cpp
C++
gpl-3.0
14,664
/* * Copyright (C) 2015 Lenny Knockaert <lknockx@gmail.com> * * This file is part of ZetCam * * ZetCam 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. * * ZetCam 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.maksvzw.zetcam.core.audio.buffers; import com.xuggle.xuggler.IAudioSamples; /** * * @author Lenny Knockaert */ public abstract class ByteSampleBuffer extends AudioSampleBuffer<Byte> { private final byte[] tempBuf; private byte[] mixBuf; protected ByteSampleBuffer(IAudioSamples samples) { super(samples); this.tempBuf = new byte[1024]; } @Override protected final Byte getSample(IAudioSamples samples, int index) { samples.get(index, this.tempBuf, 0, 1); return this.tempBuf[0]; } @Override protected final void putSample(IAudioSamples samples, int index, Byte sample) { this.tempBuf[0] = sample; samples.put(this.tempBuf, 0, index, 1); } @Override protected final void copySamples(IAudioSamples src, int srcIndex, IAudioSamples dst, int dstIndex, int length) { int tempLength; while(length > 0) { tempLength = Math.min(this.tempBuf.length, length); src.get(srcIndex, this.tempBuf, 0, tempLength); dst.put(this.tempBuf, 0, dstIndex, tempLength); srcIndex += tempLength; dstIndex += tempLength; length -= tempLength; } } @Override protected final void mixSamples(IAudioSamples src, int srcIndex, IAudioSamples dst, int dstIndex, int length) { if (this.mixBuf == null) this.mixBuf = new byte[this.tempBuf.length]; int tempLength; while(length > 0) { tempLength = Math.min(this.tempBuf.length, length); src.get(srcIndex, this.tempBuf, 0, tempLength); dst.get(srcIndex, this.mixBuf, 0, tempLength); for(int i = 0; i < tempLength; i++) this.mixBuf[i] = this.mixSample(this.tempBuf[i], this.mixBuf[i]); dst.put(this.mixBuf, 0, dstIndex, tempLength); srcIndex += tempLength; dstIndex += tempLength; length -= tempLength; } } @Override protected final void scaleSamples(IAudioSamples samples, int index, int length, double scale) { int tempLength; while(length > 0) { tempLength = Math.min(length, this.tempBuf.length); samples.get(index, this.tempBuf, 0, tempLength); for(int i = 0; i < tempLength; i++) this.tempBuf[i] = this.scaleSample(this.tempBuf[i], scale); samples.put(this.tempBuf, 0, index, tempLength); length -= tempLength; index += tempLength; } } @Override protected final void fillSamples(IAudioSamples samples, int index, int length, Byte sample) { int tempLength; while(length > 0) { tempLength = Math.min(length, this.tempBuf.length); samples.get(index, this.tempBuf, 0, tempLength); for(int i = 0; i < tempLength; i++) this.tempBuf[i] = sample; samples.put(this.tempBuf, 0, index, tempLength); length -= tempLength; index += tempLength; } } }
maksvzw/zetcam
src/main/java/org/maksvzw/zetcam/core/audio/buffers/ByteSampleBuffer.java
Java
gpl-3.0
3,890
package me.staartvin.statz.datamanager.player.specification; import java.util.UUID; public class EnteredBedsSpecification extends PlayerStatSpecification { public EnteredBedsSpecification(UUID uuid, int value, String worldName) { super(); this.putInData(Keys.UUID.toString(), uuid); this.putInData(Keys.VALUE.toString(), value); this.putInData(Keys.WORLD.toString(), worldName); } @Override public boolean hasWorldSupport() { return true; } public enum Keys {UUID, VALUE, WORLD} }
Staartvin/Statz
src/me/staartvin/statz/datamanager/player/specification/EnteredBedsSpecification.java
Java
gpl-3.0
551
export default { div: 'Div', aside: 'Aside', main: 'Main', h1: 'Heading', h2: 'Heading', h3: 'Heading', h4: 'Heading', h5: 'Heading', h6: 'Heading', p: 'Paragraph', span: 'Span', ul: 'Unordered List', li: 'List Item', img: 'Image', strong: 'Strong Text', em: 'Emphasised Text', i: 'Icon', a: 'Link', input: 'Input', blockquote: 'Quote', figcaption: 'Caption', button: 'Button', header: 'Header', footer: 'Footer' };
builify/builify
src/javascript/components/canvas/click-toolbox/html-tagnames.js
JavaScript
gpl-3.0
512
// watch "use strict"; module.exports = { options: { livereload: false }, // docs: { // files: [ // "<%= pkg.source %>" + "/javascript/**/*.js" // ], // tasks: [ // "docs" // ] // }, js: { files: [ "<%= pkg.source %>" + "/javascript/**/*.js" ], tasks: [ // 'clean:js', "newer:copy:js", "newer:copy:libs" ] }, html: { files: [ "<%= pkg.source %>" + "/html/**/*.html" ], tasks: [ // 'clean:html', "newer:copy:html" ] }, less: { files: [ "<%= pkg.source %>" + "/css/**/*.less" ], tasks: [ "less:dev", "postcss:dev" ] }, images: { files: [ "<%= pkg.source %>" + "/images/**/*.{png,jpg,jpeg,gif}" ], tasks: [ "newer:imagemin:dev" ] }, livereload: { options: { livereload: true }, files: [ "<%= pkg.development %>" + "/**/*" ] } };
LOA-SEAD/cuidando-bem
grunt/options/watch.js
JavaScript
gpl-3.0
1,178
/*===========================================================================*\ * * * OpenFlipper * * Copyright (C) 2001-2014 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$ * * $LastChangedBy$ * * $Date$ * * * \*===========================================================================*/ #ifdef ENABLE_OPENVOLUMEMESH_SUPPORT #define OVM_PROPERTY_VISUALIZER_CC #ifdef ENABLE_OPENVOLUMEMESH_POLYHEDRAL_SUPPORT #include <ObjectTypes/PolyhedralMesh/PolyhedralMesh.hh> #endif #ifdef ENABLE_OPENVOLUMEMESH_HEXAHEDRAL_SUPPORT #include <ObjectTypes/HexahedralMesh/HexahedralMesh.hh> #endif #include "OVMPropertyVisualizer.hh" template <typename MeshT> template <typename InnerType> QString OVMPropertyVisualizer<MeshT>::getPropertyText_(unsigned int index) { if (PropertyVisualizer::propertyInfo.isCellProp()) { OpenVolumeMesh::CellPropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_cell_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); return PropertyVisualizer::toStr(prop[OpenVolumeMesh::CellHandle(index)]); } else if (PropertyVisualizer::propertyInfo.isFaceProp()) { OpenVolumeMesh::FacePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_face_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); return PropertyVisualizer::toStr(prop[OpenVolumeMesh::FaceHandle(index)]); } else if (PropertyVisualizer::propertyInfo.isHalffaceProp()) { OpenVolumeMesh::HalfFacePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_halfface_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); return PropertyVisualizer::toStr(prop[OpenVolumeMesh::HalfFaceHandle(index)]); } else if (PropertyVisualizer::propertyInfo.isEdgeProp()) { OpenVolumeMesh::EdgePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_edge_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); return PropertyVisualizer::toStr(prop[OpenVolumeMesh::EdgeHandle(index)]); } else if (PropertyVisualizer::propertyInfo.isHalfedgeProp()) { OpenVolumeMesh::HalfEdgePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_halfedge_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); return PropertyVisualizer::toStr(prop[OpenVolumeMesh::HalfEdgeHandle(index)]); } else //if (propertyInfo.isVertexProp()) { OpenVolumeMesh::VertexPropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_vertex_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); return PropertyVisualizer::toStr(prop[OpenVolumeMesh::VertexHandle(index)]); } } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::setPropertyFromText(unsigned int index, QString text) { if (propertyInfo.isCellProp()) setCellPropertyFromText(index, text); else if (propertyInfo.isFaceProp()) setFacePropertyFromText(index, text); else if (propertyInfo.isHalffaceProp()) setHalffacePropertyFromText(index, text); else if (propertyInfo.isEdgeProp()) setEdgePropertyFromText(index, text); else if (propertyInfo.isHalfedgeProp()) setHalfedgePropertyFromText(index, text); else //if (propertyInfo.isVertexProp()) setVertexPropertyFromText(index, text); } template <typename MeshT> int OVMPropertyVisualizer<MeshT>::getEntityCount() { if (propertyInfo.isCellProp()) return mesh->n_cells(); if (propertyInfo.isFaceProp()) return mesh->n_faces(); if (propertyInfo.isHalffaceProp()) return mesh->n_halffaces(); else if (propertyInfo.isEdgeProp()) return mesh->n_edges(); else if (propertyInfo.isHalfedgeProp()) return mesh->n_halfedges(); else //if (propertyInfo.isVertexProp()) return mesh->n_vertices(); } template <typename MeshT> QString OVMPropertyVisualizer<MeshT>::getHeader() { //Header: headerVersion, numberOfEntities, typeOfEntites, typeOfProperty, propertyName QString header = QObject::tr("1"); //version header.append(QObject::tr(", %1").arg(getEntityCount())); //number of entities header.append(QObject::tr(", %1").arg(propertyInfo.entityType())); //type of entities header.append(", ").append(propertyInfo.friendlyTypeName()); //type of property header.append(", ").append(propertyInfo.propName().c_str()); // name of property return header; } template <typename MeshT> unsigned int OVMPropertyVisualizer<MeshT>::getClosestPrimitiveId(unsigned int _face, ACG::Vec3d& _hitPoint) { if (propertyInfo.isHalffaceProp()) return getClosestHalffaceId(_face, _hitPoint); else// if (propertyInfo.isHalfedgeProp()) return getClosestHalfedgeId(_face, _hitPoint); } template <typename MeshT> unsigned int OVMPropertyVisualizer<MeshT>::getClosestHalffaceId(unsigned int _face, ACG::Vec3d& _hitPoint) { ACG::Vec3d direction = PluginFunctions::viewingDirection(); OpenVolumeMesh::HalfFaceHandle hfh = mesh->halfface_handle(OpenVolumeMesh::FaceHandle(_face), 0); OpenVolumeMesh::HalfFaceVertexIter hfv_it = mesh->hfv_iter(hfh); ACG::Vec3d p1 = mesh->vertex(*(hfv_it+0)); ACG::Vec3d p2 = mesh->vertex(*(hfv_it+1)); ACG::Vec3d p3 = mesh->vertex(*(hfv_it+2)); ACG::Vec3d normal = (p2-p1)%(p3-p1); if ((direction | normal) < 0) return hfh.idx(); else return mesh->halfface_handle(OpenVolumeMesh::FaceHandle(_face), 1).idx(); } template <typename MeshT> unsigned int OVMPropertyVisualizer<MeshT>::getClosestHalfedgeId(unsigned int _face, ACG::Vec3d& _hitPoint) { unsigned int halfface = getClosestHalffaceId(_face, _hitPoint); OpenVolumeMesh::OpenVolumeMeshFace face = mesh->halfface(halfface); const std::vector<OpenVolumeMesh::HalfEdgeHandle> & halfedges = face.halfedges(); double min_distance = DBL_MAX; OpenVolumeMesh::HalfEdgeHandle closestHalfEdgeHandle; for (std::vector<OpenVolumeMesh::HalfEdgeHandle>::const_iterator he_it = halfedges.begin(); he_it != halfedges.end(); ++he_it) { OpenVolumeMesh::OpenVolumeMeshEdge edge = OVMPropertyVisualizer<MeshT>::mesh->halfedge(*he_it); ACG::Vec3d v1 = mesh->vertex(edge.from_vertex()); ACG::Vec3d v2 = mesh->vertex(edge.to_vertex()); ACG::Vec3d p = 0.5 * (v1+v2); double distance = (p-_hitPoint).length(); if (distance < min_distance) { min_distance = distance; closestHalfEdgeHandle = *he_it; } } return closestHalfEdgeHandle.idx(); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::visualize(bool _setDrawMode) { if (propertyInfo.isCellProp()) visualizeCellProp(_setDrawMode); else if (propertyInfo.isFaceProp()) visualizeFaceProp(_setDrawMode); else if (propertyInfo.isHalffaceProp()) visualizeHalffaceProp(_setDrawMode); else if (propertyInfo.isEdgeProp()) visualizeEdgeProp(_setDrawMode); else if (propertyInfo.isHalfedgeProp()) visualizeHalfedgeProp(_setDrawMode); else if (propertyInfo.isVertexProp()) visualizeVertexProp(_setDrawMode); } template <typename MeshT> OpenMesh::Vec4f OVMPropertyVisualizer<MeshT>::convertColor(const QColor _color){ OpenMesh::Vec4f color; color[0] = _color.redF(); color[1] = _color.greenF(); color[2] = _color.blueF(); color[3] = _color.alphaF(); return color; } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::visualizeFaceProp(bool /*_setDrawMode*/) { emit log(LOGERR, "Visualizing FaceProp not implemented"); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::visualizeEdgeProp(bool /*_setDrawMode*/) { emit log(LOGERR, "Visualizing EdgeProp not implemented"); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::visualizeHalfedgeProp(bool /*_setDrawMode*/) { emit log(LOGERR, "Visualizing HalfedgeProp not implemented"); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::visualizeVertexProp(bool /*_setDrawMode*/) { emit log(LOGERR, "Visualizing VertexProp not implemented"); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::visualizeCellProp(bool /*_setDrawMode*/) { emit log(LOGERR, "Visualizing CellProp not implemented"); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::visualizeHalffaceProp(bool /*_setDrawMode*/) { emit log(LOGERR, "Visualizing HalffaceProp not implemented"); } template<typename MeshT> template<typename PropType> inline void OVMPropertyVisualizer<MeshT>::duplicateProperty_stage1() { std::string newPropertyName; for (int i = 1;; ++i) { std::ostringstream oss; oss << propertyInfo.propName() << " Copy " << i; newPropertyName = oss.str(); if (propertyInfo.isCellProp()) { if(!mesh->template cell_property_exists<PropType>(newPropertyName)) break; } else if (propertyInfo.isFaceProp()) { if(!mesh->template face_property_exists<PropType>(newPropertyName)) break; } else if (propertyInfo.isHalffaceProp()) { if(!mesh->template halfface_property_exists<PropType>(newPropertyName)) break; } else if (propertyInfo.isEdgeProp()) { if(!mesh->template edge_property_exists<PropType>(newPropertyName)) break; } else if (propertyInfo.isHalfedgeProp()) { if(!mesh->template halfedge_property_exists<PropType>(newPropertyName)) break; } else if (propertyInfo.isVertexProp()) { if(!mesh->template vertex_property_exists<PropType>(newPropertyName)) break; } } if (propertyInfo.isCellProp()) { OpenVolumeMesh::CellPropertyT<PropType> prop = mesh->template request_cell_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); OpenVolumeMesh::CellPropertyT<PropType> newProp = mesh->template request_cell_property< PropType >(newPropertyName); mesh->set_persistent(newProp, true); std::for_each(mesh->cells_begin(), mesh->cells_end(), CopyProperty<OpenVolumeMesh::CellPropertyT<PropType> >(newProp, prop, mesh)); } else if (propertyInfo.isFaceProp()) { OpenVolumeMesh::FacePropertyT<PropType> prop = mesh->template request_face_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); OpenVolumeMesh::FacePropertyT<PropType> newProp = mesh->template request_face_property< PropType >(newPropertyName); mesh->set_persistent(newProp, true); std::for_each(mesh->faces_begin(), mesh->faces_end(), CopyProperty<OpenVolumeMesh::FacePropertyT<PropType> >(newProp, prop, mesh)); } else if (propertyInfo.isHalffaceProp()) { OpenVolumeMesh::HalfFacePropertyT<PropType> prop = mesh->template request_halfface_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); OpenVolumeMesh::HalfFacePropertyT<PropType> newProp = mesh->template request_halfface_property< PropType >(newPropertyName); mesh->set_persistent(newProp, true); std::for_each(mesh->halffaces_begin(), mesh->halffaces_end(), CopyProperty<OpenVolumeMesh::HalfFacePropertyT<PropType> >(newProp, prop, mesh)); } else if (propertyInfo.isEdgeProp()) { OpenVolumeMesh::EdgePropertyT<PropType> prop = mesh->template request_edge_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); OpenVolumeMesh::EdgePropertyT<PropType> newProp = mesh->template request_edge_property< PropType >(newPropertyName); mesh->set_persistent(newProp, true); std::for_each(mesh->edges_begin(), mesh->edges_end(), CopyProperty<OpenVolumeMesh::EdgePropertyT<PropType> >(newProp, prop, mesh)); } else if (propertyInfo.isHalfedgeProp()) { OpenVolumeMesh::HalfEdgePropertyT<PropType> prop = mesh->template request_halfedge_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); OpenVolumeMesh::HalfEdgePropertyT<PropType> newProp = mesh->template request_halfedge_property< PropType >(newPropertyName); mesh->set_persistent(newProp, true); std::for_each(mesh->halfedges_begin(), mesh->halfedges_end(), CopyProperty<OpenVolumeMesh::HalfEdgePropertyT<PropType> >(newProp, prop, mesh)); } else if (propertyInfo.isVertexProp()) { OpenVolumeMesh::VertexPropertyT<PropType> prop = mesh->template request_vertex_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName()); OpenVolumeMesh::VertexPropertyT<PropType> newProp = mesh->template request_vertex_property< PropType >(newPropertyName); mesh->set_persistent(newProp, true); std::for_each(mesh->vertices_begin(), mesh->vertices_end(), CopyProperty<OpenVolumeMesh::VertexPropertyT<PropType> >(newProp, prop, mesh)); } } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::clear() { VolumeMeshObject<MeshT>* object; PluginFunctions::getObject(OVMPropertyVisualizer<MeshT>::mObjectID, object); if (propertyInfo.isCellProp()) object->colors().clear_cell_colors(); else if (propertyInfo.isFaceProp()) object->colors().clear_face_colors(); else if (propertyInfo.isHalffaceProp()) object->colors().clear_halfface_colors(); else if (propertyInfo.isEdgeProp()) object->colors().clear_edge_colors(); else if (propertyInfo.isHalfedgeProp()) object->colors().clear_halfedge_colors(); else if (propertyInfo.isVertexProp()) object->colors().clear_vertex_colors(); object->setObjectDrawMode(drawModes.cellsFlatShaded); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::setCellPropertyFromText(unsigned int /*index*/, QString /*text*/) { emit log(LOGERR, "Setting CellProp not implemented for this property type"); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::setFacePropertyFromText(unsigned int /*index*/, QString /*text*/) { emit log(LOGERR, "Setting FaceProp not implemented for this property type"); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::setHalffacePropertyFromText(unsigned int /*index*/, QString /*text*/) { emit log(LOGERR, "Setting HalffaceProp not implemented for this property type"); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::setEdgePropertyFromText(unsigned int /*index*/, QString /*text*/) { emit log(LOGERR, "Setting EdgeProp not implemented for this property type"); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::setHalfedgePropertyFromText(unsigned int /*index*/, QString /*text*/) { emit log(LOGERR, "Setting HalfedgeProp not implemented for this property type"); } template <typename MeshT> void OVMPropertyVisualizer<MeshT>::setVertexPropertyFromText(unsigned int /*index*/, QString /*text*/) { emit log(LOGERR, "Setting VertexProp not implemented for this property type"); } #endif /* ENABLE_OPENVOLUMEMESH_SUPPORT */
heartvalve/OpenFlipper
Plugin-PropertyVis/OpenVolumeMesh/OVMPropertyVisualizerT.cc
C++
gpl-3.0
18,016
///** // * This file is part of FXL GUI API. // * // * FXL GUI API 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. // * // * FXL GUI API 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 FXL GUI API. If not, see <http://www.gnu.org/licenses/>. // * // * Copyright (c) 2010-2015 Dangelmayr IT GmbH. All rights reserved. // */ //package co.fxl.gui.style.gplus; // //import co.fxl.gui.api.ILabel; //import co.fxl.gui.api.IPanel; //import co.fxl.gui.style.api.IStyle.ITable; // //public class GPlusTable implements ITable { // // @Override // public IColumnSelection columnSelection() { // return new IColumnSelection() { // // @Override // public IColumnSelection panel(IPanel<?> b, boolean visible) { // if (visible) // b.color().gray(); // else // b.color().white(); // return this; // } // // @Override // public IColumnSelection label(ILabel b, boolean visible) { // if (visible) // b.font().color().white(); // else // b.font().color().gray(); // return this; // } // // }; // } // // @Override // public ITable statusPanel(IPanel<?> statusPanel) { // statusPanel.color().remove().white(); // // statusPanel.border().remove(); // return this; // } // // @Override // public ITable topPanel(IPanel<?> topPanel) { // topPanel.color().remove().white(); // topPanel.border().remove(); // return this; // } // // }
Letractively/fxlgui
co.fxl.gui.style.gplus/src/main/java/co/fxl/gui/style/gplus/GPlusTable.java
Java
gpl-3.0
1,909
namespace Tower_Unite_Instrument_Autoplayer.Core { /// <summary> /// This interface is a set of rules that all notes has to follow /// in order to qualify as a note /// </summary> interface INote { /// <summary> /// This method is invoked when the note is reached in the song /// </summary> void Play(); } }
Sejemus/Tower-Unite-Piano-Bot
Tower Unite Instrument Autoplayer/Core/Interfaces/INote.cs
C#
gpl-3.0
371
import libtcodpy as libtcod #globs are imported almost everywhere, so unnecessary libtcod imports should be omitted ########################################################## # Options ########################################################## #it's better to pack them into separate file LIMIT_FPS = 20 #size of the map MAP_WIDTH = 100 MAP_HEIGHT = 80 #size of the camera screen CAMERA_WIDTH = 80 CAMERA_HEIGHT = 43 #size of the window SCREEN_WIDTH = 80 SCREEN_HEIGHT = 50 #map generating settings MAX_ROOM_ENEMIES = 3 MAX_ROOM_ITEMS = 3 #BSP options DEPTH = 10 #number of node splittings ROOM_MIN_SIZE = 6 FULL_ROOMS = False #sizes and coordinates for GUI PANEL_HEIGHT = 7 BAR_WIDTH = 20 PANEL_Y = SCREEN_HEIGHT - PANEL_HEIGHT MESSAGE_X = BAR_WIDTH + 2 MESSAGE_WIDTH = SCREEN_WIDTH - BAR_WIDTH - 2 MESSAGE_HEIGHT = PANEL_HEIGHT - 1 #inventory properties MAX_INVENTORY_SIZE = 26 INVENTORY_WIDTH = 50 #item properties STIM_HEAL_AMOUNT = 50 DISCHARGE_DAMAGE = 100 ITEM_USING_RANGE = 5 CONFUSE_TURNS = 10 GRENADE_DAMAGE = 30 GRENADE_RADIUS = 3 #weapon properties WEAPON_RANGE = 5 LASER_PISTOL_DAMAGE = 20 LASER_RIFLE_DAMAGE = 50 #experience properties LEVEL_UP_BASE = 100 LEVEL_UP_FACTOR = 150 #FOV properties FOV_ALGO = 0 FOV_LIGHT_WALLS = True TORCH_RADIUS = 10 ########################################################## #colors of invisible tiles c_hid_wall = libtcod.Color(22, 7, 115) c_hid_floor = libtcod.Color(55, 46, 133) #colors of visible tiles c_vis_wall = libtcod.Color(148, 122, 23) c_vis_floor = libtcod.Color(180, 155, 58) #colors of highlighted tiles c_hi_wall = libtcod.Color(67, 128, 211) c_hi_floor = libtcod.Color(105, 150, 211) #possible tile types #properties description: # title - just a name for a specific terrain, also used as key for a corresponding tile type in 'TYLE_TYPES' dict # walkable - indicates, if tiles of this type can hold an object (character, item and so on) on the top of itself # transparent - indicates, whether the tile blocks line of sight during calculating FOV for characters or not # vis_color, hid_color, hi_color - visible color, hidden color, highlighted color respectively; used in 'calculate_color' function # #current types: 'floor', 'wall' # #in order to add new type, just create additional dict holding its properties as shown below and append it to 'TYLE_TYPES' #'tile_type' used in 'Tile.set_type' is the keyword of a corresponding type in 'TILE_TYPES' floor = {'title': 'f1loor', 'walkable': True, 'transparent': True, 'vis_color': c_vis_floor, 'hid_color': c_hid_floor, 'hi_color': c_hi_floor} wall = {'title': 'metal wall', 'walkable': False, 'transparent': False, 'vis_color': c_vis_wall, 'hid_color': c_hid_wall, 'hi_color': c_hi_wall} TILE_TYPES = {'floor': floor, 'wall': wall} #variables for input handling #they are kept here, as they don't hold any used information outside input-handling functions #it doesn't matter, if they are constantly reinitializing key = libtcod.Key() mouse = libtcod.Mouse() ##########################################################
MaxGavr/breakdown_game
globs.py
Python
gpl-3.0
3,049
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class AutoRevealStatListener : gameScriptStatsListener { [Ordinal(0)] [RED("owner")] public wCHandle<gameObject> Owner { get; set; } public AutoRevealStatListener(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/AutoRevealStatListener.cs
C#
gpl-3.0
381
from .main import create_random_key, vigenere, otp
D-Vaillant/julius
julius/__init__.py
Python
gpl-3.0
51
package vinamax import ( "log" ) var ( //These variables can be set in the input files B_ext func(t float64) (float64, float64, float64) // External applied field in T B_ext_space func(t, x, y, z float64) (float64, float64, float64) // External applied field in T Dt float64 = -1 // Timestep in s Mindt float64 = 1e-20 //smallest allowed timestep Maxdt float64 = 1 //largest allowed timestep T float64 // Time in s Alpha float64 = -1 // Gilbert damping constant gammaoveralpha float64 //g/1+alfa^2 Temp float64 = -1 // Temperature in K Ku1 float64 = 0 // Uniaxial anisotropy constant in J/m**3 Kc1 float64 = 0 // Cubic anisotropy constant in J/m**3 Errortolerance float64 = 1e-5 Thresholdbeta float64 = 0.3 // The threshold value for the FMM demagtime float64 universe node // The entire universe of the simulation FMM bool = false // Calculate demag with FMM method Demag bool = true // Calculate demag demagevery bool = false // Calculate demag only after certain interval Adaptivestep bool = false outdir string // The output directory solver string = "dopri" // The solver used outputinterval float64 maxtauwitht float64 = 0. //maximum torque during the simulations with temperature // suggest_timestep bool = false order int = 5 //the order of the solver constradius float64 logradius_m float64 logradius_s float64 Tau0 float64 =1e-8 msatcalled bool = false radiuscalled bool = false constradiuscalled bool = false logradiuscalled bool = false uaniscalled bool = false c1called bool = false c2called bool = false worldcalled bool = false magnetisationcalled bool = false treecalled bool = false outputcalled bool = false randomseedcalled bool = false tableaddcalled bool = false Jumpnoise bool = false Brown bool = false ) //initialised B_ext functions func init() { B_ext = func(t float64) (float64, float64, float64) { return 0, 0, 0 } // External applied field in T B_ext_space = func(t, x, y, z float64) (float64, float64, float64) { return 0, 0, 0 } // External applied field in T } //demag every interval func Demagevery(t float64) { demagevery = true demagtime = t } //test the inputvalues for unnatural things func testinput() { if Demag == true && demagevery == true { log.Fatal("You cannot call both Demagevery and Demag, pick one") } if Dt < 0 { log.Fatal("Dt cannot be smaller than 0, did you forget to initialise?") } if Alpha < 0 { log.Fatal("Alpha cannot be smaller than 0, did you forget to initialise?") } if Temp < 0 { log.Fatal("Temp cannot be smaller than 0, did you forget to initialise?") } if universe.number == 0 { log.Fatal("There are no particles in the geometry") } } //checks the inputfiles for functions that should have been called but weren't func syntaxrun() { if msatcalled == false { log.Fatal("You have to specify msat") } if radiuscalled == false { log.Fatal("You have to specify the size of the particles") } if uaniscalled == false && Ku1 != 0 { log.Fatal("You have to specify the uniaxial anisotropy-axis") } if (c1called == false || c2called == false) && Kc1 != 0 { log.Fatal("You have to specify the cubic anisotropy-axes") } if worldcalled == false { log.Fatal("You have define a \"World\"") } if magnetisationcalled == false { log.Fatal("You have specify the initial magnetisation") } if treecalled == false && FMM == true { log.Fatal("You have to run Maketree() as last command in front of Run() when using the FMM method") } if Temp != 0 && randomseedcalled == false { log.Fatal("You have to run Setrandomseed() when using nonzero temperatures") } if tableaddcalled == true && outputcalled == false { log.Fatal("You have to run Output(interval) when calling tableadd") } if Brown == true && Adaptivestep == true { log.Fatal("Brown Temperature can only be used with fixed timestep") } if Jumpnoise == true { resetswitchtimes(universe.lijst) } if Temp != 0 && Brown == false && Jumpnoise == false { log.Fatal("You have to specify which temperature you want to use: \"Jumpnoise\" or \"Brown\"") } if Brown { calculatetempnumbers(universe.lijst) } }
acoene/vinamax
var.go
GO
gpl-3.0
4,996
#include <DefenseManager.h> #include <BorderManager.h> using namespace BWAPI; DefenseManager::DefenseManager(Arbitrator::Arbitrator<BWAPI::Unit*,double>* arbitrator) { firsss2 = false; //chc very_early_rush = false; early_attack_assimi = true; very_early_attack_gate = true; early_attack_gate = true; early_rush =false; firsss=false; lastFrameCheck = 0; this->arbitrator = arbitrator; } void DefenseManager::setBorderManager(BorderManager* borderManager) { this->borderManager=borderManager; } void DefenseManager::setBaseManager(BaseManager *baseManager) { this->baseManager = baseManager; } void DefenseManager::setInformationManager(InformationManager *informationManager) { this->informationManager = informationManager; } std::set<BWAPI::Unit*>& DefenseManager::getIdleDefenders() { idleDefenders.clear(); for (std::map<BWAPI::Unit*, DefenseData>::iterator it = defenders.begin(); it != defenders.end(); it++) { if ((it->second.mode == DefenseData::Idle) || (it->second.mode == DefenseData::Moving)) idleDefenders.insert(it->first); } return idleDefenders; } void DefenseManager::onOffer(std::set<BWAPI::Unit*> units) { for(std::set<BWAPI::Unit*>::iterator u = units.begin(); u != units.end(); u++) { if (defenders.find(*u) == defenders.end()) { arbitrator->accept(this, *u); DefenseData temp; defenders.insert(std::make_pair(*u, temp)); } } } void DefenseManager::onRevoke(BWAPI::Unit* unit, double bid) { defenders.erase(unit); } void DefenseManager::onRemoveUnit(BWAPI::Unit* unit) { defenders.erase(unit); } void DefenseManager::update() { //chc int enemy_assimilator = 0; int enemy_gateway = 0; for (std::set<BWAPI::Unit *>::const_iterator en = Broodwar->enemy()->getUnits().begin(); en != BWAPI::Broodwar->enemy()->getUnits().end(); ++en) { if((*en)->getType() == BWAPI::UnitTypes::Protoss_Assimilator) enemy_assimilator++; if((*en)->getType() == BWAPI::UnitTypes::Protoss_Gateway) enemy_gateway++; } if(enemy_assimilator == 0) early_attack_assimi = false; if(enemy_gateway >= 2) early_attack_gate = false; if(enemy_gateway >=3) very_early_attack_gate = false; if(!very_early_rush && !firsss2) { if(BWAPI::Broodwar->self()->allUnitCount(BWAPI::UnitTypes::Protoss_Cybernetics_Core) == 1) { if(Broodwar->self()->incompleteUnitCount(UnitTypes::Protoss_Cybernetics_Core) != 1) // »çÀ̹ö ³×½ºÆ½Äھ Áö¾îÁö°í ÀÖ´Â µµÁßÀÌ ¾Æ´Ï¶ó¸é firsss2 = true; //´õ ÀÌ»ó ÀÌ if¹®À¸·Î ¸øµé¾î¿È. if(!very_early_attack_gate && early_attack_assimi == false) very_early_rush = true; } } if ((lastFrameCheck == 0) || (BWAPI::Broodwar->getFrameCount() > lastFrameCheck + 10)) { lastFrameCheck = BWAPI::Broodwar->getFrameCount(); // Bid on all completed military units std::set<BWAPI::Unit*> myPlayerUnits=BWAPI::Broodwar->self()->getUnits(); for (std::set<BWAPI::Unit*>::iterator u = myPlayerUnits.begin(); u != myPlayerUnits.end(); u++) { if ((*u)->isCompleted() && !(*u)->getType().isWorker() && !(*u)->getType().isBuilding() && (*u)->getType().canAttack() && (*u)->getType() != BWAPI::UnitTypes::Zerg_Egg && (*u)->getType() != BWAPI::UnitTypes::Zerg_Larva) { arbitrator->setBid(this, *u, 20); } } bool borderUpdated=false; if (myBorder!=borderManager->getMyBorder()) { myBorder=borderManager->getMyBorder(); borderUpdated=true; } //search among our bases which ones are in a border region std::vector<Base*> borderBases; for each (Base *base in baseManager->getAllBases()) { bool isBorderBase = false; for each (BWTA::Chokepoint *c in base->getBaseLocation()->getRegion()->getChokepoints()) { if (myBorder.find(c) != myBorder.end()) { isBorderBase = true; break; } } if (isBorderBase) borderBases.push_back(base); } std::set<BWTA::BaseLocation*> enemyBasesLocation = informationManager->getEnemyBases(); myBorderVector.clear(); for(int i=0; i < (int)borderBases.size(); i++) { //search the nearest enemy base from current borderBases[i] BWTA::BaseLocation *nearestEnemyBaseLocation; double shortestDistance = 9999999; for each (BWTA::BaseLocation *bl in enemyBasesLocation) { double distance = borderBases[i]->getBaseLocation()->getGroundDistance(bl); if (distance < shortestDistance) { shortestDistance = distance; nearestEnemyBaseLocation = bl; } } if (nearestEnemyBaseLocation == NULL) nearestEnemyBaseLocation = informationManager->getEnemyStartLocation(); //now search the nearest choke of borderBases[i] from the enemy base BWTA::Chokepoint *bestChoke; shortestDistance = 9999999; for each(BWTA::Chokepoint *c in borderBases[i]->getBaseLocation()->getRegion()->getChokepoints()) { double distance = nearestEnemyBaseLocation->getPosition().getApproxDistance(c->getCenter()); if (distance < shortestDistance) { shortestDistance = distance; bestChoke = c; } } myBorderVector.push_back(bestChoke); } //Order all units to choke /* int i=0; if (!myBorder.empty()) { for (std::map<BWAPI::Unit*,DefenseData>::iterator u = defenders.begin(); u != defenders.end(); u++) { if ((*u).second.mode == DefenseData::Idle || borderUpdated) { BWAPI::Position chokePosition=myBorderVector[i]->getCenter(); i++; if (i>=(int)myBorderVector.size()) i=0; (*u).first->attack(chokePosition); (*u).second.mode = DefenseData::Moving; } } } */ /* //Àû ÃÊÅ©Æ÷ÀÎÆ®Å×½ºÆ® if (enemyBorder!=borderManager->getEnemyBorder()) { enemyBorder=borderManager->getEnemyBorder(); enemyBorderVector.clear(); for(std::set<BWTA::Chokepoint*>::iterator i=enemyBorder.begin();i!=enemyBorder.end();i++) enemyBorderVector.push_back(*i); //borderUpdated=true; } //Order all units to choke int i=0; if (!enemyBorder.empty()) { for (std::map<BWAPI::Unit*,DefenseData>::iterator u = defenders.begin(); u != defenders.end(); u++) { BWAPI::Position chokePosition2=enemyBorderVector[i]->getCenter(); i++; if (i>=(int)myBorderVector.size()) i=0; // (*u).first->attackMove(chokePosition); // (*u).second.mode = DefenseData::Moving; } } */ ////////////////// //ÇÁ·ÎÅ佺À̸é if((Broodwar->enemy()->getRace() == Races::Protoss || Broodwar->enemy()->getRace() == Races::Zerg || Broodwar->enemy()->getRace() == Races::Terran) && very_early_rush == false) //chc¼öÁ¤ { round = (int)myBorderVector.size() - 1; if (!myBorder.empty()) { for (std::map<BWAPI::Unit*,DefenseData>::iterator u = defenders.begin(); u != defenders.end(); u++) { if (u->first->isIdle()) { u->second.mode = DefenseData::Idle; } if (u->second.mode == DefenseData::Idle || borderUpdated) { BWAPI::Position chokePosition=myBorderVector[round]->getCenter(); round--; if (round < 0) round = (int)myBorderVector.size() - 1; //wait to the 2/3 between your current position and the center of the choke to protect int borderBasesSize = (int)borderBases.size(); BWAPI::Position lastBase = borderBases[borderBasesSize - round - 1]->getBaseLocation()->getPosition(); int x_wait = chokePosition.x() - lastBase.x(); int y_wait = chokePosition.y() - lastBase.y(); x_wait = (x_wait / 4) * 3; y_wait = (y_wait / 4) * 3; x_wait += lastBase.x(); y_wait += lastBase.y(); BWAPI::Position waitPosition(x_wait, y_wait); (*u).first->attack(waitPosition); (*u).second.mode = DefenseData::Moving; } if (u->first->isUnderAttack()) { std::set<BWAPI::Unit *> backup = this->getIdleDefenders(); for each (BWAPI::Unit *bck in backup) { bck->attack(u->first->getPosition()); defenders[bck].mode = DefenseData::Defending; } } } } } // round = (int)myBorderVector.size() - 1; else { int i=0; if (!myBorder.empty()) { for (std::map<BWAPI::Unit*,DefenseData>::iterator u = defenders.begin(); u != defenders.end(); u++) { if (u->first->isIdle()) { u->second.mode = DefenseData::Idle; } if (u->second.mode == DefenseData::Idle || borderUpdated) { BWAPI::Position chokePosition=myBorderVector[i]->getCenter(); i++; if (i>=(int)myBorderVector.size()) i=0; (*u).first->attack(chokePosition); (*u).second.mode = DefenseData::Moving; } if (u->first->isUnderAttack()) { std::set<BWAPI::Unit *> backup = this->getIdleDefenders(); for each (BWAPI::Unit *bck in backup) { bck->attack(u->first->getPosition()); defenders[bck].mode = DefenseData::Defending; } } } } } } } std::string DefenseManager::getName() const { return "Defense Manager"; } std::string DefenseManager::getShortName() const { return "Def"; }
chc2212/Xelnaga-Starcraft-game-AI-bot-AIIDE2014
src/src/DefenseManager.cpp
C++
gpl-3.0
9,063
<?php namespace OCAX\Backup; use Symfony\Component\HttpKernel\Bundle\Bundle; class BackupBundle extends Bundle { }
omgslinux/oc2
src/OCAX/Backup/BackupBundle.php
PHP
gpl-3.0
118
/* libSDL2pp - C++11 bindings/wrapper for SDL2 Copyright (C) 2015 Dmitry Marakasov <amdmi3@amdmi3.ru> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_mixer.h> #include <SDL2pp/SDL.hh> #include <SDL2pp/SDLMixer.hh> #include <SDL2pp/Mixer.hh> #include <SDL2pp/Chunk.hh> using namespace SDL2pp; int main(int, char*[]) try { SDL sdl(SDL_INIT_AUDIO); SDLMixer mixerlib(MIX_INIT_OGG); Mixer mixer(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096); Chunk sound(TESTDATA_DIR "/test.ogg"); mixer.SetChannelFinishedHandler([](int channel){ std::cerr << "Channel " << channel << " finished playback" << std::endl; }); int chan; // Fade in chan = mixer.FadeInChannel(-1, sound, 0, 1000); std::cerr << "Fading sound in on channel " << chan << "\n"; SDL_Delay(2000); // Mix 3 sounds chan = mixer.PlayChannel(-1, sound); std::cerr << "Playing sound on channel " << chan << "\n"; SDL_Delay(250); chan = mixer.PlayChannel(-1, sound); std::cerr << "Playing sound on channel " << chan << "\n"; SDL_Delay(250); chan = mixer.PlayChannel(-1, sound); std::cerr << "Playing sound on channel " << chan << "\n"; SDL_Delay(2000); // Fade out chan = mixer.PlayChannel(-1, sound); std::cerr << "Fading out sound on channel " << chan << "\n"; mixer.FadeOutChannel(chan, 2000); SDL_Delay(2000); return 0; } catch (std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; }
manuporto/megaman
extern/libSDL2pp/examples/mixer.cc
C++
gpl-3.0
2,304
/* * Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.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 <http://www.gnu.org/licenses/>. */ #include "ScriptPCH.h" #include "ruby_sanctum.h" enum Texts { SAY_AGGRO = 0, // You will sssuffer for this intrusion! (17528) SAY_CONFLAGRATION = 1, // Burn in the master's flame! (17532) EMOTE_ENRAGED = 2, // %s becomes enraged! SAY_KILL = 3, // Halion will be pleased. (17530) - As it should be.... (17529) }; enum Spells { SPELL_CONFLAGRATION = 74452, SPELL_FLAME_BEACON = 74453, SPELL_CONFLAGRATION_2 = 74454, // Unknown dummy effect SPELL_ENRAGE = 78722, SPELL_FLAME_BREATH = 74403, }; enum Events { EVENT_ENRAGE = 1, EVENT_FLIGHT = 2, EVENT_FLAME_BREATH = 3, EVENT_CONFLAGRATION = 4, // Event group EVENT_GROUP_LAND_PHASE = 1, }; enum MovementPoints { POINT_FLIGHT = 1, POINT_LAND = 2, }; enum Misc { SOUND_ID_DEATH = 17531, }; Position const SavianaRagefireFlyPos = {3155.51f, 683.844f, 95.20f, 4.69f}; Position const SavianaRagefireLandPos = {3151.07f, 636.443f, 79.54f, 4.69f}; class boss_saviana_ragefire : public CreatureScript { public: boss_saviana_ragefire() : CreatureScript("boss_saviana_ragefire") { } struct boss_saviana_ragefireAI : public BossAI { boss_saviana_ragefireAI(Creature* creature) : BossAI(creature, DATA_SAVIANA_RAGEFIRE) { } void Reset() { _Reset(); me->SetReactState(REACT_AGGRESSIVE); } void EnterCombat(Unit* /*who*/) { _EnterCombat(); Talk(SAY_AGGRO); events.Reset(); events.ScheduleEvent(EVENT_ENRAGE, 20000, EVENT_GROUP_LAND_PHASE); events.ScheduleEvent(EVENT_FLAME_BREATH, 14000, EVENT_GROUP_LAND_PHASE); events.ScheduleEvent(EVENT_FLIGHT, 60000); } void JustDied(Unit* /*killer*/) { _JustDied(); me->PlayDirectSound(SOUND_ID_DEATH); } void MovementInform(uint32 type, uint32 point) { if (type != POINT_MOTION_TYPE) return; switch (point) { case POINT_FLIGHT: events.ScheduleEvent(EVENT_CONFLAGRATION, 1000); Talk(SAY_CONFLAGRATION); break; case POINT_LAND: me->SetFlying(false); me->SetLevitate(false); me->SetReactState(REACT_AGGRESSIVE); if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE) me->GetMotionMaster()->MovementExpired(); DoStartMovement(me->getVictim()); break; default: break; } } void JustReachedHome() { _JustReachedHome(); me->SetFlying(false); me->SetLevitate(false); } void KilledUnit(Unit* victim) { if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_KILL); } void UpdateAI(uint32 const diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_FLIGHT: { me->SetFlying(true); me->SetLevitate(true); me->SetReactState(REACT_PASSIVE); me->GetMotionMaster()->MovePoint(POINT_FLIGHT, SavianaRagefireFlyPos); events.ScheduleEvent(EVENT_FLIGHT, 50000); events.DelayEvents(12500, EVENT_GROUP_LAND_PHASE); break; } case EVENT_CONFLAGRATION: DoCast(me, SPELL_CONFLAGRATION, true); break; case EVENT_ENRAGE: DoCast(me, SPELL_ENRAGE); Talk(EMOTE_ENRAGED); events.ScheduleEvent(EVENT_ENRAGE, urand(15000, 20000), EVENT_GROUP_LAND_PHASE); break; case EVENT_FLAME_BREATH: DoCastVictim(SPELL_FLAME_BREATH); events.ScheduleEvent(EVENT_FLAME_BREATH, urand(20000, 30000), EVENT_GROUP_LAND_PHASE); break; default: break; } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return GetRubySanctumAI<boss_saviana_ragefireAI>(creature); } }; class ConflagrationTargetSelector { public: ConflagrationTargetSelector() { } bool operator()(Unit* unit) { return unit->GetTypeId() != TYPEID_PLAYER; } }; class spell_saviana_conflagration_init : public SpellScriptLoader { public: spell_saviana_conflagration_init() : SpellScriptLoader("spell_saviana_conflagration_init") { } class spell_saviana_conflagration_init_SpellScript : public SpellScript { PrepareSpellScript(spell_saviana_conflagration_init_SpellScript); void FilterTargets(std::list<Unit*>& unitList) { unitList.remove_if (ConflagrationTargetSelector()); uint8 maxSize = uint8(GetCaster()->GetMap()->GetSpawnMode() & 1 ? 6 : 3); if (unitList.size() > maxSize) Trinity::RandomResizeList(unitList, maxSize); } void HandleDummy(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); GetCaster()->CastSpell(GetHitUnit(), SPELL_FLAME_BEACON, true); GetCaster()->CastSpell(GetHitUnit(), SPELL_CONFLAGRATION_2, false); } void Register() { OnUnitTargetSelect += SpellUnitTargetFn(spell_saviana_conflagration_init_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnEffectHitTarget += SpellEffectFn(spell_saviana_conflagration_init_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_saviana_conflagration_init_SpellScript(); } }; class spell_saviana_conflagration_throwback : public SpellScriptLoader { public: spell_saviana_conflagration_throwback() : SpellScriptLoader("spell_saviana_conflagration_throwback") { } class spell_saviana_conflagration_throwback_SpellScript : public SpellScript { PrepareSpellScript(spell_saviana_conflagration_throwback_SpellScript); void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); GetHitUnit()->CastSpell(GetCaster(), uint32(GetEffectValue()), true); GetHitUnit()->GetMotionMaster()->MovePoint(POINT_LAND, SavianaRagefireLandPos); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_saviana_conflagration_throwback_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_saviana_conflagration_throwback_SpellScript(); } }; void AddSC_boss_saviana_ragefire() { new boss_saviana_ragefire(); new spell_saviana_conflagration_init(); new spell_saviana_conflagration_throwback(); }
Zapuss/ZapekFapeCore
src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp
C++
gpl-3.0
8,541
/* * SOS * Copyright (C) 2016 zDuo (Adithya J, Vazbloke) * * 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.zduo.sos.activity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.widget.TextView; import android.widget.Toast; import com.zduo.sos.R; import com.zduo.sos.db.HB1ACReading; import com.zduo.sos.presenter.AddA1CPresenter; import com.zduo.sos.tools.FormatDateTime; import java.util.Calendar; public class AddA1CActivity extends AddReadingActivity { private TextView readingTextView; private TextView unitTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_hb1ac); Toolbar toolbar = (Toolbar) findViewById(R.id.activity_main_toolbar); if (toolbar != null) { setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setElevation(2); } this.retrieveExtra(); AddA1CPresenter presenter = new AddA1CPresenter(this); setPresenter(presenter); presenter.setReadingTimeNow(); readingTextView = (TextView) findViewById(R.id.hb1ac_add_value); unitTextView = (TextView) findViewById(R.id.hb1ac_unit); this.createDateTimeViewAndListener(); this.createFANViewAndListener(); if (!"percentage".equals(presenter.getA1CUnitMeasuerement())) { unitTextView.setText(getString(R.string.mmol_mol)); } // If an id is passed, open the activity in edit mode FormatDateTime formatDateTime = new FormatDateTime(getApplicationContext()); if (this.isEditing()) { setTitle(R.string.title_activity_add_hb1ac_edit); HB1ACReading readingToEdit = presenter.getHB1ACReadingById(getEditId()); readingTextView.setText(readingToEdit.getReading() + ""); Calendar cal = Calendar.getInstance(); cal.setTime(readingToEdit.getCreated()); this.getAddDateTextView().setText(formatDateTime.getDate(cal)); this.getAddTimeTextView().setText(formatDateTime.getTime(cal)); presenter.updateReadingSplitDateTime(readingToEdit.getCreated()); } else { this.getAddDateTextView().setText(formatDateTime.getCurrentDate()); this.getAddTimeTextView().setText(formatDateTime.getCurrentTime()); } } @Override protected void dialogOnAddButtonPressed() { AddA1CPresenter presenter = (AddA1CPresenter) getPresenter(); if (this.isEditing()) { presenter.dialogOnAddButtonPressed(this.getAddTimeTextView().getText().toString(), this.getAddDateTextView().getText().toString(), readingTextView.getText().toString(), this.getEditId()); } else { presenter.dialogOnAddButtonPressed(this.getAddTimeTextView().getText().toString(), this.getAddDateTextView().getText().toString(), readingTextView.getText().toString()); } } public void showErrorMessage() { Toast.makeText(getApplicationContext(), getString(R.string.dialog_error2), Toast.LENGTH_SHORT).show(); } }
adithya321/SOS-The-Healthcare-Companion
app/src/main/java/com/zduo/sos/activity/AddA1CActivity.java
Java
gpl-3.0
3,876
<header> <!--Navigation--> <nav id="menu" class="navbar container"> <div class="navbar-header"> <button type="button" class="btn btn-navbar navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"><i class="fa fa-bars"></i></button> <a class="navbar-brand" href="#"> <div class="logo"><span>Newspaper</span></div> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li><a href="index.html">Home</a></li> <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Login <i class="fa fa-arrow-circle-o-down"></i></a> <div class="dropdown-menu"> <div class="dropdown-inner"> <ul class="list-unstyled"> <li><a href="archive.html">Text 101</a></li> <li><a href="archive.html">Text 102</a></li> </ul> </div> </div> </li> <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Video <i class="fa fa-arrow-circle-o-down"></i></a> <div class="dropdown-menu"> <div class="dropdown-inner"> <ul class="list-unstyled"> <li><a href="archive.html">Text 201</a></li> <li><a href="archive.html">Text 202</a></li> <li><a href="archive.html">Text 203</a></li> <li><a href="archive.html">Text 204</a></li> <li><a href="archive.html">Text 205</a></li> </ul> </div> </div> </li> <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Category <i class="fa fa-arrow-circle-o-down"></i></a> <div class="dropdown-menu" style="margin-left: -203.625px;"> <div class="dropdown-inner"> <ul class="list-unstyled"> <li><a href="archive.html">Text 301</a></li> <li><a href="archive.html">Text 302</a></li> <li><a href="archive.html">Text 303</a></li> <li><a href="archive.html">Text 304</a></li> <li><a href="archive.html">Text 305</a></li> </ul> <ul class="list-unstyled"> <li><a href="archive.html">Text 306</a></li> <li><a href="archive.html">Text 307</a></li> <li><a href="archive.html">Text 308</a></li> <li><a href="archive.html">Text 309</a></li> <li><a href="archive.html">Text 310</a></li> </ul> <ul class="list-unstyled"> <li><a href="archive.html">Text 311</a></li> <li><a href="archive.html">Text 312</a></li> <li><a href="archive.html#">Text 313</a></li> <li><a href="archive.html#">Text 314</a></li> <li><a href="archive.html">Text 315</a></li> </ul> </div> </div> </li> <li><a href="archive.html"><i class="fa fa-cubes"></i> Blocks</a></li> <li><a href="contact.html"><i class="fa fa-envelope"></i> Contact</a></li> </ul> <ul class="list-inline navbar-right top-social"> <li><a href="#"><i class="fa fa-facebook"></i></a></li> <li><a href="#"><i class="fa fa-twitter"></i></a></li> <li><a href="#"><i class="fa fa-pinterest"></i></a></li> <li><a href="#"><i class="fa fa-google-plus-square"></i></a></li> <li><a href="#"><i class="fa fa-youtube"></i></a></li> </ul> </div> </nav> </header>
normeno/laravel-blog
resources/views/layouts/partials/frontendhead.blade.php
PHP
gpl-3.0
4,423
/* * _____ _ _ _____ _ * | __ \| | | | / ____| | | * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| * | | * |_| * PlotSquared plot management system for Minecraft * Copyright (C) 2014 - 2022 IntellectualSites * * 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/>. */ package com.plotsquared.core.plot.flag.implementations; import com.plotsquared.core.configuration.caption.TranslatableCaption; import com.plotsquared.core.plot.flag.FlagParseException; import com.plotsquared.core.plot.flag.types.ListFlag; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.Arrays; import java.util.Collections; import java.util.List; public class BlockedCmdsFlag extends ListFlag<String, BlockedCmdsFlag> { public static final BlockedCmdsFlag BLOCKED_CMDS_FLAG_NONE = new BlockedCmdsFlag(Collections.emptyList()); protected BlockedCmdsFlag(List<String> valueList) { super(valueList, TranslatableCaption.of("flags.flag_category_string_list"), TranslatableCaption.of("flags.flag_description_blocked_cmds") ); } @Override public BlockedCmdsFlag parse(@NonNull String input) throws FlagParseException { return flagOf(Arrays.asList(input.split(","))); } @Override public String getExample() { return "gamemode survival, spawn"; } @Override protected BlockedCmdsFlag flagOf(@NonNull List<String> value) { return new BlockedCmdsFlag(value); } }
IntellectualSites/PlotSquared
Core/src/main/java/com/plotsquared/core/plot/flag/implementations/BlockedCmdsFlag.java
Java
gpl-3.0
2,524
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Linq; using Microsoft.VisualBasic.FileIO; using Telerik.WinControls.UI; namespace StockControl { public partial class Types : Telerik.WinControls.UI.RadRibbonForm { public Types() { InitializeComponent(); } //private int RowView = 50; //private int ColView = 10; DataTable dt = new DataTable(); private void radMenuItem2_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; HistoryView hw = new HistoryView(this.Name); this.Cursor = Cursors.Default; hw.ShowDialog(); } private void radRibbonBar1_Click(object sender, EventArgs e) { } private void GETDTRow() { dt.Columns.Add(new DataColumn("GroupCode", typeof(string))); dt.Columns.Add(new DataColumn("TypeCode", typeof(string))); dt.Columns.Add(new DataColumn("TypeDetail", typeof(string))); dt.Columns.Add(new DataColumn("TypeActive", typeof(bool))); } private void Unit_Load(object sender, EventArgs e) { RMenu3.Click += RMenu3_Click; RMenu4.Click += RMenu4_Click; RMenu5.Click += RMenu5_Click; RMenu6.Click += RMenu6_Click; radGridView1.ReadOnly = true; radGridView1.AutoGenerateColumns = false; GETDTRow(); DataLoad(); LoadDefualt(); } private void RMenu6_Click(object sender, EventArgs e) { DeleteUnit(); DataLoad(); } private void RMenu5_Click(object sender, EventArgs e) { EditClick(); } private void RMenu4_Click(object sender, EventArgs e) { ViewClick(); } private void RMenu3_Click(object sender, EventArgs e) { NewClick(); } private void LoadDefualt() { try { using (DataClasses1DataContext db = new DataClasses1DataContext()) { var gt = (from ix in db.tb_GroupTypes where ix.GroupActive == true select ix).ToList(); GridViewComboBoxColumn comboBoxColumn = this.radGridView1.Columns["GroupCode"] as GridViewComboBoxColumn; comboBoxColumn.DisplayMember = "GroupCode"; comboBoxColumn.ValueMember = "GroupCode"; comboBoxColumn.DataSource = gt; //comboBoxColumn.DataSource= new string[] { "INSERT","Mr.", "Mrs.", "Dr.", "Ms." }; //GridViewComboBoxColumn lookUpColumn = new GridViewComboBoxColumn(); //lookUpColumn.FieldName = "GroupCode1"; //lookUpColumn.Name = "GroupCode1"; //lookUpColumn.HeaderText = "GroupCode"; //lookUpColumn.DataSource = new string[] { "Mr.", "Mrs.", "Dr.", "Ms." }; //lookUpColumn.Width = 100; //lookUpColumn.IsVisible = true; //this.radGridView1.Columns.Add(lookUpColumn); } }catch(Exception ex) { MessageBox.Show(ex.Message); dbClss.AddError("เพิ่มปรเภท", ex.Message, this.Name); } } private void DataLoad() { //dt.Rows.Clear(); using (DataClasses1DataContext db = new DataClasses1DataContext()) { //dt = ClassLib.Classlib.LINQToDataTable(db.tb_Units.ToList()); radGridView1.DataSource = db.tb_Types.ToList(); int ck = 0; foreach(var x in radGridView1.Rows) { x.Cells["dgvCodeTemp"].Value = x.Cells["GroupCode"].Value.ToString(); x.Cells["dgvCodeTemp2"].Value = x.Cells["TypeCode"].Value.ToString(); x.Cells["dgvOldDetail"].Value= x.Cells["TypeDetail"].Value.ToString(); x.Cells["GroupCode"].ReadOnly = true; x.Cells["TypeCode"].ReadOnly = true; x.Cells["GroupCode"].Style.ForeColor = Color.MidnightBlue; x.Cells["TypeCode"].Style.ForeColor = Color.MidnightBlue; if (row >= 0 && row == ck) { x.ViewInfo.CurrentRow = x; } ck += 1; } } // radGridView1.DataSource = dt; } private bool CheckDuplicate(string code,string Typecode) { bool ck = false; using (DataClasses1DataContext db = new DataClasses1DataContext()) { int i = (from ix in db.tb_Types where ix.GroupCode == code && ix.TypeCode==Typecode select ix).Count(); if (i > 0) ck = false; else ck = true; } return ck; } private bool AddUnit() { bool ck = false; int C = 0; try { radGridView1.EndEdit(); using (DataClasses1DataContext db = new DataClasses1DataContext()) { foreach (var g in radGridView1.Rows) { if (!Convert.ToString(g.Cells["GroupCode"].Value).Equals("") && !Convert.ToString(g.Cells["TypeCode"].Value).Equals("")) { if (Convert.ToString(g.Cells["dgvC"].Value).Equals("T")) { if (Convert.ToString(g.Cells["dgvCodeTemp"].Value).Equals("") && Convert.ToString(g.Cells["dgvCodeTemp2"].Value).Equals("") ) { // MessageBox.Show("11"); tb_Type gy = new tb_Type(); gy.GroupCode = Convert.ToString(g.Cells["GroupCode"].Value); gy.TypeCode= Convert.ToString(g.Cells["TypeCode"].Value); gy.TypeActive = Convert.ToBoolean(g.Cells["TypeActive"].Value); gy.TypeDetail= Convert.ToString(g.Cells["TypeDetail"].Value); db.tb_Types.InsertOnSubmit(gy); db.SubmitChanges(); C += 1; dbClss.AddHistory(this.Name, "เพิ่มประเภท", "Insert Type Code [" + gy.TypeCode+ "]",""); } else { var unit1 = (from ix in db.tb_Types where ix.GroupCode == Convert.ToString(g.Cells["dgvCodeTemp"].Value) && ix.TypeCode == Convert.ToString(g.Cells["dgvCodeTemp2"].Value) select ix).First(); unit1.TypeDetail = Convert.ToString(g.Cells["TypeDetail"].Value); unit1.TypeActive = Convert.ToBoolean(g.Cells["TypeActive"].Value); C += 1; db.SubmitChanges(); dbClss.AddHistory(this.Name, "แก้ไข", "Update Type Code [" + unit1.TypeCode+ "]",""); } } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); dbClss.AddError("เพิ่มปรเภท", ex.Message, this.Name); } if (C > 0) MessageBox.Show("บันทึกสำเร็จ!"); return ck; } private bool DeleteUnit() { bool ck = false; int C = 0; try { if (row >= 0) { string CodeDelete = Convert.ToString(radGridView1.Rows[row].Cells["GroupCode"].Value); string CodeDelete2 = Convert.ToString(radGridView1.Rows[row].Cells["TypeCode"].Value); string CodeTemp = Convert.ToString(radGridView1.Rows[row].Cells["dgvCodeTemp"].Value); string CodeTemp2 = Convert.ToString(radGridView1.Rows[row].Cells["dgvCodeTemp2"].Value); radGridView1.EndEdit(); if (MessageBox.Show("ต้องการลบรายการ ( "+ CodeDelete+" ) หรือไม่ ?", "ลบรายการ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { using (DataClasses1DataContext db = new DataClasses1DataContext()) { if (!CodeDelete.Equals("") && !CodeDelete2.Equals("")) { if (!CodeTemp.Equals("") && !CodeTemp2.Equals("")) { var unit1 = (from ix in db.tb_Types where ix.GroupCode == CodeDelete && ix.TypeCode == CodeDelete2 select ix).ToList(); foreach (var d in unit1) { db.tb_Types.DeleteOnSubmit(d); dbClss.AddHistory(this.Name, "ลบประเภท", "Delete Type Code ["+d.TypeCode+"]",""); } C += 1; db.SubmitChanges(); } } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); dbClss.AddError("ลบประเภท", ex.Message, this.Name); } if (C > 0) { row = row - 1; MessageBox.Show("ลบรายการ สำเร็จ!"); } return ck; } private void btnCancel_Click(object sender, EventArgs e) { DataLoad(); } private void NewClick() { radGridView1.ReadOnly = false; radGridView1.AllowAddNewRow = false; btnEdit.Enabled = false; btnView.Enabled = true; radGridView1.Rows.AddNew(); } private void EditClick() { radGridView1.ReadOnly = false; btnEdit.Enabled = false; btnView.Enabled = true; radGridView1.AllowAddNewRow = false; } private void ViewClick() { radGridView1.ReadOnly = true; btnView.Enabled = false; btnEdit.Enabled = true; radGridView1.AllowAddNewRow = false; DataLoad(); } private void btnNew_Click(object sender, EventArgs e) { NewClick(); } private void btnView_Click(object sender, EventArgs e) { ViewClick(); } private void btnEdit_Click(object sender, EventArgs e) { EditClick(); } private void btnSave_Click(object sender, EventArgs e) { if(MessageBox.Show("ต้องการบันทึก ?","บันทึก",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.Yes) { AddUnit(); DataLoad(); } } private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e) { try { radGridView1.Rows[e.RowIndex].Cells["dgvC"].Value = "T"; string check1 = Convert.ToString(radGridView1.Rows[e.RowIndex].Cells["GroupCode"].Value); string check2 = Convert.ToString(radGridView1.Rows[e.RowIndex].Cells["TypeCode"].Value); string TM= Convert.ToString(radGridView1.Rows[e.RowIndex].Cells["dgvCodeTemp"].Value); if (!check1.Trim().Equals("") && !check2.Trim().Equals("") && TM.Equals("")) { if (!CheckDuplicate(check1.Trim(), check2.Trim())) { MessageBox.Show("ข้อมูล รหัสปรเภท ซ้ำ"); radGridView1.Rows[e.RowIndex].Cells["TypeCode"].Value = ""; radGridView1.Rows[e.RowIndex].Cells["GroupCode"].IsSelected = true; } } } catch { } } private void Unit_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { // MessageBox.Show(e.KeyCode.ToString()); } private void radGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { // MessageBox.Show(e.KeyCode.ToString()); if(e.KeyData==(Keys.Control|Keys.S)) { if (MessageBox.Show("ต้องการบันทึก ?", "บันทึก", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { AddUnit(); DataLoad(); } } else if (e.KeyData == (Keys.Control | Keys.N)) { if (MessageBox.Show("ต้องการสร้างใหม่ ?", "สร้างใหม่", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { NewClick(); } } } private void btnDelete_Click(object sender, EventArgs e) { DeleteUnit(); DataLoad(); } int row = -1; private void radGridView1_CellClick(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e) { row = e.RowIndex; } private void btnExport_Click(object sender, EventArgs e) { //dbClss.ExportGridCSV(radGridView1); dbClss.ExportGridXlSX(radGridView1); } private void btnImport_Click(object sender, EventArgs e) { OpenFileDialog op = new OpenFileDialog(); op.Filter = "Spread Sheet files (*.csv)|*.csv|All files (*.csv)|*.csv"; if (op.ShowDialog() == DialogResult.OK) { using (TextFieldParser parser = new TextFieldParser(op.FileName)) { dt.Rows.Clear(); parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(","); int a = 0; int c = 0; while (!parser.EndOfData) { //Processing row a += 1; DataRow rd = dt.NewRow(); // MessageBox.Show(a.ToString()); string[] fields = parser.ReadFields(); c = 0; foreach (string field in fields) { c += 1; //TODO: Process field //MessageBox.Show(field); if (a>1) { if(c==1) rd["GroupCode"] = Convert.ToString(field); else if(c==2) rd["Typecode"] = Convert.ToString(field); else if(c==3) rd["TypeDetail"] = Convert.ToString(field); else if (c == 4) rd["TypeActive"] = Convert.ToBoolean(field); } else { if (c == 1) rd["GroupCode"] = ""; else if (c == 2) rd["Typecode"] = ""; else if (c == 3) rd["TypeDetail"] = ""; else if (c == 4) rd["TypeActive"] = false; } // //rd[""] = ""; //rd[""] } dt.Rows.Add(rd); } } if(dt.Rows.Count>0) { dbClss.AddHistory(this.Name, "Import [Type]", "Import file CSV in to System", ""); ImportData(); MessageBox.Show("Import Completed."); DataLoad(); } } } private void ImportData() { try { using (DataClasses1DataContext db = new DataClasses1DataContext()) { foreach (DataRow rd in dt.Rows) { if (!rd["GroupCode"].ToString().Equals("") && !rd["TypeCode"].ToString().Equals("")) { var x = (from ix in db.tb_Types where ix.GroupCode.ToLower().Trim() == rd["GroupCode"].ToString().ToLower().Trim() && ix.TypeCode.ToLower().Trim() == rd["TypeCode"].ToString().ToLower().Trim() select ix).FirstOrDefault(); if(x==null) { tb_Type ts = new tb_Type(); ts.GroupCode= Convert.ToString(rd["GroupCode"].ToString()); ts.TypeCode = Convert.ToString(rd["TypeCode"].ToString()); ts.TypeDetail= Convert.ToString(rd["TypeDetail"].ToString()); ts.TypeActive = Convert.ToBoolean(rd["TypeActive"].ToString()); db.tb_Types.InsertOnSubmit(ts); db.SubmitChanges(); } else { x.TypeDetail= Convert.ToString(rd["TypeDetail"].ToString()); x.TypeActive = Convert.ToBoolean(rd["TypeActive"].ToString()); db.SubmitChanges(); } } } } } catch(Exception ex) { MessageBox.Show(ex.Message); dbClss.AddError("InportData", ex.Message, this.Name); } } private void btnFilter1_Click(object sender, EventArgs e) { radGridView1.EnableFiltering = true; } private void btnUnfilter1_Click(object sender, EventArgs e) { radGridView1.EnableFiltering = false; } private void radMenuItem1_Click(object sender, EventArgs e) { this.Close(); } private void radGridView1_CellFormatting(object sender, CellFormattingEventArgs e) { if (e.CellElement.ColumnInfo.HeaderText == "รหัสประเภทกลุ่ม" ) { if (e.CellElement.RowInfo.Cells["GroupCode"].Value != null) { if (!e.CellElement.RowInfo.Cells["GroupCode"].Value.Equals("")) { e.CellElement.DrawFill = true; // e.CellElement.ForeColor = Color.Blue; e.CellElement.NumberOfColors = 1; e.CellElement.BackColor = Color.WhiteSmoke; } //else //{ // e.CellElement.DrawFill = true; // //e.CellElement.ForeColor = Color.Yellow; // e.CellElement.NumberOfColors = 1; // e.CellElement.BackColor = Color.WhiteSmoke; //} } } } } }
Tay-nakub/Stockcontrol
StockControl/Process/Types.cs
C#
gpl-3.0
21,576
/* * MicroJIAC - A Lightweight Agent Framework * This file is part of Example: PingPong. * * Copyright (c) 2007-2011 DAI-Labor, Technische Universität Berlin * * This library includes software developed at DAI-Labor, Technische * Universität Berlin (http://www.dai-labor.de) * * This library 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 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ /* * $Id$ */ package de.jiac.micro.examples.pingpong; import de.jiac.micro.internal.ApplicationLauncher; /** * @author Marcel Patzlaff * @version $Revision:$ */ public class PingNodeLauncher { public static void main(String[] args) { ApplicationLauncher.main(new String[] {"config.ping"}); } }
mcpat/microjiac-examples-public
pingpong/src/main/java/de/jiac/micro/examples/pingpong/PingNodeLauncher.java
Java
gpl-3.0
1,256
/* Copyright 2010-2012 Infracom & Eurotechnia (support@webcampak.com) This file is part of the Webcampak project. Webcampak 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. Webcampak is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 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 Webcampak. If not, see http://www.gnu.org/licenses/. */ console.log('Log: Load: Webcampak.controller.dashboard.SourceDiskUsage'); Ext.define('Webcampak.controller.dashboard.SourceDiskUsage', { extend: 'Ext.app.Controller', stores: [ 'dashboard.SourceDiskUsage', 'permissions.sources.Sources' ], models: [ 'dashboard.SourceDiskUsage' ], views: [ 'dashboard.sourcediskusage.SourceDiskUsageWindow', 'dashboard.sourcediskusage.SourceDiskUsage', 'dashboard.sourcediskusage.SourcesList' ], refs: [ {ref: 'sourcediskusagewindow', selector: 'sourcediskusagewindow', xtype: 'sourcediskusagewindow'}, {ref: 'sourcediskusage', selector: 'sourcediskusage', xtype: 'sourcediskusage'}, {ref: 'statssourceslist', selector: 'statssourceslist', xtype: 'statssourceslist'} ], onLaunch: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller onLaunch: function()'); /* //Show Files Graph window (stats about size of pictures per day) if(!this.getSourcediskusagewindow().isVisible()) { this.getSourcediskusagewindow().show(); console.log('Log: Controller->Menu: openPhotos - getSourcepicturefileswindow().show()'); //Load the sources store this.getPermissionsSourcesSourcesStore().on('load',this.loadGraphContent,this,{single:true}); this.getPermissionsSourcesSourcesStore().load(); } else { this.getSourcediskusagewindow().hide(); console.log('Log: Controller->Menu: openPhotos - getSourcepicturefileswindow().hide()'); } */ }, init: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller init: function()'); // Start listening for events on views this.control({ 'sourcediskusagewindow button[action=reload]': {click: this.reloadGraph}, 'sourcediskusagewindow button[action=save]': {click: this.saveGraph}, 'statssourceslist': {select: this.onSourceSelected}, 'sourcediskusagewindow combo[action=updateRange]': {select: this.onUpdateRange}, 'sourcediskusagewindow': {resize: this.windowResize} }); }, loadGraphContent: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: loadGraphContent: function()'); }, windowResize: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: windowResize: function()'); this.getSourcediskusage().axes.items[1].setTitle(Ext.getStore('permissions.sources.Sources').first().get('name')); Ext.getStore('dashboard.SourceDiskUsage').getProxy().setExtraParam('sourceid', Ext.getStore('permissions.sources.Sources').first().get('sourceid')); //Load the latest picture for the selected source this.getDashboardSourceDiskUsageStore().on('load',this.loadGraphContent,this,{single:true}); this.getDashboardSourceDiskUsageStore().load(); }, onUpdateRange: function(selModel, selection) { console.log('Log: Controller->Dashboard->SourceDiskUsage: onUpdateRange: function()'); console.log('Log: Controller->Dashboard->SourceDiskUsage: onUpdateRange: Selected range is:' + selection[0].get('name')); Ext.getStore('dashboard.SourceDiskUsage').getProxy().setExtraParam('range', selection[0].get('value')); //Load the latest picture for the selected source this.getDashboardSourceDiskUsageStore().on('load',this.loadGraphContent,this,{single:true}); this.getDashboardSourceDiskUsageStore().load(); }, onSourceSelected: function(selModel, selection) { console.log('Log: Controller->Dashboard->SourceDiskUsage: onSourceSelected: function()'); console.log('Log: Controller->Dashboard->SourceDiskUsage: onSourceSelected: Selected name is:' + selection[0].get('name')); console.log('Log: Controller->Dashboard->SourceDiskUsage: onSourceSelected: Selected Sourceid is:' + selection[0].get('sourceid')); Ext.getStore('dashboard.SourceDiskUsage').getProxy().setExtraParam('sourceid', selection[0].get('sourceid')); //Set Sourcename as the title // this.getSourcediskusagewindow().setTitle(i18n.gettext('Graph: Disk usage per source') + " (" + selection[0].get('name') + ")"); this.getSourcediskusage().axes.items[1].setTitle(selection[0].get('name')); //Load the latest picture for the selected source this.getDashboardSourceDiskUsageStore().on('load',this.loadGraphContent,this,{single:true}); this.getDashboardSourceDiskUsageStore().load(); }, reloadGraph: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller reloadGraph: function()'); this.getDashboardSourceDiskUsageStore().load(); }, saveGraph: function() { console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller saveGraph: function()'); currentChart = this.getSourcediskusage(); Ext.MessageBox.confirm(i18n.gettext('Confirm Download'), i18n.gettext('Would you like to download the chart as an image?'), function(choice){ if(choice == 'yes'){ currentChart.save({ type: 'image/png' }); } }); } });
Webcampak/v2.0
src/www/interface/dev/app/controller/dashboard/SourceDiskUsage.js
JavaScript
gpl-3.0
5,637
<?php /** * @auther Saurabh Chandra Patel * @link https://github.com/saurabhaec/PHPLogger/ for PHP Log report * @license https://github.com/saurabhaec/PHPLogger/blob/master/LICENSE GNU GENERAL PUBLIC LICENSE */ class PHPLogger implements \SplSubject { /** * [$name log file name ] * @var [type] */ private $filename; /** * [$observers description] * @var array */ private $observers = array(); /** * [$content description] * @var [type] */ private $content; /** * [$path description] * @var [type] */ private $path = '/var/log/'; /** * [__construct description] * @param [type] $name [description] */ public function __construct($path) { $this->filename = date('y-m-d') . '.log'; $this->path = $path; } public function __get($pro) { return $this->$pro; } /** * [__set description] * @param [string] $pro [description] * @param [string] $value [description] */ public function __set($pro, $value) { return $this->$pro = $value; } //add observer /** * [attach description] * @param \SplObserver $observer [description] * @return [null] [description] */ public function attach(\SplObserver $observer) { $this->observers[] = $observer; } //remove observer /** * [detach description] * @param \SplObserver $observer [description] * @return [null] [description] */ public function detach(\SplObserver $observer) { $key = array_search($observer, $this->observers, true); if ($key) { unset($this->observers[$key]); } } public function getContent() { return $this->content . " ({$this->filename})"; } //notify observers(or some of them) /** * [notify description] * @return [null] [description] */ public function notify() { foreach ($this->observers as $value) { $value->update($this); } } public function writeLog() { $this->notify(); } } class Reportlog implements SplObserver { private $action; /** * [__construct description] * @param $action [report identifiers] */ public function __construct($action) { $this->action = $action; } /** * [update description] * @param \SplSubject $subject [description] * @return [type] [description] */ public function update(\SplSubject $subject) { $msg = date('y-m-d H:i:s') . "\t" . $this->action . "\n"; $path = $subject->__get('path') . '' . $subject->__get('filename'); error_log($msg, 3, $path); } } ?>
saurabhaec/PHPLogger
PHPLogger.php
PHP
gpl-3.0
2,465
/* Copyright 2012, mokasin * * 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 database import ( "database/sql" "errors" "fmt" _ "github.com/mattn/go-sqlite3" "os" "time" ) var ( ErrNoOpenTransaction = errors.New("No open transaction.") ErrExistingTransaction = errors.New("There is an existing transaction.") ErrDatabaseExists = errors.New("Can't create new database. A database already exists.") ) type CreateTableFunc func(db *Database) error // A Result is a mapping from column name to its value. type Result map[string]interface{} type Database struct { Filename string db *sql.DB mtime int64 tx *sql.Tx // global transaction txOpen bool // flag true, when exists an open transaction fctables []CreateTableFunc newDB bool } // Creates a new Database struct and connects it to the database at filename. // Needs to be closed with method Close()! func NewDatabase(filename string) (*Database, error) { _, err := os.Stat(filename) newdatabase := os.IsNotExist(err) db, err := sql.Open("sqlite3", filename) if err != nil { return nil, err } datab := &Database{Filename: filename, db: db, newDB: newdatabase} // Make it nosync and disable the journal if _, err := db.Exec("PRAGMA synchronous=OFF"); err != nil { return nil, err } if _, err := db.Exec("PRAGMA journal_mode=OFF"); err != nil { return nil, err } //if _, err := db.Exec("PRAGMA case_sensitive_like=TRUE"); err != nil { // return nil, err //} return datab, nil } func (self *Database) Mtime() int64 { return self.mtime } // Closes the opened database. func (self *Database) Close() { self.db.Close() } // Creates the basic database structure. func (self *Database) CreateDatabase() error { if !self.newDB { return ErrDatabaseExists } if len(self.fctables) == 0 { return fmt.Errorf("Can't create database. " + "No functions to create the tables are registered.") } if err := self.BeginTransaction(); err != nil { return err } defer self.EndTransaction() for _, t := range self.fctables { err := t(self) if err != nil { return err } } return nil } // Add registers a new function to create a table. func (self *Database) Register(m CreateTableFunc) { self.fctables = append(self.fctables, m) } // BeginTransaction starts a new database transaction. func (self *Database) BeginTransaction() (err error) { if self.txOpen { return ErrExistingTransaction } self.tx, err = self.db.Begin() if err != nil { return err } self.txOpen = true // Updating mtime when something has changed self.mtime = time.Now().Unix() return nil } // EndTransaction closes a opened database transaction. func (self *Database) EndTransaction() error { if !self.txOpen { return ErrNoOpenTransaction } self.txOpen = false return self.tx.Commit() } // Execute just executes sql query in global transaction. func (self *Database) Execute(sql string, args ...interface{}) (res sql.Result, err error) { if !self.txOpen { err = self.BeginTransaction() if err != nil { return nil, err } defer self.EndTransaction() } res, err = self.tx.Exec(sql, args...) return res, err } // QueryDB queries the database with a given SQL-string and arguments args and // returns the result as a map from column name to its value. func (self *Database) Query(sql string, args ...interface{}) ([]Result, error) { if !self.txOpen { err := self.BeginTransaction() if err != nil { return nil, err } defer self.EndTransaction() } // do the actual query rows, err := self.tx.Query(sql, args...) if err != nil { return nil, err } defer rows.Close() // find out about the columns in the database columns, err := rows.Columns() if err != nil { return nil, err } // prepare result var result []Result // stupid trick, because rows.Scan will not take []interface as args col_vals := make([]interface{}, len(columns)) col_args := make([]interface{}, len(columns)) // initialize col_args for i := 0; i < len(columns); i++ { col_args[i] = &col_vals[i] } // read out columns and save them in a Result map for rows.Next() { if err := rows.Scan(col_args...); err != nil { return nil, err } res := make(Result) for i := 0; i < len(columns); i++ { res[columns[i]] = col_vals[i] } result = append(result, res) } return result, rows.Err() }
mokasin/musicrawler
lib/database/database.go
GO
gpl-3.0
4,976
# Tests of triangular lattices # # Copyright (C) 2017--2019 Simon Dobson # # This file is part of simplicial, simplicial topology in Python. # # Simplicial 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. # # Simplicial 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 Simplicial. If not, see <http://www.gnu.org/licenses/gpl.html>. import unittest import six from simplicial import * import math import numpy.random class TriangularLatticeTests(unittest.TestCase): def _simplexCounts( self, r, c ): """Check we have the right numbers of simplices.""" self._complex = TriangularLattice(r, c) ntriperr = 2 * (c - 1) + 1 ns = self._complex.numberOfSimplicesOfOrder() self.assertEqual(ns[0], r * c) if len(ns) > 1: self.assertEqual(ns[1], (r - 1) * (2 * c - 1) + (r - 2) * c) if len(ns) > 2: self.assertEqual(ns[2], (r - 2) * ntriperr) def testSimplest(self): """Test simplest triangular lattice.""" self._simplexCounts(2, 2) def testNextSimplest(self): """Test the next simplest lattice.""" self._simplexCounts(3, 3) def testEvenEven( self ): """Test a lattice with even rows and columns.""" self._simplexCounts(10, 10) def testEvenOdd( self ): """Test a lattice with even rows and odd columns.""" self._simplexCounts(10, 11) def testOddEven( self ): """Test a lattice with odd rows and even columns.""" self._simplexCounts(11, 10) def testOddOdd( self ): """Test a lattice with odd rows and columns.""" self._simplexCounts(11, 10) def testEuler( self ): """Test the Euler characteristic calculations.""" self._complex = TriangularLattice(20, 20) self.assertEqual(self._complex.eulerCharacteristic(), 1) def testRegularEmbedding( self ): """Test that the embedding is regular.""" self._complex = TriangularLattice(10, 10) e = TriangularLatticeEmbedding(self._complex, 11, 11) pos = e.positionsOf() eps = 0.0001 # all columns equidistant for i in range(10): for j in range(9): s1 = self._complex._indexOfVertex(i, j) s2 = self._complex._indexOfVertex(i, j + 1) self.assertTrue(pos[s2][0] - pos[s1][0] < (11.0 / 10) + eps) # all rows equidistant for i in range(9): for j in range(10): s1 = self._complex._indexOfVertex(i, j) s2 = self._complex._indexOfVertex(i + 1, j) self.assertTrue(pos[s2][1] - pos[s1][1] < (11.0 / 10) + eps) # odd rows are offset for i in range(9): for j in range(9): s1 = self._complex._indexOfVertex(i, j) s2 = self._complex._indexOfVertex(i + 1, j) if i % 2 == 0: self.assertTrue(pos[s2][0] > pos[s1][0]) else: self.assertTrue(pos[s2][0] < pos[s1][0]) def testPerturbedEmbedding( self ): """Test that we can perturb the embedding with explicit new positions.""" self._complex = TriangularLattice(10, 10) e = TriangularLatticeEmbedding(self._complex, 11, 11) ss = list(self._complex.simplicesOfOrder(0)) pos = e.positionsOf() # choose a random simplex i = int(numpy.random.random() * len(ss)) s = ss[i] # re-position simplex e.positionSimplex(s, [ 12, 13 ]) # make sure position is preserved pos1 = e.positionsOf() six.assertCountEqual(self, pos1[s], [ 12, 13 ])
simoninireland/simplicial
test/test_triangularlattice.py
Python
gpl-3.0
4,117
<?php // Exit if accessed directly if ( !defined('ABSPATH')) exit; /** * Main Widget Template * * * @file sidebar.php * @package Responsive * @author Emil Uzelac * @copyright 2003 - 2013 ThemeID * @license license.txt * @version Release: 1.0 * @filesource wp-content/themes/responsive/sidebar.php * @link http://codex.wordpress.org/Theme_Development#Widgets_.28sidebar.php.29 * @since available since Release 1.0 */ ?> <div id="widgets" class="grid col-300 fit"> <?php responsive_widgets(); // above widgets hook ?> <?php if (!dynamic_sidebar('bbpress')) : ?> <div class="widget-wrapper"> <div class="widget-title"><?php _e('In Archive', 'responsive'); ?></div> <ul> <?php wp_get_archives( array( 'type' => 'monthly' ) ); ?> </ul> </div><!-- end of .widget-wrapper --> <?php endif; //end of main-sidebar ?> <?php responsive_widgets_end(); // after widgets hook ?> </div><!-- end of #widgets -->
mhawksey/moocinabox
oocinabox/responsive-child-octel/sidebar-bbpress.php
PHP
gpl-3.0
1,109
var NAVTREEINDEX1 = { "var__init_8h.html#a0764b32f40bbe284b6ba2a1fee678d6c":[2,0,0,16,4], "var__init_8h.html#a2fd24bcbadb8b59c176dccc6f13250e9":[2,0,0,16,3], "var__init_8h.html#a3482785bd2a4c8b307f9e0b6f54e2c36":[2,0,0,16,8], "var__init_8h.html#a6b57f01d3c576db5368dd0efc2f435a4":[2,0,0,16,1], "var__init_8h.html#a78fa3957d73de49cb81d047857504218":[2,0,0,16,5], "var__init_8h.html#a8194731fdeea643e725e3a89d2f7ec59":[2,0,0,16,6], "var__init_8h.html#ab454541ae58bcf6555e8d723b1eb95e7":[2,0,0,16,7], "var__init_8h.html#abe06f96c5aeacdb02e4b66e34e609982":[2,0,0,16,2], "var__init_8h.html#ae86e3a2639bfd6cac9c94470ec2825c8":[2,0,0,16,9], "var__init_8h_source.html":[2,0,0,16] };
SimonItaly/duckhunt
doc/html/navtreeindex1.js
JavaScript
gpl-3.0
675
var a00572 = [ [ "Nrf_bootloader", "a00573.html", null ], [ "Nrf_dfu", "a00574.html", null ], [ "Nrf_dfu_transport", "a00575.html", null ], [ "Nrf_bootloader_util", "a00576.html", null ], [ "Ble_sdk_app_bootloader_main", "a00577.html", null ] ];
DroneBucket/Drone_Bucket_CrazyFlie2_NRF_Firmware
nrf51_sdk/Documentation/s120/html/a00572.js
JavaScript
gpl-3.0
265
package greymerk.roguelike.dungeon.segment; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import greymerk.roguelike.dungeon.IDungeonLevel; import greymerk.roguelike.theme.ITheme; import greymerk.roguelike.util.WeightedChoice; import greymerk.roguelike.util.WeightedRandomizer; import greymerk.roguelike.worldgen.Cardinal; import greymerk.roguelike.worldgen.Coord; import greymerk.roguelike.worldgen.IStair; import greymerk.roguelike.worldgen.IWorldEditor; public class SegmentGenerator implements ISegmentGenerator{ protected Segment arch; protected WeightedRandomizer<Segment> segments; public SegmentGenerator(){ this(Segment.ARCH); } public SegmentGenerator(Segment arch){ this.segments = new WeightedRandomizer<Segment>(); this.arch = arch; } public SegmentGenerator(SegmentGenerator toCopy){ this.arch = toCopy.arch; this.segments = new WeightedRandomizer<Segment>(toCopy.segments); } public SegmentGenerator(JsonObject json){ String archType = json.get("arch").getAsString(); arch = Segment.valueOf(archType); this.segments = new WeightedRandomizer<Segment>(); JsonArray segmentList = json.get("segments").getAsJsonArray(); for(JsonElement e : segmentList){ JsonObject segData = e.getAsJsonObject(); this.add(segData); } } public void add(JsonObject entry){ String segType = entry.get("type").getAsString(); Segment type = Segment.valueOf(segType); if(entry.has("arch")){ boolean a = entry.get("arch").getAsBoolean(); if(a) this.arch = type; return; } int weight = entry.has("weight") ? entry.get("weight").getAsInt() : 1; this.segments.add(new WeightedChoice<Segment>(type, weight)); } public void add(Segment toAdd, int weight){ this.segments.add(new WeightedChoice<Segment>(toAdd, weight)); } @Override public List<ISegment> genSegment(IWorldEditor editor, Random rand, IDungeonLevel level, Cardinal dir, Coord pos) { int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); List<ISegment> segs = new ArrayList<ISegment>(); for(Cardinal orth : Cardinal.orthogonal(dir)){ ISegment seg = pickSegment(editor, rand, level, dir, pos); if(seg == null) return segs; seg.generate(editor, rand, level, orth, level.getSettings().getTheme(), new Coord(pos)); segs.add(seg); } if(!level.hasNearbyNode(pos) && rand.nextInt(3) == 0) addSupport(editor, rand, level.getSettings().getTheme(), x, y, z); return segs; } private ISegment pickSegment(IWorldEditor editor, Random rand, IDungeonLevel level, Cardinal dir, Coord pos){ int x = pos.getX(); int z = pos.getZ(); if((dir == Cardinal.NORTH || dir == Cardinal.SOUTH) && z % 3 == 0){ if(z % 6 == 0) return Segment.getSegment(arch); return this.segments.isEmpty() ? Segment.getSegment(Segment.WALL) : Segment.getSegment(this.segments.get(rand)); } if((dir == Cardinal.WEST || dir == Cardinal.EAST) && x % 3 == 0){ if(x % 6 == 0) return Segment.getSegment(arch); return this.segments.isEmpty() ? Segment.getSegment(Segment.WALL) : Segment.getSegment(this.segments.get(rand)); } return null; } private void addSupport(IWorldEditor editor, Random rand, ITheme theme, int x, int y, int z){ if(!editor.isAirBlock(new Coord(x, y - 2, z))) return; editor.fillDown(rand, new Coord(x, y - 2, z), theme.getPrimary().getPillar()); IStair stair = theme.getPrimary().getStair(); stair.setOrientation(Cardinal.WEST, true); stair.set(editor, new Coord(x - 1, y - 2, z)); stair.setOrientation(Cardinal.EAST, true); stair.set(editor, new Coord(x + 1, y - 2, z)); stair.setOrientation(Cardinal.SOUTH, true); stair.set(editor, new Coord(x, y - 2, z + 1)); stair.setOrientation(Cardinal.NORTH, true); stair.set(editor, new Coord(x, y - 2, z - 1)); } public static SegmentGenerator getRandom(Random rand, int count) { SegmentGenerator segments = new SegmentGenerator(Segment.ARCH); for(int i = 0; i < count; ++i){ segments.add(Segment.getRandom(rand), 1); } return segments; } }
Greymerk/minecraft-roguelike
src/main/java/greymerk/roguelike/dungeon/segment/SegmentGenerator.java
Java
gpl-3.0
4,198
<?php /** * Belgian Police Web Platform - Signatures Component * * @copyright Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link https://github.com/belgianpolice/internet-platform */ use Nooku\Library; class SignaturesViewSignatureHtml extends SignaturesViewHtml { public function render() { //Get the article $signature = $this->getModel()->getData(); $category = $this->getCategory(); //Set the pathway $this->getObject('application')->getPathway()->addItem($category->title, $this->getTemplate()->getHelper('route')->category(array('row' => $category))); $this->getObject('application')->getPathway()->addItem($signature->title, ''); // Get the zone $this->zone = $this->getObject('com:police.model.zone')->id($this->getObject('application')->getCfg('site' ))->getRow(); //Get the attachments if ($signature->id && $signature->isAttachable()) { $this->attachments($signature->getAttachments()); } return parent::render(); } public function getCategory() { //Get the category $category = $this->getObject('com:signatures.model.categories') ->table('signatures') ->slug($this->getModel()->getState()->category) ->getRow(); return $category; } }
yiendos/snowsport
application/site/component/signatures/view/signature/html.php
PHP
gpl-3.0
1,434
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] #include "stdafx.h" #include <QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { Q_INIT_RESOURCE(application); QApplication app(argc, argv); app.setOrganizationName("Trolltech"); app.setApplicationName("Application Example"); MainWindow mainWin; mainWin.show(); return app.exec(); } //! [0]
austin98x/cross-platform-desktop-app
gui/qt-demo/main.cpp
C++
gpl-3.0
2,452
// Copyright 2015 The go-ethereum Authors // This file is part of go-ethereum. // // go-ethereum 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. // // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>. // +build !evmjit package vm import "fmt" func NewJitVm(env Environment) VirtualMachine { fmt.Printf("Warning! EVM JIT not enabled.\n") return New(env) }
tgerring/go-ethereum
core/vm/vm_jit_fake.go
GO
gpl-3.0
906
/* * Copyright (C) 2016 - 2017 Aurum * * Mystery 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. * * Mystery 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.aurum.mystery2.game; import com.aurum.mystery2.BitConverter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.aurum.mystery2.ByteBuffer; import com.aurum.mystery2.ByteOrder; import com.aurum.mystery2.Lists; public class DungeonPokemon implements Cloneable { // Entry fields public List<Entry> entries; // Other fields public int offset; // Static fields public static final int SIZE = 0x8; private static final byte[] NULL = new byte[SIZE]; public static class Entry implements Cloneable { public int species, level, probability; @Override public String toString() { return Lists.pokemon.get(species) + ": Lv. " + level + " (" + probability + ")"; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException ex) { return null; } } } @Override public Object clone() { try { DungeonPokemon clone = (DungeonPokemon) super.clone(); clone.entries = new ArrayList(); for (Entry entry : entries) clone.entries.add((Entry) entry.clone()); return clone; } catch (CloneNotSupportedException ex) { return null; } } public boolean checkProbabilitySum() { int sum = 0; for (Entry entry : entries) sum += entry.probability; return sum != 10000; } public static DungeonPokemon unpack(ByteBuffer buffer) { DungeonPokemon pokemon = new DungeonPokemon(); pokemon.offset = buffer.position(); pokemon.entries = new ArrayList(); int storedoffset = buffer.position(); int diff = 0; while(!Arrays.equals(buffer.readBytes(SIZE), NULL)) { buffer.seek(storedoffset); Entry entry = new Entry(); int mask = buffer.readUnsignedShort(); entry.level = (mask ^ 0x1A8) / 0x200; entry.species = mask - 0x200 * entry.level; entry.probability = buffer.readUnsignedShort(); int val = entry.probability; if (val != 0) { val -= diff; diff = entry.probability; } entry.probability = val; pokemon.entries.add(entry); buffer.skip(0x4); storedoffset = buffer.position(); } return pokemon; } public static byte[] pack(DungeonPokemon pokemon) { ByteBuffer buffer = new ByteBuffer(pokemon.entries.size() * 8 + 8, ByteOrder.LITTLE_ENDIAN); int sum = 0; for (Entry entry : pokemon.entries) { buffer.writeUnsignedShort(entry.species + entry.level * 0x200); if (sum < 10000) { int val = (entry.probability != 0) ? sum += entry.probability : 0; buffer.writeUnsignedShort(val); buffer.writeUnsignedShort(val); } else { buffer.writeUnsignedShort(0); buffer.writeUnsignedShort(0); } buffer.writeUnsignedShort(0); } buffer.writeBytes(NULL); return buffer.getBuffer(); } }
SunakazeKun/PMDe
src/com/aurum/mystery2/game/DungeonPokemon.java
Java
gpl-3.0
4,157
/** * JSkat - A skat program written in Java * by Jan Schäfer, Markus J. Luzius and Daniel Loreck * * Version 0.11.0 * Copyright (C) 2012-08-28 * * Licensed under the Apache License, Version 2.0. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jskat.gui.action.iss; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import org.jskat.gui.action.AbstractJSkatAction; import org.jskat.gui.action.JSkatAction; import org.jskat.gui.img.JSkatGraphicRepository.Icon; import org.jskat.util.JSkatResourceBundle; /** * Implements the action for showing about dialog */ public class ShowLoginPanelAction extends AbstractJSkatAction { private static final long serialVersionUID = 1L; /** * @see AbstractJSkatAction#AbstractJSkatAction() */ public ShowLoginPanelAction() { putValue(Action.NAME, JSkatResourceBundle.instance().getString("play_on_iss")); //$NON-NLS-1$ setActionCommand(JSkatAction.SHOW_ISS_LOGIN); setIcon(Icon.CONNECT_ISS); } /** * @see AbstractAction#actionPerformed(ActionEvent) */ @Override public void actionPerformed(final ActionEvent e) { jskat.getIssController().showISSLoginPanel(); } }
mfrasca/jskat-gui
src/main/java/org/jskat/gui/action/iss/ShowLoginPanelAction.java
Java
gpl-3.0
1,581
/* Copyright (C) 1996-2017 John W. Eaton This file is part of Octave. Octave 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. Octave 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 Octave; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. */ #if defined (HAVE_CONFIG_H) # include "config.h" #endif #include "Array-util.h" #include "errwarn.h" #include "ovl.h" #include "ov.h" #include "ov-scalar.h" #include "ov-float.h" #include "ov-flt-re-mat.h" #include "ov-typeinfo.h" #include "ov-null-mat.h" #include "ops.h" #include "xdiv.h" #include "xpow.h" // scalar unary ops. DEFUNOP (not, float_scalar) { const octave_float_scalar& v = dynamic_cast<const octave_float_scalar&> (a); float x = v.float_value (); if (octave::math::isnan (x)) octave::err_nan_to_logical_conversion (); return octave_value (x == 0.0f); } DEFUNOP_OP (uplus, float_scalar, /* no-op */) DEFUNOP_OP (uminus, float_scalar, -) DEFUNOP_OP (transpose, float_scalar, /* no-op */) DEFUNOP_OP (hermitian, float_scalar, /* no-op */) DEFNCUNOP_METHOD (incr, float_scalar, increment) DEFNCUNOP_METHOD (decr, float_scalar, decrement) // float by float ops. DEFBINOP_OP (add, float_scalar, float_scalar, +) DEFBINOP_OP (sub, float_scalar, float_scalar, -) DEFBINOP_OP (mul, float_scalar, float_scalar, *) DEFBINOP (div, float_scalar, float_scalar) { const octave_float_scalar& v1 = dynamic_cast<const octave_float_scalar&> (a1); const octave_float_scalar& v2 = dynamic_cast<const octave_float_scalar&> (a2); float d = v2.float_value (); if (d == 0.0) warn_divide_by_zero (); return octave_value (v1.float_value () / d); } DEFBINOP_FN (pow, float_scalar, float_scalar, xpow) DEFBINOP (ldiv, float_scalar, float_scalar) { const octave_float_scalar& v1 = dynamic_cast<const octave_float_scalar&> (a1); const octave_float_scalar& v2 = dynamic_cast<const octave_float_scalar&> (a2); float d = v1.float_value (); if (d == 0.0) warn_divide_by_zero (); return octave_value (v2.float_value () / d); } DEFBINOP_OP (lt, float_scalar, float_scalar, <) DEFBINOP_OP (le, float_scalar, float_scalar, <=) DEFBINOP_OP (eq, float_scalar, float_scalar, ==) DEFBINOP_OP (ge, float_scalar, float_scalar, >=) DEFBINOP_OP (gt, float_scalar, float_scalar, >) DEFBINOP_OP (ne, float_scalar, float_scalar, !=) DEFBINOP_OP (el_mul, float_scalar, float_scalar, *) DEFBINOP (el_div, float_scalar, float_scalar) { const octave_float_scalar& v1 = dynamic_cast<const octave_float_scalar&> (a1); const octave_float_scalar& v2 = dynamic_cast<const octave_float_scalar&> (a2); float d = v2.float_value (); if (d == 0.0) warn_divide_by_zero (); return octave_value (v1.float_value () / d); } DEFBINOP_FN (el_pow, float_scalar, float_scalar, xpow) DEFBINOP (el_ldiv, float_scalar, float_scalar) { const octave_float_scalar& v1 = dynamic_cast<const octave_float_scalar&> (a1); const octave_float_scalar& v2 = dynamic_cast<const octave_float_scalar&> (a2); float d = v1.float_value (); if (d == 0.0) warn_divide_by_zero (); return octave_value (v2.float_value () / d); } DEFSCALARBOOLOP_OP (el_and, float_scalar, float_scalar, &&) DEFSCALARBOOLOP_OP (el_or, float_scalar, float_scalar, ||) DEFNDCATOP_FN (fs_fs, float_scalar, float_scalar, float_array, float_array, concat) DEFNDCATOP_FN (s_fs, scalar, float_scalar, float_array, float_array, concat) DEFNDCATOP_FN (fs_s, float_scalar, scalar, float_array, float_array, concat) void install_fs_fs_ops (void) { INSTALL_UNOP (op_not, octave_float_scalar, not); INSTALL_UNOP (op_uplus, octave_float_scalar, uplus); INSTALL_UNOP (op_uminus, octave_float_scalar, uminus); INSTALL_UNOP (op_transpose, octave_float_scalar, transpose); INSTALL_UNOP (op_hermitian, octave_float_scalar, hermitian); INSTALL_NCUNOP (op_incr, octave_float_scalar, incr); INSTALL_NCUNOP (op_decr, octave_float_scalar, decr); INSTALL_BINOP (op_add, octave_float_scalar, octave_float_scalar, add); INSTALL_BINOP (op_sub, octave_float_scalar, octave_float_scalar, sub); INSTALL_BINOP (op_mul, octave_float_scalar, octave_float_scalar, mul); INSTALL_BINOP (op_div, octave_float_scalar, octave_float_scalar, div); INSTALL_BINOP (op_pow, octave_float_scalar, octave_float_scalar, pow); INSTALL_BINOP (op_ldiv, octave_float_scalar, octave_float_scalar, ldiv); INSTALL_BINOP (op_lt, octave_float_scalar, octave_float_scalar, lt); INSTALL_BINOP (op_le, octave_float_scalar, octave_float_scalar, le); INSTALL_BINOP (op_eq, octave_float_scalar, octave_float_scalar, eq); INSTALL_BINOP (op_ge, octave_float_scalar, octave_float_scalar, ge); INSTALL_BINOP (op_gt, octave_float_scalar, octave_float_scalar, gt); INSTALL_BINOP (op_ne, octave_float_scalar, octave_float_scalar, ne); INSTALL_BINOP (op_el_mul, octave_float_scalar, octave_float_scalar, el_mul); INSTALL_BINOP (op_el_div, octave_float_scalar, octave_float_scalar, el_div); INSTALL_BINOP (op_el_pow, octave_float_scalar, octave_float_scalar, el_pow); INSTALL_BINOP (op_el_ldiv, octave_float_scalar, octave_float_scalar, el_ldiv); INSTALL_BINOP (op_el_and, octave_float_scalar, octave_float_scalar, el_and); INSTALL_BINOP (op_el_or, octave_float_scalar, octave_float_scalar, el_or); INSTALL_CATOP (octave_float_scalar, octave_float_scalar, fs_fs); INSTALL_CATOP (octave_scalar, octave_float_scalar, s_fs); INSTALL_CATOP (octave_float_scalar, octave_scalar, fs_s); INSTALL_ASSIGNCONV (octave_float_scalar, octave_float_scalar, octave_float_matrix); INSTALL_ASSIGNCONV (octave_scalar, octave_float_scalar, octave_matrix); INSTALL_ASSIGNCONV (octave_float_scalar, octave_null_matrix, octave_float_matrix); INSTALL_ASSIGNCONV (octave_float_scalar, octave_null_str, octave_float_matrix); INSTALL_ASSIGNCONV (octave_float_scalar, octave_null_sq_str, octave_float_matrix); }
xmjiao/octave-debian
libinterp/operators/op-fs-fs.cc
C++
gpl-3.0
6,381
/*---------------------------------------------------------------------------*\ ========= | \\ / 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/>. Class Foam::vanAlbadaLimiter Description Class with limiter function which returns the limiter for the vanAlbada differencing scheme based on r obtained from the LimiterFunc class. Used in conjunction with the template class LimitedScheme. SourceFiles vanAlbada.C \*---------------------------------------------------------------------------*/ #ifndef vanAlbada_H #define vanAlbada_H #include "vector.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class vanAlbadaLimiter Declaration \*---------------------------------------------------------------------------*/ template<class LimiterFunc> class vanAlbadaLimiter : public LimiterFunc { public: vanAlbadaLimiter(Istream&) {} scalar limiter ( const scalar cdWeight, const scalar faceFlux, const typename LimiterFunc::phiType& phiP, const typename LimiterFunc::phiType& phiN, const typename LimiterFunc::gradPhiType& gradcP, const typename LimiterFunc::gradPhiType& gradcN, const vector& d ) const { scalar r = LimiterFunc::r ( faceFlux, phiP, phiN, gradcP, gradcN, d ); // New formulation. Oliver Borm and Aleks Jemcov // HJ, 13/Jan/2011 return max((r + 1)/(r + 1/stabilise(r, SMALL)), 0); } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/finiteVolume/interpolation/surfaceInterpolation/limitedSchemes/vanAlbada/vanAlbada.H
C++
gpl-3.0
2,902
package patterns.builder; import org.junit.Test; import static org.junit.Assert.assertNotNull; import lombok.extern.slf4j.Slf4j; /** * The BuilderTest class. */ @Slf4j public final class BuilderTest { /** * Unit Test to build one. */ @Test public void testBuilderOne() { final BuilderOne builder = new BuilderOne(); assertNotNull(builder); final AbstractPart product = builder.build(); log.info("product = {}", product); } /** * Unit Test to build two. */ @Test public void testBuilderTwo() { final BuilderTwo builder = new BuilderTwo(); assertNotNull(builder); final AbstractPart product = builder.build(); log.info("product = {}", product); } }
Martin-Spamer/java-coaching
src/test/java/patterns/builder/BuilderTest.java
Java
gpl-3.0
817
<?php /* EINSATZZWECK / USE CASE * Auslesen der Statistik aus der Datenbank * Schreiben der Ergebnisse in eine Textdatei * Die Textdatei kann dann von RESULTS.HTML und RESULTS.JS ausgelesen werden * Read statistics from database * Write results into text-file * The text-file can be accessed via RESULTS.HTML and RESULTS.JS. */ $filename = 'results_db.txt'; $somecontent = ""; echo "<p>Current file path and file: <strong>".$_SERVER['SCRIPT_FILENAME']."</strong></p>"; // https://www.w3schools.com/php/php_mysql_select.asp // Include Database Settings echo "<p> Loading DB-Settings ... </p>"; include "../statistics/db_settings.php"; // Establish Connection echo "<p> Establishing Connection ... </p>"; $conn = new mysqli($servername, $username, $password, $dbname); // Check connection echo "<p> Checking Connection ... </p>"; if ($conn->connect_error) { die("Mat-o-Wahl: Connection failed: " . $conn->connect_error); } echo "<p> Query SQL ... </p>"; $sql = "SELECT ip, timestamp, personal, parties FROM `$tablename` "; $result = $conn->query($sql); $counter = 0; if ($result->num_rows > 0) { // output data of each row echo "<p> Reading data for file ".$filename." ... </p>"; while($row = $result->fetch_assoc()) { $counter++; $ip = $row["ip"]; $timestamp = $row["timestamp"]; $mowpersonal = $row["personal"]; $mowparties = $row["parties"]; echo $counter." ip: " .$ip. " - Date: " .$timestamp. " Personal: " .$mowpersonal. " Parties: " .$mowparties. "<br /> "; $somecontent .= "".$ip." ".$timestamp." ".$mowpersonal." ".$mowparties."\n"; } } else { echo "<p> Error: 0 results </p>"; } echo "<p> Closing Connection. </p>"; $conn->close(); // DE: Sichergehen, dass die Datei existiert und beschreibbar ist // EN: Let's make sure the file exists and is writable first. if (is_writable($filename)) { // DE: Wir öffnen $filename im "WRITE" - Modus, so dass die Datei neu geschrieben wird. // EN: In our example we're opening $filename in WRITE mode to write it new. if (!$handle = fopen($filename, "w")) { print "<strong> Cannot open file ($filename) </strong> "; exit; } // DE: Schreibe $somecontent in die geöffnete Datei. // EN: Write $somecontent to our opened file. if (!fwrite($handle, $somecontent)) { print "<strong> Cannot write to file $filename </strong> "; exit; } print "Success! <br /> wrote: ($somecontent) <br />to file ($filename)"; fclose($handle); } else { print "<strong> The file $filename is not writable </strong> "; } echo "<p> You can now change the <strong>`var fileResults`</strong> in <strong>/SYSTEM/RESULTS.JS</strong> to <strong>".$filename."</strong> " ?>
msteudtn/Mat-O-Wahl
extras/statistics_db/read_db_write_text.php
PHP
gpl-3.0
2,864
/********************************************************** * Version $Id$ *********************************************************/ //#include "..\stdafx.h" #include <iostream> #include <vector> #include <functional> #include "ausdruck.h" #include "funktion.h" using namespace std; class compare_BB_Funktion : public greater<BBFunktion *> { public: bool operator()(const BBFunktion * &x, const BBFunktion * &y) const { return x->name < y->name; }; }; BBBaumInteger::BBBaumInteger() { typ = NoOp; memset(&k, 0, sizeof(BBKnoten)); } BBBaumInteger::~BBBaumInteger() { if (typ == NoOp) return; switch(typ) { case BIOperator: if (k.BiOperator.links != NULL) delete k.BiOperator.links; if (k.BiOperator.rechts != NULL) delete k.BiOperator.rechts; break; case UniOperator: if (k.UniOperator.rechts != NULL) delete k.UniOperator.rechts; break; case MIndex: if (k.MatrixIndex.P != NULL) delete k.MatrixIndex.P; break; case Funktion: if (k.func != NULL) delete k.func; break; case IZahl: case FZahl: case IVar: case FVar: break; } memset(&k, 0, sizeof(BBKnoten)); } BBBaumMatrixPoint::BBBaumMatrixPoint() : typ(NoOp) , isMatrix(true) { memset(&k, 0, sizeof(BBKnoten)); } BBBaumMatrixPoint::~BBBaumMatrixPoint() { if (typ == NoOp) return; switch(typ) { case BIOperator: if (k.BiOperator.links != NULL) delete k.BiOperator.links; if (k.BiOperator.rechts != NULL) delete k.BiOperator.rechts; break; case UniOperator: if (k.UniOperator.rechts != NULL) delete k.UniOperator.rechts; break; case IFAusdruck: if (k.IntFloatAusdruck.b != NULL) delete k.IntFloatAusdruck.b; break; case MVar: case PVar: break; } memset(&k, 0, sizeof(BBKnoten)); } bool getFirstCharKlammer(const string& statement, const string& cmp, char& c, int& pos) { if (statement.empty()) return false; int klammer_ebene = 0, klammerE_ebene = 0; for (int i=0; i<statement.size()-1; i++) { if (statement[i] == '(') klammer_ebene++; if (statement[i] == ')') klammer_ebene--; if (statement[i] == '[') klammerE_ebene++; if (statement[i] == ']') klammerE_ebene--; if (klammer_ebene == 0 && klammerE_ebene == 0 && i != statement.size() -1 && i != 0) { //int p = cmp.find_first_of(statement[i]); //if (cmp.find_first_of(statement[i]) >= 0) int j; for (j=0; j<cmp.size(); j++) if (cmp[j] == statement[i]) break; if (j < cmp.size()) { c = statement[i]; pos = i; return true; } } } return false; } bool getLastCharKlammer(const string& statement, const string& cmp, char& c, int& pos) { if (statement.empty()) return false; int char_found = -1; int klammer_ebene = 0, klammerE_ebene = 0; for (int i=0; i<statement.size()-1; i++) { if (statement[i] == '(') klammer_ebene++; if (statement[i] == ')') klammer_ebene--; if (statement[i] == '[') klammerE_ebene++; if (statement[i] == ']') klammerE_ebene--; if (klammer_ebene == 0 && klammerE_ebene == 0 && i != statement.size() -1 && i != 0) { int j; for (j=0; j<cmp.size(); j++) if (cmp[j] == statement[i]) char_found = i; } } if (char_found > 0) { c = statement[char_found]; pos = char_found; return true; } return false; } bool isKlammer(const string& statement) { // klammer-Level zählen if (statement.empty()) return false; if (statement[0] != '(' || statement[statement.size()-1] != ')') return false; int klammer_ebene = 0; for (int i=0; i<statement.size()-1; i++) { if (statement[i] == '(') klammer_ebene++; if (statement[i] == ')') klammer_ebene--; if (klammer_ebene == 0 && i != statement.size() -1) return false; } return true; } //++++++++++++++ Integer/ Float ++++++++++++++++++++++++++ bool isBiOperator(const string& statement, char& c, int& pos) { // Klammern zählen, da nur zwischen Klammer-Level NULL // ein Operator stehen darf // den Operator mit der niedrigsten Priorität zuerst ausführen, da er // in der Baum-Struktur "oben" stehen muß ! if (getFirstCharKlammer(statement, "+", c, pos)) return true; if (getLastCharKlammer(statement, "-", c, pos)) return true; if (getFirstCharKlammer(statement, "*", c, pos)) return true; if (getLastCharKlammer(statement, "/", c, pos)) return true; if (getFirstCharKlammer(statement, "^", c, pos)) return true; //--> if (getFirstCharKlammer(statement, "%", c, pos)) return true; //<-- return false; } bool isUniOperator(const string& statement, char& c) { c = statement[0]; return (c == '-' || c == '+'); } bool isMatrixIndex(const string& statement, BBMatrix *& bm, BBBaumMatrixPoint *& bp, bool getMem /* = true */) { // wenn X[p] enthält und X = Matrix und p = Point if (statement.empty()) return false; string s(statement); int pos1, pos2; pos1 = s.find('['); if (pos1 > 0) { pos2 = s.find(']'); if ( pos2 > pos1 && pos2 == s.size()-1 ) { // ersten Teil string m, p; m = s.substr(0, pos1); p = s.substr(pos1+1, pos2-pos1-1); BBTyp *tm; BBBaumMatrixPoint *bmp; if (isMVar(m, tm)) { try { // erst Testen pars_matrix_point(p, bmp, false, false); } catch (BBFehlerException) { return false; } if (!getMem) // falls nichts allokieren -> test erfolgreich return true; try { // dann allokieren pars_matrix_point(p, bmp, false); } catch (BBFehlerException) { return false; } bm = (BBMatrix *) tm; bp = bmp; return true; } /* if (isMVar(m, tm) && isPVar(p, tp)) { bm = (BBMatrix *) tm; bp = (BBPoint *) tp; return true; } */ } } return false; } bool isFZahl(const string& statement) { // Format: [+-]d[d][.[d[dd]][e|E +|- d[d]]] if (statement .size() > 50) return false; char buff[100]; double f; int anz = sscanf(statement.data(), "%f%s", &f, buff); return (anz == 1); } bool isIZahl(const string& statement) { if (statement.empty()) return false; string s(statement); // eventuel voranstehenden +- if (s[0] == '+') s.erase(s.begin()); else if (s[0] == '-') s.erase(s.begin()); if (s.empty()) return false; int p = s.find_first_not_of("1234567890"); if (p >= 0) return false; return true; } bool isFVar(const string& statement, BBTyp * & b) { b = isVar(statement); if (b == NULL) return false; if (b->type == BBTyp::FType) return true; return false; } bool isIVar(const string& statement, BBTyp * & b) { b = isVar(statement); if (b == NULL) return false; if (b->type == BBTyp::IType) return true; return false; } bool isPVar(const string& statement, BBTyp * & b) { b = isVar(statement); if (b == NULL) return false; if (b->type == BBTyp::PType) return true; return false; } bool isMVar(const string& statement, BBTyp * & b) { b = isVar(statement); if (b == NULL) return false; if (b->type == BBTyp::MType) return true; return false; } BBFunktion *isFktName(const string& s) { if (FunktionList.empty()) return NULL; T_FunktionList::iterator it; for (it = FunktionList.begin(); it != FunktionList.end(); it++) { if ((*it)->name == s) return (*it); } return NULL; } bool getNextFktToken(const string& s, int& pos, string& erg) { // Syntax xx[,xx[,xx...]] if (pos >= s.size()) return false; string ss(s.substr(pos)); int pos1 = ss.find_first_of(','); if (pos1 >= 0) { erg = ss.substr(0, pos1); pos += pos1; } else { erg = ss; pos = s.size(); } if (erg.empty()) return false; return true; } bool isFunktion (const string& statement, BBFktExe * & fktexe, bool getMem /* = true */, bool AlleFunktionen /* = true */) { // Syntax: fktname([arg1[, arg2]]) string s(statement); int pos1, pos2; pos1 = s.find_first_of('('); pos2 = s.find_last_of(')'); if (pos1 <= 0 || pos2 != s.size()-1) return false; // Variablen-Name string sub1, sub2; sub1 = s.substr(0, pos1); trim(sub1); sub2 = s.substr(pos1+1, pos2-pos1-1); trim(sub2); if (sub1.empty()) return false; BBFunktion *fkt = isFktName(sub1); if (fkt == NULL) return false; if (!AlleFunktionen) { // nur diejenigen Funktionen mit Return-Typ if (fkt->ret.typ == BBArgumente::NoOp) // kein Return-Typ return false; } if (sub2.empty()) // keine Argumente { if (!fkt->args.empty()) return false; if (getMem) { fktexe = new BBFktExe; fktexe->args = fkt->args; fktexe->f = fkt; // vorher ... = NULL; } return true; } else { // Argumente zählen // 1. Float/Integer lassen sich konvertieren // 2. Matrix // 3. Point if (getMem) { fktexe = new BBFktExe; fktexe->args = fkt->args; // vector kopieren fktexe->f = fkt; } int anz = fkt->args.size(); int possub2 = 0; for (int i=0; i<anz; i++) { // finde Token string ss; if (!getNextFktToken(sub2, possub2, ss)) return false; // BBTyp *bt = isVar(ss); // if (bt == NULL) // return false; if (fkt->args[i].typ == BBArgumente::ITyp || fkt->args[i].typ == BBArgumente::FTyp) { // if (bt->type != BBTyp::IType || // bt->type != BBTyp::FType) // return false; try { BBBaumInteger *b; pars_integer_float(ss, b, getMem); if (getMem) fktexe->args[i].ArgTyp.IF = b; } catch (BBFehlerException) { if (getMem) delete fktexe; return false; } } else { /* if (fkt->args[i].typ == BBArgumente::MTyp && bt->type != BBTyp::MType) return false; if (fkt->args[i].typ == BBArgumente::PTyp && bt->type != BBTyp::PType) return false; */ try { BBBaumMatrixPoint *b; pars_matrix_point(ss, b, fkt->args[i].typ == BBArgumente::MTyp, getMem); if (getMem) fktexe->args[i].ArgTyp.MP = b; } catch (BBFehlerException) { if (getMem) delete fktexe; return false; } } possub2++; // Komma entfernen } if (possub2 < sub2.size()) // zuviel Parameter angegeben { if (getMem) delete fktexe; return false; } } return true; } // ------------- Hauptroutine ------------------- static char c; static BBTyp *b; static BBMatrix *bm; static BBPoint *bp; static BBBaumMatrixPoint *bmp; static int pos; static BBFktExe *bfkt; void pars_integer_float(const string& statement, BBBaumInteger * & Knoten, int getMem /* = true */) { string s(statement); trim(s); if (s.empty()) throw BBFehlerException(); if (isKlammer(s)) { s.erase(s.begin()); s.erase(s.end()-1); pars_integer_float(s, Knoten, getMem); } else if (isMatrixIndex(s, bm, bmp, getMem!=0)) { if (getMem) { Knoten = new BBBaumInteger; Knoten->typ = BBBaumInteger::MIndex; Knoten->k.MatrixIndex.M = bm; Knoten->k.MatrixIndex.P = bmp; } } else if (isBiOperator(s, c, pos)) { string links = s.substr(0, pos); string rechts = s.substr(pos+1, s.size()-pos-1); if (links.empty() || rechts.empty()) throw BBFehlerException(); if (getMem) { Knoten = new BBBaumInteger; Knoten->typ = BBBaumInteger::BIOperator; switch(c) { case '+': Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Plus; break; case '-': Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Minus; break; case '*': Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Mal; break; case '/': Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Geteilt; break; case '^': Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Hoch; break; //--> case '%': Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Modulo; break; //<-- } pars_integer_float(links, Knoten->k.BiOperator.links); pars_integer_float(rechts, Knoten->k.BiOperator.rechts); } else { pars_integer_float(links, Knoten, getMem); pars_integer_float(rechts, Knoten, getMem); } } else if (isUniOperator(s, c)) { s.erase(s.begin()); if (getMem) { Knoten = new BBBaumInteger; Knoten->typ = BBBaumInteger::UniOperator; Knoten->k.UniOperator.OpTyp = (c == '+' ? BBBaumInteger::BBKnoten::BBUniOperator::Plus : BBBaumInteger::BBKnoten::BBUniOperator::Minus); pars_integer_float(s, Knoten->k.UniOperator.rechts); } else pars_integer_float(s, Knoten->k.UniOperator.rechts, getMem); } else if (isFZahl(s)) { if (getMem) { Knoten = new BBBaumInteger; Knoten->typ = BBBaumInteger::FZahl; Knoten->k.FZahl = atof(s.data()); } } else if (isIZahl(s)) { if (getMem) { Knoten = new BBBaumInteger; Knoten->typ = BBBaumInteger::IZahl; Knoten->k.IZahl = (int)atof(s.data()); } } else if (isFVar(s, b)) { if (getMem) { Knoten = new BBBaumInteger; Knoten->typ = BBBaumInteger::FVar; Knoten->k.FVar = getVarF(b); } } else if (isIVar(s, b)) { if (getMem) { Knoten = new BBBaumInteger; Knoten->typ = BBBaumInteger::IVar; Knoten->k.IVar = getVarI(b); } } else if (isFunktion (s, bfkt, getMem!=0, false)) // nur die Funktionen mit Return-Typ { if (getMem) { Knoten = new BBBaumInteger; Knoten->typ = BBBaumInteger::Funktion; Knoten->k.func = bfkt; } } else throw BBFehlerException(); } bool isIntFloatAusdruck(const string& s) { try { BBBaumInteger *knoten = NULL; pars_integer_float(s, knoten, false); } catch (BBFehlerException) { return false; } return true; } //++++++++++++++ Point ++++++++++++++++++++++++++ // Operator p/p + - // Operator p/i i/p p/f f/p * / //++++++++++++++ Matrix ++++++++++++++++++++++++++ // Operator M/M + - // Operator M/i i/M M/f f/M * / void pars_matrix_point(const string& statement, BBBaumMatrixPoint * &Knoten, bool matrix, bool getMem /* = true */) { string s(statement); trim(s); if (s.empty()) throw BBFehlerException(); if (isKlammer(s)) { s.erase(s.begin()); s.erase(s.end()-1); pars_matrix_point(s, Knoten, matrix, getMem); } else if (isUniOperator(s, c)) { s.erase(s.begin()); if (getMem) { Knoten = new BBBaumMatrixPoint; Knoten->typ = BBBaumMatrixPoint::UniOperator; Knoten->k.UniOperator.OpTyp = (c == '+' ? BBBaumMatrixPoint::BBKnoten::BBUniOperator::Plus : BBBaumMatrixPoint::BBKnoten::BBUniOperator::Minus); Knoten->isMatrix = matrix; pars_matrix_point(s, Knoten->k.UniOperator.rechts, matrix); } else pars_matrix_point(s, Knoten, matrix, getMem); } else if (isBiOperator(s, c, pos)) { string links = s.substr(0, pos); string rechts = s.substr(pos+1, s.size()-pos-1); if (links.empty() || rechts.empty()) throw BBFehlerException(); if (getMem) { Knoten = new BBBaumMatrixPoint; Knoten->typ = BBBaumMatrixPoint::BIOperator; Knoten->isMatrix = matrix; switch(c) { case '+': Knoten->k.BiOperator.OpTyp = BBBaumMatrixPoint::BBKnoten::BBBiOperator::Plus; break; case '-': Knoten->k.BiOperator.OpTyp = BBBaumMatrixPoint::BBKnoten::BBBiOperator::Minus; break; case '*': Knoten->k.BiOperator.OpTyp = BBBaumMatrixPoint::BBKnoten::BBBiOperator::Mal; break; case '/': Knoten->k.BiOperator.OpTyp = BBBaumMatrixPoint::BBKnoten::BBBiOperator::Geteilt; break; case '^': throw BBFehlerException(); break; case '%': throw BBFehlerException(); break; } pars_matrix_point(links, Knoten->k.BiOperator.links, matrix); pars_matrix_point(rechts, Knoten->k.BiOperator.rechts, matrix); if (c == '+' || c == '-') { // Operator nur zwischen zwei Points if (matrix && ( (Knoten->k.BiOperator.rechts)->typ != BBBaumMatrixPoint::MVar || (Knoten->k.BiOperator.links )->typ != BBBaumMatrixPoint::MVar )) { throw BBFehlerException(); } if (!matrix && ((Knoten->k.BiOperator.rechts)->typ != BBBaumMatrixPoint::PVar || (Knoten->k.BiOperator.links )->typ != BBBaumMatrixPoint::PVar )) { throw BBFehlerException(); } } if (c == '*' || c == '/') { // Operator nur zwischen i/f und p, Reihenfolge egal int pvar = 0; int mvar = 0; if ((Knoten->k.BiOperator.rechts)->typ == BBBaumMatrixPoint::PVar) pvar++; if ((Knoten->k.BiOperator.rechts)->typ == BBBaumMatrixPoint::MVar) mvar++; if ((Knoten->k.BiOperator.links)->typ == BBBaumMatrixPoint::PVar) pvar++; if ((Knoten->k.BiOperator.links)->typ == BBBaumMatrixPoint::MVar) mvar++; if (matrix && (mvar != 1 || pvar != 0)) throw BBFehlerException(); if (!matrix && (pvar != 1 || mvar != 0)) throw BBFehlerException(); } } else { pars_matrix_point(links, Knoten, matrix, getMem); pars_matrix_point(rechts, Knoten, matrix, getMem); } } else if (matrix && isMVar(s, b)) { if (getMem) { Knoten = new BBBaumMatrixPoint; Knoten->typ = BBBaumMatrixPoint::MVar; Knoten->k.M = getVarM(b); Knoten->isMatrix = matrix; } } else if (!matrix && isPVar(s, b)) { if (getMem) { Knoten = new BBBaumMatrixPoint; Knoten->typ = BBBaumMatrixPoint::PVar; Knoten->k.P = getVarP(b); Knoten->isMatrix = matrix; } } else if (isIntFloatAusdruck(s)) { if (getMem) { Knoten = new BBBaumMatrixPoint; Knoten->typ = BBBaumMatrixPoint::IFAusdruck; Knoten->isMatrix = matrix; pars_integer_float(s, Knoten->k.IntFloatAusdruck.b); } else { BBBaumInteger *k = NULL; pars_integer_float(s, k, getMem); } } else throw BBFehlerException(); }
UoA-eResearch/saga-gis
saga-gis/src/modules/grid/grid_calculus_bsl/ausdruck.cpp
C++
gpl-3.0
17,374
# Rewritten by RayzoR import sys from com.l2scoria.gameserver.model.quest import State from com.l2scoria.gameserver.model.quest import QuestState from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest qn = "112_WalkOfFate" # ~~~~~ npcId list: ~~~~~ Livina = 30572 Karuda = 32017 # ~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~ itemId list: ~~~~~~ EnchantD = 956 # ~~~~~~~~~~~~~~~~~~~~~~~~~~ class Quest (JQuest) : def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr) def onAdvEvent (self,event,npc,player) : st = player.getQuestState(qn) if not st: return htmltext = event cond = st.getInt("cond") if event == "32017-02.htm" and cond == 1 : st.giveItems(57,22308) st.giveItems(EnchantD,1) st.addExpAndSp(112876,5774) st.exitQuest(False) st.playSound("ItemSound.quest_finish") elif event == "30572-02.htm" : st.playSound("ItemSound.quest_accept") st.setState(STARTED) st.set("cond","1") return htmltext def onTalk (self,npc,player): htmltext = "<html><head><body>You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.</body></html>" st = player.getQuestState(qn) if not st : return htmltext state = st.getState() npcId = npc.getNpcId() cond = st.getInt("cond") if state == COMPLETED : htmltext = "<html><body>This quest has already been completed.</body></html>" elif state == CREATED : if npcId == Livina : if player.getLevel() >= 20 : htmltext = "30572-01.htm" else: htmltext = "30572-00.htm" st.exitQuest(1) elif state == STARTED : if npcId == Livina : htmltext = "30572-03.htm" elif npcId == Karuda : htmltext = "32017-01.htm" return htmltext QUEST = Quest(112,qn,"Walk of Fate") CREATED = State('Start', QUEST) STARTED = State('Started', QUEST) COMPLETED = State('Completed', QUEST) QUEST.setInitialState(CREATED) QUEST.addStartNpc(Livina) QUEST.addTalkId(Livina) QUEST.addTalkId(Karuda)
zenn1989/scoria-interlude
L2Jscoria-Game/data/scripts/quests/112_WalkOfFate/__init__.py
Python
gpl-3.0
2,208
#include "reversead/algorithm/base_reverse_tensor.hpp" #include "reversead/forwardtype/single_forward.hpp" template class ReverseAD::BaseReverseTensor<double>; template class ReverseAD::BaseReverseTensor<ReverseAD::SingleForward>;
wangmu0701/ReverseAD
ReverseAD/src/algorithm/base_reverse_tensor.cpp
C++
gpl-3.0
232
package com.aepronunciation.ipa; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; import androidx.appcompat.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.RadioButton; import android.widget.RadioGroup; import java.util.ArrayList; import static android.content.Context.MODE_PRIVATE; import static com.aepronunciation.ipa.MainActivity.PRACTICE_MODE_IS_SINGLE_KEY; import static com.aepronunciation.ipa.MainActivity.PREFS_NAME; public class SelectSoundDialogFragment extends DialogFragment { public interface SelectSoundDialogListener { void onDialogPositiveClick( SoundMode numberSounds, ArrayList<String> chosenVowels, ArrayList<String> chosenConsonants); void onDialogNegativeClick(DialogFragment dialog); } static final String KEY_DIALOG_IS_SINGLE_MODE = "isSingleMode"; static final String KEY_DIALOG_VOWEL_LIST = "vowels"; static final String KEY_DIALOG_CONSONANT_LIST = "consonants"; private SelectSoundDialogListener mListener; private RadioButton rbSingle; private RadioButton rbDouble; private CheckBox cbVowelsCategory; private CheckBox cbConsonantsCategory; private CheckBox[] checkBoxesVowels; private CheckBox[] checkBoxesConsonants; private CheckBox cbSchwa; private CheckBox cbUnstressedEr; private CheckBox cbGlottalStop; private CheckBox cbFlapT; private Button positiveButton; private boolean listenerDisabled = false; @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.dialog_select_sound, null); rbSingle = view.findViewById(R.id.radio_single); rbDouble = view.findViewById(R.id.radio_double); cbSchwa = view.findViewById(R.id.cb_shwua); cbUnstressedEr = view.findViewById(R.id.cb_er_unstressed); cbGlottalStop = view.findViewById(R.id.cb_glottal_stop); cbFlapT = view.findViewById(R.id.cb_flap_t); // get saved practice mode SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, MODE_PRIVATE); boolean isSingle = settings.getBoolean(PRACTICE_MODE_IS_SINGLE_KEY, true); if (isSingle) { rbSingle.setChecked(true); } else { rbDouble.setChecked(true); cbSchwa.setVisibility(View.GONE); cbUnstressedEr.setVisibility(View.GONE); cbGlottalStop.setVisibility(View.GONE); cbFlapT.setVisibility(View.GONE); } initializeCheckBoxes(view); final RadioGroup rg = view.findViewById(R.id.select_sounds_radio_group); rg.setOnCheckedChangeListener(radioGroupListener); // disable the OK button view.post(new Runnable() { @Override public void run() { AlertDialog dialog = (AlertDialog) getDialog(); positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); } }); // build the alert dialog AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme); builder.setView(view) .setTitle(getString(R.string.select_sounds_title)) .setPositiveButton(R.string.select_sounds_positive_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { SoundMode soundType = SoundMode.Double; //RadioButton single = (RadioButton) rg.findViewById(R.id.radio_single); if (rbSingle.isChecked()) { soundType = SoundMode.Single; } // get all chosen sounds ArrayList<String> chosenVowels = new ArrayList<>(); for (CheckBox cb : checkBoxesVowels) { if (cb.isChecked() & cb.getVisibility() == View.VISIBLE) { chosenVowels.add(cb.getText().toString()); } } ArrayList<String> chosenConsonants = new ArrayList<>(); for (CheckBox cb : checkBoxesConsonants) { if (cb.isChecked() & cb.getVisibility() == View.VISIBLE) { chosenConsonants.add(cb.getText().toString()); } } // TODO: save single/double state to user preferences // report back to parent fragment mListener.onDialogPositiveClick(soundType, chosenVowels, chosenConsonants); } }) .setNegativeButton(R.string.dialog_cancel_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mListener.onDialogNegativeClick(SelectSoundDialogFragment.this); } }); return builder.create(); } @Override public void onResume() { super.onResume(); final AlertDialog alertDialog = (AlertDialog) getDialog(); Button okButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE); okButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SoundMode soundType = SoundMode.Double; RadioButton single = alertDialog.findViewById(R.id.radio_single); if (single != null && single.isChecked()) { soundType = SoundMode.Single; } // get all chosen sounds ArrayList<String> chosenVowels = new ArrayList<>(); for (CheckBox cb : checkBoxesVowels) { if (cb.isChecked() & cb.getVisibility() == View.VISIBLE) { chosenVowels.add(cb.getText().toString()); } } ArrayList<String> chosenConsonants = new ArrayList<>(); for (CheckBox cb : checkBoxesConsonants) { if (cb.isChecked() & cb.getVisibility() == View.VISIBLE) { chosenConsonants.add(cb.getText().toString()); } } mListener.onDialogPositiveClick(soundType, chosenVowels, chosenConsonants); dismiss(); } }); } private void initializeCheckBoxes(View layout) { checkBoxesVowels = new CheckBox[]{ layout.findViewById(R.id.cb_i), layout.findViewById(R.id.cb_i_short), layout.findViewById(R.id.cb_e_short), layout.findViewById(R.id.cb_ae), layout.findViewById(R.id.cb_a), layout.findViewById(R.id.cb_c_backwards), layout.findViewById(R.id.cb_u_short), layout.findViewById(R.id.cb_u), layout.findViewById(R.id.cb_v_upsidedown), cbSchwa, layout.findViewById(R.id.cb_ei), layout.findViewById(R.id.cb_ai), layout.findViewById(R.id.cb_au), layout.findViewById(R.id.cb_oi), layout.findViewById(R.id.cb_ou), layout.findViewById(R.id.cb_er_stressed), cbUnstressedEr, layout.findViewById(R.id.cb_ar), layout.findViewById(R.id.cb_er), layout.findViewById(R.id.cb_ir), layout.findViewById(R.id.cb_or) }; checkBoxesConsonants = new CheckBox[]{ layout.findViewById(R.id.cb_p), layout.findViewById(R.id.cb_b), layout.findViewById(R.id.cb_t), layout.findViewById(R.id.cb_d), layout.findViewById(R.id.cb_k), layout.findViewById(R.id.cb_g), layout.findViewById(R.id.cb_ch), layout.findViewById(R.id.cb_dzh), layout.findViewById(R.id.cb_f), layout.findViewById(R.id.cb_v), layout.findViewById(R.id.cb_th_voiceless), layout.findViewById(R.id.cb_th_voiced), layout.findViewById(R.id.cb_s), layout.findViewById(R.id.cb_z), layout.findViewById(R.id.cb_sh), layout.findViewById(R.id.cb_zh), layout.findViewById(R.id.cb_m), layout.findViewById(R.id.cb_n), layout.findViewById(R.id.cb_ng), layout.findViewById(R.id.cb_l), layout.findViewById(R.id.cb_w), layout.findViewById(R.id.cb_j), layout.findViewById(R.id.cb_h), layout.findViewById(R.id.cb_r), cbGlottalStop, cbFlapT }; if (checkBoxesConsonants.length != Ipa.NUMBER_OF_CONSONANTS || checkBoxesVowels.length != Ipa.NUMBER_OF_VOWELS) { throw new RuntimeException("update number of checkboxes if vowels or consonant number changes"); } cbVowelsCategory = layout.findViewById(R.id.cbVowels); cbConsonantsCategory = layout.findViewById(R.id.cbConsonants); // get saved settings Bundle mArgs = getArguments(); // FIXME use getSerializable to pass SoundMode enum directly boolean isSingleMode = mArgs.getBoolean(KEY_DIALOG_IS_SINGLE_MODE); SoundMode mode = SoundMode.Double; if (isSingleMode) { mode = SoundMode.Single; } ArrayList<String> vowelSounds = mArgs.getStringArrayList(KEY_DIALOG_VOWEL_LIST); ArrayList<String> consonantSounds = mArgs.getStringArrayList(KEY_DIALOG_CONSONANT_LIST); updateCheckedState(mode, vowelSounds, consonantSounds); // set listeners on the IPA checkboxes so that OK button can be disabled for (CheckBox cb : checkBoxesVowels) { cb.setOnCheckedChangeListener(checkBoxListener); } for (CheckBox cb : checkBoxesConsonants) { cb.setOnCheckedChangeListener(checkBoxListener); } cbVowelsCategory.setOnCheckedChangeListener(checkBoxListener); cbConsonantsCategory.setOnCheckedChangeListener(checkBoxListener); } // allow calling fragment to set state private void updateCheckedState(SoundMode mode, ArrayList<String> vowelSounds, ArrayList<String> consonantSounds) { if (mode == null || vowelSounds == null || consonantSounds == null) { return; } // radio group if (mode == SoundMode.Single) { rbSingle.setChecked(true); } else { rbDouble.setChecked(true); } // uncheck the vowel/consonant boxes if some of the small boxes are unchecked listenerDisabled = true; cbVowelsCategory.setChecked(checkBoxesVowels.length == vowelSounds.size()); cbConsonantsCategory.setChecked(checkBoxesConsonants.length == consonantSounds.size()); listenerDisabled = false; // check individual boxes String currentCbString; boolean found; for (CheckBox cb : checkBoxesVowels) { currentCbString = cb.getText().toString(); found = false; for (String sound : vowelSounds) { if (currentCbString.equals(sound)) { found = true; } } cb.setChecked(found); } for (CheckBox cb : checkBoxesConsonants) { currentCbString = cb.getText().toString(); found = false; for (String sound : consonantSounds) { if (currentCbString.equals(sound)) { found = true; } } cb.setChecked(found); } } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); // check if parent Fragment implements listener if (getParentFragment() instanceof SelectSoundDialogListener) { mListener = (SelectSoundDialogListener) getParentFragment(); } else { throw new RuntimeException("Parent fragment must implement SelectSoundDialogListener"); } } private RadioGroup.OnCheckedChangeListener radioGroupListener = new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int checkedId) { switch (checkedId) { case R.id.radio_single: // show optional sounds (unstressed er, shwua, glottal stop and flap t) cbSchwa.setVisibility(View.VISIBLE); cbUnstressedEr.setVisibility(View.VISIBLE); cbGlottalStop.setVisibility(View.VISIBLE); cbFlapT.setVisibility(View.VISIBLE); break; case R.id.radio_double: // hide optional sounds cbSchwa.setVisibility(View.GONE); cbUnstressedEr.setVisibility(View.GONE); cbGlottalStop.setVisibility(View.GONE); cbFlapT.setVisibility(View.GONE); break; } // disable/enable OK button if needed boolean enabledState = getButtonShouldBeEnabledState(); if (positiveButton.isEnabled() != enabledState) { positiveButton.setEnabled(enabledState); } } }; private CompoundButton.OnCheckedChangeListener checkBoxListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if (listenerDisabled) { return; } switch (compoundButton.getId()) { case R.id.cbVowels: for (CheckBox cb : checkBoxesVowels) { cb.setChecked(isChecked); } break; case R.id.cbConsonants: for (CheckBox cb : checkBoxesConsonants) { cb.setChecked(isChecked); } break; default: // all other check boxes are individual sounds // set the enabled state of the OK button boolean enabledState = getButtonShouldBeEnabledState(); if (positiveButton.isEnabled() != enabledState) { positiveButton.setEnabled(enabledState); } break; } } }; private boolean getButtonShouldBeEnabledState() { // count the number of checked boxes for consonants and vowels int vowelsChecked = 0; for (CheckBox cb : checkBoxesVowels) { if (cb.isChecked() && cb.getVisibility() == View.VISIBLE) { vowelsChecked++; if (vowelsChecked > 1) break; } } int consonantsChecked = 0; for (CheckBox cb : checkBoxesConsonants) { if (cb.isChecked() && cb.getVisibility() == View.VISIBLE) { consonantsChecked++; if (consonantsChecked > 1) break; } } // There must be at least two sounds for single or one for double if (rbSingle.isChecked()) { if (vowelsChecked + consonantsChecked <= 1) { return false; } } else { // Double if (vowelsChecked + consonantsChecked < 1) { return false; } } return true; } }
suragch/aePronunciation
app/src/main/java/com/aepronunciation/ipa/SelectSoundDialogFragment.java
Java
gpl-3.0
16,390
/* Wgs.h - Custom library for wintergarden. Created by Felix Neubauer, August 12, 2016. */ #include "Arduino.h" #include "Wgs.h" const int STATE_UNKNOWN = 0; const int STATE_ENABLED = 1; const int STATE_DISABLING = 2; const int STATE_DISABLED = 3; const int STATE_ENABLING = 4; Wgs::Wgs(int pin_on, int pin_down, long duration) { //pinMode(pin, OUTPUT); _pin_on = pin_on; _pin_down = pin_down; _duration = duration; _disable = false; } void Wgs::loop(bool button_disable, bool button_enable) { //debug("Loop. Button enable: "+button_enable); //debug("Button disable: "+button_disable); //debug("State: "+_state); if(_mute_time > millis()){ debug("Muted"); return; } if(_disable){ debug("Detected rain!!!!!!!!!!!!!!!!!!!!!!!!!!"); button_disable = true; } if(button_disable){ if(_state == STATE_DISABLED || _state == STATE_DISABLING){ //Already disabled/disabling debug("Already disabling/disabled"); return; } if(_state == STATE_ENABLING){ debug("Stop enabling"); _mute_time = millis() + 400; stopMovement(STATE_UNKNOWN); return; } debug("Start disabling"); startMovement(STATE_DISABLING); }else if(button_enable){ if(_state == STATE_ENABLED || _state == STATE_ENABLING){ //Already enabled/enabling debug("Already enabling/enabled"); return; } if(_state == STATE_DISABLING){ debug("Stop disabling"); _mute_time = millis() + 400; stopMovement(STATE_UNKNOWN); return; } debug("Start enabling"); startMovement(STATE_ENABLING); } if (_finish_time <= millis() && _finish_time > 0) { debug("reached finish time"); switch (_state) { case STATE_DISABLING: stopMovement(STATE_DISABLED); break; case STATE_ENABLING: stopMovement(STATE_ENABLED); break; } } } void Wgs::setDisable(boolean b) { _disable = b; } void Wgs::stopMovement(int state) { _finish_time = 0; //Set destination time to 0 -> it's not active anymore digitalWrite(_pin_on, HIGH); delay(150); digitalWrite(_pin_down, HIGH); _state = state; } void Wgs::debug(String text) { /*String prefix = String(); prefix = "["+ _pin_on; prefix = prefix+" "; prefix = prefix + _pin_down; prefix = prefix +"] "; String goal = String(); goal = prefix + text;*/ Serial.println(_pin_on + text); } void Wgs::startMovement(int state) { setState(state); if(_state == STATE_DISABLING){ digitalWrite(_pin_down, HIGH);//Activate relais and make it ready to disable this component }else if(_state == STATE_ENABLING){ digitalWrite(_pin_down, LOW); //Activate relais and make it ready to enable this component } delay(150); digitalWrite(_pin_on, LOW); //Activate motor _finish_time = millis() + _duration; //Set destination time } void Wgs::setState(int i) //-1 = unknown. 0 = enabled; 1 = move_disable; 2 = disabled; 3 = move_enable; { _state = i; }
ranseyer/blind-control
arduino/Wintergartensteuerung/lib/Wgs.cpp
C++
gpl-3.0
3,018
/* This file is part of Peers, a java SIP softphone. 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/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package dk.apaq.peers.sip.transactionuser; import java.util.Collection; import java.util.Hashtable; import dk.apaq.peers.sip.RFC3261; import dk.apaq.peers.sip.syntaxencoding.SipHeaderFieldName; import dk.apaq.peers.sip.syntaxencoding.SipHeaderFieldValue; import dk.apaq.peers.sip.syntaxencoding.SipHeaderParamName; import dk.apaq.peers.sip.syntaxencoding.SipHeaders; import dk.apaq.peers.sip.transport.SipMessage; import dk.apaq.peers.sip.transport.SipResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DialogManager { private static final Logger LOG = LoggerFactory.getLogger(DialogManager.class); private Hashtable<String, Dialog> dialogs; public DialogManager() { dialogs = new Hashtable<String, Dialog>(); } /** * @param sipResponse sip response must contain a To tag, a * From tag and a Call-ID * @return the new Dialog created */ public synchronized Dialog createDialog(SipResponse sipResponse) { SipHeaders sipHeaders = sipResponse.getSipHeaders(); String callID = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CALLID)).toString(); SipHeaderFieldValue from = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_FROM)); SipHeaderFieldValue to = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_TO)); String fromTag = from.getParam(new SipHeaderParamName(RFC3261.PARAM_TAG)); String toTag = to.getParam(new SipHeaderParamName(RFC3261.PARAM_TAG)); Dialog dialog; if (sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_VIA)) == null) { //createDialog is called from UAS side, in layer Transaction User dialog = new Dialog(callID, toTag, fromTag); } else { //createDialog is called from UAC side, in syntax encoding layer dialog = new Dialog(callID, fromTag, toTag); } dialogs.put(dialog.getId(), dialog); return dialog; } public void removeDialog(String dialogId) { dialogs.remove(dialogId); } public synchronized Dialog getDialog(SipMessage sipMessage) { SipHeaders sipHeaders = sipMessage.getSipHeaders(); String callID = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CALLID)).toString(); SipHeaderFieldValue from = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_FROM)); SipHeaderFieldValue to = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_TO)); SipHeaderParamName tagName = new SipHeaderParamName(RFC3261.PARAM_TAG); String fromTag = from.getParam(tagName); String toTag = to.getParam(tagName); Dialog dialog = dialogs.get(getDialogId(callID, fromTag, toTag)); if (dialog != null) { return dialog; } return dialogs.get(getDialogId(callID, toTag, fromTag)); } public synchronized Dialog getDialog(String callId) { for (Dialog dialog : dialogs.values()) { if (dialog.getCallId().equals(callId)) { return dialog; } } return null; } private String getDialogId(String callID, String localTag, String remoteTag) { StringBuffer buf = new StringBuffer(); buf.append(callID); buf.append(Dialog.ID_SEPARATOR); buf.append(localTag); buf.append(Dialog.ID_SEPARATOR); buf.append(remoteTag); return buf.toString(); } public Collection<Dialog> getDialogCollection() { return dialogs.values(); } }
Apaq/peers
peers-lib/src/main/java/dk/apaq/peers/sip/transactionuser/DialogManager.java
Java
gpl-3.0
4,300
package cz.cvut.fit.ddw.project.subprocess; import cz.cvut.fit.ddw.project.enums.News; import com.rometools.rome.feed.synd.SyndEntry; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.io.FeedException; import com.rometools.rome.io.SyndFeedInput; import com.rometools.rome.io.XmlReader; import cz.cvut.fit.ddw.project.entity.NewsArticle; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; /** * * @author Tomáš Duda <dudatom2@fit.cvut.cz> */ public class RSSFetcher { private static final Logger logger = Logger.getLogger(RSSFetcher.class); private final News news; private final SyndFeedInput input; private final SyndFeed feed; public RSSFetcher(News news) throws IllegalArgumentException, FeedException, IOException { logger.info("Inicializuji spojeni s " + news.name()); this.news = news; this.input = new SyndFeedInput(); this.feed = input.build(new XmlReader(new URL(news.getUrl()))); } public List<NewsArticle> getCurrentFeed() throws IOException { List<NewsArticle> articles = new ArrayList<>(); // 3 pokusy na navazani spojeni List<SyndEntry> entries = null; for (int i = 0; i < 3; i++) { try { logger.info("Pokus " + (i + 1) + "/" + 3 + " navazat spojeni s " + news.name()); entries = feed.getEntries(); logger.info("Pokus uspesny."); break; } catch (Exception ste) { logger.info("Pokus neuspesny."); if (i == 2) { return articles; } } } for (SyndEntry se : entries) { String title = se.getTitle(); String link = se.getLink(); String content; try { logger.debug("Pokousim se ziskat obsah clanku ze zpravodajskeho webu."); Document doc = Jsoup.connect(link).get(); Elements elements = doc.getElementsByClass(news.getClassContentName()); if (!elements.isEmpty()) { content = elements.get(0).text(); } else { content = ""; } } catch (IOException ioe) { logger.warn("Ziskani clanku z webu nebylo uspesne, preskakuji.", ioe); continue; } if (!content.isEmpty()) { NewsArticle na = new NewsArticle(news, link, title, content); articles.add(na); } else { logger.info("Vyrazuji clanek bez textoveho obsahu (video, galerie, infografika, livefeed ...): " + link); continue; } logger.debug("Clanek uspesne zpracovan."); } return articles; } }
tomas-duda/ddw
src/main/java/cz/cvut/fit/ddw/project/subprocess/RSSFetcher.java
Java
gpl-3.0
2,999
/* * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.ksenechal.javafx.bootstrapfx.skin; import com.sun.javafx.scene.control.behavior.MenuButtonBehaviorBase; import com.sun.javafx.scene.control.skin.MenuButtonSkinBase; import javafx.scene.control.MenuButton; /** * Base class for MenuButtonSkin and SplitMenuButtonSkin. It consists of the * label, the arrowButton with its arrow shape, and the popup. */ public abstract class BootstrapMenuButtonSkinBase<C extends MenuButton, B extends MenuButtonBehaviorBase<C>> extends MenuButtonSkinBase<C, B> { public BootstrapMenuButtonSkinBase(C c, B b) { super(c, b); popup.getStyleClass().add("bootstrap-context-menu"); } }
ksenechal/BootstrapFX
src/main/java/com/ksenechal/javafx/bootstrapfx/skin/BootstrapMenuButtonSkinBase.java
Java
gpl-3.0
1,850
import React from 'react'; import Grafico from './Grafico'; class Grafici extends React.Component { render() { return ( <div> <h5 className="mt-3">Grafici</h5> <Grafico titolo="Latenza" xtitle="Misurazioni" ytitle="ms" label="Ping" data={this.props.dataPing} colors={["#ffc107"]}/> <Grafico titolo="Download" xtitle="Misurazioni" ytitle="kb/s" label="Banda" data={this.props.dataDownload} colors={["#007bff"]}/> <Grafico titolo="Upload" xtitle="Misurazioni" ytitle="kb/s" label="Banda" data={this.props.dataUpload} colors={["#28a745"]}/> </div> ) } } export default Grafici;
fondazionebordoni/misurainternet-ui
src/Grafici.js
JavaScript
gpl-3.0
633
/* * ThreadPool.java * * This file is part of the IHMC Util Library * Copyright (c) 1993-2016 IHMC. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 (GPLv3) as published by the Free Software Foundation. * * U.S. Government agencies and organizations may redistribute * and/or modify this program under terms equivalent to * "Government Purpose Rights" as defined by DFARS * 252.227-7014(a)(12) (February 2014). * * Alternative licenses that allow for use within commercial products may be * available. Contact Niranjan Suri at IHMC (nsuri@ihmc.us) for details. */ /** * ThreadPool * * @author Marco Arguedas <marguedas@ihmc.us> * * @version $Revision$ * $Date$ */ package us.ihmc.util; import java.util.ArrayList; import java.util.List; /** * */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class ThreadPool { public ThreadPool (int maxNumWorkers) { if (maxNumWorkers <= 0) { throw new IllegalArgumentException ("maxNumWorker cannot be <= 0"); } _maxNumWorkers = maxNumWorkers; _workers = new ArrayList<ThreadPoolWorker>(); _tasks = new ArrayList<ThreadPoolTask>(); } /** * */ public void enqueue (Runnable runnable, ThreadPoolMonitor tpm) { ThreadPoolTask tpt = new ThreadPoolTask (runnable, tpm); this.checkAndActivateThreads(); synchronized (_tasks) { _tasks.add (tpt); _tasks.notifyAll(); } } //enqueue() /** * */ public void enqueue (Runnable runnable) { this.enqueue (runnable, null); } // ///////////////////////////////////////////////////////////////////////// // PRIVATE METHODS ///////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// /** * */ private ThreadPoolTask dequeueTask() { ThreadPoolTask task = null; synchronized (_tasks) { while (_tasks.isEmpty()) { try { _tasks.wait(); } catch (Exception ex) { ex.printStackTrace(); } } //while() task = _tasks.remove (0); } return task; } //dequeueTask() /** * */ private void threadBusyStatusChanged (boolean threadIsBusy) { synchronized (this) { if (threadIsBusy) { _numBusyWorkers++; } else { _numBusyWorkers--; } } } //threadBusyStatusChanged() /** * */ private void checkAndActivateThreads() { int numWorkers = _workers.size(); if (numWorkers >= _maxNumWorkers) { return; } synchronized (this) { int numIdleWorkers = numWorkers - _numBusyWorkers; if (numIdleWorkers == 0) { ThreadPoolWorker tpt = new ThreadPoolWorker (this); _workers.add (tpt); tpt.start(); } } } //checkAndActivateThreads() // ///////////////////////////////////////////////////////////////////////// // INTERNAL CLASSES //////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// /** * */ private class ThreadPoolTask { public ThreadPoolTask (Runnable r, ThreadPoolMonitor tpm) { runnable = r; tpMon = tpm; } Runnable runnable = null; ThreadPoolMonitor tpMon = null; } //class ThreadPoolTask /** * */ private static class ThreadPoolWorker extends Thread { ThreadPoolWorker (ThreadPool tp) { setName ("ThreadPoolWorker" + (_tpwInstanceCounter++) + "-[" + getName() + "]"); _threadPool = tp; } /** * */ public void run() { while (true) { ThreadPoolTask tpt = _threadPool.dequeueTask(); Exception runnableEx = null; _threadPool.threadBusyStatusChanged (true); try { tpt.runnable.run(); } catch (Exception ex) { runnableEx = ex; } if (tpt.tpMon != null) { try { tpt.tpMon.runFinished (tpt.runnable, runnableEx); } catch (Exception ex) { } //intentionally left blank. } _threadPool.threadBusyStatusChanged (false); } } //run() private ThreadPool _threadPool = null; private static int _tpwInstanceCounter = 0; } // class ThreadPoolWorker /** * */ public interface ThreadPoolMonitor { public void runFinished (Runnable runnable, Exception exception); } //interface ThreadPoolMonitor // ///////////////////////////////////////////////////////////////////////// private int _maxNumWorkers = 0; private int _numBusyWorkers = 0; private final List<ThreadPoolWorker> _workers; private final List<ThreadPoolTask> _tasks; } //class ThreadPool
ihmc/nomads
util/java/us/ihmc/util/ThreadPool.java
Java
gpl-3.0
5,504
// Copyright © 2008-2014 Pioneer Developers. See AUTHORS.txt for details // Licensed under the terms of the GPL v3. See licenses/GPL-3.txt #include "FileSystem.h" #include "FileSourceZip.h" #include "utils.h" #include <cstdio> #include <stdexcept> static const char *ftype_name(const FileSystem::FileInfo &info) { if (info.IsDir()) { return "directory"; } else if (info.IsFile()) { return "file"; } else if (info.IsSpecial()) { return "special"; } else { return "non-existent"; } } void test_normpath() { using namespace FileSystem; const char *TEST_PATHS[] = { "a/b/c", "a/b/c/", "/a/b/c", "a/b/../c", "..", ".", "./", "a/..", "a/b/./.././c/../", "a/b/c/d/../../../../", "a/b/c/d/../../../../../", "/a/b", "/a/b/", 0 }; for (const char **path = TEST_PATHS; *path; ++path) { try { printf("'%s' -> '%s'\n", *path, NormalisePath(*path).c_str()); } catch (std::invalid_argument) { printf("'%s' -> invalid\n", *path); } } printf("'/' + '/a/b/' -> '%s'\n", JoinPathBelow("/", "/a/b/").c_str()); } void test_sanitisename() { const char *TEST_NAMES[] = { "", ".", "..", "hello", "hello world", "hello \"Bob\"", "hello/world", "hello\nworld", 0 }; printf("sanitise names:\n"); for (const char **name = TEST_NAMES; *name; ++name) { const std::string x = FileSystem::SanitiseFileName(*name); printf("'%s' -> '%s'\n", *name, x.c_str()); } } void test_enum_models(FileSystem::FileSource &fs) { using namespace FileSystem; printf("enumerating models:\n"); FileEnumerator files(fs, FileEnumerator::Recurse | FileEnumerator::IncludeDirs); files.AddSearchRoot("models"); while (!files.Finished()) { const FileInfo &fi = files.Current(); if (fi.IsDir() || ends_with_ci(fi.GetPath(), ".model")) { printf(" %s (%s) (%s)\n", fi.GetPath().c_str(), ftype_name(fi), fi.GetSource().GetRoot().c_str()); } files.Next(); } } void test_filesystem() { using namespace FileSystem; test_normpath(); test_sanitisename(); printf("data dir is '%s'\n", FileSystem::GetDataDir().c_str()); printf("user dir is '%s'\n", FileSystem::GetUserDir().c_str()); FileSourceFS fsAppData(FileSystem::GetDataDir()); FileSourceFS fsUserData(FileSystem::JoinPath(FileSystem::GetUserDir(), "data")); //FileSourceZip fsZip("/home/jpab/.pioneer/mods/swapships.zip"); printf("data root is '%s'\n", fsAppData.GetRoot().c_str()); printf("user root is '%s'\n", fsUserData.GetRoot().c_str()); //printf("zip root is '%s'\n", fsZip.GetRoot().c_str()); FileSourceUnion fs; //fs.AppendSource(&fsZip); //printf("Just zip:\n"); //test_enum_models(fs); fs.AppendSource(&fsUserData); fs.AppendSource(&fsAppData); //test_enum_models(fs); //printf("With zip:\n"); //test_enum_models(fs); //fs.RemoveSource(&fsZip); //printf("Just data:\n"); //test_enum_models(fs); }
MeteoricGames/pioneer
src/test_FileSystem.cpp
C++
gpl-3.0
2,833
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2019 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.scxmltest; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import de.interactive_instruments.ShapeChange.TestInstance; import de.interactive_instruments.ShapeChange.Util.XMLUtil; /** * @author Johannes Echterhoff (echterhoff at interactive-instruments dot * de) * */ public class SCXMLTestResourceConverter { /** * Name of the VM argument / system property to indicate that unit tests shall * be executed using the original configuration (by setting the value of the * system property to 'true'), for unit tests with tag SCXML. */ public static final String RUN_ORIGINAL_CONFIGURATIONS_SYSTEM_PROPERTY_NAME = "runOriginalConfigurations"; /** * Name of the VM argument / system property to indicate that the model * resources and ShapeChange configuration of SCXML-tagged unit tests shall be * updated (by setting the value of the system property to 'true') based upon * the original model and configuration files - or created, if they do not exist * yet. The only exception are tests which already solely rely on SCXML models. */ public static final String UPDATE_OR_CREATE_SCXML_RESOURCES_SYSTEM_PROPERTY_NAME = "updateOrCreateScxmlResources"; String suffix_configToExportModel = "_exportModel"; String suffix_configRunWithSCXML = "_runWithSCXML"; File tmpDir = new File("scxmlTmpDir"); public String updateSCXMLTestResources(String configPath) throws Exception { if ("true".equalsIgnoreCase(System.getProperty(RUN_ORIGINAL_CONFIGURATIONS_SYSTEM_PROPERTY_NAME))) { return configPath; } else { if (!tmpDir.exists()) { tmpDir.mkdir(); } // load original config, for creation of SCXML export configs /* * WARNING: The in-memory document will be updated if SCXML really is created! * log, transformers, and targets from the original config will be removed, only * the input will be kept and a new model export target section added. */ Document doc1 = XMLUtil.loadXml(configPath); boolean notPureScxmlTest = hasModelTypeOtherThanSCXML(doc1); if ("true".equalsIgnoreCase(System.getProperty(UPDATE_OR_CREATE_SCXML_RESOURCES_SYSTEM_PROPERTY_NAME)) && notPureScxmlTest) { // create SCXML based models createScxml(doc1, configPath); /* * Load original config again (it would be incorrect to use doc1, because it may * have been updated and used as export configuration). */ Document doc2 = XMLUtil.loadXml(configPath); switchModelsToScxml(doc2, configPath); } String pathToRelevantConfig; if (notPureScxmlTest) { pathToRelevantConfig = getFileForScxmlBasedConfiguration(configPath).getPath(); System.out.println("Unit test execution uses SCXML based configuration " + pathToRelevantConfig); } else { pathToRelevantConfig = configPath; System.out.println( "Unit test execution uses (original) SCXML based configuration " + pathToRelevantConfig); } return pathToRelevantConfig; } } private void switchModelsToScxml(Document configDoc, String configPath) throws Exception { XPath xpath = XPathFactory.newInstance().newXPath(); NodeList modelTypeNodes = (NodeList) xpath.evaluate( "//*[(@name = 'inputModelType' or @name = 'referenceModelType') and @value != 'SCXML']", configDoc, XPathConstants.NODESET); for (int idx = 0; idx < modelTypeNodes.getLength(); idx++) { Node modelTypeNode = modelTypeNodes.item(idx); // set the model type modelTypeNode.getAttributes().getNamedItem("value").setTextContent("SCXML"); // now also get the node with the model file path Node modelPathNode = getModelFilePathNode(modelTypeNode); if (modelPathNode == null) { System.out.println("Model path node not found!"); } else { String modelFilePath = modelPathNode.getAttributes().getNamedItem("value").getTextContent(); String newModelFilePath = getScxmlFilePathForModel(modelFilePath); modelPathNode.getAttributes().getNamedItem("value").setTextContent(newModelFilePath); } } // store updated config File updatedConfig = getFileForScxmlBasedConfiguration(configPath); XMLUtil.writeXml(configDoc, updatedConfig); System.out.println("SCXML based config created: " + updatedConfig.getPath()); } private Node getModelFilePathNode(Node modelTypeNode) throws Exception { XPath xpath = XPathFactory.newInstance().newXPath(); Node modelPathNode = (Node) xpath.evaluate( "./preceding-sibling::*[@name = 'inputFile' or @name = 'repositoryFileNameOrConnectionString' or @name = 'referenceModelFileNameOrConnectionString']", modelTypeNode, XPathConstants.NODE); if (modelPathNode == null) { modelPathNode = (Node) xpath.evaluate( "./following-sibling::*[@name = 'inputFile' or @name = 'repositoryFileNameOrConnectionString' or @name = 'referenceModelFileNameOrConnectionString']", modelTypeNode, XPathConstants.NODE); } return modelPathNode; } // // private File getScxmlFileForModel(String modelFilePath) { // return new File(getScxmlFilePathForModel(modelFilePath)); // } private File getFileForScxmlBasedConfiguration(String configPath) { return new File(FilenameUtils.getPath(configPath) + FilenameUtils.getBaseName(configPath) + suffix_configRunWithSCXML + ".xml"); } private String getScxmlFilePathForModel(String modelFilePath) { return modelFilePath.subSequence(0, modelFilePath.lastIndexOf(".")).toString() + ".zip"; } private boolean hasModelTypeOtherThanSCXML(Document doc) throws Exception { return !findNonScxmlModelOccurrences(doc).isEmpty(); } /** * @param configPath * @throws Exception */ private void createScxml(Document doc, String configPath) throws Exception { // identify all model files that need to be converted to SCXML; for each such // file we also need to know the model type /* * key: model file path, value: model type */ SortedMap<String, String> nonScxmlModelMap = findNonScxmlModelOccurrences(doc); /* * now remove the log, transformation and target elements of the configuration * document */ NodeList logNodes = doc.getElementsByTagName("log"); for (int idx = 0; idx < logNodes.getLength(); idx++) { Node ln = logNodes.item(idx); ln.getParentNode().removeChild(ln); } NodeList transformersNodes = doc.getElementsByTagName("transformers"); for (int idx = 0; idx < transformersNodes.getLength(); idx++) { Node tn = transformersNodes.item(idx); tn.getParentNode().removeChild(tn); } NodeList targetsNodes = doc.getElementsByTagName("targets"); for (int idx = 0; idx < targetsNodes.getLength(); idx++) { Node tn = targetsNodes.item(idx); tn.getParentNode().removeChild(tn); } // now add the model export target configuration Node scConfigNode = doc.getElementsByTagName("ShapeChangeConfiguration").item(0); String scNs = scConfigNode.getNamespaceURI(); String scNsPrefix = scConfigNode.getPrefix(); Node inputNode = doc.getElementsByTagName("input").item(0); Node inputIdAttributeNode = inputNode.getAttributes().getNamedItem("id"); String inputIdAttribute = inputIdAttributeNode == null ? null : inputIdAttributeNode.getTextContent(); Element targetsE = doc.createElementNS(scNs, qname(scNsPrefix, "targets")); scConfigNode.appendChild(targetsE); Element targetE = doc.createElementNS(scNs, qname(scNsPrefix, "Target")); targetsE.appendChild(targetE); targetE.setAttribute("class", "de.interactive_instruments.ShapeChange.Target.ModelExport.ModelExport"); targetE.setAttribute("mode", "enabled"); if (inputIdAttribute != null) { targetE.setAttribute("inputs", inputIdAttribute); } Element outputDirE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter")); targetE.appendChild(outputDirE); outputDirE.setAttribute("name", "outputDirectory"); // value will be set per relevant non-scxml model Element outputFilenameE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter")); targetE.appendChild(outputFilenameE); outputFilenameE.setAttribute("name", "outputFilename"); // value will be set per relevant non-scxml model Element sortedOutputE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter")); targetE.appendChild(sortedOutputE); sortedOutputE.setAttribute("name", "sortedOutput"); sortedOutputE.setAttribute("value", "true"); Element exportProfilesFromWholeModelE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter")); targetE.appendChild(exportProfilesFromWholeModelE); exportProfilesFromWholeModelE.setAttribute("name", "exportProfilesFromWholeModel"); exportProfilesFromWholeModelE.setAttribute("value", "true"); Element zipOutputE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter")); targetE.appendChild(zipOutputE); zipOutputE.setAttribute("name", "zipOutput"); zipOutputE.setAttribute("value", "true"); Element ignoreTaggedValuesRegexE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter")); targetE.appendChild(ignoreTaggedValuesRegexE); ignoreTaggedValuesRegexE.setAttribute("name", "ignoreTaggedValuesRegex"); ignoreTaggedValuesRegexE.setAttribute("value", "^$"); // TBD: maybe profilesInModelSetExplicitly needs to be configured per unit test Element defaultEncodingRuleE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter")); targetE.appendChild(defaultEncodingRuleE); defaultEncodingRuleE.setAttribute("name", "defaultEncodingRule"); defaultEncodingRuleE.setAttribute("value", "export"); Element rulesE = doc.createElementNS(scNs, qname(scNsPrefix, "rules")); targetE.appendChild(rulesE); Element encodingRuleE = doc.createElementNS(scNs, qname(scNsPrefix, "EncodingRule")); rulesE.appendChild(encodingRuleE); encodingRuleE.setAttribute("name", "export"); Element ruleE = doc.createElementNS(scNs, qname(scNsPrefix, "rule")); encodingRuleE.appendChild(ruleE); ruleE.setAttribute("name", "rule-exp-pkg-allPackagesAreEditable"); XPath xpath = XPathFactory.newInstance().newXPath(); Node inputModelTypeNode = (Node) xpath.evaluate( "/*/*[local-name() = 'input']/*[local-name() = 'parameter' and @name = 'inputModelType']", doc, XPathConstants.NODE); Node inputFileNode = (Node) xpath.evaluate( "/*/*[local-name() = 'input']/*[local-name() = 'parameter' and (@name = 'inputFile' or @name = 'repositoryFileNameOrConnectionString')]", doc, XPathConstants.NODE); // create SCXML for each non-scxml model for (Entry<String, String> entry : nonScxmlModelMap.entrySet()) { String modelType = entry.getValue(); String modelFilePath = entry.getKey(); ((Element) inputModelTypeNode).setAttribute("value", modelType); ((Element) inputFileNode).setAttribute("value", modelFilePath); File exportDirectory = new File(tmpDir, "export" + File.separator + FilenameUtils.getBaseName(configPath)); outputDirE.setAttribute("value", exportDirectory.getPath()); outputFilenameE.setAttribute("value", FilenameUtils.getBaseName(modelFilePath)); // config document in temporäres Verzeichnis speichern File exportConfig = new File(tmpDir, FilenameUtils.getBaseName(configPath) + suffix_configToExportModel + ".xml"); XMLUtil.writeXml(doc, exportConfig); System.out.println("Export config created: " + exportConfig.getPath()); // execute export config System.out.println("Running export config ..."); @SuppressWarnings("unused") TestInstance test = new TestInstance(exportConfig.getPath()); System.out.println("... export done"); // get SCXML file that was produced List<Path> scxmlFilePaths = null; try (Stream<Path> files = Files.walk(Paths.get(exportDirectory.toURI()))) { scxmlFilePaths = files.filter( f -> f.getFileName().toString().equals(FilenameUtils.getBaseName(modelFilePath) + ".zip")) .collect(Collectors.toList()); } File scxmlFile = scxmlFilePaths.get(0).toFile(); FileUtils.copyFile(scxmlFile, new File(FilenameUtils.getPath(modelFilePath) + FilenameUtils.getBaseName(modelFilePath) + ".zip")); } } private String qname(String prefix, String name) { return prefix == null ? name : prefix + ":" + name; } // /** // * @param configDoc // * @return can be empty but not <code>null</code> // * @throws Exception // */ // private SortedMap<String, String> findRelevantNonScxmlModelOccurrences(Document configDoc, String configPath) // throws Exception { // // SortedMap<String, String> result = new TreeMap<>(); // // SortedMap<String, String> modelTypeByFilePath = findNonScxmlModelOccurrences(configDoc); // // /* // * Now determine which of these models has an SCXML file that is younger than // * both the original model AND the ShapeChange configuration (because the // * configuration influences the way that a model is loaded, and thus how the // * exported SCXML looks like). // */ // // File configFile = new File(configPath); // // for (Entry<String, String> e : modelTypeByFilePath.entrySet()) { // // String modelFilePath = e.getKey(); // String modelType = e.getValue(); // // File modelFile = new File(modelFilePath); // File scxmlFile = getScxmlFileForModel(modelFilePath); // // if (!scxmlFile.exists() || FileUtils.isFileOlder(scxmlFile, modelFile) // || FileUtils.isFileOlder(scxmlFile, configFile)) { // result.put(modelFilePath, modelType); // } // } // // return result; // } /** * @param configDoc * @return map with model file path as key and model type as value; can be empty * but not <code>null</code> * @throws Exception */ private SortedMap<String, String> findNonScxmlModelOccurrences(Document configDoc) throws Exception { SortedMap<String, String> modelTypeByFilePath = new TreeMap<>(); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList modelTypeNodes = (NodeList) xpath.evaluate( "//*[(@name = 'inputModelType' or @name = 'referenceModelType') and @value != 'SCXML']", configDoc, XPathConstants.NODESET); for (int idx = 0; idx < modelTypeNodes.getLength(); idx++) { Node modelTypeNode = modelTypeNodes.item(idx); // identify the model type String modelType = modelTypeNode.getAttributes().getNamedItem("value").getTextContent(); // now also get the model file path Node modelPathNode = (Node) xpath.evaluate( "./preceding-sibling::*[@name = 'inputFile' or @name = 'repositoryFileNameOrConnectionString' or @name = 'referenceModelFileNameOrConnectionString']", modelTypeNode, XPathConstants.NODE); if (modelPathNode == null) { modelPathNode = (Node) xpath.evaluate( "./following-sibling::*[@name = 'inputFile' or @name = 'repositoryFileNameOrConnectionString' or @name = 'referenceModelFileNameOrConnectionString']", modelTypeNode, XPathConstants.NODE); } if (modelPathNode == null) { System.out.println("Model path node not found!"); } else { String modelFilePath = modelPathNode.getAttributes().getNamedItem("value").getTextContent(); modelTypeByFilePath.put(modelFilePath, modelType); } } return modelTypeByFilePath; } }
ShapeChange/ShapeChange
src/test/java/de/interactive_instruments/ShapeChange/scxmltest/SCXMLTestResourceConverter.java
Java
gpl-3.0
16,951
package com.lamer.rc_model_car; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.Set; import java.util.UUID; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbAccessory; import android.hardware.usb.UsbManager; import android.os.Handler; import android.os.Message; import android.os.ParcelFileDescriptor; import android.os.ParcelUuid; import android.util.Log; import android.widget.Toast; public class ArduinoModule implements Runnable { //Context mComtext=null; BluetoothAdapter mBluetoothAdapter; BluetoothSocket mmSocket; BluetoothDevice mmDevice; OutputStream mmOutputStream; InputStream mmInputStream; byte[] readBuffer; int readBufferPosition; int counter; volatile boolean stopWorker; private Context mComtext; public int create(Context context){ mComtext=context; return 0; } private int findBT() { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if(mBluetoothAdapter == null) { Log.v("Arduino BT","Bluetooth null !"); Toast.makeText(mComtext, "Bluetooth is not available", Toast.LENGTH_LONG).show(); return 0; } if(!mBluetoothAdapter.isEnabled()) { Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); return 0; //startActivityForResult(enableBluetooth, 0); } Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if(pairedDevices.size() > 0) { for(BluetoothDevice device : pairedDevices) { if(device.getName().equals("HC-06")) { mmDevice = device; Log.v("Arduino BT","Bluetooth Device Found"); return 1; } } } return 0; } private int openBT() { UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard //SerialPortService ID //final String PBAP_UUID = "0000112f-0000-1000-8000-00805f9b34fb"; //standard pbap uuid //UUID uuid = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); //mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); try { mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); } catch (Exception e) {Log.e("Arduino BT","Error creating socket");} try { mmSocket.connect(); Log.e("Arduino BT","Connected"); } catch (IOException e) { Log.e("Arduino BT",e.getMessage()); try { Log.v("Arduino BT","trying fallback..."); //mmSocket =(BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mmDevice,uuid); Method m = mmDevice.getClass().getMethod("createRfcommSocket", int.class); mmSocket = (BluetoothSocket)m.invoke(mmDevice, 1); mmSocket.connect(); Log.v("Arduino BT","Connected"); } catch (Exception e2) { e2.printStackTrace(); try { mmSocket.close(); Log.v("Arduino BT","Couldn't establish Bluetooth connection! (1)"); } catch (IOException closeException) { closeException.printStackTrace(); Log.v("Arduino BT","Couldn't establish Bluetooth connection! (2)"); } return 0; } } if(mmSocket==null)return 0; //mmSocket.connect(); try{ mmOutputStream = mmSocket.getOutputStream(); mmInputStream = mmSocket.getInputStream(); beginListenForData(); connecting=false; }catch (NullPointerException e){ connecting=false; mmSocket=null; mmOutputStream=null; mmInputStream=null; return 0; } catch (IOException e) { e.printStackTrace(); closeBT(); } return 1; } void beginListenForData() { //final Handler handler = new Handler(); final byte delimiter = 10; //This is the ASCII code for a newline character stopWorker = false; readBufferPosition = 0; readBuffer = new byte[1024]; new Thread(this).start(); //workerThread.start(); } boolean connecting=false; public int tryConnect(){ if(connecting)return 2; connecting=true; if(findBT()>0){ int ret = openBT(); connecting=false; return ret; } connecting=false; return 0; } void sendData(String string){ try{ if(!stopWorker && mmOutputStream!=null && isConnected()) { mmOutputStream.write(string.getBytes()); mmOutputStream.flush(); }else{ if(tryConnect()>0) { mmOutputStream.write(string.getBytes()); mmOutputStream.flush(); } } } catch (IOException e) { closeBT(); // TODO Auto-generated catch block e.printStackTrace(); } } void closeBT(){ stopWorker = true; try{ mmSocket.close(); mmSocket=null; if(mmOutputStream!=null) mmOutputStream.close(); if(mmInputStream!=null) mmInputStream.close(); mmOutputStream=null; mmInputStream=null; mmDevice=null; }catch(NullPointerException e){ Log.v("Arduino BT","Bluetooth Bad close"); mmSocket=null; mmDevice=null; mmOutputStream=null; mmInputStream=null; }catch (IOException e) { Log.v("Arduino BT","Bluetooth IO Bad close"); mmSocket=null; mmDevice=null; mmOutputStream=null; mmInputStream=null; } Log.v("Arduino BT","Bluetooth Closed"); } public boolean isConnected(){ try{ boolean a=mmSocket.isConnected(); return a; }catch (NullPointerException e){ return false; } //return mmOutputStream!=null; } @Override public void run() { // final Handler handler = new Handler(); final byte delimiter = 10; //This is the ASCII code for a newline character stopWorker = false; readBufferPosition = 0; readBuffer = new byte[1024]; while(!Thread.currentThread().isInterrupted() && !stopWorker) { try { int bytesAvailable = mmInputStream.available(); if(bytesAvailable > 0) { Log.v("Arduino BT","Bluetooth bytesAvailable:"+bytesAvailable); byte[] packetBytes = new byte[bytesAvailable]; mmInputStream.read(packetBytes); StringBuilder byStr = new StringBuilder(); for(int i=0;i<bytesAvailable;i++) { byte b = packetBytes[i]; byStr.append( (char)b); /*if(b == delimiter) { byte[] encodedBytes = new byte[readBufferPosition]; System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length); final String data = new String(encodedBytes, "US-ASCII"); readBufferPosition = 0; /*handler.post(new Runnable() { public void run() { myLabel.setText(data); } });/ } else { readBuffer[readBufferPosition++] = b; }*/ } Log.v("Arduino BT","Bluetooth:"+byStr.toString()); } } catch (IOException ex) { stopWorker = true; } try { Thread.sleep(100); } catch (InterruptedException e) { stopWorker = true; } } } }
whitelamer/android-bt-rc-car
src/com/lamer/rc_model_car/ArduinoModule.java
Java
gpl-3.0
8,713
/* Copyright © 2014, Ryan Pavlik This file is part of xleapmouse. xleapmouse 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. xleapmouse 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 xleapmouse. If not, see <http://www.gnu.org/licenses/>. */ void get_xy(Display *dpy, Window &root, int &x, int &y) { Window r_root, r_child; int winx, winy; unsigned int mask; XQueryPointer(dpy, root, &r_root, &r_child, &x, &y, &winx, &winy, &mask); }
rpav/xleapmouse
src/util.cpp
C++
gpl-3.0
931
from django.urls import path from .views import redirect_to_archive urlpatterns = [path("<str:media_id>/", redirect_to_archive)]
whav/hav
src/hav/apps/media/urls.py
Python
gpl-3.0
130
# -*- coding: utf-8 -*- ''' Mepinta Copyright (c) 2011-2012, Joaquin G. Duo This file is part of Mepinta. Mepinta 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. Mepinta 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 Mepinta. If not, see <http://www.gnu.org/licenses/>. ''' from unittest import TestLoader from unittest.runner import TextTestRunner from common.abstract.FrameworkObject import FrameworkObject class TestDiscoveryManager(FrameworkObject): # Cannot be FrameworkBase because contexts are init in tests def __getPluginsTestDir(self): import plugins_tests.python as package return package.__path__[0] def runAllTests(self): test_suite = TestLoader().discover(start_dir=self.__getPluginsTestDir(), pattern='*.py', top_level_dir=self.__getPluginsTestDir()) TextTestRunner().run(test_suite) def testModule(): TestDiscoveryManager().runAllTests() if __name__ == "__main__": testModule()
joaduo/mepinta
core/python_core/mepinta/testing/plugins_testing/TestDiscoveryManager.py
Python
gpl-3.0
1,427
package com.megathirio.shinsei.item.powder; import com.megathirio.shinsei.item.PowderShinsei; import com.megathirio.shinsei.reference.Names; public class ItemBariumPowder extends PowderShinsei { public ItemBariumPowder(){ super(); this.setUnlocalizedName(Names.Powders.BARIUM_POWDER); } }
Mrkwtkr/shinsei
src/main/java/com/megathirio/shinsei/item/powder/ItemBariumPowder.java
Java
gpl-3.0
315
import numpy as np from scipy import constants from scipy.integrate import quad # Boltzmann constant in eV/K k = constants.value('Boltzmann constant in eV/K') class Flux() : """ This class evaluates the neutron spectrum. The thermal cutoff is treated as a variable parameter to ensure a specific fast-to-thermal ratio. At thermal energy range (e < e1 eV), the flux is approximated by Maxwellian distribution (D&H book Eq.(9-6)). At fast energy range (e2 MeV < e < 20MeV), the flux is approximated by U-235 chi-spectrum (D&H book Eq.(2-112)). At epithermal energies (e1 eV < e < e2 MeV), flux = 1/e ratio : fast-to-thermal flux ratio """ def __init__(self, ratio = 2, thermal_temp = 600.0): self.e2 = 1e6 self.thermal_temp = thermal_temp # Maxwellian distribution, Eq.(9-6) self.m = lambda x : x ** 0.5 * np.exp(-x/(k*self.thermal_temp)) # U235 chi distribution, Eq.(2-112) self.chi = lambda x : np.exp(-1.036e-6*x)*np.sinh((2.29e-6 * x)**0.5) # Middle energy range self.f = lambda x : 1 / x # Compute ratio as a function of thermal cutoff E = np.logspace(-4, 0.1, 200) R = np.array([self.compute_ratio(e1) for e1 in E]) # Compute thermal cutoff for given ratio self.e1 = np.interp(1.0/ratio, R, E) print 'Thermal cutoff is {} eV'.format(self.e1) # Compute constants for each part of the spectrum self.c1 = 1.0 self.c2 = self.m(self.e1) / self.f(self.e1) self.c3 = self.c2 * self.f(self.e2) / self.chi(self.e2) def compute_ratio(self, e1): A = quad(self.m, 0, e1)[0] C2 = self.m(e1) / self.f(e1) C3 = self.f(self.e2) / self.chi(self.e2) B = C2 * quad(self.f, e1, self.e2)[0] C = C2 * C3 * quad(self.chi, self.e2, 2e7)[0] r = A / (B + C) return r def evaluate(self, e): # Evaluate flux at Energy e in eV return (e<=self.e1) * self.c1*self.m(e) + \ (e>self.e1)*(e<=self.e2) * (self.c2 / e) + \ (e>self.e2) * self.c3*self.chi(e) if __name__ == "__main__" : import matplotlib.pyplot as plt from multigroup_utilities import * from nice_plots import init_nice_plots init_nice_plots() # PWR-like and TRIGA-like spectra pwr = Flux(7.0, 600.0) triga = Flux(1.0, 600.0) # Evaluate the flux E = np.logspace(-5, 7, 1000) phi_pwr = pwr.evaluate(E) phi_triga = triga.evaluate(E) # Collapse the flux and flux per unit lethargy onto WIMS 69-group structure bounds = energy_groups(structure='wims69') pwr_mg = collapse(bounds, phi_pwr, E) triga_mg = collapse(bounds, phi_triga, E) phi_mg_pul = collapse(bounds, E*phi_pwr, E) triga_mg_pul = collapse(bounds, E*phi_triga, E) # Produce step-plot data for each spectrum E_mg, phi_mg = plot_multigroup_data(bounds, pwr_mg) _, triga_mg = plot_multigroup_data(bounds, triga_mg) _, phi_mg_pul = plot_multigroup_data(bounds, phi_mg_pul) _, triga_mg_pul = plot_multigroup_data(bounds, triga_mg_pul) plt.figure(1) plt.loglog(E, phi_pwr, 'k', E_mg, phi_mg, 'k--', E, phi_triga, 'b', E_mg, triga_mg, 'b:') plt.xlabel('$E$ (eV)') plt.ylabel('$\phi(E)$') plt.figure(2) plt.loglog(E, E*phi_pwr, 'k', E_mg, phi_mg_pul, 'k--', E, E*phi_triga, 'b', E_mg, triga_mg_pul, 'b:') plt.xlabel('$E$ (eV)') plt.ylabel('$E\phi(E)$') plt.show()
corps-g/flux_spectrum
flux_spectrum.py
Python
gpl-3.0
3,697
#! python3 # coding: utf-8 # todo # multithreader par machine # nettoyer le code import os import sys import configparser import logging import re import gc import traceback import getpass from logging import FileHandler from colorama import Fore import colorama colorama.init() #logger = logging.getLogger('MagretUtil') ##logger_info = logging.getLogger('Info') #logger.setLevel(logging.WARNING) ##logger_info.setLevel(logging.INFO) #formatter = logging.Formatter('%(asctime)s :: %(name)s :: %(levelname)s\n' + '=' * 100 + '\n%(message)s' + '=' * 100) ## file_handler = RotatingFileHandler('error.log', mode='w', 1000000, 1) #file_handler = FileHandler('error.log', 'w') #file_handler.setLevel(logging.WARNING) #file_handler.setFormatter(formatter) #logger.addHandler(file_handler) #stream_handler = logging.StreamHandler() #stream_handler.setLevel(logging.INFO) #logger_info.addHandler(stream_handler) from Groupe import Groupe from Salle import Salle import commandes import var_global import Privilege import AutoComplete def _protect_quotes(text): lst = text.split('"') for i, item in enumerate(lst): if i % 2: lst[i] = re.sub(r'\s', "::", item) return '"'.join(lst) def _remove_protect_char(lst_str): return [re.sub(r'::', ' ', s) for s in lst_str] def lire_fichier_ini(fichier): """ Retourne les variables necessaire pour le fonctionnement retourne un dictionnaire {nom_groupe:nbre_poste}""" try: config = configparser.ConfigParser() config.read(fichier, encoding="utf-8-sig") except configparser.Error: print(Fore.LIGHTRED_EX + "[!] Erreur lors de l'initialisation du fichier ini : " + Fore.RESET) raise SystemExit(0) groupes_dict = {} groupes_dict['GroupesMagret'] = {} groupes_dict['Groupes'] = {} groupes_dict['GroupesFile'] = {} domaine = {} try: try: for groupe in config['GroupesMagret']: num_poste = config['GroupesMagret'][groupe].split('-')[1] try: nbre_poste = int(num_poste[1:]) except ValueError: nbre_poste = 0 if nbre_poste != 0: groupes_dict['GroupesMagret'][groupe.upper()] = nbre_poste except KeyError: print(Fore.LIGHTMAGENTA_EX + "[!] Aucun groupe Magret" + Fore.RESET) try: for groupe in config['Groupes']: groupes_dict['Groupes'][groupe.upper()] = config['Groupes'][groupe] except KeyError: print(Fore.LIGHTMAGENTA_EX + "[!] Aucun groupe non Magret" + Fore.RESET) try: groupes_dict['GroupesFile']['file'] = config['GroupesFile']['file'] except KeyError: print(Fore.LIGHTMAGENTA_EX + "[!] Aucun fichier pour définir des groupes" + Fore.RESET) except Exception as e: print(Fore.LIGHTRED_EX + '[!] Erreur de lecture du fichier config' + Fore.RESET) #logger.critical(e) raise e domaine['name'] = config.get('Domaine', 'domaine', fallback=None) domaine['login'] = config.get('Domaine', 'login', fallback=None) return groupes_dict, domaine def erreur_final(e_type, e_value, e_tb): if e_type == KeyboardInterrupt: raise SystemExit(0) print(Fore.LIGHTRED_EX + '[!] Erreur critique, voir le fichier de log' + Fore.RESET) os.system("pause") with open("error.log", "w") as f: f.write(''.join(traceback.format_exception(e_type, e_value, e_tb))) #logger.critical(''.join(traceback.format_exception(e_type, e_value, e_tb))) # pdb.post_mortem(e_tb) return # def init_groupes_old(ini_groupes): # global groupes, selected_groupes, machines_dict # # for ini_salle, nbre in ini_groupes['GroupesMagret'].items(): # groupes.append(Salle(ini_salle, nbre)) # for ini_groupe, list_machine in ini_groupes['Groupes'].items(): # list_machine = list_machine.split(',') # groupes.append(Groupe(ini_groupe, list_machine)) # groupes.sort(key=lambda x: x.name) # # machines_dict.update({machine.name: machine for g in groupes for machine in g}) # return def init_groupes(ini_groupes): groupes_machines_names = {} all_names_machines = [] # [GroupesMagret] for ini_salle, nbre in ini_groupes['GroupesMagret'].items(): # on reécrit le nom des machines num = len(str(nbre)) if nbre >= 10 else 2 str_template = '%s-P%0--i'.replace('--', str(num)) names_machines = [str_template % (ini_salle, i) for i in range(1, nbre + 1)] # dict qui fait le lien nom groupe-noms de machines groupes_machines_names[ini_salle] = names_machines # on crée une salle vide qu'on remplire plus tard # on l'ajoute aux groupes globaux var_global.groupes.append(Salle(ini_salle, 0)) all_names_machines.extend(names_machines) # [Groupes] for ini_groupe, list_machines in ini_groupes['Groupes'].items(): list_machines = list_machines.split(',') groupes_machines_names[ini_groupe] = list_machines all_names_machines.extend(list_machines) var_global.groupes.append(Groupe(ini_groupe, [])) # [GroupesFile] try: file = open(ini_groupes['GroupesFile']['file'], encoding="utf-8-sig", errors='replace') for line in file: list_name = line.strip(" \n,").split(',') if list_name[1:]: all_names_machines.extend(list_name[1:]) groupes_machines_names[list_name[0]] = list_name[1:] var_global.groupes.append(Groupe(list_name[0], [])) except FileNotFoundError: print(Fore.LIGHTRED_EX + "[!] Fichier csv introuvable" + Fore.RESET) except KeyError: pass # code ansi pour remonter le curseur : c'est plus jolie up = len(var_global.groupes) + 1 print('\x1b[%sA' % up) # on crée un groupe avec toute les machines, ça permet de lancer # une action en multithreadant sur toutes les machines # on met à jour le dictionnaire des machines existantes var_global.groupe_selected_machines = Groupe('en cours', all_names_machines) var_global.machines_dict.update(var_global.groupe_selected_machines.dict_machines) # on remplie les groupes avec les machines créés au dessus for g in var_global.groupes: machines = [i for k, i in var_global.machines_dict.items() if k in groupes_machines_names[g.name]] g.machines = machines g.dict_machines = {m.name: m for m in machines} g.machines.sort(key=lambda x: x.name) var_global.groupes.sort(key=lambda x: x.name) return def main(): sys.excepthook = erreur_final try: if not os.path.isdir('mac'): os.mkdir('mac') except: print(Fore.LIGHTRED_EX + "[!] Erreur lors de la création du répertoire mac" + Fore.RESET) os.system("pause") print(Fore.LIGHTGREEN_EX + '[+] Lecture de conf.ini' + Fore.RESET) ini_groupes, dom = lire_fichier_ini('conf.ini') # on initialise la variable domaine qui contient le login administrateur # du domaine var_global.domaine.update(dom) # Si le login du fichier config est différent que celui avec lequel # on est connecté, on lance la procédure délévation de privilège if var_global.domaine['login'] is not None and getpass.getuser() != var_global.domaine['login']: commandes.password([]) # Si une demande de bypasser l'uac est demandé, on lance la procédure if sys.argv[1:] and sys.argv[1] == "pass_uac": Privilege.pass_uac() raise SystemExit(0) #logger_info.info('Création des alias') print(Fore.LIGHTGREEN_EX + '[+] Création des alias' + Fore.RESET) alias_cmd = var_global.lire_alias_ini() print(Fore.LIGHTGREEN_EX + '[+] Initialisation des salles :' + Fore.RESET) init_groupes(ini_groupes) AutoComplete.init_auto_complete() # efface l'écran print('\x1b[2J', end='') commandes.select(['*']) print('-' * (os.get_terminal_size().columns - 1)) print(Fore.LIGHTGREEN_EX + "Taper help ou la touche 'enter' pour obtenir de l'aide" + Fore.RESET) print('-' * (os.get_terminal_size().columns - 1)) while True: param = input('>>>') param = _protect_quotes(param) param = param.strip() param = param.split(' ') param = _remove_protect_char(param) cmd = param[0] if cmd in alias_cmd: # permet de créer des alias avec un parametre str_replace ="" if param[1:]: str_replace = " ".join(param[1:]) param = _protect_quotes(alias_cmd[cmd].replace("$$",str_replace)) param = param.strip() param = param.split(' ') param = _remove_protect_char(param) cmd = param[0] param.remove(cmd) cmd = cmd.lower() cmd_funct = getattr(commandes, cmd, commandes.help) try: # on efface la dernière erreur avant de lancer # la prochaine commande if cmd != 'errors': for m in var_global.groupe_selected_machines: m.message_erreur = '' cmd_funct(param) # nettoie une partie de ceux qui a été laissé par les threads # de la dernière commande # contrôle l'augmentation de la mémoire pour le multithread gc.collect() # print('com-ref: ', pythoncom._GetInterfaceCount()) print('-' * (os.get_terminal_size().columns - 1)) except Warning: cmd_funct(['help']) gc.collect() # print(pythoncom._GetInterfaceCount()) print('-' * (os.get_terminal_size().columns - 1)) if __name__ == '__main__': main()
bbmt-bbmt/MagretUtil
source/MagretUtil.py
Python
gpl-3.0
9,880
<script> function puntuar(valor){ $(function(){ form = document.forms["form1"]; cr = form.elements["critica"].value; ju = form.elements["juego"].value; us = form.elements["usuario"].value; destino = "<?= base_url('index.php/criticas/puntuar') ?>"; $.post(destino,{critica: cr, juego: ju, usuario: us, confirmar: valor},function(respuesta){ $("#contenido").html(respuesta); }); }); } </script> <div id="contenido"> <?php if (isset($mensaje)): ?> <div id="mensaje"> <p><?= $mensaje ?></p> </div> <?php endif; ?> <?php if ($usuario == $this->session->userdata('id')): ?> <h1>Crítica de <?= anchor('juegos/index/'.$juego, $nombrejuego) ?> por tí</h1> <?php else: ?> <h1>Crítica de <?= anchor('juegos/index/'.$juego, $nombrejuego) ?> por <?= anchor("usuarios/index/".$usuario, $nombreusuario) ?></h1> <?php endif;?> <div class="capa"> <table> <tr> <td> <?= anchor("usuarios/index/".$usuario, "<img class='avatar' src=".base_url('imagenes/'.$avatar)." />") ?> </td> <td class="celda_descripcion"> <h3 <?= ($karma < 0) ? "class='negativo'" : "class='positivo'" ?>> Karma del autor: <?= $karma ?> punto<?php if ($karma != 1 && $karma != -1) echo "s"; ?> </h3> </td> </tr> <tr> <td> <?= anchor('juegos/index/'.$juego, "<img class='caratula_pequeña' src=".base_url('imagenes/'.$caratula)." />") ?> </td> <td class="celda_descripcion"> <h3 <?= ($media < 5) ? "class='negativo'" : "class='positivo'" ?>> Nota media del juego: <?= $media ?> </h3> </td> </tr> </table> </div> <fieldset><legend>Contenido</legend> <span id="capa_nota"> <h2 <?= ($nota < 5) ? "class='negativo'" : "class='positivo'" ?>> Nota: <?= $nota ?> </h2> </span> <br/><br/> <div class="capa"> <?= $contenido ?> </div> <br/> <div style="text-align: right;"> <em style="font-size: small;">Realizado el <?= date("d-m-Y", strtotime($fecha)) ?></em> <br/> </div> </fieldset> <div class="capa"> <br/> <div> <?php if ($votos == 0): ?> Aún no han valorado esta crítica <?php else: ?> <div class="caja_de_barra"> <div id="barra_positiva" style="width: <?= $positivos ?>%;"><?= $positivos ?>%</div> Valoraciones positivas </div> <br/> <div class="caja_de_barra"> <div id="barra_negativa" style="width: <?= (100 - $positivos) ?>%;"><?= (100 - $positivos) ?>%</div> Valoraciones negativas </div> <br/> <?php endif; ?> </div> <?php if ($this->session->userdata('id')): ?> <?php if ($usuario != $this->session->userdata('id')): ?> <div id="capa_valoracion"> <form name="form1" id="form1"> <?= form_hidden('critica', $id) ?> <?= form_hidden('juego', $juego) ?> <?= form_hidden('usuario', $usuario) ?> <?php if (!isset($valoracion)): ?> <input type="button" name="confirmar" class="boton" value="Dar punto positivo" onClick="puntuar('Dar punto positivo');"/> <input type="button" name="confirmar" class="boton" value="Dar punto negativo" onClick="puntuar('Dar punto negativo');"/> <?php elseif ($valoracion == 1): ?> <em class="positivo">Has puntuado positivamente esta crítica</em> <input type="button" name="confirmar" class="boton" value="Retirar punto" onClick="puntuar('Retirar punto');"/> <input type="button" name="confirmar" class="boton" value="Dar punto negativo" onClick="puntuar('Dar punto negativo');"/> <?php elseif ($valoracion == -1): ?> <em class="negativo">Has puntuado negativamente esta crítica</em> <input type="button" name="confirmar" class="boton" value="Retirar punto" onClick="puntuar('Retirar punto');"/> <input type="button" name="confirmar" class="boton" value="Dar punto positivo" onClick="puntuar('Dar punto positivo');"/> <?php endif; ?> </form> </div> <?php else: ?> <?= form_open('criticas/editar/'.$juego) ?> <?= form_hidden('critica', $id) ?> <?= form_submit('editar', 'Editar crítica', "class='boton'") ?> <?= form_close() ?> <?php endif; ?> <br/> <?php if ($votos == 0): ?> <?php elseif ($votos == 1 && isset($valoracion)): ?> Solamente tú has puntuado esta crítica <?php elseif ($votos == 2 && isset($valoracion)): ?> <?= anchor('usuarios/listar/critica/'.$id, 'Otra persona') ?> más ha puntuado esta crítica <?php elseif ($votos == 1 && !isset($valoracion)): ?> <?= anchor('usuarios/listar/critica/'.$id, 'Una persona') ?> ha puntuado esta crítica <?php elseif ($votos > 1 && !isset($valoracion)): ?> <?= anchor('usuarios/listar/critica/'.$id, "$votos personas") ?> puntuaron esta crítica <?php else: ?> <?= anchor('usuarios/listar/critica/'.$id, "Otras ".($votos-1)." personas") ?> más puntuaron esta crítica <?php endif; ?> <?php endif; ?> </div> </div>
tonigallego/gamerland
application/views/criticas/index.php
PHP
gpl-3.0
5,024
/* * Copyright (C) 2005-2012 BetaCONCEPT Limited. * * This file is part of Astroboa. * * Astroboa 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. * * Astroboa 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 Astroboa. If not, see <http://www.gnu.org/licenses/>. */ package org.betaconceptframework.astroboa.api.model.io; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.betaconceptframework.astroboa.api.model.ContentObject; import org.betaconceptframework.astroboa.api.model.ValueType; /** * Contains configuration for import/deserialization process. * * <p> * ImportConfiguration allows users to control how to import content * to an Astroboa repository. * </p> * * <p> * In order to build a configuration, one must specify the type * of the entity whose instances will be imported and then, she must * use the available methods in order to provide values to one or more * parameters. Finally, method <code>build</code> must be called to complete * configuration creation. * * For example, configuration for importing objects can be declared like this: * * <pre> * ImportConfiguration configuration = ImportConfiguration.object() .persist(PersistMode.PERSIST_MAIN_ENTITY) .version(false) .updateLastModificationTime(false) .build(); * </pre> * * </p> * * * @author Gregory Chomatas (gchomatas@betaconcept.com) * @author Savvas Triantafyllou (striantafyllou@betaconcept.com) * */ public class ImportConfiguration implements Serializable{ /** * */ private static final long serialVersionUID = -2785751336766426516L; public enum PersistMode { /** * Import content to all * corresponding entities but do not persist them. */ DO_NOT_PERSIST, /** * Import content to all * corresponding entities and persist them. */ PERSIST_MAIN_ENTITY, /** * Import content to all corresponding entities * and persist not only the main entity but the whole * entity tree. * Used mainly for Topic, Taxonomy and Space. */ PERSIST_ENTITY_TREE, } /** * <code>true</code> to create a new version for content * object, <code>false</code> otherwise. * It is used only when <code>save</code> is <code>true</code> * and imported entity is a {@link ContentObject}. */ private final boolean version; /** * Control whether to persist or not * imported content */ private final PersistMode persistMode; /** * <code>true</code> to change last modification date of the imported entity, * <code>false</code> otherwise. * It is used only when <code>save</code> is <code>true</code> * and imported entity is a {@link ContentObject}. */ private final boolean updateLastModificationTime; /** * Define the behavior of the import process when the values of one or more properties * of the objects being imported, are references to other objects which do not exist in * the repository. * * The default behavior is to stop the import process and to throw an exception, in order * to notify the user for the non-existence of the objects. * * Set this flag to <code>true</code> in order to suppress this behavior and to allow * the import process to continue. In this case, a warning is issued, the missing * reference is saved as the value of the property as if the referred object exists and the * import process smoothly continues. * */ private final boolean saveMissingObjectReferences; /** * Map containing the binary content of one or more properties of type {@link ValueType#Binary}. * The key of the map must match the value of the 'url' attribute of the property * in the XML/JSON representation of the content. * It is used only when imported entity is a {@link ContentObject}. */ private final Map<String, byte[]> binaryContent; /** * User credentials to be used when downloading binary content * from a provided URL in order to save it to a repository. * If any credentials are provided then an authorization header will be * created and it will be used upon request. */ private final Credentials credentialsOfUserWhoHasAccessToBinaryContent; public static class Configuration implements Serializable { /** * */ private static final long serialVersionUID = -8216577761965559480L; protected PersistMode persistMode; protected boolean version; protected boolean updateLastModificationTime; protected Map<String, byte[]> binaryContent; protected boolean saveMissingObjectReferences; protected Credentials credentialsOfUserWhoHasAccessToBinaryContent; private Configuration(){ } public ImportConfiguration build(){ return new ImportConfiguration(this); } } public static class TaxonomyImportConfiguration extends Configuration{ /** * */ private static final long serialVersionUID = 6987813675753693566L; private TaxonomyImportConfiguration(){ super(); } public TaxonomyImportConfiguration persist(PersistMode persistMode){ this.persistMode = persistMode; return this; } } public static class TopicImportConfiguration extends Configuration{ /** * */ private static final long serialVersionUID = -8672051521906802611L; private TopicImportConfiguration(){ super(); } public TopicImportConfiguration persist(PersistMode persistMode){ this.persistMode = persistMode; return this; } } public static class RepositoryUserImportConfiguration extends Configuration{ /** * */ private static final long serialVersionUID = -3327651249846102439L; private RepositoryUserImportConfiguration(){ super(); } public RepositoryUserImportConfiguration persist(PersistMode persistMode){ this.persistMode = persistMode; return this; } } public static class SpaceImportConfiguration extends Configuration{ /** * */ private static final long serialVersionUID = -3119157151529381090L; private SpaceImportConfiguration(){ super(); } public SpaceImportConfiguration persist(PersistMode persistMode){ this.persistMode = persistMode; return this; } } public static class RepositoryImportConfiguration extends Configuration{ /** * */ private static final long serialVersionUID = -717092049149850366L; private RepositoryImportConfiguration(){ super(); this.persistMode = PersistMode.PERSIST_ENTITY_TREE; this.saveMissingObjectReferences = false; } public RepositoryImportConfiguration version(boolean version){ this.version = version; return this; } public RepositoryImportConfiguration updateLastModificationTime(boolean updateLastModificationTime){ this.updateLastModificationTime = updateLastModificationTime; return this; } public RepositoryImportConfiguration addBinaryContent(String binaryContentId, byte[] binaryContent){ if (binaryContentId == null || binaryContentId.trim().length() == 0){ return this; } if (this.binaryContent == null){ this.binaryContent = new HashMap<String, byte[]>(); } this.binaryContent.put(binaryContentId, binaryContent); return this; } public RepositoryImportConfiguration addBinaryContent(Map<String, byte[]> binaryContent){ if (binaryContent == null || binaryContent.isEmpty()){ return this; } if (this.binaryContent == null){ this.binaryContent = new HashMap<String, byte[]>(); } this.binaryContent.putAll(binaryContent); return this; } public RepositoryImportConfiguration saveMissingObjectReferences(boolean saveMissingObjectReferences){ this.saveMissingObjectReferences = saveMissingObjectReferences; return this; } public RepositoryImportConfiguration credentialsOfUserWithAccessToBinaryContent(String username, String password){ this.credentialsOfUserWhoHasAccessToBinaryContent = new Credentials(username, password); return this; } } public static class ObjectImportConfiguration extends Configuration { /** * */ private static final long serialVersionUID = -1749977202658061221L; private ObjectImportConfiguration(){ super(); this.updateLastModificationTime = true; //Default value is true } public ObjectImportConfiguration version(boolean version){ this.version = version; return this; } public ObjectImportConfiguration persist(PersistMode persistMode){ this.persistMode = persistMode; return this; } public ObjectImportConfiguration updateLastModificationTime(boolean updateLastModificationTime){ this.updateLastModificationTime = updateLastModificationTime; return this; } public ObjectImportConfiguration addBinaryContent(String binaryContentId, byte[] binaryContent){ if (binaryContentId == null || binaryContentId.trim().length() == 0){ return this; } if (this.binaryContent == null){ this.binaryContent = new HashMap<String, byte[]>(); } this.binaryContent.put(binaryContentId, binaryContent); return this; } public ObjectImportConfiguration addBinaryContent(Map<String, byte[]> binaryContent){ if (binaryContent == null || binaryContent.isEmpty()){ return this; } if (this.binaryContent == null){ this.binaryContent = new HashMap<String, byte[]>(); } this.binaryContent.putAll(binaryContent); return this; } public ObjectImportConfiguration saveMissingObjectReferences(boolean saveMissingObjectReferences){ this.saveMissingObjectReferences = saveMissingObjectReferences; return this; } public ObjectImportConfiguration credentialsOfUserWithAccessToBinaryContent(String username, String password){ this.credentialsOfUserWhoHasAccessToBinaryContent = new Credentials(username, password); return this; } } private ImportConfiguration(Configuration builder) { this.persistMode = builder.persistMode; this.binaryContent = builder.binaryContent; this.updateLastModificationTime = builder.updateLastModificationTime; this.version = builder.version; this.saveMissingObjectReferences = builder.saveMissingObjectReferences; this.credentialsOfUserWhoHasAccessToBinaryContent = builder.credentialsOfUserWhoHasAccessToBinaryContent; } public static ObjectImportConfiguration object(){ return new ObjectImportConfiguration(); } public static RepositoryImportConfiguration repository(){ return new RepositoryImportConfiguration(); } public static RepositoryUserImportConfiguration repositoryUser(){ return new RepositoryUserImportConfiguration(); } public static TaxonomyImportConfiguration taxonomy(){ return new TaxonomyImportConfiguration(); } public static TopicImportConfiguration topic(){ return new TopicImportConfiguration(); } public static SpaceImportConfiguration space(){ return new SpaceImportConfiguration(); } public PersistMode getPersistMode() { return persistMode; } public boolean isVersion() { return version; } public boolean isUpdateLastModificationTime() { return updateLastModificationTime; } public Map<String, byte[]> getBinaryContent() { return binaryContent; } public boolean saveMissingObjectReferences() { return saveMissingObjectReferences; } public Credentials credentialsOfUserWhoHasAccessToBinaryContent() { return credentialsOfUserWhoHasAccessToBinaryContent; } public static class Credentials implements Serializable { /** * */ private static final long serialVersionUID = -2154087866791803405L; private final String username; private final String password; private Credentials(String username,String password){ this.username = username; this.password = password; } public String getUsername() { return username; } public String getPassword() { return password; } } }
BetaCONCEPT/astroboa
astroboa-api/src/main/java/org/betaconceptframework/astroboa/api/model/io/ImportConfiguration.java
Java
gpl-3.0
12,356
/* * * This file is part of Genome Artist. * * Genome Artist 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. * * Genome Artist 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 Genome Artist. If not, see <http://www.gnu.org/licenses/>. * */ package ro.genomeartist.components.utils; import java.util.Arrays; /** * * @author iulian */ public class StringUtilities { /** Test whether a given string is a valid Java identifier. * @param id string which should be checked * @return <code>true</code> if a valid identifier */ public static boolean isJavaIdentifier(String id) { if (id == null) return false; if (id.equals("")) return false; // NOI18N if (!(java.lang.Character.isJavaIdentifierStart(id.charAt(0))) ) return false; for (int i = 1; i < id.length(); i++) { if (!(java.lang.Character.isJavaIdentifierPart(id.charAt(i))) ) return false; } return Arrays.binarySearch(keywords, id) < 0; } /** * Vector cu identificatorii java */ private static final String[] keywords = new String[] { //If adding to this, insert in alphabetical order! "abstract","assert","boolean","break","byte","case", //NOI18N "catch","char","class","const","continue","default", //NOI18N "do","double","else","extends","false","final", //NOI18N "finally","float","for","goto","if","implements", //NOI18N "import","instanceof","int","interface","long", //NOI18N "native","new","null","package","private", //NOI18N "protected","public","return","short","static", //NOI18N "strictfp","super","switch","synchronized","this", //NOI18N "throw","throws","transient","true","try","void", //NOI18N "volatile","while" //NOI18N }; /** * Fac escape la un string pentru a-l afisa in XML * @param text * @return */ public static String removeWindowsCarriageReturn(String text){ return text.replaceAll("\\r", ""); } }
genomeartist/genomeartist
sources_java/Components/src/ro/genomeartist/components/utils/StringUtilities.java
Java
gpl-3.0
2,529
package uk.gov.selfserve; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; //import lagan.api.auth.*; import lagan.api.main.*; //import org.apache.axis.EngineConfiguration; //import org.apache.axis.configuration.FileProvider; import org.apache.axis.client.Stub; import org.apache.axis.message.SOAPHeaderElement; public class LaganUpdateReceipt extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //System.getProperties().put("http.proxyHost", "localhost"); //System.getProperties().put("http.proxyPort", "8888"); String laganSystem = getServletConfig().getInitParameter("laganSystem"); String errorEmailTo = getServletContext().getInitParameter("errorEmailTo"); String emailFrom = getServletContext().getInitParameter("emailFrom"); String smtpHost = getServletContext().getInitParameter("smtpHost"); String reference=request.getParameter("CallingApplicationTransactionReference"); String receipt=request.getParameter("IncomeManagementReceiptNumber"); String[] strErrorEmailTo = { errorEmailTo }; String[] strErrorEmailBCC = new String[0]; response.setContentType("text/html"); PrintWriter webPageOutput=null; webPageOutput=response.getWriter(); LaganLogIn laganLogIn = new LaganLogIn(); LogIn objLogIn = laganLogIn.logIn(laganSystem, getServletContext().getRealPath("/WEB-INF/mycouncil.wsdd"), strErrorEmailTo, strErrorEmailBCC, emailFrom, smtpHost); if (objLogIn.getSuccess()) { lagan.api.main.FLWebService webService = new lagan.api.main.FLWebServiceLocator(objLogIn.getConfig()); org.apache.axis.client.Stub webStub = null; try { lagan.api.main.FLWebInterface webInterface = webService.getFL(); webStub = (Stub)webInterface; SOAPHeaderElement[] respHdrs = objLogIn.getStub().getResponseHeaders(); for (int i = 0; i < respHdrs.length; i++) { webStub.setHeader(respHdrs[i]); } lagan.api.main.FWTCaseEventNew caseEvent = new lagan.api.main.FWTCaseEventNew(reference, "Payment Confirmation", "Receipt Number : " + receipt,"",""); webInterface.addCaseEvent(caseEvent); } catch (Exception e) { webPageOutput.println("*** Error updating Lagan"); webPageOutput.println("laganSystem=" + laganSystem + "<BR>"); webPageOutput.println("URL=" + request.getQueryString() + "<BR>"); webPageOutput.println("Reference=" + reference + "<BR>"); webPageOutput.println("Receipt=" + receipt); webPageOutput.println(e.toString()); } //// response.sendRedirect("http://selfserve.northampton.gov.uk/Ef3/nbcPayLinkReturn.jsp" + "?" + request.getQueryString()); // response.sendRedirect("http://fscrmtestw2k3:8080/Ef3/nbcPayLinkReturn.jsp" + "?" + request.getQueryString()); webPageOutput.close(); } } }
lgss/MyCouncil
WEB-INF/classes/uk/gov/selfserve/LaganUpdateReceipt.java
Java
gpl-3.0
3,109
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Nibbler.Core.Simple; using Nibbler.Core.Simple.Definition; using Nibbler.Core.Simple.Tapes; namespace Nibbler.Core.Simple.Run { public class TmConfiguration<TTape> where TTape : class, ITape { public readonly State Q; public readonly TTape T; public TmConfiguration (State q, TTape t) { if (q == null) throw new ArgumentNullException (); if (t == null) throw new ArgumentNullException (); Q = q; T = t; } public override string ToString () { return T.ToString (Q.ToString ()); } public TmConfiguration<TTape> Clone () { var c = T as ICloneable; if (c != null) { return new TmConfiguration<TTape> (Q, c.Clone () as TTape); } else { throw new InvalidOperationException ("This tape does not support cloning."); } } public override int GetHashCode () { unchecked { return (int.MaxValue - Q.Id) ^ (int) T.TotalTapeLength; } } public override bool Equals (object obj) { if (obj == null || obj.GetType () != GetType ()) { return false; } return Equals (obj as TmConfiguration<TTape>); } public bool Equals (TmConfiguration<TTape> c) { if (c == null) { return false; } if (Q != c.Q) { return false; } return T.CompleteContentEquals (c.T); } } }
nerai/Nibbler
src/Nibbler.Core.Simple/Run/TmConfiguration.cs
C#
mpl-2.0
1,447
package etomica.normalmode.nptdemo; import java.awt.Color; import etomica.api.IAtom; import etomica.api.IAtomList; import etomica.api.IBoundary; import etomica.api.IBox; import etomica.api.IVector; import etomica.api.IVectorMutable; import etomica.graphics.ColorSchemeCollectiveAgent; import etomica.nbr.list.NeighborListManager; import etomica.nbr.list.PotentialMasterList; import etomica.normalmode.CoordinateDefinition; import etomica.space.ISpace; /** * Color atoms based on being neighbors of the reference atom * * @author Andrew Schultz */ public class ColorSchemeScaledOverlap extends ColorSchemeCollectiveAgent { public ColorSchemeScaledOverlap(ISpace space, PotentialMasterList potentialMaster, CoordinateDefinition coordinateDefinition) { super(coordinateDefinition.getBox()); this.coordinateDefinition = coordinateDefinition; IBox box = coordinateDefinition.getBox(); nOverlaps = new int[box.getLeafList().getAtomCount()]; neighborManager = potentialMaster.getNeighborManager(box); pi = space.makeVector(); pj = space.makeVector(); dr = space.makeVector(); } public void setPressure(double newPressure) { pressure = newPressure; } public double getPressure() { return pressure; } public void setDisplayDensity(double newDisplayDensity) { displayDensity = newDisplayDensity; } public double getDisplayDensity() { return displayDensity; } public synchronized void colorAllAtoms() { IBox box = coordinateDefinition.getBox(); IAtomList leafList = box.getLeafList(); double vOld = box.getBoundary().volume(); int nAtoms = box.getLeafList().getAtomCount(); double vNew = nAtoms/displayDensity; double rScale = Math.sqrt(vNew/vOld); double latticeScale = Math.exp((pressure*(vNew-vOld))/((nAtoms-1)*1*2))/rScale; // T=1, D=2 double sigma = 1.0; double scaledSig = sigma/rScale; double sig2 = scaledSig*scaledSig; //color all atoms according to their type int nLeaf = leafList.getAtomCount(); for (int iLeaf=0; iLeaf<nLeaf; iLeaf++) { nOverlaps[iLeaf] = 0; } IBoundary boundary = box.getBoundary(); for (int i=0; i<leafList.getAtomCount(); i++) { //color blue the neighbor atoms in same group IAtom atom = leafList.getAtom(i); pi.E(atom.getPosition()); IVector l = coordinateDefinition.getLatticePosition(atom); pi.ME(l); pi.TE(latticeScale); pi.PE(l); IAtomList list = neighborManager.getDownList(atom)[0]; for (int j=0; j<list.getAtomCount(); j++) { IAtom jAtom = list.getAtom(j); pj.E(jAtom.getPosition()); IVector lj = coordinateDefinition.getLatticePosition(jAtom); pj.ME(lj); pj.TE(latticeScale); pj.PE(lj); dr.Ev1Mv2(pi, pj); boundary.nearestImage(dr); double r2 = dr.squared(); if (r2 < sig2) { nOverlaps[i]++; nOverlaps[jAtom.getLeafIndex()]++; } } } for (int i=0; i<leafList.getAtomCount(); i++) { //color green the target atom agentManager.setAgent(leafList.getAtom(i), colors[nOverlaps[i]]); } } private static final long serialVersionUID = 1L; private final NeighborListManager neighborManager; protected final IVectorMutable dr; protected final IVectorMutable pi, pj; protected final int[] nOverlaps; protected double pressure, displayDensity; protected final CoordinateDefinition coordinateDefinition; protected Color[] colors = new Color[]{Color.RED, Color.BLUE, Color.GREEN, Color.BLACK, Color.CYAN, Color.PINK, new Color(0.5f, 0.0f, 0.5f)}; }
ajschult/etomica
etomica-apps/src/main/java/etomica/normalmode/nptdemo/ColorSchemeScaledOverlap.java
Java
mpl-2.0
4,038
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.orginal.ast; import org.mozilla.javascript.orginal.Token; /** * AST node representing unary operators such as {@code ++}, * {@code ~}, {@code typeof} and {@code delete}. The type field * is set to the appropriate Token type for the operator. The node length spans * from the operator to the end of the operand (for prefix operators) or from * the start of the operand to the operator (for postfix).<p> * * The {@code default xml namespace = &lt;expr&gt;} statement in E4X * (JavaScript 1.6) is represented as a {@code UnaryExpression} of node * type {@link Token#DEFAULTNAMESPACE}, wrapped with an * {@link ExpressionStatement}. */ public class UnaryExpression extends AstNode { private AstNode operand; private boolean isPostfix; public UnaryExpression() { } public UnaryExpression(int pos) { super(pos); } /** * Constructs a new postfix UnaryExpression */ public UnaryExpression(int pos, int len) { super(pos, len); } /** * Constructs a new prefix UnaryExpression. */ public UnaryExpression(int operator, int operatorPosition, AstNode operand) { this(operator, operatorPosition, operand, false); } /** * Constructs a new UnaryExpression with the specified operator * and operand. It sets the parent of the operand, and sets its own bounds * to encompass the operator and operand. * @param operator the node type * @param operatorPosition the absolute position of the operator. * @param operand the operand expression * @param postFix true if the operator follows the operand. Int * @throws IllegalArgumentException} if {@code operand} is {@code null} */ public UnaryExpression(int operator, int operatorPosition, AstNode operand, boolean postFix) { assertNotNull(operand); int beg = postFix ? operand.getPosition() : operatorPosition; // JavaScript only has ++ and -- postfix operators, so length is 2 int end = postFix ? operatorPosition + 2 : operand.getPosition() + operand.getLength(); setBounds(beg, end); setOperator(operator); setOperand(operand); isPostfix = postFix; } /** * Returns operator token &ndash; alias for {@link #getType} */ public int getOperator() { return type; } /** * Sets operator &ndash; same as {@link #setType}, but throws an * exception if the operator is invalid * @throws IllegalArgumentException if operator is not a valid * Token code */ public void setOperator(int operator) { if (!Token.isValidToken(operator)) throw new IllegalArgumentException("Invalid token: " + operator); setType(operator); } public AstNode getOperand() { return operand; } /** * Sets the operand, and sets its parent to be this node. * @throws IllegalArgumentException} if {@code operand} is {@code null} */ public void setOperand(AstNode operand) { assertNotNull(operand); this.operand = operand; operand.setParent(this); } /** * Returns whether the operator is postfix */ public boolean isPostfix() { return isPostfix; } /** * Returns whether the operator is prefix */ public boolean isPrefix() { return !isPostfix; } /** * Sets whether the operator is postfix */ public void setIsPostfix(boolean isPostfix) { this.isPostfix = isPostfix; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); int type = getType(); if (!isPostfix) { sb.append(operatorToString(type)); if (type == Token.TYPEOF || type == Token.DELPROP || type == Token.VOID) { sb.append(" "); } } sb.append(operand.toSource()); if (isPostfix) { sb.append(operatorToString(type)); } return sb.toString(); } /** * Visits this node, then the operand. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { operand.visit(v); } } }
WolframG/Rhino-Prov-Mod
src/org/mozilla/javascript/orginal/ast/UnaryExpression.java
Java
mpl-2.0
4,690
/*~ * Copyright (C) 2013 - 2016 George Makrydakis <george@irrequietus.eu> * * This file is part of 'clause', a highly generic C++ meta-programming library, * subject to the terms and conditions of the Mozilla Public License v 2.0. If * a copy of the MPLv2 license text was not distributed with this file, you can * obtain it at: http://mozilla.org/MPL/2.0/. * * The 'clause' library is an experimental library in active development with * a source code repository at: https://github.com/irrequietus/clause.git and * issue tracker at https://github.com/irrequietus/clause/issues. * */ /*~ * @warn This file should not be included directly in code deploying library * constructs from 'clause'; it is part of a high level meta-macro * construct where multiple #if directives control its actual inclusion. */ #undef PPMPF_VXPP_S7F34 #undef PPMPF_VXPP_S7F33 #undef PPMPF_VXPP_S7F32 #undef PPMPF_VXPP_S7F31 #undef PPMPF_VXPP_S7F30 #if (_PPMPF_FARG73() / 10000) % 10 == 0 #define PPMPF_VXPP_S7F34 0 #elif (_PPMPF_FARG73() / 10000) % 10 == 1 #define PPMPF_VXPP_S7F34 1 #elif (_PPMPF_FARG73() / 10000) % 10 == 2 #define PPMPF_VXPP_S7F34 2 #elif (_PPMPF_FARG73() / 10000) % 10 == 3 #define PPMPF_VXPP_S7F34 3 #elif (_PPMPF_FARG73() / 10000) % 10 == 4 #define PPMPF_VXPP_S7F34 4 #elif (_PPMPF_FARG73() / 10000) % 10 == 5 #define PPMPF_VXPP_S7F34 5 #elif (_PPMPF_FARG73() / 10000) % 10 == 6 #define PPMPF_VXPP_S7F34 6 #elif (_PPMPF_FARG73() / 10000) % 10 == 7 #define PPMPF_VXPP_S7F34 7 #elif (_PPMPF_FARG73() / 10000) % 10 == 8 #define PPMPF_VXPP_S7F34 8 #elif (_PPMPF_FARG73() / 10000) % 10 == 9 #define PPMPF_VXPP_S7F34 9 #endif #if (_PPMPF_FARG73() / 1000) % 10 == 0 #define PPMPF_VXPP_S7F33 0 #elif (_PPMPF_FARG73() / 1000) % 10 == 1 #define PPMPF_VXPP_S7F33 1 #elif (_PPMPF_FARG73() / 1000) % 10 == 2 #define PPMPF_VXPP_S7F33 2 #elif (_PPMPF_FARG73() / 1000) % 10 == 3 #define PPMPF_VXPP_S7F33 3 #elif (_PPMPF_FARG73() / 1000) % 10 == 4 #define PPMPF_VXPP_S7F33 4 #elif (_PPMPF_FARG73() / 1000) % 10 == 5 #define PPMPF_VXPP_S7F33 5 #elif (_PPMPF_FARG73() / 1000) % 10 == 6 #define PPMPF_VXPP_S7F33 6 #elif (_PPMPF_FARG73() / 1000) % 10 == 7 #define PPMPF_VXPP_S7F33 7 #elif (_PPMPF_FARG73() / 1000) % 10 == 8 #define PPMPF_VXPP_S7F33 8 #elif (_PPMPF_FARG73() / 1000) % 10 == 9 #define PPMPF_VXPP_S7F33 9 #endif #if (_PPMPF_FARG73() / 100) % 10 == 0 #define PPMPF_VXPP_S7F32 0 #elif (_PPMPF_FARG73() / 100) % 10 == 1 #define PPMPF_VXPP_S7F32 1 #elif (_PPMPF_FARG73() / 100) % 10 == 2 #define PPMPF_VXPP_S7F32 2 #elif (_PPMPF_FARG73() / 100) % 10 == 3 #define PPMPF_VXPP_S7F32 3 #elif (_PPMPF_FARG73() / 100) % 10 == 4 #define PPMPF_VXPP_S7F32 4 #elif (_PPMPF_FARG73() / 100) % 10 == 5 #define PPMPF_VXPP_S7F32 5 #elif (_PPMPF_FARG73() / 100) % 10 == 6 #define PPMPF_VXPP_S7F32 6 #elif (_PPMPF_FARG73() / 100) % 10 == 7 #define PPMPF_VXPP_S7F32 7 #elif (_PPMPF_FARG73() / 100) % 10 == 8 #define PPMPF_VXPP_S7F32 8 #elif (_PPMPF_FARG73() / 100) % 10 == 9 #define PPMPF_VXPP_S7F32 9 #endif #if (_PPMPF_FARG73() / 10) % 10 == 0 #define PPMPF_VXPP_S7F31 0 #elif (_PPMPF_FARG73() / 10) % 10 == 1 #define PPMPF_VXPP_S7F31 1 #elif (_PPMPF_FARG73() / 10) % 10 == 2 #define PPMPF_VXPP_S7F31 2 #elif (_PPMPF_FARG73() / 10) % 10 == 3 #define PPMPF_VXPP_S7F31 3 #elif (_PPMPF_FARG73() / 10) % 10 == 4 #define PPMPF_VXPP_S7F31 4 #elif (_PPMPF_FARG73() / 10) % 10 == 5 #define PPMPF_VXPP_S7F31 5 #elif (_PPMPF_FARG73() / 10) % 10 == 6 #define PPMPF_VXPP_S7F31 6 #elif (_PPMPF_FARG73() / 10) % 10 == 7 #define PPMPF_VXPP_S7F31 7 #elif (_PPMPF_FARG73() / 10) % 10 == 8 #define PPMPF_VXPP_S7F31 8 #elif (_PPMPF_FARG73() / 10) % 10 == 9 #define PPMPF_VXPP_S7F31 9 #endif #if _PPMPF_FARG73() % 10 == 0 #define PPMPF_VXPP_S7F30 0 #elif _PPMPF_FARG73() % 10 == 1 #define PPMPF_VXPP_S7F30 1 #elif _PPMPF_FARG73() % 10 == 2 #define PPMPF_VXPP_S7F30 2 #elif _PPMPF_FARG73() % 10 == 3 #define PPMPF_VXPP_S7F30 3 #elif _PPMPF_FARG73() % 10 == 4 #define PPMPF_VXPP_S7F30 4 #elif _PPMPF_FARG73() % 10 == 5 #define PPMPF_VXPP_S7F30 5 #elif _PPMPF_FARG73() % 10 == 6 #define PPMPF_VXPP_S7F30 6 #elif _PPMPF_FARG73() % 10 == 7 #define PPMPF_VXPP_S7F30 7 #elif _PPMPF_FARG73() % 10 == 8 #define PPMPF_VXPP_S7F30 8 #elif _PPMPF_FARG73() % 10 == 9 #define PPMPF_VXPP_S7F30 9 #endif
irrequietus/clause
clause/ppmpf/vxpp/slots/func/arty/arty74.hh
C++
mpl-2.0
4,493
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2019, Joyent, Inc. */ var mod_fs = require('fs'); var mod_path = require('path'); var mod_assert = require('assert-plus'); var DEFAULT_DEBOUNCE_TIME = 600; var DEFAULT_RETAIN_TIME = 0; var LOGSETS; function load_logsets() { var NAMES_SEEN = []; LOGSETS = JSON.parse(mod_fs.readFileSync(mod_path.join(__dirname, '..', 'etc', 'logsets.json'), 'utf8')); for (var i = 0; i < LOGSETS.length; i++) { var ls = LOGSETS[i]; ls.regex = new RegExp(ls.regex); mod_assert.optionalString( ls.search_dirs_pattern, 'search_dirs_pattern'); mod_assert.arrayOfString(ls.search_dirs, 'search_dirs'); mod_assert.optionalBool(ls.no_upload, 'no_upload'); mod_assert.string(ls.manta_path, 'manta_path'); mod_assert.optionalNumber(ls.debounce_time, 'debounce_time'); if (!ls.debounce_time) ls.debounce_time = DEFAULT_DEBOUNCE_TIME; mod_assert.optionalNumber(ls.retain_time, 'retain_time'); if (!ls.retain_time) ls.retain_time = DEFAULT_RETAIN_TIME; mod_assert.ok(NAMES_SEEN.indexOf(ls.name) === -1, 'duplicate logset name'); NAMES_SEEN.push(ls.name); } } var COPY_FIELDS = [ 'search_dirs', 'search_dirs_pattern', 'manta_path', 'date_string', 'date_adjustment', 'debounce_time', 'retain_time', 'customer_uuid', 'no_upload' ]; /* * Create a JSON-safe object for transport across the wire to the actor: */ function format_logset(logset, zonename, zonerole) { var o = { name: logset.name + (zonename ? '@' + zonename : ''), zonename: zonename || 'global', zonerole: zonerole || 'global', regex: logset.regex.source }; for (var i = 0; i < COPY_FIELDS.length; i++) { var cf = COPY_FIELDS[i]; o[cf] = logset[cf]; } return (o); } function logsets_for_server(zone_list_for_server) { var out = []; for (var i = 0; i < LOGSETS.length; i++) { var ls = LOGSETS[i]; /* * This logset applies to the global zone: */ if (ls.zones.indexOf('global') !== -1) { out.push(format_logset(ls)); } for (var j = 0; j < zone_list_for_server.length; j++) { var zz = zone_list_for_server[j]; if (ls.zones.indexOf(zz.role) !== -1) { out.push(format_logset(ls, zz.uuid, zz.role)); } } } return (out); } /* * Initialisation: */ load_logsets(); /* * API: */ module.exports = { logsets_for_server: logsets_for_server }; /* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */
joyent/sdc-hermes
lib/logsets.js
JavaScript
mpl-2.0
2,593
/* * Copyright © 2016 Mathias Doenitz * * 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 swave.core.impl; final class Statics { static final Integer _0 = 0; static final Integer _1 = 1; static final Integer _2 = 2; static final Integer _3 = 3; static final Integer _4 = 4; static final Integer _5 = 5; static final Integer _6 = 6; static final Integer _7 = 7; static final Integer _8 = 8; static final Integer _9 = 9; static final Integer _10 = 10; static final Integer _11 = 11; static final Integer _12 = 12; static final java.lang.Integer[] NEG_INTS = { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, -32 }; static final java.lang.Integer[] INTS_PLUS_100 = { 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132 }; }
sirthias/swave
core/src/main/java/swave/core/impl/Statics.java
Java
mpl-2.0
1,574
// Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. // Licensed under the Mozilla Public License v2.0 package oci import ( "context" "fmt" "testing" "time" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/terraform" "github.com/oracle/oci-go-sdk/v46/common" oci_kms "github.com/oracle/oci-go-sdk/v46/keymanagement" "github.com/terraform-providers/terraform-provider-oci/httpreplay" ) var ( KeyRequiredOnlyResource = KeyResourceDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Required, Create, keyRepresentation) KeyResourceConfig = KeyResourceDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Update, keyRepresentation) keySingularDataSourceRepresentation = map[string]interface{}{ "key_id": Representation{repType: Required, create: `${oci_kms_key.test_key.id}`}, "management_endpoint": Representation{repType: Required, create: `${data.oci_kms_vault.test_vault.management_endpoint}`}, } keyDataSourceRepresentation = map[string]interface{}{ "compartment_id": Representation{repType: Required, create: `${var.compartment_id}`}, "management_endpoint": Representation{repType: Required, create: `${data.oci_kms_vault.test_vault.management_endpoint}`}, "protection_mode": Representation{repType: Optional, create: `SOFTWARE`}, "algorithm": Representation{repType: Optional, create: `AES`}, "length": Representation{repType: Optional, create: `16`}, "filter": RepresentationGroup{Required, keyDataSourceFilterRepresentation}} keyDataSourceFilterRepresentation = map[string]interface{}{ "name": Representation{repType: Required, create: `id`}, "values": Representation{repType: Required, create: []string{`${oci_kms_key.test_key.id}`}}, } deletionTime = time.Now().UTC().AddDate(0, 0, 8).Truncate(time.Millisecond) keyRepresentation = map[string]interface{}{ "compartment_id": Representation{repType: Required, create: `${var.compartment_id}`}, "display_name": Representation{repType: Required, create: `Key C`, update: `displayName2`}, "key_shape": RepresentationGroup{Required, keyKeyShapeRepresentation}, "management_endpoint": Representation{repType: Required, create: `${data.oci_kms_vault.test_vault.management_endpoint}`}, "desired_state": Representation{repType: Optional, create: `ENABLED`, update: `DISABLED`}, "freeform_tags": Representation{repType: Optional, create: map[string]string{"Department": "Finance"}, update: map[string]string{"Department": "Accounting"}}, "protection_mode": Representation{repType: Optional, create: `SOFTWARE`}, "time_of_deletion": Representation{repType: Required, create: deletionTime.Format(time.RFC3339Nano)}, } keyKeyShapeRepresentation = map[string]interface{}{ "algorithm": Representation{repType: Required, create: `AES`}, "length": Representation{repType: Required, create: `16`}, } kmsVaultId = getEnvSettingWithBlankDefault("kms_vault_ocid") KmsVaultIdVariableStr = fmt.Sprintf("variable \"kms_vault_id\" { default = \"%s\" }\n", kmsVaultId) kmsKeyIdForCreate = getEnvSettingWithBlankDefault("key_ocid_for_create") kmsKeyIdCreateVariableStr = fmt.Sprintf("variable \"kms_key_id_for_create\" { default = \"%s\" }\n", kmsKeyIdForCreate) kmsKeyIdForUpdate = getEnvSettingWithBlankDefault("key_ocid_for_update") kmsKeyIdUpdateVariableStr = fmt.Sprintf("variable \"kms_key_id_for_update\" { default = \"%s\" }\n", kmsKeyIdForUpdate) kmsKeyCompartmentId = getEnvSettingWithBlankDefault("compartment_ocid") kmsKeyCompartmentIdVariableStr = fmt.Sprintf("variable \"kms_key_compartment_id\" { default = \"%s\" }\n", kmsKeyCompartmentId) // Should deprecate use of tenancy level resources KeyResourceDependencies = KmsVaultIdVariableStr + ` data "oci_kms_vault" "test_vault" { #Required vault_id = "${var.kms_vault_id}" } ` KeyResourceDependencyConfig = KeyResourceDependencies + ` data "oci_kms_keys" "test_keys_dependency" { #Required compartment_id = "${var.tenancy_ocid}" management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}" algorithm = "AES" filter { name = "state" values = ["ENABLED", "UPDATING"] } } data "oci_kms_keys" "test_keys_dependency_RSA" { #Required compartment_id = "${var.tenancy_ocid}" management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}" algorithm = "RSA" filter { name = "state" values = ["ENABLED", "UPDATING"] } } ` KeyResourceDependencyConfig2 = KeyResourceDependencies + kmsKeyCompartmentIdVariableStr + ` data "oci_kms_keys" "test_keys_dependency" { #Required compartment_id = "${var.kms_key_compartment_id}" management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}" algorithm = "AES" filter { name = "state" values = ["ENABLED", "UPDATING"] } } data "oci_kms_keys" "test_keys_dependency_RSA" { #Required compartment_id = "${var.kms_key_compartment_id}" management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}" algorithm = "RSA" filter { name = "state" values = ["ENABLED", "UPDATING"] } } ` ) // issue-routing-tag: kms/default func TestKmsKeyResource_basic(t *testing.T) { httpreplay.SetScenario("TestKmsKeyResource_basic") defer httpreplay.SaveScenario() provider := testAccProvider config := testProviderConfig() compartmentId := getEnvSettingWithBlankDefault("compartment_ocid") compartmentIdVariableStr := fmt.Sprintf("variable \"compartment_id\" { default = \"%s\" }\n", compartmentId) compartmentIdU := getEnvSettingWithDefault("compartment_id_for_update", compartmentId) compartmentIdUVariableStr := fmt.Sprintf("variable \"compartment_id_for_update\" { default = \"%s\" }\n", compartmentIdU) resourceName := "oci_kms_key.test_key" datasourceName := "data.oci_kms_keys.test_keys" singularDatasourceName := "data.oci_kms_key.test_key" var resId, resId2 string // Save TF content to create resource with optional properties. This has to be exactly the same as the config part in the "create with optionals" step in the test. saveConfigContent(config+compartmentIdVariableStr+KeyResourceDependencies+ generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, keyRepresentation), "keymanagement", "key", t) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, CheckDestroy: testAccCheckKMSKeyDestroy, Providers: map[string]terraform.ResourceProvider{ "oci": provider, }, Steps: []resource.TestStep{ // verify create { Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Required, Create, keyRepresentation), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentId), resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"), resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"), func(s *terraform.State) (err error) { resId, err = fromInstanceState(s, resourceName, "id") return err }, ), }, // delete before next create { Config: config + compartmentIdVariableStr + KeyResourceDependencies, }, // verify create with optionals { Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, keyRepresentation), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentId), resource.TestCheckResourceAttrSet(resourceName, "current_key_version"), resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"), resource.TestCheckResourceAttr(resourceName, "freeform_tags.%", "1"), resource.TestCheckResourceAttrSet(resourceName, "id"), resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"), resource.TestCheckResourceAttrSet(resourceName, "management_endpoint"), resource.TestCheckResourceAttr(resourceName, "protection_mode", "SOFTWARE"), resource.TestCheckResourceAttrSet(resourceName, "state"), resource.TestCheckResourceAttrSet(resourceName, "time_created"), resource.TestCheckResourceAttrSet(resourceName, "vault_id"), func(s *terraform.State) (err error) { resId, err = fromInstanceState(s, resourceName, "id") return err }, ), }, // verify update to the compartment (the compartment will be switched back in the next step) { Config: config + compartmentIdVariableStr + compartmentIdUVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, representationCopyWithNewProperties(keyRepresentation, map[string]interface{}{ "compartment_id": Representation{repType: Required, create: `${var.compartment_id_for_update}`}, })), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentIdU), resource.TestCheckResourceAttrSet(resourceName, "current_key_version"), resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"), resource.TestCheckResourceAttr(resourceName, "freeform_tags.%", "1"), resource.TestCheckResourceAttrSet(resourceName, "id"), resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"), resource.TestCheckResourceAttr(resourceName, "protection_mode", "SOFTWARE"), resource.TestCheckResourceAttrSet(resourceName, "state"), resource.TestCheckResourceAttrSet(resourceName, "time_created"), resource.TestCheckResourceAttrSet(resourceName, "vault_id"), func(s *terraform.State) (err error) { resId2, err = fromInstanceState(s, resourceName, "id") if resId != resId2 { return fmt.Errorf("resource recreated when it was supposed to be updated") } return err }, ), }, // verify updates to updatable parameters { Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Update, keyRepresentation), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentId), resource.TestCheckResourceAttrSet(resourceName, "current_key_version"), resource.TestCheckResourceAttr(resourceName, "display_name", "displayName2"), resource.TestCheckResourceAttr(resourceName, "freeform_tags.%", "1"), resource.TestCheckResourceAttrSet(resourceName, "id"), resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"), resource.TestCheckResourceAttr(resourceName, "protection_mode", "SOFTWARE"), resource.TestCheckResourceAttrSet(resourceName, "state"), resource.TestCheckResourceAttrSet(resourceName, "time_created"), resource.TestCheckResourceAttrSet(resourceName, "vault_id"), func(s *terraform.State) (err error) { resId2, err = fromInstanceState(s, resourceName, "id") if resId != resId2 { return fmt.Errorf("Resource recreated when it was supposed to be updated.") } return err }, ), }, // verify datasource { Config: config + generateDataSourceFromRepresentationMap("oci_kms_keys", "test_keys", Optional, Update, keyDataSourceRepresentation) + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Update, keyRepresentation), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(datasourceName, "algorithm", "AES"), resource.TestCheckResourceAttr(datasourceName, "compartment_id", compartmentId), resource.TestCheckResourceAttrSet(datasourceName, "management_endpoint"), resource.TestCheckResourceAttr(datasourceName, "protection_mode", "SOFTWARE"), resource.TestCheckResourceAttr(datasourceName, "length", "16"), resource.TestCheckResourceAttr(datasourceName, "keys.#", "1"), resource.TestCheckResourceAttr(datasourceName, "keys.0.compartment_id", compartmentId), resource.TestCheckResourceAttr(datasourceName, "keys.0.display_name", "displayName2"), resource.TestCheckResourceAttr(datasourceName, "keys.0.freeform_tags.%", "1"), resource.TestCheckResourceAttrSet(datasourceName, "keys.0.id"), resource.TestCheckResourceAttr(datasourceName, "keys.0.protection_mode", "SOFTWARE"), resource.TestCheckResourceAttrSet(datasourceName, "keys.0.state"), resource.TestCheckResourceAttrSet(datasourceName, "keys.0.time_created"), resource.TestCheckResourceAttrSet(datasourceName, "keys.0.vault_id"), ), }, // verify singular datasource { Config: config + generateDataSourceFromRepresentationMap("oci_kms_key", "test_key", Required, Create, keySingularDataSourceRepresentation) + compartmentIdVariableStr + KeyResourceConfig + DefinedTagsDependencies, Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttrSet(singularDatasourceName, "key_id"), resource.TestCheckResourceAttr(singularDatasourceName, "compartment_id", compartmentId), resource.TestCheckResourceAttrSet(singularDatasourceName, "current_key_version"), resource.TestCheckResourceAttr(singularDatasourceName, "display_name", "displayName2"), resource.TestCheckResourceAttr(singularDatasourceName, "freeform_tags.%", "1"), resource.TestCheckResourceAttrSet(singularDatasourceName, "id"), resource.TestCheckResourceAttrSet(singularDatasourceName, "is_primary"), resource.TestCheckResourceAttr(singularDatasourceName, "key_shape.#", "1"), resource.TestCheckResourceAttr(singularDatasourceName, "key_shape.0.algorithm", "AES"), resource.TestCheckResourceAttr(singularDatasourceName, "key_shape.0.length", "16"), resource.TestCheckResourceAttr(singularDatasourceName, "protection_mode", "SOFTWARE"), resource.TestCheckResourceAttrSet(singularDatasourceName, "state"), resource.TestCheckResourceAttrSet(singularDatasourceName, "time_created"), resource.TestCheckResourceAttrSet(singularDatasourceName, "vault_id"), ), }, // remove singular datasource from previous step so that it doesn't conflict with import tests { Config: config + compartmentIdVariableStr + KeyResourceConfig + DefinedTagsDependencies, }, // revert the updates { Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, keyRepresentation), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"), resource.TestCheckResourceAttr(resourceName, "state", "ENABLED"), func(s *terraform.State) (err error) { resId2, err = fromInstanceState(s, resourceName, "id") if resId != resId2 { return fmt.Errorf("Resource recreated when it was supposed to be updated.") } return err }, ), }, // verify resource import { Config: config, ImportState: true, ImportStateVerify: true, ImportStateIdFunc: keyImportId, ImportStateVerifyIgnore: []string{ "desired_state", "time_of_deletion", "replica_details", }, ResourceName: resourceName, }, }, }) } func testAccCheckKMSKeyDestroy(s *terraform.State) error { noResourceFound := true for _, rs := range s.RootModule().Resources { if rs.Type == "oci_kms_key" { client, err := testAccProvider.Meta().(*OracleClients).KmsManagementClient(rs.Primary.Attributes["management_endpoint"]) if err != nil { return err } noResourceFound = false request := oci_kms.GetKeyRequest{} tmp := rs.Primary.ID request.KeyId = &tmp request.RequestMetadata.RetryPolicy = getRetryPolicy(true, "kms") response, err := client.GetKey(context.Background(), request) if err == nil { deletedLifecycleStates := map[string]bool{ string(oci_kms.KeyLifecycleStateSchedulingDeletion): true, string(oci_kms.KeyLifecycleStatePendingDeletion): true, } if _, ok := deletedLifecycleStates[string(response.LifecycleState)]; !ok { //resource lifecycle state is not in expected deleted lifecycle states. return fmt.Errorf("resource lifecycle state: %s is not in expected deleted lifecycle states", response.LifecycleState) } if !response.TimeOfDeletion.Equal(deletionTime) && !httpreplay.ModeRecordReplay() { return fmt.Errorf("resource time_of_deletion: %s is not set to %s", response.TimeOfDeletion.Format(time.RFC3339Nano), deletionTime.Format(time.RFC3339Nano)) } //resource lifecycle state is in expected deleted lifecycle states. continue with next one. continue } //Verify that exception is for '404 not found'. if failure, isServiceError := common.IsServiceError(err); !isServiceError || failure.GetHTTPStatusCode() != 404 { return err } } } if noResourceFound { return fmt.Errorf("at least one resource was expected from the state file, but could not be found") } return nil } func keyImportId(state *terraform.State) (string, error) { for _, rs := range state.RootModule().Resources { if rs.Type == "oci_kms_key" { return fmt.Sprintf("managementEndpoint/%s/keys/%s", rs.Primary.Attributes["management_endpoint"], rs.Primary.ID), nil } } return "", fmt.Errorf("unable to create import id as no resource of type oci_kms_key in state") }
oracle/terraform-provider-baremetal
oci/kms_key_test.go
GO
mpl-2.0
18,702
package org.bear.bookstore.concurrent; import java.util.PriorityQueue; public class PriorityQueueTest { public static void main(String[] args) { PriorityQueue<String> queue = new PriorityQueue<>((a,b)->{ return a.compareTo(b); }); queue.add("a"); queue.add("x"); queue.add("c"); queue.add("e"); queue.add("a"); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); int x = 15 & (("abcd".hashCode()) ^ ("abcd".hashCode() >>> 16)); System.out.println(Integer.toBinaryString("abcd".hashCode())); System.out.println(Integer.toBinaryString("abcd".hashCode() >>> 16)); System.out.println(Integer.toBinaryString(("abcd".hashCode()) ^ ("abcd".hashCode() >>> 16))); System.out.println(Integer.toBinaryString(15)); System.out.println(x); } }
zhougithui/bookstore-single
src/test/java/org/bear/bookstore/concurrent/PriorityQueueTest.java
Java
mpl-2.0
831
// Copyright 2020 Google LLC // // 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. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.22.0 // protoc v3.11.2 // source: google/monitoring/v3/alert.proto package monitoring import ( reflect "reflect" sync "sync" proto "github.com/golang/protobuf/proto" duration "github.com/golang/protobuf/ptypes/duration" wrappers "github.com/golang/protobuf/ptypes/wrappers" _ "google.golang.org/genproto/googleapis/api/annotations" status "google.golang.org/genproto/googleapis/rpc/status" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 // Operators for combining conditions. type AlertPolicy_ConditionCombinerType int32 const ( // An unspecified combiner. AlertPolicy_COMBINE_UNSPECIFIED AlertPolicy_ConditionCombinerType = 0 // Combine conditions using the logical `AND` operator. An // incident is created only if all the conditions are met // simultaneously. This combiner is satisfied if all conditions are // met, even if they are met on completely different resources. AlertPolicy_AND AlertPolicy_ConditionCombinerType = 1 // Combine conditions using the logical `OR` operator. An incident // is created if any of the listed conditions is met. AlertPolicy_OR AlertPolicy_ConditionCombinerType = 2 // Combine conditions using logical `AND` operator, but unlike the regular // `AND` option, an incident is created only if all conditions are met // simultaneously on at least one resource. AlertPolicy_AND_WITH_MATCHING_RESOURCE AlertPolicy_ConditionCombinerType = 3 ) // Enum value maps for AlertPolicy_ConditionCombinerType. var ( AlertPolicy_ConditionCombinerType_name = map[int32]string{ 0: "COMBINE_UNSPECIFIED", 1: "AND", 2: "OR", 3: "AND_WITH_MATCHING_RESOURCE", } AlertPolicy_ConditionCombinerType_value = map[string]int32{ "COMBINE_UNSPECIFIED": 0, "AND": 1, "OR": 2, "AND_WITH_MATCHING_RESOURCE": 3, } ) func (x AlertPolicy_ConditionCombinerType) Enum() *AlertPolicy_ConditionCombinerType { p := new(AlertPolicy_ConditionCombinerType) *p = x return p } func (x AlertPolicy_ConditionCombinerType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (AlertPolicy_ConditionCombinerType) Descriptor() protoreflect.EnumDescriptor { return file_google_monitoring_v3_alert_proto_enumTypes[0].Descriptor() } func (AlertPolicy_ConditionCombinerType) Type() protoreflect.EnumType { return &file_google_monitoring_v3_alert_proto_enumTypes[0] } func (x AlertPolicy_ConditionCombinerType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use AlertPolicy_ConditionCombinerType.Descriptor instead. func (AlertPolicy_ConditionCombinerType) EnumDescriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 0} } // A description of the conditions under which some aspect of your system is // considered to be "unhealthy" and the ways to notify people or services about // this state. For an overview of alert policies, see // [Introduction to Alerting](https://cloud.google.com/monitoring/alerts/). type AlertPolicy struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required if the policy exists. The resource name for this policy. The // format is: // // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] // // `[ALERT_POLICY_ID]` is assigned by Stackdriver Monitoring when the policy // is created. When calling the // [alertPolicies.create][google.monitoring.v3.AlertPolicyService.CreateAlertPolicy] // method, do not include the `name` field in the alerting policy passed as // part of the request. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // A short name or phrase used to identify the policy in dashboards, // notifications, and incidents. To avoid confusion, don't use the same // display name for multiple policies in the same project. The name is // limited to 512 Unicode characters. DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` // Documentation that is included with notifications and incidents related to // this policy. Best practice is for the documentation to include information // to help responders understand, mitigate, escalate, and correct the // underlying problems detected by the alerting policy. Notification channels // that have limited capacity might not show this documentation. Documentation *AlertPolicy_Documentation `protobuf:"bytes,13,opt,name=documentation,proto3" json:"documentation,omitempty"` // User-supplied key/value data to be used for organizing and // identifying the `AlertPolicy` objects. // // The field can contain up to 64 entries. Each key and value is limited to // 63 Unicode characters or 128 bytes, whichever is smaller. Labels and // values can contain only lowercase letters, numerals, underscores, and // dashes. Keys must begin with a letter. UserLabels map[string]string `protobuf:"bytes,16,rep,name=user_labels,json=userLabels,proto3" json:"user_labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // A list of conditions for the policy. The conditions are combined by AND or // OR according to the `combiner` field. If the combined conditions evaluate // to true, then an incident is created. A policy can have from one to six // conditions. // If `condition_time_series_query_language` is present, it must be the only // `condition`. Conditions []*AlertPolicy_Condition `protobuf:"bytes,12,rep,name=conditions,proto3" json:"conditions,omitempty"` // How to combine the results of multiple conditions to determine if an // incident should be opened. // If `condition_time_series_query_language` is present, this must be // `COMBINE_UNSPECIFIED`. Combiner AlertPolicy_ConditionCombinerType `protobuf:"varint,6,opt,name=combiner,proto3,enum=google.monitoring.v3.AlertPolicy_ConditionCombinerType" json:"combiner,omitempty"` // Whether or not the policy is enabled. On write, the default interpretation // if unset is that the policy is enabled. On read, clients should not make // any assumption about the state if it has not been populated. The // field should always be populated on List and Get operations, unless // a field projection has been specified that strips it out. Enabled *wrappers.BoolValue `protobuf:"bytes,17,opt,name=enabled,proto3" json:"enabled,omitempty"` // Read-only description of how the alert policy is invalid. OK if the alert // policy is valid. If not OK, the alert policy will not generate incidents. Validity *status.Status `protobuf:"bytes,18,opt,name=validity,proto3" json:"validity,omitempty"` // Identifies the notification channels to which notifications should be sent // when incidents are opened or closed or when new violations occur on // an already opened incident. Each element of this array corresponds to // the `name` field in each of the // [`NotificationChannel`][google.monitoring.v3.NotificationChannel] // objects that are returned from the [`ListNotificationChannels`] // [google.monitoring.v3.NotificationChannelService.ListNotificationChannels] // method. The format of the entries in this field is: // // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] NotificationChannels []string `protobuf:"bytes,14,rep,name=notification_channels,json=notificationChannels,proto3" json:"notification_channels,omitempty"` // A read-only record of the creation of the alerting policy. If provided // in a call to create or update, this field will be ignored. CreationRecord *MutationRecord `protobuf:"bytes,10,opt,name=creation_record,json=creationRecord,proto3" json:"creation_record,omitempty"` // A read-only record of the most recent change to the alerting policy. If // provided in a call to create or update, this field will be ignored. MutationRecord *MutationRecord `protobuf:"bytes,11,opt,name=mutation_record,json=mutationRecord,proto3" json:"mutation_record,omitempty"` } func (x *AlertPolicy) Reset() { *x = AlertPolicy{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy) ProtoMessage() {} func (x *AlertPolicy) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy.ProtoReflect.Descriptor instead. func (*AlertPolicy) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0} } func (x *AlertPolicy) GetName() string { if x != nil { return x.Name } return "" } func (x *AlertPolicy) GetDisplayName() string { if x != nil { return x.DisplayName } return "" } func (x *AlertPolicy) GetDocumentation() *AlertPolicy_Documentation { if x != nil { return x.Documentation } return nil } func (x *AlertPolicy) GetUserLabels() map[string]string { if x != nil { return x.UserLabels } return nil } func (x *AlertPolicy) GetConditions() []*AlertPolicy_Condition { if x != nil { return x.Conditions } return nil } func (x *AlertPolicy) GetCombiner() AlertPolicy_ConditionCombinerType { if x != nil { return x.Combiner } return AlertPolicy_COMBINE_UNSPECIFIED } func (x *AlertPolicy) GetEnabled() *wrappers.BoolValue { if x != nil { return x.Enabled } return nil } func (x *AlertPolicy) GetValidity() *status.Status { if x != nil { return x.Validity } return nil } func (x *AlertPolicy) GetNotificationChannels() []string { if x != nil { return x.NotificationChannels } return nil } func (x *AlertPolicy) GetCreationRecord() *MutationRecord { if x != nil { return x.CreationRecord } return nil } func (x *AlertPolicy) GetMutationRecord() *MutationRecord { if x != nil { return x.MutationRecord } return nil } // A content string and a MIME type that describes the content string's // format. type AlertPolicy_Documentation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The text of the documentation, interpreted according to `mime_type`. // The content may not exceed 8,192 Unicode characters and may not exceed // more than 10,240 bytes when encoded in UTF-8 format, whichever is // smaller. Content string `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"` // The format of the `content` field. Presently, only the value // `"text/markdown"` is supported. See // [Markdown](https://en.wikipedia.org/wiki/Markdown) for more information. MimeType string `protobuf:"bytes,2,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,omitempty"` } func (x *AlertPolicy_Documentation) Reset() { *x = AlertPolicy_Documentation{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy_Documentation) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy_Documentation) ProtoMessage() {} func (x *AlertPolicy_Documentation) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy_Documentation.ProtoReflect.Descriptor instead. func (*AlertPolicy_Documentation) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 0} } func (x *AlertPolicy_Documentation) GetContent() string { if x != nil { return x.Content } return "" } func (x *AlertPolicy_Documentation) GetMimeType() string { if x != nil { return x.MimeType } return "" } // A condition is a true/false test that determines when an alerting policy // should open an incident. If a condition evaluates to true, it signifies // that something is wrong. type AlertPolicy_Condition struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required if the condition exists. The unique resource name for this // condition. Its format is: // // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[POLICY_ID]/conditions/[CONDITION_ID] // // `[CONDITION_ID]` is assigned by Stackdriver Monitoring when the // condition is created as part of a new or updated alerting policy. // // When calling the // [alertPolicies.create][google.monitoring.v3.AlertPolicyService.CreateAlertPolicy] // method, do not include the `name` field in the conditions of the // requested alerting policy. Stackdriver Monitoring creates the // condition identifiers and includes them in the new policy. // // When calling the // [alertPolicies.update][google.monitoring.v3.AlertPolicyService.UpdateAlertPolicy] // method to update a policy, including a condition `name` causes the // existing condition to be updated. Conditions without names are added to // the updated policy. Existing conditions are deleted if they are not // updated. // // Best practice is to preserve `[CONDITION_ID]` if you make only small // changes, such as those to condition thresholds, durations, or trigger // values. Otherwise, treat the change as a new condition and let the // existing condition be deleted. Name string `protobuf:"bytes,12,opt,name=name,proto3" json:"name,omitempty"` // A short name or phrase used to identify the condition in dashboards, // notifications, and incidents. To avoid confusion, don't use the same // display name for multiple conditions in the same policy. DisplayName string `protobuf:"bytes,6,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` // Only one of the following condition types will be specified. // // Types that are assignable to Condition: // *AlertPolicy_Condition_ConditionThreshold // *AlertPolicy_Condition_ConditionAbsent Condition isAlertPolicy_Condition_Condition `protobuf_oneof:"condition"` } func (x *AlertPolicy_Condition) Reset() { *x = AlertPolicy_Condition{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy_Condition) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy_Condition) ProtoMessage() {} func (x *AlertPolicy_Condition) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy_Condition.ProtoReflect.Descriptor instead. func (*AlertPolicy_Condition) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1} } func (x *AlertPolicy_Condition) GetName() string { if x != nil { return x.Name } return "" } func (x *AlertPolicy_Condition) GetDisplayName() string { if x != nil { return x.DisplayName } return "" } func (m *AlertPolicy_Condition) GetCondition() isAlertPolicy_Condition_Condition { if m != nil { return m.Condition } return nil } func (x *AlertPolicy_Condition) GetConditionThreshold() *AlertPolicy_Condition_MetricThreshold { if x, ok := x.GetCondition().(*AlertPolicy_Condition_ConditionThreshold); ok { return x.ConditionThreshold } return nil } func (x *AlertPolicy_Condition) GetConditionAbsent() *AlertPolicy_Condition_MetricAbsence { if x, ok := x.GetCondition().(*AlertPolicy_Condition_ConditionAbsent); ok { return x.ConditionAbsent } return nil } type isAlertPolicy_Condition_Condition interface { isAlertPolicy_Condition_Condition() } type AlertPolicy_Condition_ConditionThreshold struct { // A condition that compares a time series against a threshold. ConditionThreshold *AlertPolicy_Condition_MetricThreshold `protobuf:"bytes,1,opt,name=condition_threshold,json=conditionThreshold,proto3,oneof"` } type AlertPolicy_Condition_ConditionAbsent struct { // A condition that checks that a time series continues to // receive new data points. ConditionAbsent *AlertPolicy_Condition_MetricAbsence `protobuf:"bytes,2,opt,name=condition_absent,json=conditionAbsent,proto3,oneof"` } func (*AlertPolicy_Condition_ConditionThreshold) isAlertPolicy_Condition_Condition() {} func (*AlertPolicy_Condition_ConditionAbsent) isAlertPolicy_Condition_Condition() {} // Specifies how many time series must fail a predicate to trigger a // condition. If not specified, then a `{count: 1}` trigger is used. type AlertPolicy_Condition_Trigger struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A type of trigger. // // Types that are assignable to Type: // *AlertPolicy_Condition_Trigger_Count // *AlertPolicy_Condition_Trigger_Percent Type isAlertPolicy_Condition_Trigger_Type `protobuf_oneof:"type"` } func (x *AlertPolicy_Condition_Trigger) Reset() { *x = AlertPolicy_Condition_Trigger{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy_Condition_Trigger) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy_Condition_Trigger) ProtoMessage() {} func (x *AlertPolicy_Condition_Trigger) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy_Condition_Trigger.ProtoReflect.Descriptor instead. func (*AlertPolicy_Condition_Trigger) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1, 0} } func (m *AlertPolicy_Condition_Trigger) GetType() isAlertPolicy_Condition_Trigger_Type { if m != nil { return m.Type } return nil } func (x *AlertPolicy_Condition_Trigger) GetCount() int32 { if x, ok := x.GetType().(*AlertPolicy_Condition_Trigger_Count); ok { return x.Count } return 0 } func (x *AlertPolicy_Condition_Trigger) GetPercent() float64 { if x, ok := x.GetType().(*AlertPolicy_Condition_Trigger_Percent); ok { return x.Percent } return 0 } type isAlertPolicy_Condition_Trigger_Type interface { isAlertPolicy_Condition_Trigger_Type() } type AlertPolicy_Condition_Trigger_Count struct { // The absolute number of time series that must fail // the predicate for the condition to be triggered. Count int32 `protobuf:"varint,1,opt,name=count,proto3,oneof"` } type AlertPolicy_Condition_Trigger_Percent struct { // The percentage of time series that must fail the // predicate for the condition to be triggered. Percent float64 `protobuf:"fixed64,2,opt,name=percent,proto3,oneof"` } func (*AlertPolicy_Condition_Trigger_Count) isAlertPolicy_Condition_Trigger_Type() {} func (*AlertPolicy_Condition_Trigger_Percent) isAlertPolicy_Condition_Trigger_Type() {} // A condition type that compares a collection of time series // against a threshold. type AlertPolicy_Condition_MetricThreshold struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A [filter](https://cloud.google.com/monitoring/api/v3/filters) that // identifies which time series should be compared with the threshold. // // The filter is similar to the one that is specified in the // [`ListTimeSeries` // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list) // (that call is useful to verify the time series that will be retrieved / // processed) and must specify the metric type and optionally may contain // restrictions on resource type, resource labels, and metric labels. // This field may not exceed 2048 Unicode characters in length. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Specifies the alignment of data points in individual time series as // well as how to combine the retrieved time series together (such as // when aggregating multiple streams on each resource to a single // stream for each resource or when aggregating streams across all // members of a group of resrouces). Multiple aggregations // are applied in the order specified. // // This field is similar to the one in the [`ListTimeSeries` // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list). // It is advisable to use the `ListTimeSeries` method when debugging this // field. Aggregations []*Aggregation `protobuf:"bytes,8,rep,name=aggregations,proto3" json:"aggregations,omitempty"` // A [filter](https://cloud.google.com/monitoring/api/v3/filters) that // identifies a time series that should be used as the denominator of a // ratio that will be compared with the threshold. If a // `denominator_filter` is specified, the time series specified by the // `filter` field will be used as the numerator. // // The filter must specify the metric type and optionally may contain // restrictions on resource type, resource labels, and metric labels. // This field may not exceed 2048 Unicode characters in length. DenominatorFilter string `protobuf:"bytes,9,opt,name=denominator_filter,json=denominatorFilter,proto3" json:"denominator_filter,omitempty"` // Specifies the alignment of data points in individual time series // selected by `denominatorFilter` as // well as how to combine the retrieved time series together (such as // when aggregating multiple streams on each resource to a single // stream for each resource or when aggregating streams across all // members of a group of resources). // // When computing ratios, the `aggregations` and // `denominator_aggregations` fields must use the same alignment period // and produce time series that have the same periodicity and labels. DenominatorAggregations []*Aggregation `protobuf:"bytes,10,rep,name=denominator_aggregations,json=denominatorAggregations,proto3" json:"denominator_aggregations,omitempty"` // The comparison to apply between the time series (indicated by `filter` // and `aggregation`) and the threshold (indicated by `threshold_value`). // The comparison is applied on each time series, with the time series // on the left-hand side and the threshold on the right-hand side. // // Only `COMPARISON_LT` and `COMPARISON_GT` are supported currently. Comparison ComparisonType `protobuf:"varint,4,opt,name=comparison,proto3,enum=google.monitoring.v3.ComparisonType" json:"comparison,omitempty"` // A value against which to compare the time series. ThresholdValue float64 `protobuf:"fixed64,5,opt,name=threshold_value,json=thresholdValue,proto3" json:"threshold_value,omitempty"` // The amount of time that a time series must violate the // threshold to be considered failing. Currently, only values // that are a multiple of a minute--e.g., 0, 60, 120, or 300 // seconds--are supported. If an invalid value is given, an // error will be returned. When choosing a duration, it is useful to // keep in mind the frequency of the underlying time series data // (which may also be affected by any alignments specified in the // `aggregations` field); a good duration is long enough so that a single // outlier does not generate spurious alerts, but short enough that // unhealthy states are detected and alerted on quickly. Duration *duration.Duration `protobuf:"bytes,6,opt,name=duration,proto3" json:"duration,omitempty"` // The number/percent of time series for which the comparison must hold // in order for the condition to trigger. If unspecified, then the // condition will trigger if the comparison is true for any of the // time series that have been identified by `filter` and `aggregations`, // or by the ratio, if `denominator_filter` and `denominator_aggregations` // are specified. Trigger *AlertPolicy_Condition_Trigger `protobuf:"bytes,7,opt,name=trigger,proto3" json:"trigger,omitempty"` } func (x *AlertPolicy_Condition_MetricThreshold) Reset() { *x = AlertPolicy_Condition_MetricThreshold{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy_Condition_MetricThreshold) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy_Condition_MetricThreshold) ProtoMessage() {} func (x *AlertPolicy_Condition_MetricThreshold) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy_Condition_MetricThreshold.ProtoReflect.Descriptor instead. func (*AlertPolicy_Condition_MetricThreshold) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1, 1} } func (x *AlertPolicy_Condition_MetricThreshold) GetFilter() string { if x != nil { return x.Filter } return "" } func (x *AlertPolicy_Condition_MetricThreshold) GetAggregations() []*Aggregation { if x != nil { return x.Aggregations } return nil } func (x *AlertPolicy_Condition_MetricThreshold) GetDenominatorFilter() string { if x != nil { return x.DenominatorFilter } return "" } func (x *AlertPolicy_Condition_MetricThreshold) GetDenominatorAggregations() []*Aggregation { if x != nil { return x.DenominatorAggregations } return nil } func (x *AlertPolicy_Condition_MetricThreshold) GetComparison() ComparisonType { if x != nil { return x.Comparison } return ComparisonType_COMPARISON_UNSPECIFIED } func (x *AlertPolicy_Condition_MetricThreshold) GetThresholdValue() float64 { if x != nil { return x.ThresholdValue } return 0 } func (x *AlertPolicy_Condition_MetricThreshold) GetDuration() *duration.Duration { if x != nil { return x.Duration } return nil } func (x *AlertPolicy_Condition_MetricThreshold) GetTrigger() *AlertPolicy_Condition_Trigger { if x != nil { return x.Trigger } return nil } // A condition type that checks that monitored resources // are reporting data. The configuration defines a metric and // a set of monitored resources. The predicate is considered in violation // when a time series for the specified metric of a monitored // resource does not include any data in the specified `duration`. type AlertPolicy_Condition_MetricAbsence struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A [filter](https://cloud.google.com/monitoring/api/v3/filters) that // identifies which time series should be compared with the threshold. // // The filter is similar to the one that is specified in the // [`ListTimeSeries` // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list) // (that call is useful to verify the time series that will be retrieved / // processed) and must specify the metric type and optionally may contain // restrictions on resource type, resource labels, and metric labels. // This field may not exceed 2048 Unicode characters in length. Filter string `protobuf:"bytes,1,opt,name=filter,proto3" json:"filter,omitempty"` // Specifies the alignment of data points in individual time series as // well as how to combine the retrieved time series together (such as // when aggregating multiple streams on each resource to a single // stream for each resource or when aggregating streams across all // members of a group of resrouces). Multiple aggregations // are applied in the order specified. // // This field is similar to the one in the [`ListTimeSeries` // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list). // It is advisable to use the `ListTimeSeries` method when debugging this // field. Aggregations []*Aggregation `protobuf:"bytes,5,rep,name=aggregations,proto3" json:"aggregations,omitempty"` // The amount of time that a time series must fail to report new // data to be considered failing. Currently, only values that // are a multiple of a minute--e.g. 60, 120, or 300 // seconds--are supported. If an invalid value is given, an // error will be returned. The `Duration.nanos` field is // ignored. Duration *duration.Duration `protobuf:"bytes,2,opt,name=duration,proto3" json:"duration,omitempty"` // The number/percent of time series for which the comparison must hold // in order for the condition to trigger. If unspecified, then the // condition will trigger if the comparison is true for any of the // time series that have been identified by `filter` and `aggregations`. Trigger *AlertPolicy_Condition_Trigger `protobuf:"bytes,3,opt,name=trigger,proto3" json:"trigger,omitempty"` } func (x *AlertPolicy_Condition_MetricAbsence) Reset() { *x = AlertPolicy_Condition_MetricAbsence{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy_Condition_MetricAbsence) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy_Condition_MetricAbsence) ProtoMessage() {} func (x *AlertPolicy_Condition_MetricAbsence) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy_Condition_MetricAbsence.ProtoReflect.Descriptor instead. func (*AlertPolicy_Condition_MetricAbsence) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1, 2} } func (x *AlertPolicy_Condition_MetricAbsence) GetFilter() string { if x != nil { return x.Filter } return "" } func (x *AlertPolicy_Condition_MetricAbsence) GetAggregations() []*Aggregation { if x != nil { return x.Aggregations } return nil } func (x *AlertPolicy_Condition_MetricAbsence) GetDuration() *duration.Duration { if x != nil { return x.Duration } return nil } func (x *AlertPolicy_Condition_MetricAbsence) GetTrigger() *AlertPolicy_Condition_Trigger { if x != nil { return x.Trigger } return nil } var File_google_monitoring_v3_alert_proto protoreflect.FileDescriptor var file_google_monitoring_v3_alert_proto_rawDesc = []byte{ 0x0a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x14, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x21, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xf7, 0x13, 0x0a, 0x0b, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x55, 0x0a, 0x0d, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x52, 0x0a, 0x0b, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x18, 0x10, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x12, 0x4b, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x0c, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x53, 0x0a, 0x08, 0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x37, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x52, 0x08, 0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x12, 0x34, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x11, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x2e, 0x0a, 0x08, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x69, 0x74, 0x79, 0x18, 0x12, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x08, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x69, 0x74, 0x79, 0x12, 0x33, 0x0a, 0x15, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x73, 0x18, 0x0e, 0x20, 0x03, 0x28, 0x09, 0x52, 0x14, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x73, 0x12, 0x4d, 0x0a, 0x0f, 0x63, 0x72, 0x65, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x52, 0x0e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x12, 0x4d, 0x0a, 0x0f, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x52, 0x0e, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x1a, 0x46, 0x0a, 0x0d, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x6d, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6d, 0x69, 0x6d, 0x65, 0x54, 0x79, 0x70, 0x65, 0x1a, 0xf4, 0x0a, 0x0a, 0x09, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x6e, 0x0a, 0x13, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x3b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x48, 0x00, 0x52, 0x12, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x66, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x61, 0x62, 0x73, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x39, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x41, 0x62, 0x73, 0x65, 0x6e, 0x63, 0x65, 0x48, 0x00, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x62, 0x73, 0x65, 0x6e, 0x74, 0x1a, 0x45, 0x0a, 0x07, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1a, 0x0a, 0x07, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x48, 0x00, 0x52, 0x07, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x42, 0x06, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x1a, 0xf2, 0x03, 0x0a, 0x0f, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x45, 0x0a, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x5c, 0x0a, 0x18, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x0a, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x17, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x44, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x72, 0x69, 0x73, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x43, 0x6f, 0x6d, 0x70, 0x61, 0x72, 0x69, 0x73, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0a, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x72, 0x69, 0x73, 0x6f, 0x6e, 0x12, 0x27, 0x0a, 0x0f, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0e, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x4d, 0x0a, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x52, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x1a, 0xf4, 0x01, 0x0a, 0x0d, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x41, 0x62, 0x73, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x45, 0x0a, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x35, 0x0a, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x4d, 0x0a, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x52, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x3a, 0x97, 0x02, 0xea, 0x41, 0x93, 0x02, 0x0a, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x46, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x7b, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x2f, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x12, 0x50, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x2f, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x12, 0x44, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x73, 0x2f, 0x7b, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x2f, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x12, 0x01, 0x2a, 0x42, 0x0b, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0x3d, 0x0a, 0x0f, 0x55, 0x73, 0x65, 0x72, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x61, 0x0a, 0x15, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x12, 0x17, 0x0a, 0x13, 0x43, 0x4f, 0x4d, 0x42, 0x49, 0x4e, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x4e, 0x44, 0x10, 0x01, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x1e, 0x0a, 0x1a, 0x41, 0x4e, 0x44, 0x5f, 0x57, 0x49, 0x54, 0x48, 0x5f, 0x4d, 0x41, 0x54, 0x43, 0x48, 0x49, 0x4e, 0x47, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x03, 0x3a, 0xc9, 0x01, 0xea, 0x41, 0xc5, 0x01, 0x0a, 0x25, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x2f, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x7b, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x12, 0x39, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x12, 0x2d, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x73, 0x2f, 0x7b, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x12, 0x01, 0x2a, 0x42, 0xc2, 0x01, 0x0a, 0x18, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x42, 0x0a, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0xaa, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x56, 0x33, 0xca, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x5c, 0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x5c, 0x56, 0x33, 0xea, 0x02, 0x1d, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x3a, 0x3a, 0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x3a, 0x3a, 0x56, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_google_monitoring_v3_alert_proto_rawDescOnce sync.Once file_google_monitoring_v3_alert_proto_rawDescData = file_google_monitoring_v3_alert_proto_rawDesc ) func file_google_monitoring_v3_alert_proto_rawDescGZIP() []byte { file_google_monitoring_v3_alert_proto_rawDescOnce.Do(func() { file_google_monitoring_v3_alert_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_monitoring_v3_alert_proto_rawDescData) }) return file_google_monitoring_v3_alert_proto_rawDescData } var file_google_monitoring_v3_alert_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_google_monitoring_v3_alert_proto_msgTypes = make([]protoimpl.MessageInfo, 7) var file_google_monitoring_v3_alert_proto_goTypes = []interface{}{ (AlertPolicy_ConditionCombinerType)(0), // 0: google.monitoring.v3.AlertPolicy.ConditionCombinerType (*AlertPolicy)(nil), // 1: google.monitoring.v3.AlertPolicy (*AlertPolicy_Documentation)(nil), // 2: google.monitoring.v3.AlertPolicy.Documentation (*AlertPolicy_Condition)(nil), // 3: google.monitoring.v3.AlertPolicy.Condition nil, // 4: google.monitoring.v3.AlertPolicy.UserLabelsEntry (*AlertPolicy_Condition_Trigger)(nil), // 5: google.monitoring.v3.AlertPolicy.Condition.Trigger (*AlertPolicy_Condition_MetricThreshold)(nil), // 6: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold (*AlertPolicy_Condition_MetricAbsence)(nil), // 7: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence (*wrappers.BoolValue)(nil), // 8: google.protobuf.BoolValue (*status.Status)(nil), // 9: google.rpc.Status (*MutationRecord)(nil), // 10: google.monitoring.v3.MutationRecord (*Aggregation)(nil), // 11: google.monitoring.v3.Aggregation (ComparisonType)(0), // 12: google.monitoring.v3.ComparisonType (*duration.Duration)(nil), // 13: google.protobuf.Duration } var file_google_monitoring_v3_alert_proto_depIdxs = []int32{ 2, // 0: google.monitoring.v3.AlertPolicy.documentation:type_name -> google.monitoring.v3.AlertPolicy.Documentation 4, // 1: google.monitoring.v3.AlertPolicy.user_labels:type_name -> google.monitoring.v3.AlertPolicy.UserLabelsEntry 3, // 2: google.monitoring.v3.AlertPolicy.conditions:type_name -> google.monitoring.v3.AlertPolicy.Condition 0, // 3: google.monitoring.v3.AlertPolicy.combiner:type_name -> google.monitoring.v3.AlertPolicy.ConditionCombinerType 8, // 4: google.monitoring.v3.AlertPolicy.enabled:type_name -> google.protobuf.BoolValue 9, // 5: google.monitoring.v3.AlertPolicy.validity:type_name -> google.rpc.Status 10, // 6: google.monitoring.v3.AlertPolicy.creation_record:type_name -> google.monitoring.v3.MutationRecord 10, // 7: google.monitoring.v3.AlertPolicy.mutation_record:type_name -> google.monitoring.v3.MutationRecord 6, // 8: google.monitoring.v3.AlertPolicy.Condition.condition_threshold:type_name -> google.monitoring.v3.AlertPolicy.Condition.MetricThreshold 7, // 9: google.monitoring.v3.AlertPolicy.Condition.condition_absent:type_name -> google.monitoring.v3.AlertPolicy.Condition.MetricAbsence 11, // 10: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.aggregations:type_name -> google.monitoring.v3.Aggregation 11, // 11: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.denominator_aggregations:type_name -> google.monitoring.v3.Aggregation 12, // 12: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.comparison:type_name -> google.monitoring.v3.ComparisonType 13, // 13: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.duration:type_name -> google.protobuf.Duration 5, // 14: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.trigger:type_name -> google.monitoring.v3.AlertPolicy.Condition.Trigger 11, // 15: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence.aggregations:type_name -> google.monitoring.v3.Aggregation 13, // 16: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence.duration:type_name -> google.protobuf.Duration 5, // 17: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence.trigger:type_name -> google.monitoring.v3.AlertPolicy.Condition.Trigger 18, // [18:18] is the sub-list for method output_type 18, // [18:18] is the sub-list for method input_type 18, // [18:18] is the sub-list for extension type_name 18, // [18:18] is the sub-list for extension extendee 0, // [0:18] is the sub-list for field type_name } func init() { file_google_monitoring_v3_alert_proto_init() } func file_google_monitoring_v3_alert_proto_init() { if File_google_monitoring_v3_alert_proto != nil { return } file_google_monitoring_v3_common_proto_init() file_google_monitoring_v3_mutation_record_proto_init() if !protoimpl.UnsafeEnabled { file_google_monitoring_v3_alert_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_monitoring_v3_alert_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy_Documentation); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_monitoring_v3_alert_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy_Condition); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_monitoring_v3_alert_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy_Condition_Trigger); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_monitoring_v3_alert_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy_Condition_MetricThreshold); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_monitoring_v3_alert_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy_Condition_MetricAbsence); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } file_google_monitoring_v3_alert_proto_msgTypes[2].OneofWrappers = []interface{}{ (*AlertPolicy_Condition_ConditionThreshold)(nil), (*AlertPolicy_Condition_ConditionAbsent)(nil), } file_google_monitoring_v3_alert_proto_msgTypes[4].OneofWrappers = []interface{}{ (*AlertPolicy_Condition_Trigger_Count)(nil), (*AlertPolicy_Condition_Trigger_Percent)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_monitoring_v3_alert_proto_rawDesc, NumEnums: 1, NumMessages: 7, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_monitoring_v3_alert_proto_goTypes, DependencyIndexes: file_google_monitoring_v3_alert_proto_depIdxs, EnumInfos: file_google_monitoring_v3_alert_proto_enumTypes, MessageInfos: file_google_monitoring_v3_alert_proto_msgTypes, }.Build() File_google_monitoring_v3_alert_proto = out.File file_google_monitoring_v3_alert_proto_rawDesc = nil file_google_monitoring_v3_alert_proto_goTypes = nil file_google_monitoring_v3_alert_proto_depIdxs = nil }
hartsock/vault
vendor/google.golang.org/genproto/googleapis/monitoring/v3/alert.pb.go
GO
mpl-2.0
58,646
package gotry import ( "errors" "testing" "time" ) func TestTry_noError(t *testing.T) { r := Retry{} attempt := 0 err := Try(func() error { attempt++ return nil }, r) if err != nil { t.Fatal(err) } expected := 1 if attempt != expected { t.Errorf("expected attempt to be %d got %d", expected, attempt) } } func TestTry_error(t *testing.T) { r := Retry{Max: 1} attempt := 0 err := Try(func() error { attempt++ return errors.New("error") }, r) if err == nil { t.Error("expected error") } expected := 2 if attempt != expected { t.Errorf("expected attempt to be %d got %d", expected, attempt) } } func TestTry_timeout(t *testing.T) { r := Retry{Max: 1, Timeout: 2 * time.Millisecond} start := time.Now() attempt := 0 err := Try(func() error { attempt++ return errors.New("error") }, r) if err == nil { t.Error("expected error") } expected := 2 if attempt != expected { t.Errorf("expected attempt to be %d got %d", expected, attempt) } diff := time.Now().Sub(start) if diff < r.Timeout { t.Errorf("expected %s to be less than %s", r.Timeout, diff) } }
selimekizoglu/gotry
gotry_test.go
GO
mpl-2.0
1,117
#!/usr/bin/env python ''' THIS APP IS NOT PRODUCTION READY!! DO NOT USE! Flask app that provides a RESTful API to MultiScanner. Supported operations: GET / ---> Test functionality. {'Message': 'True'} GET /api/v1/files/<sha256>?raw={t|f} ----> download sample, defaults to passwd protected zip GET /api/v1/modules ---> Receive list of modules available GET /api/v1/tags ----> Receive list of all tags in use GET /api/v1/tasks ---> Receive list of tasks in MultiScanner POST /api/v1/tasks ---> POST file and receive report id Sample POST usage: curl -i -X POST http://localhost:8080/api/v1/tasks -F file=@/bin/ls GET /api/v1/tasks/<task_id> ---> receive task in JSON format DELETE /api/v1/tasks/<task_id> ----> delete task_id GET /api/v1/tasks/search/ ---> receive list of most recent report for matching samples GET /api/v1/tasks/search/history ---> receive list of most all reports for matching samples GET /api/v1/tasks/<task_id>/file?raw={t|f} ----> download sample, defaults to passwd protected zip GET /api/v1/tasks/<task_id>/maec ----> download the Cuckoo MAEC 5.0 report, if it exists GET /api/v1/tasks/<task_id>/notes ---> Receive list of this task's notes POST /api/v1/tasks/<task_id>/notes ---> Add a note to task PUT /api/v1/tasks/<task_id>/notes/<note_id> ---> Edit a note DELETE /api/v1/tasks/<task_id>/notes/<note_id> ---> Delete a note GET /api/v1/tasks/<task_id>/report?d={t|f}---> receive report in JSON, set d=t to download GET /api/v1/tasks/<task_id>/pdf ---> Receive PDF report POST /api/v1/tasks/<task_id>/tags ---> Add tags to task DELETE /api/v1/tasks/<task_id>/tags ---> Remove tags from task GET /api/v1/analytics/ssdeep_compare---> Run ssdeep.compare analytic GET /api/v1/analytics/ssdeep_group---> Receive list of sample hashes grouped by ssdeep hash The API endpoints all have Cross Origin Resource Sharing (CORS) enabled. By default it will allow requests from any port on localhost. Change this setting by modifying the 'cors' setting in the 'api' section of the api config file. TODO: * Add doc strings to functions ''' from __future__ import print_function import os import sys import time import hashlib import codecs import configparser import json import multiprocessing import subprocess import queue import shutil from datetime import datetime from flask_cors import CORS from flask import Flask, jsonify, make_response, request, abort from flask.json import JSONEncoder from jinja2 import Markup from six import PY3 import rarfile import zipfile import requests MS_WD = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if os.path.join(MS_WD, 'storage') not in sys.path: sys.path.insert(0, os.path.join(MS_WD, 'storage')) if os.path.join(MS_WD, 'analytics') not in sys.path: sys.path.insert(0, os.path.join(MS_WD, 'analytics')) if os.path.join(MS_WD, 'libs') not in sys.path: sys.path.insert(0, os.path.join(MS_WD, 'libs')) if MS_WD not in sys.path: sys.path.insert(0, os.path.join(MS_WD)) import multiscanner import sql_driver as database import elasticsearch_storage import common from utils.pdf_generator import create_pdf_document TASK_NOT_FOUND = {'Message': 'No task or report with that ID found!'} INVALID_REQUEST = {'Message': 'Invalid request parameters'} HTTP_OK = 200 HTTP_CREATED = 201 HTTP_BAD_REQUEST = 400 HTTP_NOT_FOUND = 404 DEFAULTCONF = { 'host': 'localhost', 'port': 8080, 'upload_folder': '/mnt/samples/', 'distributed': True, 'web_loc': 'http://localhost:80', 'cors': 'https?://localhost(:\d+)?', 'batch_size': 100, 'batch_interval': 60 # Number of seconds to wait for additional files # submitted to the create/ API } # Customize timestamp format output of jsonify() class CustomJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() return str(obj) else: return JSONEncoder.default(self, obj) app = Flask(__name__) app.json_encoder = CustomJSONEncoder api_config_object = configparser.SafeConfigParser() api_config_object.optionxform = str api_config_file = multiscanner.common.get_config_path(multiscanner.CONFIG, 'api') api_config_object.read(api_config_file) if not api_config_object.has_section('api') or not os.path.isfile(api_config_file): # Write default config api_config_object.add_section('api') for key in DEFAULTCONF: api_config_object.set('api', key, str(DEFAULTCONF[key])) conffile = codecs.open(api_config_file, 'w', 'utf-8') api_config_object.write(conffile) conffile.close() api_config = multiscanner.common.parse_config(api_config_object) # Needs api_config in order to function properly from celery_worker import multiscanner_celery, ssdeep_compare_celery from ssdeep_analytics import SSDeepAnalytic db = database.Database(config=api_config.get('Database')) # To run under Apache, we need to set up the DB outside of __main__ db.init_db() storage_conf = multiscanner.common.get_config_path(multiscanner.CONFIG, 'storage') storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) for handler in storage_handler.loaded_storage: if isinstance(handler, elasticsearch_storage.ElasticSearchStorage): break ms_config_object = configparser.SafeConfigParser() ms_config_object.optionxform = str ms_configfile = multiscanner.CONFIG ms_config_object.read(ms_configfile) ms_config = common.parse_config(ms_config_object) try: DISTRIBUTED = api_config['api']['distributed'] except KeyError: DISTRIBUTED = False if not DISTRIBUTED: work_queue = multiprocessing.Queue() try: cors_origins = api_config['api']['cors'] except KeyError: cors_origins = DEFAULTCONF['cors'] CORS(app, origins=cors_origins) batch_size = api_config['api']['batch_size'] batch_interval = api_config['api']['batch_interval'] # Add `delete_after_scan = True` to api_config.ini to delete samples after scan has completed delete_after_scan = api_config['api'].get('delete_after_scan', False) def multiscanner_process(work_queue, exit_signal): '''Not used in distributed mode. ''' metadata_list = [] time_stamp = None while True: time.sleep(1) try: metadata_list.append(work_queue.get_nowait()) if not time_stamp: time_stamp = time.time() while len(metadata_list) < batch_size: metadata_list.append(work_queue.get_nowait()) except queue.Empty: if metadata_list and time_stamp: if len(metadata_list) >= batch_size: pass elif time.time() - time_stamp > batch_interval: pass else: continue else: continue filelist = [item[0] for item in metadata_list] #modulelist = [item[5] for item in metadata_list] resultlist = multiscanner.multiscan( filelist, configfile=multiscanner.CONFIG #module_list ) results = multiscanner.parse_reports(resultlist, python=True) scan_time = datetime.now().isoformat() if delete_after_scan: for file_name in results: os.remove(file_name) for item in metadata_list: # Use the original filename as the index instead of the full path results[item[1]] = results[item[0]] del results[item[0]] results[item[1]]['Scan Time'] = scan_time results[item[1]]['Metadata'] = item[4] db.update_task( task_id=item[2], task_status='Complete', timestamp=scan_time, ) metadata_list = [] storage_handler.store(results, wait=False) filelist = [] time_stamp = None storage_handler.close() @app.errorhandler(HTTP_BAD_REQUEST) def invalid_request(error): '''Return a 400 with the INVALID_REQUEST message.''' return make_response(jsonify(INVALID_REQUEST), HTTP_BAD_REQUEST) @app.errorhandler(HTTP_NOT_FOUND) def not_found(error): '''Return a 404 with a TASK_NOT_FOUND message.''' return make_response(jsonify(TASK_NOT_FOUND), HTTP_NOT_FOUND) @app.route('/') def index(): ''' Return a default standard message for testing connectivity. ''' return jsonify({'Message': 'True'}) @app.route('/api/v1/modules', methods=['GET']) def modules(): ''' Return a list of module names available for MultiScanner to use, and whether or not they are enabled in the config. ''' files = multiscanner.parseDir(multiscanner.MODULEDIR, True) filenames = [os.path.splitext(os.path.basename(f)) for f in files] module_names = [m[0] for m in filenames if m[1] == '.py'] ms_config = configparser.SafeConfigParser() ms_config.optionxform = str ms_config.read(multiscanner.CONFIG) modules = {} for module in module_names: try: modules[module] = ms_config.get(module, 'ENABLED') except (configparser.NoSectionError, configparser.NoOptionError): pass return jsonify({'Modules': modules}) @app.route('/api/v1/tasks', methods=['GET']) def task_list(): ''' Return a JSON dictionary containing all the tasks in the tasks DB. ''' return jsonify({'Tasks': db.get_all_tasks()}) def search(params, get_all=False): # Pass search term to Elasticsearch, get back list of sample_ids sample_id = params.get('sha256') if sample_id: task_id = db.exists(sample_id) if task_id: return { 'TaskID' : task_id } else: return TASK_NOT_FOUND search_term = params.get('search[value]') search_type = params.pop('search_type', 'default') if not search_term: es_result = None else: es_result = handler.search(search_term, search_type) # Search the task db for the ids we got from Elasticsearch if get_all: return db.search(params, es_result, return_all=True) else: return db.search(params, es_result) @app.route('/api/v1/tasks/search/history', methods=['GET']) def task_search_history(): ''' Handle query between jQuery Datatables, the task DB, and Elasticsearch. Return all reports for matching samples. ''' params = request.args.to_dict() resp = search(params, get_all=True) return jsonify(resp) @app.route('/api/v1/tasks/search', methods=['GET']) def task_search(): ''' Handle query between jQuery Datatables, the task DB, and Elasticsearch. Return only the most recent report for each of the matching samples. ''' params = request.args.to_dict() resp = search(params) return jsonify(resp) @app.route('/api/v1/tasks/<int:task_id>', methods=['GET']) def get_task(task_id): ''' Return a JSON dictionary corresponding to the given task ID. ''' task = db.get_task(task_id) if task: return jsonify({'Task': task.to_dict()}) else: abort(HTTP_NOT_FOUND) @app.route('/api/v1/tasks/<int:task_id>', methods=['DELETE']) def delete_task(task_id): ''' Delete the specified task. Return deleted message. ''' result = db.delete_task(task_id) if not result: abort(HTTP_NOT_FOUND) return jsonify({'Message': 'Deleted'}) def save_hashed_filename(f, zipped=False): ''' Save given file to the upload folder, with its SHA256 hash as its filename. ''' f_name = hashlib.sha256(f.read()).hexdigest() # Reset the file pointer to the beginning to allow us to save it f.seek(0) # TODO: should we check if the file is already there # and skip this step if it is? file_path = os.path.join(api_config['api']['upload_folder'], f_name) full_path = os.path.join(MS_WD, file_path) if zipped: shutil.copy2(f.name, full_path) else: f.save(file_path) return (f_name, full_path) class InvalidScanTimeFormatError(ValueError): pass def import_task(file_): ''' Import a JSON report that was downloaded from MultiScanner. ''' report = json.loads(file_.read().decode('utf-8')) try: report['Scan Time'] = datetime.strptime(report['Scan Time'], '%Y-%m-%dT%H:%M:%S.%f') except ValueError: raise InvalidScanTimeFormatError() task_id = db.add_task( sample_id=report['SHA256'], task_status='Complete', timestamp=report['Scan Time'], ) storage_handler.store({report['filename']: report}, wait=False) return task_id def queue_task(original_filename, f_name, full_path, metadata, rescan=False): ''' Queue up a single new task, for a single non-archive file. ''' # If option set, or no scan exists for this sample, skip and scan sample again # Otherwise, pull latest scan for this sample if (not rescan): t_exists = db.exists(f_name) if t_exists: return t_exists # Add task to sqlite DB # Make the sample_id equal the sha256 hash task_id = db.add_task(sample_id=f_name) if DISTRIBUTED: # Publish the task to Celery multiscanner_celery.delay(full_path, original_filename, task_id, f_name, metadata, config=multiscanner.CONFIG) else: # Put the task on the queue work_queue.put((full_path, original_filename, task_id, f_name, metadata)) return task_id @app.route('/api/v1/tasks', methods=['POST']) def create_task(): ''' Create a new task for a submitted file. Save the submitted file to UPLOAD_FOLDER, optionally unzipping it. Return task id and 201 status. ''' file_ = request.files['file'] if request.form.get('upload_type', None) == 'import': try: task_id = import_task(file_) except KeyError: return make_response( jsonify({'Message': 'Cannot import report missing \'Scan Time\' field!'}), HTTP_BAD_REQUEST) except InvalidScanTimeFormatError: return make_response( jsonify({'Message': 'Cannot import report with \'Scan Time\' of invalid format!'}), HTTP_BAD_REQUEST) except (UnicodeDecodeError, ValueError): return make_response( jsonify({'Message': 'Cannot import non-JSON files!'}), HTTP_BAD_REQUEST) return make_response( jsonify({'Message': {'task_ids': [task_id]}}), HTTP_CREATED ) original_filename = file_.filename metadata = {} task_id_list = [] extract_dir = None rescan = False for key in request.form.keys(): if key in ['file_id', 'archive-password', 'upload_type'] or request.form[key] == '': continue elif key == 'duplicate': if request.form[key] == 'latest': rescan = False elif request.form[key] == 'rescan': rescan = True elif key == 'modules': module_names = request.form[key] files = multiscanner.parseDir(multiscanner.MODULEDIR, True) modules = [] for f in files: split = os.path.splitext(os.path.basename(f)) if split[0] in module_names and split[1] == '.py': modules.append(f) elif key == 'archive-analyze' and request.form[key] == 'true': extract_dir = api_config['api']['upload_folder'] if not os.path.isdir(extract_dir): return make_response( jsonify({'Message': "'upload_folder' in API config is not " "a valid folder!"}), HTTP_BAD_REQUEST) # Get password if present if 'archive-password' in request.form: password = request.form['archive-password'] if PY3: password = bytes(password, 'utf-8') else: password = '' else: metadata[key] = request.form[key] if extract_dir: # Extract a zip if zipfile.is_zipfile(file_): z = zipfile.ZipFile(file_) try: # NOTE: zipfile module prior to Py 2.7.4 is insecure! # https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.extract z.extractall(path=extract_dir, pwd=password) for uzfile in z.namelist(): unzipped_file = open(os.path.join(extract_dir, uzfile)) f_name, full_path = save_hashed_filename(unzipped_file, True) tid = queue_task(uzfile, f_name, full_path, metadata, rescan=rescan) task_id_list.append(tid) except RuntimeError as e: msg = "ERROR: Failed to extract " + str(file_) + ' - ' + str(e) return make_response( jsonify({'Message': msg}), HTTP_BAD_REQUEST) # Extract a rar elif rarfile.is_rarfile(file_): r = rarfile.RarFile(file_) try: r.extractall(path=extract_dir, pwd=password) for urfile in r.namelist(): unrarred_file = open(os.path.join(extract_dir, urfile)) f_name, full_path = save_hashed_filename(unrarred_file, True) tid = queue_task(urfile, f_name, full_path, metadata, rescan=rescan) task_id_list.append(tid) except RuntimeError as e: msg = "ERROR: Failed to extract " + str(file_) + ' - ' + str(e) return make_response( jsonify({'Message': msg}), HTTP_BAD_REQUEST) else: # File was not an archive to extract f_name, full_path = save_hashed_filename(file_) tid = queue_task(original_filename, f_name, full_path, metadata, rescan=rescan) task_id_list = [tid] msg = {'task_ids': task_id_list} return make_response( jsonify({'Message': msg}), HTTP_CREATED ) @app.route('/api/v1/tasks/<task_id>/report', methods=['GET']) def get_report(task_id): ''' Return a JSON dictionary corresponding to the given task ID. ''' download = request.args.get('d', default='False', type=str)[0].lower() report_dict, success = get_report_dict(task_id) if success: if (download == 't' or download == 'y' or download == '1'): # raw JSON response = make_response(jsonify(report_dict)) response.headers['Content-Type'] = 'application/json' response.headers['Content-Disposition'] = 'attachment; filename=%s.json' % task_id return response else: # processed JSON intended for web UI report_dict = _pre_process(report_dict) return jsonify(report_dict) else: return jsonify(report_dict) def _pre_process(report_dict={}): ''' Returns a JSON dictionary where a series of pre-processing steps are executed on report_dict. ''' # pop unecessary keys if report_dict.get('Report', {}).get('ssdeep', {}): for k in ['chunksize', 'chunk', 'double_chunk']: try: report_dict['Report']['ssdeep'].pop(k) except KeyError as e: pass report_dict = _add_links(report_dict) return report_dict def _add_links(report_dict): ''' Returns a JSON dictionary where certain keys and/or values are replaced with hyperlinks. ''' web_loc = api_config['api']['web_loc'] # ssdeep matches matches_dict = report_dict.get('Report', {}) \ .get('ssdeep', {}) \ .get('matches', {}) if matches_dict: links_dict = {} # k=SHA256, v=ssdeep.compare result for k, v in matches_dict.items(): t_id = db.exists(k) if t_id: url = '{h}/report/{t_id}'.format(h=web_loc, t_id=t_id) href = _linkify(k, url, True) links_dict[href] = v else: links_dict[k] = v # replace with updated dict report_dict['Report']['ssdeep']['matches'] = links_dict return report_dict #TODO: should we move these helper functions to separate file? def _linkify(s, url, new_tab=True): ''' Return string s as HTML a tag with href pointing to url. ''' return '<a{new_tab} href="{url}">{s}</a>'.format( new_tab=' target="_blank"' if new_tab else '', url=url, s=s) @app.route('/api/v1/tasks/<task_id>/file', methods=['GET']) def files_get_task(task_id): # try to get report dict report_dict, success = get_report_dict(task_id) if not success: return jsonify(report_dict) # okay, we have report dict; get sha256 sha256 = report_dict.get('Report', {}).get('SHA256') if sha256: return files_get_sha256_helper( sha256, request.args.get('raw', default=None)) else: return jsonify({'Error': 'sha256 not in report!'}) @app.route('/api/v1/tasks/<task_id>/maec', methods=['GET']) def get_maec_report(task_id): # try to get report dict report_dict, success = get_report_dict(task_id) if not success: return jsonify(report_dict) # okay, we have report dict; get cuckoo task ID try: cuckoo_task_id = report_dict['Report']['Cuckoo Sandbox']['info']['id'] except KeyError: return jsonify({'Error': 'No MAEC report found for that task!'}) # Get the MAEC report from Cuckoo try: maec_report = requests.get( '{}/v1/tasks/report/{}/maec'.format(ms_config.get('Cuckoo', {}).get('API URL', ''), cuckoo_task_id) ) except: return jsonify({'Error': 'No MAEC report found for that task!'}) # raw JSON response = make_response(jsonify(maec_report.json())) response.headers['Content-Type'] = 'application/json' response.headers['Content-Disposition'] = 'attachment; filename=%s.json' % task_id return response def get_report_dict(task_id): task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) if task.task_status == 'Complete': return {'Report': handler.get_report(task.sample_id, task.timestamp)}, True elif task.task_status == 'Pending': return {'Report': 'Task still pending'}, False else: return {'Report': 'Task failed'}, False @app.route('/api/v1/tasks/<task_id>', methods=['DELETE']) def delete_report(task_id): ''' Delete the specified task. Return deleted message. ''' task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) if handler.delete(task.report_id): return jsonify({'Message': 'Deleted'}) else: abort(HTTP_NOT_FOUND) @app.route('/api/v1/tags/', methods=['GET']) def taglist(): ''' Return a list of all tags currently in use. ''' response = handler.get_tags() return jsonify({'Tags': response}) @app.route('/api/v1/tasks/<task_id>/tags', methods=['POST', 'DELETE']) def tags(task_id): ''' Add/Remove the specified tag to the specified task. ''' task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) tag = request.values.get('tag', '') if request.method == 'POST': response = handler.add_tag(task.sample_id, tag) if not response: abort(HTTP_BAD_REQUEST) return jsonify({'Message': 'Tag Added'}) elif request.method == 'DELETE': response = handler.remove_tag(task.sample_id, tag) if not response: abort(HTTP_BAD_REQUEST) return jsonify({'Message': 'Tag Removed'}) @app.route('/api/v1/tasks/<task_id>/notes', methods=['GET']) def get_notes(task_id): ''' Get one or more analyst notes/comments associated with the specified task. ''' task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) if ('ts' in request.args and 'uid' in request.args): ts = request.args.get('ts', '') uid = request.args.get('uid', '') response = handler.get_notes(task.sample_id, [ts, uid]) else: response = handler.get_notes(task.sample_id) if not response: abort(HTTP_BAD_REQUEST) if 'hits' in response and 'hits' in response['hits']: response = response['hits']['hits'] try: for hit in response: hit['_source']['text'] = Markup.escape(hit['_source']['text']) except: pass return jsonify(response) @app.route('/api/v1/tasks/<task_id>/notes', methods=['POST']) def add_note(task_id): ''' Add an analyst note/comment to the specified task. ''' task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) response = handler.add_note(task.sample_id, request.form.to_dict()) if not response: abort(HTTP_BAD_REQUEST) return jsonify(response) @app.route('/api/v1/tasks/<task_id>/notes/<note_id>', methods=['PUT', 'DELETE']) def edit_note(task_id, note_id): ''' Modify/remove the specified analyst note/comment. ''' task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) if request.method == 'PUT': response = handler.edit_note(task.sample_id, note_id, Markup(request.form.get('text', '')).striptags()) elif request.method == 'DELETE': response = handler.delete_note(task.sample_id, note_id) if not response: abort(HTTP_BAD_REQUEST) return jsonify(response) @app.route('/api/v1/files/<sha256>', methods=['GET']) # get raw file - /api/v1/files/get/<sha256>?raw=true def files_get_sha256(sha256): ''' Returns binary from storage. Defaults to password protected zipfile. ''' # is there a robust way to just get this as a bool? raw = request.args.get('raw', default='False', type=str) return files_get_sha256_helper(sha256, raw) def files_get_sha256_helper(sha256, raw=None): ''' Returns binary from storage. Defaults to password protected zipfile. ''' file_path = os.path.join(api_config['api']['upload_folder'], sha256) if not os.path.exists(file_path): abort(HTTP_NOT_FOUND) with open(file_path, "rb") as fh: fh_content = fh.read() raw = raw[0].lower() if raw == 't' or raw == 'y' or raw == '1': response = make_response(fh_content) response.headers['Content-Type'] = 'application/octet-stream; charset=UTF-8' response.headers['Content-Disposition'] = 'inline; filename={}.bin'.format(sha256) # better way to include fname? else: # ref: https://github.com/crits/crits/crits/core/data_tools.py#L122 rawname = sha256 + '.bin' with open(os.path.join('/tmp/', rawname), 'wb') as raw_fh: raw_fh.write(fh_content) zipname = sha256 + '.zip' args = ['/usr/bin/zip', '-j', os.path.join('/tmp', zipname), os.path.join('/tmp', rawname), '-P', 'infected'] proc = subprocess.Popen(args) wait_seconds = 30 while proc.poll() is None and wait_seconds: time.sleep(1) wait_seconds -= 1 if proc.returncode: return make_response(jsonify({'Error': 'Failed to create zip ()'.format(proc.returncode)})) elif not wait_seconds: proc.terminate() return make_response(jsonify({'Error': 'Process timed out'})) else: with open(os.path.join('/tmp', zipname), 'rb') as zip_fh: zip_data = zip_fh.read() if len(zip_data) == 0: return make_response(jsonify({'Error': 'Zip file empty'})) response = make_response(zip_data) response.headers['Content-Type'] = 'application/zip; charset=UTF-8' response.headers['Content-Disposition'] = 'inline; filename={}.zip'.format(sha256) return response @app.route('/api/v1/analytics/ssdeep_compare', methods=['GET']) def run_ssdeep_compare(): ''' Runs ssdeep compare analytic and returns success / error message. ''' try: if DISTRIBUTED: # Publish task to Celery ssdeep_compare_celery.delay() return make_response(jsonify({ 'Message': 'Success' })) else: ssdeep_analytic = SSDeepAnalytic() ssdeep_analytic.ssdeep_compare() return make_response(jsonify({ 'Message': 'Success' })) except Exception as e: return make_response( jsonify({'Message': 'Unable to complete request.'}), HTTP_BAD_REQUEST) @app.route('/api/v1/analytics/ssdeep_group', methods=['GET']) def run_ssdeep_group(): ''' Runs ssdeep group analytic and returns list of groups as a list. ''' try: ssdeep_analytic = SSDeepAnalytic() groups = ssdeep_analytic.ssdeep_group() return make_response(jsonify({ 'groups': groups })) except Exception as e: return make_response( jsonify({'Message': 'Unable to complete request.'}), HTTP_BAD_REQUEST) @app.route('/api/v1/tasks/<task_id>/pdf', methods=['GET']) def get_pdf_report(task_id): ''' Generates a PDF version of a JSON report. ''' report_dict, success = get_report_dict(task_id) if not success: return jsonify(report_dict) pdf = create_pdf_document(MS_WD, report_dict) response = make_response(pdf) response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] = 'attachment; filename=%s.pdf' % task_id return response if __name__ == '__main__': if not os.path.isdir(api_config['api']['upload_folder']): print('Creating upload dir') os.makedirs(api_config['api']['upload_folder']) if not DISTRIBUTED: exit_signal = multiprocessing.Value('b') exit_signal.value = False ms_process = multiprocessing.Process( target=multiscanner_process, args=(work_queue, exit_signal) ) ms_process.start() app.run(host=api_config['api']['host'], port=api_config['api']['port']) if not DISTRIBUTED: ms_process.join()
awest1339/multiscanner
utils/api.py
Python
mpl-2.0
30,509
/* * Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ define([ 'require', 'module', 'jquery', '{lodash}/lodash', '{angular}/angular', '[text]!{w20-business-theme}/templates/topbar.html', '[text]!{w20-business-theme}/templates/sidebar.html', '{angular-sanitize}/angular-sanitize', '{w20-core}/modules/ui', '{w20-core}/modules/notifications', '{w20-core}/modules/culture', '{w20-core}/modules/utils' ], function (require, module, $, _, angular, topbarTemplate, sidebarTemplate) { 'use strict'; var w20BusinessTheme = angular.module('w20BusinessTheme', ['w20CoreCulture', 'w20CoreUtils', 'w20CoreUI', 'w20CoreNotifications', 'ngSanitize']), _config = module && module.config() || {}, showTopbar = true, showSidebar = _config.sidebar && typeof _config.sidebar.show === 'boolean' ? _config.show : true, includes = _.contains || _.includes; w20BusinessTheme.directive('w20Topbar', ['ApplicationService', 'EventService', 'EnvironmentService', 'DisplayService', 'MenuService', 'NavigationService', function (applicationService, eventService, environmentService, displayService, menuService, navigationService) { return { template: topbarTemplate, replace: true, restrict: 'A', scope: true, link: function (scope, iElement, iAttrs) { scope.navActions = menuService.getActions; scope.navAction = menuService.getAction; scope.envtype = environmentService.environment; scope.buildLink = navigationService.buildLink; scope.title = iAttrs.title || '\'' + applicationService.applicationId + '\''; scope.description = iAttrs.subtitle || ''; scope.logo = _config.logo; scope.brandFixedWidth = true; if (_config.brand) { scope.brandFixedWidth = _config.brand.fixedWidth === false ? _config.brand.fixedWidth : true; scope.brandBackgroundColor = _config.brand.backgroundColor ? _config.brand.backgroundColor : undefined; scope.brandTextColor = _config.brand.textColor ? _config.brand.textColor : undefined; } scope.showTopbar = function () { return showTopbar; }; scope.toggleSidebar = function () { eventService.emit('SidebarToggleEvent'); }; displayService.registerContentShiftCallback(function () { return [showTopbar ? 50 : 0, 0, 0, 0]; }); } }; }]); w20BusinessTheme.directive('w20Sidebar', ['EventService', 'DisplayService', 'NavigationService', 'MenuService', '$location', '$window', function (eventService, displayService, navigationService, menuService, $location, $window) { return { template: sidebarTemplate, replace: true, restrict: 'A', scope: true, link: function (scope) { var previousSidebarState = showSidebar; if (_config.sidebar) { scope.sideBarWidth = _config.sidebar.width ? _config.sidebar.width : undefined; } scope.menuSections = menuService.getSections; scope.menuActiveSectionName = scope.menuSections()[0]; scope.showSidebar = function () { return showSidebar; }; scope.menuSection = function (name) { return name ? menuService.getSection(name) : null; }; eventService.on('SidebarToggleEvent', function () { showSidebar = !showSidebar; previousSidebarState = showSidebar; displayService.computeContentShift(); }); displayService.registerContentShiftCallback(function () { return [10, 0, 0, showSidebar ? (scope.sideBarWidth || 270) : 0]; }); angular.element($window).bind('resize', function () { showSidebar = $(window).width() < 768 ? false : previousSidebarState; scope.$apply(); displayService.computeContentShift(); }); } }; }]); w20BusinessTheme.filter('routeFilter', ['CultureService', 'SecurityExpressionService', function (cultureService, securityExpressionService) { function isRouteVisible(route) { return !route.hidden && (typeof route.security === 'undefined' || securityExpressionService.evaluate(route.security)); } return function (routes, expected) { if (!expected) { return; } return _.filter(routes, function (route) { if (isRouteVisible(route) && cultureService.displayName(route).toLowerCase().indexOf(expected.toLowerCase()) !== -1) { return route; } }); }; }]); w20BusinessTheme.controller('W20btViewsController', ['$scope', 'NavigationService', 'CultureService', '$route', '$location', function ($scope, navigationService, cultureService, $route, $location) { var openedCategories = navigationService.expandedRouteCategories(); function recursiveOpen(tree) { openedCategories.push(tree.categoryName); for (var key in tree) { if (tree.hasOwnProperty(key)) { var subTree = tree[key]; if (subTree instanceof Array) { recursiveOpen(subTree); } } } } $scope.routes = $route.routes; $scope.filteredRoutes = []; $scope.menuTree = navigationService.routeTree; $scope.subMenuTree = navigationService.computeSubTree; $scope.topLevelCategories = navigationService.topLevelRouteCategories; $scope.topLevelRoutes = navigationService.topLevelRoutes; $scope.routesFromCategory = navigationService.routesFromCategory; $scope.displayName = cultureService.displayName; $scope.buildLink = navigationService.buildLink; if (_config.brand) { $scope.brandColor = _config.brand.backgroundColor ? _config.brand.backgroundColor : undefined; } $scope.activeRoutePath = function () { return $location.path(); }; $scope.localizeCategory = function (categoryName) { var lastPartIndex = categoryName.lastIndexOf('.'); if (lastPartIndex !== -1) { return cultureService.localize('application.viewcategory.' + categoryName, undefined, null) || cultureService.localize('application.viewcategory.' + categoryName.substring(lastPartIndex + 1)); } else { return cultureService.localize('application.viewcategory.' + categoryName); } }; $scope.toggleTree = function (tree) { if ($scope.isOpened(tree.categoryName)) { openedCategories.splice(openedCategories.indexOf(tree.categoryName), 1); } else { openedCategories.push(tree.categoryName); } }; $scope.isOpened = function (categoryName) { return includes(openedCategories, categoryName); }; $scope.routeSortKey = function (route) { return route.sortKey || route.path; }; }]); w20BusinessTheme.run(['$rootScope', 'EventService', 'DisplayService', 'MenuService', 'CultureService', function ($rootScope, eventService, displayService, menuService, cultureService) { $rootScope.$on('$routeChangeSuccess', function (event, routeInfo) { if (routeInfo && routeInfo.$$route) { switch (routeInfo.$$route.navigation) { case 'none': showSidebar = false; showTopbar = false; break; case 'sidebar': showSidebar = true; showTopbar = false; break; case 'topbar': showSidebar = false; showTopbar = true; break; case 'full': /* falls through */ default: break; } displayService.computeContentShift(); } }); if (!_config.hideSecurity) { if (!_config.profileChooser) { menuService.addAction('login', 'w20-login', { sortKey: 100 }); } else { menuService.addAction('profile', 'w20-profile', { sortKey: 100 }); } } if (!_config.hideConnectivity) { menuService.addAction('connectivity', 'w20-connectivity', { sortKey: 200 }); } if (!_config.hideCulture) { menuService.addAction('culture', 'w20-culture', { sortKey: 300 }); } _.each(_config.links, function (link, idx) { if (idx < 10) { menuService.addAction('link-' + idx, 'w20-link', _.extend(link, { sortKey: 400 + idx })); } }); if (!_config.hideSecurity && !_config.profileChooser) { menuService.addAction('logout', 'w20-logout', { sortKey: 1000 }); } menuService.addSection('views', 'w20-views', { templateUrl: '{w20-business-theme}/templates/sidebar-views.html' }); eventService.on('w20.security.authenticated', function () { displayService.computeContentShift(); }); eventService.on('w20.security.deauthenticated', function () { displayService.computeContentShift(); }); eventService.on('w20.security.refreshed', function () { displayService.computeContentShift(); }); }]); return { angularModules: ['w20BusinessTheme'], lifecycle: { pre: function (modules, fragments, callback) { angular.element('body').addClass('w20-top-shift-padding w20-right-shift-padding w20-bottom-shift-padding w20-left-shift-padding'); callback(module); } } }; });
seedstack/w20-business-theme
modules/main.js
JavaScript
mpl-2.0
11,739
package aws import ( "fmt" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) func TestAccDataSourceAwsSubnet_basic(t *testing.T) { rInt := acctest.RandIntRange(0, 256) cidr := fmt.Sprintf("172.%d.123.0/24", rInt) tag := "tf-acc-subnet-data-source" snResourceName := "aws_subnet.test" vpcResourceName := "aws_vpc.test" ds1ResourceName := "data.aws_subnet.by_id" ds2ResourceName := "data.aws_subnet.by_cidr" ds3ResourceName := "data.aws_subnet.by_tag" ds4ResourceName := "data.aws_subnet.by_vpc" ds5ResourceName := "data.aws_subnet.by_filter" ds6ResourceName := "data.aws_subnet.by_az_id" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckVpcDestroy, Steps: []resource.TestStep{ { Config: testAccDataSourceAwsSubnetConfig(rInt), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(ds1ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds1ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds1ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds1ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds1ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds1ResourceName, "outpost_arn", snResourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(ds2ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds2ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds2ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds2ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds2ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds2ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds2ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds2ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds2ResourceName, "outpost_arn", snResourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(ds3ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds3ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds3ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds3ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds3ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds3ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds3ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds3ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds3ResourceName, "outpost_arn", snResourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(ds4ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds4ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds4ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds4ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds4ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds4ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds4ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds4ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds4ResourceName, "outpost_arn", snResourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(ds5ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds5ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds5ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds5ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds5ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds5ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds5ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds5ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds5ResourceName, "outpost_arn", snResourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(ds6ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds6ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds6ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds6ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds6ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds6ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds6ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds6ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds6ResourceName, "outpost_arn", snResourceName, "outpost_arn"), ), }, }, }) } func TestAccDataSourceAwsSubnet_ipv6ByIpv6Filter(t *testing.T) { rInt := acctest.RandIntRange(0, 256) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { Config: testAccDataSourceAwsSubnetConfigIpv6(rInt), }, { Config: testAccDataSourceAwsSubnetConfigIpv6WithDataSourceFilter(rInt), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block_association_id"), resource.TestCheckResourceAttrSet("data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block"), ), }, }, }) } func TestAccDataSourceAwsSubnet_ipv6ByIpv6CidrBlock(t *testing.T) { rInt := acctest.RandIntRange(0, 256) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { Config: testAccDataSourceAwsSubnetConfigIpv6(rInt), }, { Config: testAccDataSourceAwsSubnetConfigIpv6WithDataSourceIpv6CidrBlock(rInt), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block_association_id"), ), }, }, }) } func testAccDataSourceAwsSubnetConfig(rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } resource "aws_vpc" "test" { cidr_block = "172.%d.0.0/16" tags = { Name = "terraform-testacc-subnet-data-source" } } resource "aws_subnet" "test" { vpc_id = "${aws_vpc.test.id}" cidr_block = "172.%d.123.0/24" availability_zone = "${data.aws_availability_zones.available.names[0]}" tags = { Name = "tf-acc-subnet-data-source" } } data "aws_subnet" "by_id" { id = "${aws_subnet.test.id}" } data "aws_subnet" "by_cidr" { vpc_id = "${aws_subnet.test.vpc_id}" cidr_block = "${aws_subnet.test.cidr_block}" } data "aws_subnet" "by_tag" { vpc_id = "${aws_subnet.test.vpc_id}" tags = { Name = "${aws_subnet.test.tags["Name"]}" } } data "aws_subnet" "by_vpc" { vpc_id = "${aws_subnet.test.vpc_id}" } data "aws_subnet" "by_filter" { filter { name = "vpc-id" values = ["${aws_subnet.test.vpc_id}"] } } data "aws_subnet" "by_az_id" { vpc_id = "${aws_subnet.test.vpc_id}" availability_zone_id = "${aws_subnet.test.availability_zone_id}" } `, rInt, rInt) } func testAccDataSourceAwsSubnetConfigIpv6(rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } resource "aws_vpc" "test" { cidr_block = "172.%d.0.0/16" assign_generated_ipv6_cidr_block = true tags = { Name = "terraform-testacc-subnet-data-source-ipv6" } } resource "aws_subnet" "test" { vpc_id = "${aws_vpc.test.id}" cidr_block = "172.%d.123.0/24" availability_zone = "${data.aws_availability_zones.available.names[0]}" ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}" tags = { Name = "tf-acc-subnet-data-source-ipv6" } } `, rInt, rInt) } func testAccDataSourceAwsSubnetConfigIpv6WithDataSourceFilter(rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } resource "aws_vpc" "test" { cidr_block = "172.%d.0.0/16" assign_generated_ipv6_cidr_block = true tags = { Name = "terraform-testacc-subnet-data-source-ipv6-with-ds-filter" } } resource "aws_subnet" "test" { vpc_id = "${aws_vpc.test.id}" cidr_block = "172.%d.123.0/24" availability_zone = "${data.aws_availability_zones.available.names[0]}" ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}" tags = { Name = "tf-acc-subnet-data-source-ipv6-with-ds-filter" } } data "aws_subnet" "by_ipv6_cidr" { filter { name = "ipv6-cidr-block-association.ipv6-cidr-block" values = ["${aws_subnet.test.ipv6_cidr_block}"] } } `, rInt, rInt) } func testAccDataSourceAwsSubnetConfigIpv6WithDataSourceIpv6CidrBlock(rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } resource "aws_vpc" "test" { cidr_block = "172.%d.0.0/16" assign_generated_ipv6_cidr_block = true tags = { Name = "terraform-testacc-subnet-data-source-ipv6-cidr-block" } } resource "aws_subnet" "test" { vpc_id = "${aws_vpc.test.id}" cidr_block = "172.%d.123.0/24" availability_zone = "${data.aws_availability_zones.available.names[0]}" ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}" tags = { Name = "tf-acc-subnet-data-source-ipv6-cidr-block" } } data "aws_subnet" "by_ipv6_cidr" { ipv6_cidr_block = "${aws_subnet.test.ipv6_cidr_block}" } `, rInt, rInt) }
kjmkznr/terraform-provider-aws
aws/data_source_aws_subnet_test.go
GO
mpl-2.0
11,340
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; const { Cu } = require('chrome'); const sp = require('sdk/simple-prefs'); const app = require('sdk/system/xul-app'); const { id, preferencesBranch } = require('sdk/self'); const { open } = require('sdk/preferences/utils'); const { getTabForId } = require('sdk/tabs/utils'); const { modelFor } = require('sdk/model/core'); const { getAddonByID } = require('sdk/addon/manager'); const { AddonManager } = Cu.import('resource://gre/modules/AddonManager.jsm', {}); require('sdk/tabs'); exports.testDefaultValues = function (assert) { assert.equal(sp.prefs.myHiddenInt, 5, 'myHiddenInt default is 5'); assert.equal(sp.prefs.myInteger, 8, 'myInteger default is 8'); assert.equal(sp.prefs.somePreference, 'TEST', 'somePreference default is correct'); } exports.testOptionsType = function*(assert) { let addon = yield getAddonByID(id); assert.equal(addon.optionsType, AddonManager.OPTIONS_TYPE_INLINE, 'options type is inline'); } exports.testButton = function(assert, done) { open({ id: id }).then(({ tabId, document }) => { let tab = modelFor(getTabForId(tabId)); sp.once('sayHello', _ => { assert.pass('The button was pressed!'); tab.close(done); }); tab.attach({ contentScript: 'unsafeWindow.document.querySelector("button[label=\'Click me!\']").click();' }); }); } if (app.is('Firefox')) { exports.testAOM = function(assert, done) { open({ id: id }).then(({ tabId }) => { let tab = modelFor(getTabForId(tabId)); assert.pass('the add-on prefs page was opened.'); tab.attach({ contentScriptWhen: "end", contentScript: 'self.postMessage({\n' + 'someCount: unsafeWindow.document.querySelectorAll("setting[title=\'some-title\']").length,\n' + 'somePreference: getAttributes(unsafeWindow.document.querySelector("setting[title=\'some-title\']")),\n' + 'myInteger: getAttributes(unsafeWindow.document.querySelector("setting[title=\'my-int\']")),\n' + 'myHiddenInt: getAttributes(unsafeWindow.document.querySelector("setting[title=\'hidden-int\']")),\n' + 'sayHello: getAttributes(unsafeWindow.document.querySelector("button[label=\'Click me!\']"))\n' + '});\n' + 'function getAttributes(ele) {\n' + 'if (!ele) return {};\n' + 'return {\n' + 'pref: ele.getAttribute("pref"),\n' + 'type: ele.getAttribute("type"),\n' + 'title: ele.getAttribute("title"),\n' + 'desc: ele.getAttribute("desc"),\n' + '"data-jetpack-id": ele.getAttribute(\'data-jetpack-id\')\n' + '}\n' + '}\n', onMessage: msg => { // test against doc caching assert.equal(msg.someCount, 1, 'there is exactly one <setting> node for somePreference'); // test somePreference assert.equal(msg.somePreference.type, 'string', 'some pref is a string'); assert.equal(msg.somePreference.pref, 'extensions.' + id + '.somePreference', 'somePreference path is correct'); assert.equal(msg.somePreference.title, 'some-title', 'somePreference title is correct'); assert.equal(msg.somePreference.desc, 'Some short description for the preference', 'somePreference description is correct'); assert.equal(msg.somePreference['data-jetpack-id'], id, 'data-jetpack-id attribute value is correct'); // test myInteger assert.equal(msg.myInteger.type, 'integer', 'myInteger is a int'); assert.equal(msg.myInteger.pref, 'extensions.' + id + '.myInteger', 'extensions.test-simple-prefs.myInteger'); assert.equal(msg.myInteger.title, 'my-int', 'myInteger title is correct'); assert.equal(msg.myInteger.desc, 'How many of them we have.', 'myInteger desc is correct'); assert.equal(msg.myInteger['data-jetpack-id'], id, 'data-jetpack-id attribute value is correct'); // test myHiddenInt assert.equal(msg.myHiddenInt.type, undefined, 'myHiddenInt was not displayed'); assert.equal(msg.myHiddenInt.pref, undefined, 'myHiddenInt was not displayed'); assert.equal(msg.myHiddenInt.title, undefined, 'myHiddenInt was not displayed'); assert.equal(msg.myHiddenInt.desc, undefined, 'myHiddenInt was not displayed'); // test sayHello assert.equal(msg.sayHello['data-jetpack-id'], id, 'data-jetpack-id attribute value is correct'); tab.close(done); } }); }) } // run it again, to test against inline options document caching // and duplication of <setting> nodes upon re-entry to about:addons exports.testAgainstDocCaching = exports.testAOM; } exports.testDefaultPreferencesBranch = function(assert) { assert.equal(preferencesBranch, id, 'preferencesBranch default the same as self.id'); } require('sdk/test/runner').runTestsFromModule(module);
Yukarumya/Yukarum-Redfoxes
addon-sdk/source/test/addons/simple-prefs/lib/main.js
JavaScript
mpl-2.0
5,341
#ifndef RBX_GC_IMMIX_HPP #define RBX_GC_IMMIX_HPP #include "memory/address.hpp" #include "memory/immix_region.hpp" #include "memory/gc.hpp" #include "exception.hpp" #include "object_position.hpp" namespace rubinius { class Memory; namespace memory { class ImmixGC; class ImmixMarker; /** * ImmixGC uses the immix memory management strategy to perform garbage * collection on the mature objects in the immix space. */ class ImmixGC : public GarbageCollector { public: class Diagnostics : public diagnostics::MemoryDiagnostics { public: int64_t collections_; int64_t total_bytes_; int64_t chunks_; int64_t holes_; double percentage_; Diagnostics(); void update(); }; private: /** * Class used as an interface to the Rubinius specific object memory layout * by the (general purpose) Immix memory manager. By imposing this interface * between Memory and the utility Immix memory manager, the latter can * be made reusable. * * The Immix memory manager delegates to this class to: * - determine the size of an object at a particular memory address * - copy an object * - return the forwarding pointer for an object * - set the forwarding pointer for an object that it moves * - mark an address as visited * - determine if an object is pinned and cannot be moved * - walk all root pointers * * It will also notify this class when: * - it adds chunks * - allocates from the last free block, indicating a collection is needed */ class ObjectDescriber { Memory* memory_; ImmixGC* gc_; public: ObjectDescriber() : memory_(0) , gc_(NULL) {} void set_object_memory(Memory* om, ImmixGC* gc) { memory_ = om; gc_ = gc; } void added_chunk(int count); void last_block() { } void set_forwarding_pointer(Address from, Address to); Address forwarding_pointer(Address cur) { Object* obj = cur.as<Object>(); if(obj->forwarded_p()) return obj->forward(); return Address::null(); } bool pinned(Address addr) { return addr.as<Object>()->pinned_p(); } Address copy(Address original, ImmixAllocator& alloc); void walk_pointers(Address addr, Marker<ObjectDescriber>& mark) { Object* obj = addr.as<Object>(); if(obj) gc_->scan_object(obj); } Address update_pointer(Address addr); int size(Address addr); /** * Called when the GC object wishes to mark an object. * * @returns true if the object is not already marked, and in the Immix * space; otherwise false. */ bool mark_address(Address addr, MarkStack& ms, bool push = true); }; GC<ObjectDescriber> gc_; ExpandingAllocator allocator_; Memory* memory_; ImmixMarker* marker_; int chunks_left_; int chunks_before_collection_; Diagnostics* diagnostics_; public: ImmixGC(Memory* om); virtual ~ImmixGC(); Object* allocate(size_t bytes, bool& collect_now); Object* move_object(Object* orig, size_t bytes, bool& collect_now); virtual Object* saw_object(Object*); virtual void scanned_object(Object*); virtual bool mature_gc_in_progress(); void collect(GCData* data); void collect_start(GCData* data); void collect_finish(GCData* data); void sweep(); void walk_finalizers(); ObjectPosition validate_object(Object*); public: // Inline Memory* memory() { return memory_; } size_t& bytes_allocated() { return gc_.bytes_allocated(); } int dec_chunks_left() { return --chunks_left_; } void reset_chunks_left() { chunks_left_ = chunks_before_collection_; } Diagnostics* diagnostics() { return diagnostics_; } void start_marker(STATE, GCData* data); bool process_mark_stack(); bool process_mark_stack(bool& exit); MarkStack& mark_stack(); private: void collect_scan(GCData* data); }; } } #endif
jsyeo/rubinius
machine/memory/immix_collector.hpp
C++
mpl-2.0
4,136
/* * Copyright (c) 2012-2016 Arne Schwabe * Distributed under the GNU GPL v2 with additional terms. For full terms see the file doc/LICENSE.txt */ package de.blinkt.openvpn.api; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import java.util.HashSet; import java.util.Set; public class ExternalAppDatabase { private final String PREFERENCES_KEY = "PREFERENCES_KEY"; Context mContext; public ExternalAppDatabase(Context c) { mContext = c; } boolean isAllowed(String packagename) { Set<String> allowedapps = getExtAppList(); return allowedapps.contains(packagename); } public Set<String> getExtAppList() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); return prefs.getStringSet(PREFERENCES_KEY, new HashSet<String>()); } void addApp(String packagename) { Set<String> allowedapps = getExtAppList(); allowedapps.add(packagename); saveExtAppList(allowedapps); } private void saveExtAppList(Set<String> allowedapps) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); Editor prefedit = prefs.edit(); prefedit.putStringSet(PREFERENCES_KEY, allowedapps); prefedit.apply(); } public void clearAllApiApps() { saveExtAppList(new HashSet<String>()); } public void removeApp(String packagename) { Set<String> allowedapps = getExtAppList(); allowedapps.remove(packagename); saveExtAppList(allowedapps); } }
yonadev/yona-app-android
openvpn/src/main/java/de/blinkt/openvpn/api/ExternalAppDatabase.java
Java
mpl-2.0
1,694
set :base_url, "https://www.consul.io/" activate :hashicorp do |h| h.name = "consul" h.version = "1.4.0" h.github_slug = "hashicorp/consul" end helpers do # Returns a segment tracking ID such that local development is not # tracked to production systems. def segmentId() if (ENV['ENV'] == 'production') 'IyzLrqXkox5KJ8XL4fo8vTYNGfiKlTCm' else '0EXTgkNx0Ydje2PGXVbRhpKKoe5wtzcE' end end # Returns the FQDN of the image URL. # # @param [String] path # # @return [String] def image_url(path) File.join(base_url, image_path(path)) end # Get the title for the page. # # @param [Middleman::Page] page # # @return [String] def title_for(page) if page && page.data.page_title return "#{page.data.page_title} - Consul by HashiCorp" end "Consul by HashiCorp" end # Get the description for the page # # @param [Middleman::Page] page # # @return [String] def description_for(page) description = (page.data.description || "Consul by HashiCorp") .gsub('"', '') .gsub(/\n+/, ' ') .squeeze(' ') return escape_html(description) end # This helps by setting the "active" class for sidebar nav elements # if the YAML frontmatter matches the expected value. def sidebar_current(expected) current = current_page.data.sidebar_current || "" if current.start_with?(expected) return " class=\"active\"" else return "" end end # Returns the id for this page. # @return [String] def body_id_for(page) if !(name = page.data.sidebar_current).blank? return "page-#{name.strip}" end if page.url == "/" || page.url == "/index.html" return "page-home" end if !(title = page.data.page_title).blank? return title .downcase .gsub('"', '') .gsub(/[^\w]+/, '-') .gsub(/_+/, '-') .squeeze('-') .squeeze(' ') end return "" end # Returns the list of classes for this page. # @return [String] def body_classes_for(page) classes = [] if !(layout = page.data.layout).blank? classes << "layout-#{page.data.layout}" end if !(title = page.data.page_title).blank? title = title .downcase .gsub('"', '') .gsub(/[^\w]+/, '-') .gsub(/_+/, '-') .squeeze('-') .squeeze(' ') classes << "page-#{title}" end return classes.join(" ") end end
youhong316/consul
website/config.rb
Ruby
mpl-2.0
2,474
// ---------------------------------------------------------------------------- // // *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** // // ---------------------------------------------------------------------------- // // This file is automatically generated by Magic Modules and manual // changes will be clobbered when the file is regenerated. // // Please read more about how to change this file in // .github/CONTRIBUTING.md. // // ---------------------------------------------------------------------------- package google import ( "context" "log" "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) func init() { resource.AddTestSweepers("ComputeInstanceGroupNamedPort", &resource.Sweeper{ Name: "ComputeInstanceGroupNamedPort", F: testSweepComputeInstanceGroupNamedPort, }) } // At the time of writing, the CI only passes us-central1 as the region func testSweepComputeInstanceGroupNamedPort(region string) error { resourceName := "ComputeInstanceGroupNamedPort" log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName) config, err := sharedConfigForRegion(region) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err) return err } err = config.LoadAndValidate(context.Background()) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err) return err } t := &testing.T{} billingId := getTestBillingAccountFromEnv(t) // Setup variables to replace in list template d := &ResourceDataMock{ FieldsInSchema: map[string]interface{}{ "project": config.Project, "region": region, "location": region, "zone": "-", "billing_account": billingId, }, } listTemplate := strings.Split("https://www.googleapis.com/compute/v1/projects/{{project}}/aggregated/instanceGroups/{{group}}", "?")[0] listUrl, err := replaceVars(d, config, listTemplate) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err) return nil } res, err := sendRequest(config, "GET", config.Project, listUrl, nil) if err != nil { log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) return nil } resourceList, ok := res["namedPorts"] if !ok { log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.") return nil } var rl []interface{} zones := resourceList.(map[string]interface{}) // Loop through every zone in the list response for _, zonesValue := range zones { zone := zonesValue.(map[string]interface{}) for k, v := range zone { // Zone map either has resources or a warning stating there were no resources found in the zone if k != "warning" { resourcesInZone := v.([]interface{}) rl = append(rl, resourcesInZone...) } } } log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName) // Keep count of items that aren't sweepable for logging. nonPrefixCount := 0 for _, ri := range rl { obj := ri.(map[string]interface{}) if obj["name"] == nil { log.Printf("[INFO][SWEEPER_LOG] %s resource name was nil", resourceName) return nil } name := GetResourceNameFromSelfLink(obj["name"].(string)) // Skip resources that shouldn't be sweeped if !isSweepableTestResource(name) { nonPrefixCount++ continue } deleteTemplate := "https://www.googleapis.com/compute/v1/projects/{{project}}/zones/{{zone}}/instanceGroups/{{group}}/setNamedPorts" if obj["zone"] == nil { log.Printf("[INFO][SWEEPER_LOG] %s resource zone was nil", resourceName) return nil } zone := GetResourceNameFromSelfLink(obj["zone"].(string)) deleteTemplate = strings.Replace(deleteTemplate, "{{zone}}", zone, -1) deleteUrl, err := replaceVars(d, config, deleteTemplate) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err) return nil } deleteUrl = deleteUrl + name // Don't wait on operations as we may have a lot to delete _, err = sendRequest(config, "DELETE", config.Project, deleteUrl, nil) if err != nil { log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err) } else { log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name) } } if nonPrefixCount > 0 { log.Printf("[INFO][SWEEPER_LOG] %d items were non-sweepable and skipped.", nonPrefixCount) } return nil }
terraform-providers/terraform-provider-google
google/resource_compute_instance_group_named_port_sweeper_test.go
GO
mpl-2.0
4,472
/* * <?xml version="1.0" encoding="utf-8"?><!-- * ~ Copyright (c) 2018 Stichting Yona Foundation * ~ * ~ This Source Code Form is subject to the terms of the Mozilla Public * ~ License, v. 2.0. If a copy of the MPL was not distributed with this * ~ file, You can obtain one at https://mozilla.org/MPL/2.0/. * --> */ package nu.yona.app.enums; public enum UserStatus { ACTIVE, NUMBER_NOT_CONFIRMED, NOT_REGISTERED, BLOCKED }
yonadev/yona-app-android
app/src/main/java/nu/yona/app/enums/UserStatus.java
Java
mpl-2.0
448
function (user, context, callback) { // dictionary of applications and their related mozillians groups to worry about const applicationGroupMapping = { 'EnEylt4OZW6i7yCWzZmCxyCxDRp6lOY0': 'mozilliansorg_ghe_saml-test-integrations_users', }; const fetch = require('node-fetch@2.6.0'); const AUTH0_TIMEOUT = 5000; // milliseconds const PERSONAPI_BEARER_TOKEN_REFRESH_AGE = 64770; // 18 hours - 30 seconds for refresh timeout allowance const PERSONAPI_TIMEOUT = 5000; // milliseconds const USER_ID = context.primaryUser || user.user_id; const getBearerToken = async () => { // if we have the bearer token stored, we don't need to fetch it again if (global.personapi_bearer_token && global.personapi_bearer_token_creation_time && Date.now() - global.personapi_bearer_token_creation_time < PERSONAPI_BEARER_TOKEN_REFRESH_AGE) { return global.personapi_bearer_token; } const options = { method: 'POST', headers: { 'Content-Type': 'application/json', }, timeout: AUTH0_TIMEOUT, body: JSON.stringify({ audience: configuration.personapi_audience, client_id: configuration.personapi_read_profile_api_client_id, client_secret: configuration.personapi_read_profile_api_secret, grant_type: 'client_credentials', }) }; try { //console.log(configuration.personapi_oauth_url); const response = await fetch(configuration.personapi_oauth_url, options); const data = await response.json(); // store the bearer token in the global object, so it's not constantly retrieved global.personapi_bearer_token = data.access_token; global.personapi_bearer_token_creation_time = Date.now(); console.log(`Successfully retrieved bearer token from Auth0`); return global.personapi_bearer_token; } catch (error) { throw Error(`Unable to retrieve bearer token from Auth0: ${error.message}`); } }; const getPersonProfile = async () => { // Retrieve a bearer token to gain access to the person api // return the profile data const bearer = await getBearerToken(); const options = { method: 'GET', headers: { 'Authorization': `Bearer ${bearer}`, }, timeout: PERSONAPI_TIMEOUT, }; const url = `${configuration.personapi_url}/v2/user/user_id/${encodeURI(USER_ID)}`; //console.log(`Fetching person profile of ${USER_ID}`); //console.log("url is " + url); const response = await fetch(url, options); return await response.json(); }; // We only care about SSO applications that exist in the applicationGroupMapping // If the SSO ID is undefined in applicationGroupMapping, skip processing and return callback() if(applicationGroupMapping[context.clientID] !== undefined) { getPersonProfile().then(profile => { let githubUsername = null; // Get githubUsername from person api, otherwise we'll redirect try { githubUsername = profile.usernames.values['HACK#GITHUB']; // Explicitely setting githubUsername to null if undefined if(githubUsername === undefined) { githubUsername = null; } // If somehow dinopark allows a user to store an empty value // Let's set to null to be redirected later if(githubUsername.length === 0) { console.log("empty HACK#GITHUB"); githubUsername = null; } //console.log("githubUsername: " + githubUsername); } catch (e) { // Unable to do the githubUsername lookup } // Confirm the user has the group defined from mozillians matching the application id // confirm the user has a githubUsername stored in mozillians, otherwise redirect if(!user.app_metadata.groups.includes(applicationGroupMapping[context.clientID]) || githubUsername === null) { context.redirect = { url: configuration.github_enterprise_wiki_url }; } return callback(null, user, context); }); // Nothing matched, return callback() and proceed rules processing } else { return callback(null, user, context); } }
mozilla-iam/auth0-deploy
rules/GHE-Groups.js
JavaScript
mpl-2.0
4,302
#include <cllogger.h> #include <stdarg.h> #ifdef CC_PF_WIN32 # include <process.h> #endif cl::ClLogger::ClLogger() : m_write_interval(CL_INIT_WRITE_INTERVAL), m_check_interval(CL_INIT_CHECK_INTERVAL), m_stop_times(CL_INIT_STOP_TIMES), m_stop_count(CL_INIT_STOP_COUNT), m_write_flag(false), m_check_flag(false), m_msg_queue() { m_msg_queue.init(); } cl::ClLogger::ClLogger(size_t queue_size, int queue_waits) : m_write_interval(CL_INIT_WRITE_INTERVAL), m_check_interval(CL_INIT_CHECK_INTERVAL), m_stop_times(CL_INIT_STOP_TIMES), m_stop_count(CL_INIT_STOP_COUNT), m_write_flag(false), m_check_flag(false), m_msg_queue(queue_size, queue_waits) { m_msg_queue.init(); } bool cl::ClLogger::start() { bool ret = false; if (__start()) { for(std::vector<ClInfoPtr>::iterator it = m_infos_reg.begin(); it != m_infos_reg.end();it ++){ cl::ClInfoPtr& cip = *it; ret = ret && cip->startWork(); } } return ret; } void cl::ClLogger::stop() { cc::microSleep(m_stop_times); m_write_flag = m_check_flag = false; #if __cplusplus >= 201103L m_write_thr.detach(); m_check_thr.join(); #else # if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32) pthread_detach(m_write_thr); pthread_join(m_check_thr, 0); # elif (defined CC_PF_WIN32) static const int S_WAIT_FOR = 5000; if (WAIT_TIMEOUT == WaitForSingleObject(m_check_thr, S_WAIT_FOR)){ TerminateThread(m_check_thr, 1); } # endif #endif } bool cl::ClLogger::start(const size_t &id) { if(id == 0 || id > m_infos_reg.size()){ return false; } if(__start()){ return m_infos_reg[id]->startWork(); }else{ return false; } } bool cl::ClLogger::start(const string &name) { ClInfoPtr curr_info = m_infos_reg[name]; if(curr_info == nullptr){ return false; } if(__start()){ return curr_info->startWork(); }else{ return false; } } void cl::ClLogger::stop(const size_t &id) { if(id == 0 || id > m_infos_reg.size()){ return; } if(m_write_flag && m_check_flag){ m_infos_reg[id]->stopWork(); } } void cl::ClLogger::stop(const string &name) { ClInfoPtr curr_info = m_infos_reg[name]; if(curr_info == nullptr){ return; } if(m_write_flag && m_check_flag){ curr_info->stopWork(); } } size_t cl::ClLogger::registerLogInfo(const cl::ClInfoPtr &clinfo) { return m_infos_reg.registerInfo(clinfo); } size_t cl::ClLogger::registerLogInfo(const string &name) { ClInfoPtr clinfo = new ClInfo(name); return m_infos_reg.registerInfo(clinfo); } size_t cl::ClLogger::registerLogInfo(const string &name, const string &prefix, const string &postfix) { ClInfoPtr clinfo = new ClInfo(name); clinfo->m_prefix = prefix; clinfo->m_postfix = postfix; return m_infos_reg.registerInfo(clinfo); } size_t cl::ClLogger::registerLogInfo(const string &name, const string &path, const string &feed, const cl::log_mode_t &mode) { ClInfoPtr clinfo = new ClInfo(name, path, feed, mode); return m_infos_reg.registerInfo(clinfo); } size_t cl::ClLogger::registerLogInfo(const string &name, const string &prefix, const string &postfix, const string &path, const string &feed, const cl::log_mode_t &mode) { ClInfoPtr clinfo = new ClInfo(name, path, feed, mode); clinfo->m_prefix = prefix; clinfo->m_postfix = postfix; return m_infos_reg.registerInfo(clinfo); } bool cl::ClLogger::writef(const size_t &id, const char *format, ...) { static const size_t S_BUFF_SIZE = 4096; if(id == 0 || id > m_infos_reg.size()){ return false; } if(!m_infos_reg[id]->isWork()){ return false; } va_list argslist; char buff[S_BUFF_SIZE]; int ret = 0; va_start(argslist, format); #if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32) ret = std::vsnprintf(buff, S_BUFF_SIZE, format, argslist); #elif (defined CC_PF_WIN32) ret = _vsnprintf_s(buff, S_BUFF_SIZE, format, argslist); #endif va_end(argslist); if(ret <= 0){ return false; } ClMessage message(id, string(buff, ret)); m_msg_queue.push(message); return true; } bool cl::ClLogger::writef(const string &name, const char *format, ...) { static const size_t S_BUFF_SIZE = 4096; size_t id = m_infos_reg.getLogId(name); if(id == 0 || !m_infos_reg[id]->isWork()){ return false; } va_list argslist; char buff[S_BUFF_SIZE]; int ret = 0; va_start(argslist, format); #if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32) ret = std::vsnprintf(buff, S_BUFF_SIZE, format, argslist); #elif (defined CC_PF_WIN32) ret = _vsnprintf_s(buff, S_BUFF_SIZE, format, argslist); #endif va_end(argslist); if(ret <= 0){ return false; } ClMessage message(id, string(buff, ret)); m_msg_queue.push(message); return true; } bool cl::ClLogger::write(const size_t &id, const string &msg) { if(id == 0 || id > m_infos_reg.size()){ return false; } if(!m_infos_reg[id]->isWork()){ return false; } ClMessage message(id, msg); m_msg_queue.push(message); return true; } bool cl::ClLogger::write(const string &name, const string &msg) { size_t id = m_infos_reg.getLogId(name); if(id == 0 || !m_infos_reg[id]->isWork()){ return false; } ClMessage message(id, msg); m_msg_queue.push(message); return true; } bool cl::ClLogger::__start() { if(m_write_flag && m_check_flag){ return true; } if(!m_write_flag){ m_write_flag = true; if(!__startThread(m_write_thr, cl::ClLogger::s_write, static_cast<cc::thread_para_t>(this))){ m_write_flag = false; return false; } } if(!m_check_flag){ m_check_flag = true; if(!__startThread(m_check_thr, cl::ClLogger::s_check, static_cast<cc::thread_para_t>(this))){ m_check_flag = false; return false; } } return true; } bool cl::ClLogger::__startThread(cc::thread_t &thread, cc::thread_func *pfunc, cc::thread_para_t para) { #if __cplusplus >= 201103L cc::thread_t thr(pfunc, para); thread.swap(thr); #else # if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32) int ret = pthread_create(&thread, 0, pfunc, para); if(ret != 0){ return false; } # elif (defined CC_PF_WIN32) thread = (cc::thread_t)_beginthreadex(0, 0, pfunc, para, 0, 0); # endif #endif return true; } cc::thread_ret_t CC_THREAD cl::ClLogger::s_write(cc::thread_para_t para) { cl::ClLogger* logger = static_cast<cl::ClLogger*>(para); cc::SeqQueue<cl::ClMessage>& msgqueue = logger->m_msg_queue; cl::ClInfoRegistry& registry = logger->m_infos_reg; cl::ClMessage message; bool& is_write = logger->m_write_flag; int& sleep_tm = logger->m_write_interval; int quit_wait = logger->m_stop_count; for(;is_write || quit_wait;is_write ? quit_wait : quit_wait --){ msgqueue.pop(message); ClInfoPtr curr_info = registry[message.m_id]; curr_info->write(message.m_msg); message.reset(); cc::microSleep(sleep_tm); } return static_cast<cc::thread_ret_t>(0); } cc::thread_ret_t CC_THREAD cl::ClLogger::s_check(cc::thread_para_t para) { cl::ClLogger* logger = static_cast<cl::ClLogger*>(para); cl::ClInfoRegistry& registry = logger->m_infos_reg; bool& is_check = logger->m_check_flag; int& sleep_tm = logger->m_check_interval; int quit_wait = logger->m_stop_count; for(;is_check || quit_wait;is_check ? quit_wait : quit_wait --){ for(std::vector<ClInfoPtr>::iterator it = registry.begin(); it != registry.end();it ++){ cl::ClInfoPtr& cip = *it; if(cip && cip->isWork()){ cip->check(); } } cc::microSleep(sleep_tm); } return static_cast<cc::thread_ret_t>(0); }
araraloren/FunctionFind
cpplogger/cllogger.cpp
C++
mpl-2.0
8,085
var toolURL = { 'application/x-popcorn': 'https://popcorn.webmaker.org', 'application/x-thimble': 'https://thimble.webmaker.org', 'application/x-x-ray-goggles': 'https://goggles.mozilla.org' }; module.exports = function (options) { var moment = require('moment'); var MakeClient = require('makeapi-client'); function generateGravatar(hash) { var DEFAULT_AVATAR = 'https%3A%2F%2Fstuff.webmaker.org%2Favatars%2Fwebmaker-avatar-44x44.png', DEFAULT_SIZE = 44; return 'https://secure.gravatar.com/avatar/' + hash + '?s=' + DEFAULT_SIZE + '&d=' + DEFAULT_AVATAR; } // Create a make client with or without auth function createMakeClient(url, hawk) { var options = { apiURL: url }; if (hawk) { options.hawk = hawk; } var makeClient = new MakeClient(options); // Moment.js default language is 'en'. This function will override // the default language globally on the coming request for the homepage makeClient.setLang = function (lang) { moment.lang(lang); }; // Given a prefix for an app tag (e.g. "webmaker:p-") sort an array of makes based on that tag // The tag must be of the format "prefix-1", "prefix-2", etc. makeClient.sortByPriority = function (prefix, data) { var sortedData = [], duplicates = [], priorityIndex, regex = new RegExp('^' + prefix + '(\\d+)$'); function extractStickyPriority(tags) { var res; for (var i = tags.length - 1; i >= 0; i--) { res = regex.exec(tags[i]); if (res) { return +res[1]; } } } for (var i = 0; i < data.length; i++) { priorityIndex = extractStickyPriority(data[i].appTags); data[i].index = priorityIndex; if (sortedData[priorityIndex - 1]) { duplicates.push('Duplicate found for ' + prefix + priorityIndex); } else { sortedData[priorityIndex - 1] = data[i]; } } return { results: sortedData, errors: duplicates }; }; makeClient.process = function (callback, id) { makeClient.then(function (err, data, totalHits) { if (err) { return callback(err); } if (!Array.isArray(data)) { return callback('There was no data returned'); } data.forEach(function (make) { // Set the tool make.tool = make.contentType.replace(/application\/x\-/g, ''); make.toolurl = toolURL[make.contentType]; // Convert tags and set the "make.type" if (make.taggedWithAny(['guide'])) { make.type = 'guide'; } else if (make.taggedWithAny(['webmaker:template'])) { make.type = 'template'; } else if (make.contentType) { make.type = make.tool; } if (make.taggedWithAny(['beginner'])) { make.level = 'beginner'; } else if (make.taggedWithAny(['intermediate'])) { make.level = 'intermediate'; } else if (make.taggedWithAny(['advanced'])) { make.level = 'advanced'; } // Remove tutorial tags make.prettyTags = make.rawTags.filter(function (tag) { return !(tag.match(/^tutorial-/)); }); if (id) { make.hasBeenLiked = make.likes.some(function (like) { return like.userId === +id; }); } // Convert the created at and updated at to human time make.updatedAt = moment(make.updatedAt).fromNow(); make.createdAt = moment(make.createdAt).fromNow(); // Set the remix URL if (make.type !== 'Appmaker') { make.remixurl = make.url + '/remix'; } // Create a function for generating the avatar make.avatar = generateGravatar(make.emailHash); }); callback(err, data, totalHits); }); }; return makeClient; } module.exports = { authenticated: createMakeClient(options.authenticatedURL, options.hawk), readOnly: createMakeClient(options.readOnlyURL) }; };
mozilla/webmaker.org
lib/makeapi.js
JavaScript
mpl-2.0
4,168
#!/usr/bin/python3 from lxml import etree import sys class Word: def __init__(self): self.word = '' self.pos = '' self.props = [] def __hash__(self): return (self.word + self.pos).__hash__() def __cmp__(self, other): n = cmp(self.word, other.word) if n != 0: return n n = cmp(self.pos, other.pos) if n != 0: return n # FIXME: 이렇게 하면 순서가 다를텐데. set에서 뭐가 먼저 나올지 알고... if self.pos == '명사': return 0 for prop in other.props: if not prop in self.props: return -1 for prop in self.props: if not prop in other.props: return 1 return 0 ###################################################################### if len(sys.argv) < 1: sys.exit(1) filename = sys.argv[1] doc = etree.parse(open(filename)) root = doc.getroot() wordset = set() for item in root: w = Word() for field in item: if field.tag == 'word': w.word = field.text elif field.tag == 'pos': w.pos = field.text elif field.tag == 'props' and field.text: w.props = field.text.split(',') w.props.sort() if w in wordset: sys.stderr.write(('%s (%s)\n' % (w.word, w.pos)).encode('UTF-8')) else: wordset.add(w)
changwoo/hunspell-dict-ko
utils/findduplicates.py
Python
mpl-2.0
1,426
<?php /** * Jamroom 5 User Accounts module * * copyright 2003 - 2015 * by The Jamroom Network * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. Please see the included "license.html" file. * * This module may include works that are not developed by * The Jamroom Network * and are used under license - any licenses are included and * can be found in the "contrib" directory within this module. * * Jamroom may use modules and skins that are licensed by third party * developers, and licensed under a different license - please * reference the individual module or skin license that is included * with your installation. * * This software is provided "as is" and any express or implied * warranties, including, but not limited to, the implied warranties * of merchantability and fitness for a particular purpose are * disclaimed. In no event shall the Jamroom Network be liable for * any direct, indirect, incidental, special, exemplary or * consequential damages (including but not limited to, procurement * of substitute goods or services; loss of use, data or profits; * or business interruption) however caused and on any theory of * liability, whether in contract, strict liability, or tort * (including negligence or otherwise) arising from the use of this * software, even if advised of the possibility of such damage. * Some jurisdictions may not allow disclaimers of implied warranties * and certain statements in the above disclaimer may not apply to * you as regards implied warranties; the other terms and conditions * remain enforceable notwithstanding. In some jurisdictions it is * not permitted to limit liability and therefore such limitations * may not apply to you. * * @copyright 2012 Talldude Networks, LLC. */ // make sure we are not being called directly defined('APP_DIR') or exit(); /** * quota_config */ function jrUser_quota_config() { // Allow Signups $_tmp = array( 'name' => 'allow_signups', 'type' => 'checkbox', 'validate' => 'onoff', 'label' => 'allow signups', 'help' => 'If the &quot;Allow Signups&quot; option is <b>checked</b>, then new users signing up for your system will be able to signup directly to this Profile Quota.', 'default' => 'off', 'order' => 1 ); jrProfile_register_quota_setting('jrUser', $_tmp); // Signup Method $_als = array( 'instant' => 'Instant Validation', 'email' => 'Email Validation', 'admin' => 'Admin Validation' ); $_tmp = array( 'name' => 'signup_method', 'type' => 'select', 'options' => $_als, 'default' => 'email', 'required' => 'on', 'label' => 'signup method', 'help' => 'How should users signup for this Quota?<br><br><b>Instant Validation</b> - The new user account and profile are activated on signup.<br><b>Email Validation</b> - An activation email is sent on signup to activate the new account.', 'order' => 2 ); jrProfile_register_quota_setting('jrUser', $_tmp); // device notice $_tmp = array( 'name' => 'device_notice', 'type' => 'checkbox', 'default' => 'off', 'validate' => 'onoff', 'label' => 'new device notice', 'help' => 'If this option is checked, when a user logs in for the first time on a new device, they will be sent an email notification letting them know about the login.', 'order' => 3 ); jrProfile_register_quota_setting('jrUser', $_tmp); // Power User $_tmp = array( 'name' => 'power_user', 'type' => 'checkbox', 'validate' => 'onoff', 'label' => 'power user enabled', 'help' => 'If this option is checked, User Accounts belonging to profiles in this Quota will be Power Users that can create new profiles.', 'default' => 'off', 'section' => 'power user', 'order' => 10 ); jrProfile_register_quota_setting('jrUser', $_tmp); // Power User Profiles $_tmp = array( 'name' => 'power_user_max', 'type' => 'text', 'validate' => 'number_nz', 'label' => 'max profiles', 'help' => 'How many profiles can a Power User in this quota create?', 'default' => 2, 'section' => 'power user', 'order' => 11 ); jrProfile_register_quota_setting('jrUser', $_tmp); // Power User Quotas $_tmp = array( 'name' => 'power_user_quotas', 'type' => 'select_multiple', 'label' => 'allowed quotas', 'help' => 'When a Power User in this Quota creates a new Profile, what Quotas can they select for their new profile?', 'options' => 'jrProfile_get_quotas', 'default' => 0, 'section' => 'power user', 'order' => 12 ); jrProfile_register_quota_setting('jrUser', $_tmp); return true; }
jeffreybrayne/TheBreakContest
modules/jrUser/quota.php
PHP
mpl-2.0
5,055
/* * Copyright (C) 2019 DataSwift Ltd - All Rights Reserved * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * Written by Eleftherios Myteletsis <eleftherios.myteletsis@dataswift.io> 3, 2019 */ import { Component, OnInit } from '@angular/core'; @Component({ selector: 'rum-settings-page', templateUrl: './settings-page.component.html', styleUrls: ['./settings-page.component.scss'] }) export class SettingsPageComponent implements OnInit { constructor() { } ngOnInit() { } }
Hub-of-all-Things/Rumpel
src/app/settings/settings-page/settings-page.component.ts
TypeScript
mpl-2.0
649
/* Created by Blake Gideon. <blake at chicagoan.io> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package io.chicagoan.ctawaittime; import android.telephony.PhoneStateListener; import android.telephony.ServiceState; public class SmsStateListener extends PhoneStateListener { ServiceState serviceState; public SmsStateListener () { serviceState = new ServiceState(); } @Override public void onServiceStateChanged(ServiceState serviceState) { super.onServiceStateChanged(serviceState); this.serviceState.setState(serviceState.getState()); } public int getState() { return serviceState.getState(); } }
ChicagoDev/Android_CTA_Bus_Tracker
app/src/main/java/io/chicagoan/ctawaittime/SmsStateListener.java
Java
mpl-2.0
833
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Future Modules: from __future__ import annotations # Built-in Modules: import threading from collections.abc import Callable from typing import Any, Union class BaseDelay(threading.Thread): """ Implements the base delay class. """ _delays: list[threading.Thread] = [] def __init__( self, duration: float, count: Union[int, None], function: Callable[..., Any], *args: Any, **kwargs: Any, ) -> None: """ Defines the constructor for the object. Args: duration: The amount of time (in seconds) to delay between iterations. count: The number of iterations to delay, or None to repeat indefinitely. function: The function to be called at each iteration. *args: Positional arguments to be passed to the called function. **kwargs: Key-word only arguments to be passed to the called function. """ if count is not None and count < 0: raise ValueError("count must be a positive number or None.") super().__init__() self.daemon: bool = True self._duration: float = duration self._count: Union[int, None] = count self._function: Callable[..., Any] = function self._args: tuple[Any, ...] = args self._kwargs: dict[str, Any] = kwargs self._finished: threading.Event = threading.Event() def stop(self) -> None: """Stops an active delay.""" self._finished.set() def run(self) -> None: try: self._delays.append(self) while not self._finished.is_set() and self._count != 0: self._finished.wait(self._duration) if not self._finished.is_set(): self._function(*self._args, **self._kwargs) if self._count is not None: self._count -= 1 finally: del self._function, self._args, self._kwargs self._delays.remove(self) if not self._finished.is_set(): self.stop() class Delay(BaseDelay): """ Implements a delay which automatically starts upon creation. """ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.start() class OneShot(Delay): """ Implements a delay which is run only once. """ def __init__(self, duration: float, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: """ Defines the constructor for the object. Args: duration: The amount of time (in seconds) to delay. function: The function to be called when the delay completes. *args: Positional arguments to be passed to the called function. **kwargs: Key-word only arguments to be passed to the called function. """ super().__init__(duration, 1, function, *args, **kwargs) class Repeating(Delay): """ Implements a delay which runs indefinitely. """ def __init__(self, duration: float, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: """ Defines the constructor for the object. Args: duration: The amount of time (in seconds) to delay between iterations. function: The function to be called at each iteration. *args: Positional arguments to be passed to the called function. **kwargs: Key-word only arguments to be passed to the called function. """ super().__init__(duration, None, function, *args, **kwargs)
nstockton/mapperproxy-mume
mapper/delays.py
Python
mpl-2.0
3,316
// META: timeout=long // META: script=../util/helpers.js // META: script=failures.js run_test(["AES-CTR"]);
mbrubeck/servo
tests/wpt/web-platform-tests/WebCryptoAPI/generateKey/failures_AES-CTR.https.any.js
JavaScript
mpl-2.0
108
from tqdm import tqdm from django.core.management.base import BaseCommand from django.db.models import Exists, OuterRef from ...models import Locality, Operator, Service class Command(BaseCommand): def handle(self, *args, **options): for locality in tqdm(Locality.objects.with_documents()): locality.search_vector = locality.document locality.save(update_fields=['search_vector']) has_services = Exists(Service.objects.filter(current=True, operator=OuterRef('pk'))) for operator in tqdm(Operator.objects.with_documents().filter(has_services)): operator.search_vector = operator.document operator.save(update_fields=['search_vector']) print(Operator.objects.filter(~has_services).update(search_vector=None)) for service in tqdm(Service.objects.with_documents().filter(current=True)): service.search_vector = service.document service.save(update_fields=['search_vector']) print(Service.objects.filter(current=False).update(search_vector=None))
jclgoodwin/bustimes.org.uk
busstops/management/commands/update_search_indexes.py
Python
mpl-2.0
1,072
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-05-01 08:10 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('os2webscanner', '0013_auto_20180501_1006'), ] operations = [ migrations.AlterModelTable( name='scan', table='os2webscanner_scan', ), ]
os2webscanner/os2webscanner
django-os2webscanner/os2webscanner/migrations/0014_auto_20180501_1010.py
Python
mpl-2.0
408