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
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \*---------------------------------------------------------------------------*/ #include "cyclicFaePatchFields.H" #include "faePatchFields.H" #include "addToRunTimeSelectionTable.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // makeFaePatchFields(cyclic); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // ************************************************************************* //
CFDEMproject/OpenFOAM-1.6-ext
src/finiteArea/fields/faePatchFields/constraint/cyclic/cyclicFaePatchFields.C
C++
gpl-2.0
1,713
<?php /** * Single Product Thumbnails * * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $post, $product, $woocommerce; ?> <div class="thumbnails"><?php $attachment_ids = $product->get_gallery_attachment_ids(); if ( $attachment_ids ) { $loop = 0; $columns = apply_filters( 'woocommerce_product_thumbnails_columns', 3 ); foreach ( $attachment_ids as $id ) { $classes = array( 'zoom' ); if ( $loop == 0 || $loop % $columns == 0 ) $classes[] = 'first'; if ( ( $loop + 1 ) % $columns == 0 ) $classes[] = 'last'; $attachment_url = wp_get_attachment_url( $id ); if ( ! $attachment_url ) continue; printf( '<a href="%s" title="%s" rel="prettyPhoto[product-gallery]" class="%s">%s</a>', esc_attr( $attachment_url ), esc_attr( get_the_title( $id ) ), implode( ' ', $classes ), wp_get_attachment_image( $id, apply_filters( 'single_product_small_thumbnail_size', 'shop_thumbnail' ) ) ); $loop++; } } ?></div>
mchibouni/wp_classified_ad_poc
wp-content/themes/sommerce/woocommerce/single-product/product-thumbnails.php
PHP
gpl-2.0
1,064
/* * $Id: EditorActions.java,v 1.38 2012/09/20 14:59:30 david Exp $ * Copyright (c) 2001-2012, JGraph Ltd */ package com.variamos.gui.refas.editor.actions; import java.awt.Color; import java.awt.Component; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.lang.reflect.Method; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.HashSet; import java.util.Map; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JColorChooser; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JSplitPane; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileFilter; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import org.w3c.dom.Document; import com.cfm.productline.io.SXFMWriter; import com.mxgraph.analysis.mxDistanceCostFunction; import com.mxgraph.analysis.mxGraphAnalysis; import com.mxgraph.canvas.mxGraphics2DCanvas; import com.mxgraph.canvas.mxICanvas; import com.mxgraph.canvas.mxSvgCanvas; import com.mxgraph.io.mxCodec; import com.mxgraph.io.mxGdCodec; import com.mxgraph.model.mxGraphModel; import com.mxgraph.model.mxIGraphModel; import com.mxgraph.shape.mxStencilShape; import com.mxgraph.swing.mxGraphComponent; import com.mxgraph.swing.mxGraphOutline; import com.mxgraph.swing.handler.mxConnectionHandler; import com.mxgraph.swing.util.mxGraphActions; import com.mxgraph.swing.view.mxCellEditor; import com.mxgraph.util.mxCellRenderer; import com.mxgraph.util.mxCellRenderer.CanvasFactory; import com.mxgraph.util.mxConstants; import com.mxgraph.util.mxDomUtils; import com.mxgraph.util.mxResources; import com.mxgraph.util.mxUtils; import com.mxgraph.util.mxXmlUtils; import com.mxgraph.util.png.mxPngEncodeParam; import com.mxgraph.util.png.mxPngImageEncoder; import com.mxgraph.util.png.mxPngTextDecoder; import com.mxgraph.view.mxGraph; import com.variamos.gui.maineditor.BasicGraphEditor; import com.variamos.gui.maineditor.DefaultFileFilter; import com.variamos.gui.maineditor.EditorPalette; import com.variamos.gui.maineditor.EditorRuler; import com.variamos.gui.maineditor.MainFrame; import com.variamos.gui.maineditor.VariamosGraphEditor; import com.variamos.gui.pl.editor.ProductLineGraph; /** * A class to support most of the actions through the interface. Initially * copied from EditorActions on maineditor. Part of PhD work at University of * Paris 1 * * @author Juan C. Muñoz Fernández <jcmunoz@gmail.com> * * @version 1.1 * @since 2014-11-10 * @see com.variamos.gui.maineditor.EditorActions */ public class EditorActions { /** * * @param e * @return Returns the graph for the given action event. */ public static final BasicGraphEditor getEditor(ActionEvent e) { if (e.getSource() instanceof Component) { Component component = (Component) e.getSource(); while (component != null && !(component instanceof BasicGraphEditor)) { component = component.getParent(); } return (BasicGraphEditor) component; } return null; } /** * */ @SuppressWarnings("serial") public static class ToggleRulersItem extends JCheckBoxMenuItem { /** * */ public ToggleRulersItem(final BasicGraphEditor editor, String name) { super(name); setSelected(editor.getGraphComponent().getColumnHeader() != null); addActionListener(new ActionListener() { /** * */ public void actionPerformed(ActionEvent e) { mxGraphComponent graphComponent = editor .getGraphComponent(); if (graphComponent.getColumnHeader() != null) { graphComponent.setColumnHeader(null); graphComponent.setRowHeader(null); } else { graphComponent.setColumnHeaderView(new EditorRuler( graphComponent, EditorRuler.ORIENTATION_HORIZONTAL)); graphComponent.setRowHeaderView(new EditorRuler( graphComponent, EditorRuler.ORIENTATION_VERTICAL)); } } }); } } /** * */ @SuppressWarnings("serial") public static class ToggleGridItem extends JCheckBoxMenuItem { /** * */ public ToggleGridItem(final BasicGraphEditor editor, String name) { super(name); setSelected(true); addActionListener(new ActionListener() { /** * */ public void actionPerformed(ActionEvent e) { mxGraphComponent graphComponent = editor .getGraphComponent(); mxGraph graph = graphComponent.getGraph(); boolean enabled = !graph.isGridEnabled(); graph.setGridEnabled(enabled); graphComponent.setGridVisible(enabled); graphComponent.repaint(); setSelected(enabled); } }); } } /** * */ @SuppressWarnings("serial") public static class ToggleOutlineItem extends JCheckBoxMenuItem { /** * */ public ToggleOutlineItem(final BasicGraphEditor editor, String name) { super(name); setSelected(true); addActionListener(new ActionListener() { /** * */ public void actionPerformed(ActionEvent e) { final mxGraphOutline outline = editor.getGraphOutline(); outline.setVisible(!outline.isVisible()); outline.revalidate(); SwingUtilities.invokeLater(new Runnable() { /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ public void run() { if (outline.getParent() instanceof JSplitPane) { if (outline.isVisible()) { ((JSplitPane) outline.getParent()) .setDividerLocation(editor .getHeight() - 300); ((JSplitPane) outline.getParent()) .setDividerSize(6); } else { ((JSplitPane) outline.getParent()) .setDividerSize(0); } } } }); } }); } } /** * */ @SuppressWarnings("serial") public static class ExitAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { BasicGraphEditor editor = getEditor(e); if (editor != null) { editor.exit(); } } } /** * */ @SuppressWarnings("serial") public static class StylesheetAction extends AbstractAction { /** * */ protected String stylesheet; /** * */ public StylesheetAction(String stylesheet) { this.stylesheet = stylesheet; } /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); mxGraph graph = graphComponent.getGraph(); mxCodec codec = new mxCodec(); Document doc = mxUtils.loadDocument(EditorActions.class .getResource(stylesheet).toString()); if (doc != null) { codec.decode(doc.getDocumentElement(), graph.getStylesheet()); graph.refresh(); } } } } /** * */ @SuppressWarnings("serial") public static class ZoomPolicyAction extends AbstractAction { /** * */ protected int zoomPolicy; /** * */ public ZoomPolicyAction(int zoomPolicy) { this.zoomPolicy = zoomPolicy; } /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); graphComponent.setPageVisible(true); graphComponent.setZoomPolicy(zoomPolicy); } } } /** * */ @SuppressWarnings("serial") public static class GridStyleAction extends AbstractAction { /** * */ protected int style; /** * */ public GridStyleAction(int style) { this.style = style; } /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); graphComponent.setGridStyle(style); graphComponent.repaint(); } } } /** * */ @SuppressWarnings("serial") public static class GridColorAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); Color newColor = JColorChooser.showDialog(graphComponent, mxResources.get("gridColor"), graphComponent.getGridColor()); if (newColor != null) { graphComponent.setGridColor(newColor); graphComponent.repaint(); } } } } /** * */ @SuppressWarnings("serial") public static class ScaleAction extends AbstractAction { /** * */ protected double scale; /** * */ public ScaleAction(double scale) { this.scale = scale; } /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); double scale = this.scale; if (scale == 0) { String value = (String) JOptionPane.showInputDialog( graphComponent, mxResources.get("value"), mxResources.get("scale") + " (%)", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null) { scale = Double.parseDouble(value.replace("%", "")) / 100; } } if (scale > 0) { graphComponent.zoomTo(scale, graphComponent.isCenterZoom()); } } } } /** * */ @SuppressWarnings("serial") public static class PageSetupAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); PrinterJob pj = PrinterJob.getPrinterJob(); PageFormat format = pj.pageDialog(graphComponent .getPageFormat()); if (format != null) { graphComponent.setPageFormat(format); graphComponent.zoomAndCenter(); } } } } /** * */ @SuppressWarnings("serial") public static class PrintAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); PrinterJob pj = PrinterJob.getPrinterJob(); if (pj.printDialog()) { PageFormat pf = graphComponent.getPageFormat(); Paper paper = new Paper(); double margin = 36; paper.setImageableArea(margin, margin, paper.getWidth() - margin * 2, paper.getHeight() - margin * 2); pf.setPaper(paper); pj.setPrintable(graphComponent, pf); try { pj.print(); } catch (PrinterException e2) { System.out.println(e2); } } } } } /** * */ @SuppressWarnings("serial") public static class SaveAction extends AbstractAction { /** * */ protected boolean showDialog; /** * */ protected String lastDir = null; /** * */ public SaveAction(boolean showDialog) { this.showDialog = showDialog; } /** * Saves XML+PNG format. */ protected void saveXmlPng(BasicGraphEditor editor, String filename, Color bg) throws IOException { mxGraphComponent graphComponent = editor.getGraphComponent(); mxGraph graph = graphComponent.getGraph(); // Creates the image for the PNG file BufferedImage image = mxCellRenderer.createBufferedImage(graph, null, 1, bg, graphComponent.isAntiAlias(), null, graphComponent.getCanvas()); // Creates the URL-encoded XML data mxCodec codec = new mxCodec(); String xml = URLEncoder.encode( mxXmlUtils.getXml(codec.encode(graph.getModel())), "UTF-8"); mxPngEncodeParam param = mxPngEncodeParam .getDefaultEncodeParam(image); param.setCompressedText(new String[] { "mxGraphModel", xml }); // Saves as a PNG file FileOutputStream outputStream = new FileOutputStream(new File( filename)); try { mxPngImageEncoder encoder = new mxPngImageEncoder(outputStream, param); if (image != null) { encoder.encode(image); editor.setModified(false); editor.setCurrentFile(new File(filename)); } else { JOptionPane.showMessageDialog(graphComponent, mxResources.get("noImageData")); } } finally { outputStream.close(); } } /** * */ public void actionPerformed(ActionEvent e) { VariamosGraphEditor editor = (VariamosGraphEditor) getEditor(e); if (editor != null) { ((MainFrame) editor.getFrame()).waitingCursor(true); mxGraphComponent graphComponent = editor.getGraphComponent(); mxGraph graph = graphComponent.getGraph(); FileFilter selectedFilter = null; DefaultFileFilter xmlPngFilter = new DefaultFileFilter(".png", "PNG+XML " + mxResources.get("file") + " (.png)"); FileFilter vmlFileFilter = new DefaultFileFilter(".html", "VML " + mxResources.get("file") + " (.html)"); String filename = null; boolean dialogShown = false; if (showDialog || editor.getCurrentFile() == null) { String wd; if (lastDir != null) { wd = lastDir; } else if (editor.getCurrentFile() != null) { wd = editor.getCurrentFile().getParent(); } else { wd = System.getProperty("user.dir"); } JFileChooser fc = new JFileChooser(wd); // Adds the default file format FileFilter defaultFilter = xmlPngFilter; fc.addChoosableFileFilter(defaultFilter); // Adds special vector graphics formats and HTML fc.addChoosableFileFilter(new DefaultFileFilter(".mxe", "mxGraph Editor " + mxResources.get("file") + " (.mxe)")); fc.addChoosableFileFilter(new DefaultFileFilter(".txt", "Graph Drawing " + mxResources.get("file") + " (.txt)")); fc.addChoosableFileFilter(new DefaultFileFilter(".svg", "SVG " + mxResources.get("file") + " (.svg)")); fc.addChoosableFileFilter(vmlFileFilter); fc.addChoosableFileFilter(new DefaultFileFilter(".html", "HTML " + mxResources.get("file") + " (.html)")); // Adds a filter for each supported image format Object[] imageFormats = ImageIO.getReaderFormatNames(); // Finds all distinct extensions HashSet<String> formats = new HashSet<String>(); for (int i = 0; i < imageFormats.length; i++) { String ext = imageFormats[i].toString().toLowerCase(); formats.add(ext); } imageFormats = formats.toArray(); for (int i = 0; i < imageFormats.length; i++) { String ext = imageFormats[i].toString(); fc.addChoosableFileFilter(new DefaultFileFilter("." + ext, ext.toUpperCase() + " " + mxResources.get("file") + " (." + ext + ")")); } // Adds filter that accepts all supported image formats fc.addChoosableFileFilter(new DefaultFileFilter.ImageFileFilter( mxResources.get("allImages"))); fc.setFileFilter(defaultFilter); int rc = fc.showDialog(null, mxResources.get("save")); dialogShown = true; if (rc != JFileChooser.APPROVE_OPTION) { return; } else { lastDir = fc.getSelectedFile().getParent(); } filename = fc.getSelectedFile().getAbsolutePath(); selectedFilter = fc.getFileFilter(); if (selectedFilter instanceof DefaultFileFilter) { String ext = ((DefaultFileFilter) selectedFilter) .getExtension(); if (!filename.toLowerCase().endsWith(ext)) { filename += ext; } } if (new File(filename).exists() && JOptionPane.showConfirmDialog(graphComponent, mxResources.get("overwriteExistingFile")) != JOptionPane.YES_OPTION) { return; } } else { filename = editor.getCurrentFile().getAbsolutePath(); } try { String ext = filename .substring(filename.lastIndexOf('.') + 1); if (ext.equalsIgnoreCase("svg")) { mxSvgCanvas canvas = (mxSvgCanvas) mxCellRenderer .drawCells(graph, null, 1, null, new CanvasFactory() { public mxICanvas createCanvas( int width, int height) { mxSvgCanvas canvas = new mxSvgCanvas( mxDomUtils .createSvgDocument( width, height)); canvas.setEmbedded(true); return canvas; } }); mxUtils.writeFile( mxXmlUtils.getXml(canvas.getDocument()), filename); } else if (selectedFilter == vmlFileFilter) { mxUtils.writeFile(mxXmlUtils.getXml(mxCellRenderer .createVmlDocument(graph, null, 1, null, null) .getDocumentElement()), filename); } else if (ext.equalsIgnoreCase("sxfm")) { SXFMWriter writer = new SXFMWriter(); ProductLineGraph plGraph = (ProductLineGraph) graph; mxUtils.writeFile( writer.getSXFMContent(plGraph.getProductLine()), filename); } else if (ext.equalsIgnoreCase("html")) { mxUtils.writeFile(mxXmlUtils.getXml(mxCellRenderer .createHtmlDocument(graph, null, 1, null, null) .getDocumentElement()), filename); } else if (ext.equalsIgnoreCase("mxe") || ext.equalsIgnoreCase("plg") || ext.equalsIgnoreCase("xml")) { mxCodec codec = new mxCodec(); SharedActions.beforeSaveGraph(graph); String xml = mxXmlUtils.getXml(codec.encode(graph .getModel())); SharedActions.afterSaveGraph(graph, editor); mxUtils.writeFile(xml, filename); editor.setModified(false); editor.setCurrentFile(new File(filename)); } else if (ext.equalsIgnoreCase("txt")) { String content = mxGdCodec.encode(graph); mxUtils.writeFile(content, filename); } else { Color bg = null; if ((!ext.equalsIgnoreCase("gif") && !ext .equalsIgnoreCase("png")) || JOptionPane.showConfirmDialog( graphComponent, mxResources .get("transparentBackground")) != JOptionPane.YES_OPTION) { bg = graphComponent.getBackground(); } if (selectedFilter == xmlPngFilter || (editor.getCurrentFile() != null && ext.equalsIgnoreCase("png") && !dialogShown)) { saveXmlPng(editor, filename, bg); } else { BufferedImage image = mxCellRenderer .createBufferedImage(graph, null, 1, bg, graphComponent.isAntiAlias(), null, graphComponent.getCanvas()); if (image != null) { ImageIO.write(image, ext, new File(filename)); } else { JOptionPane.showMessageDialog(graphComponent, mxResources.get("noImageData")); } } } } catch (Throwable ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(graphComponent, ex.toString(), mxResources.get("error"), JOptionPane.ERROR_MESSAGE); } ((MainFrame) editor.getFrame()).waitingCursor(true); } } } /** * */ @SuppressWarnings("serial") public static class SelectShortestPathAction extends AbstractAction { /** * */ protected boolean directed; /** * */ public SelectShortestPathAction(boolean directed) { this.directed = directed; } /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); mxGraph graph = graphComponent.getGraph(); mxIGraphModel model = graph.getModel(); Object source = null; Object target = null; Object[] cells = graph.getSelectionCells(); for (int i = 0; i < cells.length; i++) { if (model.isVertex(cells[i])) { if (source == null) { source = cells[i]; } else if (target == null) { target = cells[i]; } } if (source != null && target != null) { break; } } if (source != null && target != null) { int steps = graph.getChildEdges(graph.getDefaultParent()).length; Object[] path = mxGraphAnalysis.getInstance() .getShortestPath(graph, source, target, new mxDistanceCostFunction(), steps, directed); graph.setSelectionCells(path); } else { JOptionPane.showMessageDialog(graphComponent, mxResources.get("noSourceAndTargetSelected")); } } } } /** * */ @SuppressWarnings("serial") public static class SelectSpanningTreeAction extends AbstractAction { /** * */ protected boolean directed; /** * */ public SelectSpanningTreeAction(boolean directed) { this.directed = directed; } /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); mxGraph graph = graphComponent.getGraph(); mxIGraphModel model = graph.getModel(); Object parent = graph.getDefaultParent(); Object[] cells = graph.getSelectionCells(); for (int i = 0; i < cells.length; i++) { if (model.getChildCount(cells[i]) > 0) { parent = cells[i]; break; } } Object[] v = graph.getChildVertices(parent); Object[] mst = mxGraphAnalysis.getInstance() .getMinimumSpanningTree(graph, v, new mxDistanceCostFunction(), directed); graph.setSelectionCells(mst); } } } /** * */ @SuppressWarnings("serial") public static class ToggleDirtyAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); graphComponent.showDirtyRectangle = !graphComponent.showDirtyRectangle; } } } /** * */ @SuppressWarnings("serial") public static class ToggleConnectModeAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); mxConnectionHandler handler = graphComponent .getConnectionHandler(); handler.setHandleEnabled(!handler.isHandleEnabled()); } } } /** * */ @SuppressWarnings("serial") public static class ToggleCreateTargetItem extends JCheckBoxMenuItem { /** * */ public ToggleCreateTargetItem(final BasicGraphEditor editor, String name) { super(name); setSelected(true); addActionListener(new ActionListener() { /** * */ public void actionPerformed(ActionEvent e) { mxGraphComponent graphComponent = editor .getGraphComponent(); if (graphComponent != null) { mxConnectionHandler handler = graphComponent .getConnectionHandler(); handler.setCreateTarget(!handler.isCreateTarget()); setSelected(handler.isCreateTarget()); } } }); } } /** * */ @SuppressWarnings("serial") public static class PromptPropertyAction extends AbstractAction { /** * */ protected Object target; /** * */ protected String fieldname, message; /** * */ public PromptPropertyAction(Object target, String message) { this(target, message, message); } /** * */ public PromptPropertyAction(Object target, String message, String fieldname) { this.target = target; this.message = message; this.fieldname = fieldname; } /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof Component) { try { Method getter = target.getClass().getMethod( "get" + fieldname); Object current = getter.invoke(target); // TODO: Support other atomic types if (current instanceof Integer) { Method setter = target.getClass().getMethod( "set" + fieldname, new Class[] { int.class }); String value = (String) JOptionPane.showInputDialog( (Component) e.getSource(), "Value", message, JOptionPane.PLAIN_MESSAGE, null, null, current); if (value != null) { setter.invoke(target, Integer.parseInt(value)); } } } catch (Exception ex) { ex.printStackTrace(); } } // Repaints the graph component if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); graphComponent.repaint(); } } } /** * */ @SuppressWarnings("serial") public static class TogglePropertyItem extends JCheckBoxMenuItem { /** * */ public TogglePropertyItem(Object target, String name, String fieldname) { this(target, name, fieldname, false); } /** * */ public TogglePropertyItem(Object target, String name, String fieldname, boolean refresh) { this(target, name, fieldname, refresh, null); } /** * */ public TogglePropertyItem(final Object target, String name, final String fieldname, final boolean refresh, ActionListener listener) { super(name); // Since action listeners are processed last to first we add the // given // listener here which means it will be processed after the one // below if (listener != null) { addActionListener(listener); } addActionListener(new ActionListener() { /** * */ public void actionPerformed(ActionEvent e) { execute(target, fieldname, refresh); } }); PropertyChangeListener propertyChangeListener = new PropertyChangeListener() { /* * (non-Javadoc) * * @see * java.beans.PropertyChangeListener#propertyChange(java.beans * .PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equalsIgnoreCase(fieldname)) { update(target, fieldname); } } }; if (target instanceof mxGraphComponent) { ((mxGraphComponent) target) .addPropertyChangeListener(propertyChangeListener); } else if (target instanceof mxGraph) { ((mxGraph) target) .addPropertyChangeListener(propertyChangeListener); } update(target, fieldname); } /** * */ public void update(Object target, String fieldname) { if (target != null && fieldname != null) { try { Method getter = target.getClass().getMethod( "is" + fieldname); if (getter != null) { Object current = getter.invoke(target); if (current instanceof Boolean) { setSelected(((Boolean) current).booleanValue()); } } } catch (Exception e) { // ignore } } } /** * */ public void execute(Object target, String fieldname, boolean refresh) { if (target != null && fieldname != null) { try { Method getter = target.getClass().getMethod( "is" + fieldname); Method setter = target.getClass().getMethod( "set" + fieldname, new Class[] { boolean.class }); Object current = getter.invoke(target); if (current instanceof Boolean) { boolean value = !((Boolean) current).booleanValue(); setter.invoke(target, value); setSelected(value); } if (refresh) { mxGraph graph = null; if (target instanceof mxGraph) { graph = (mxGraph) target; } else if (target instanceof mxGraphComponent) { graph = ((mxGraphComponent) target).getGraph(); } graph.refresh(); } } catch (Exception e) { // ignore } } } } /** * */ @SuppressWarnings("serial") public static class HistoryAction extends AbstractAction { /** * */ protected boolean undo; /** * */ public HistoryAction(boolean undo) { this.undo = undo; } /** * */ public void actionPerformed(ActionEvent e) { BasicGraphEditor editor = getEditor(e); if (editor != null) { if (undo) { editor.getUndoManager().undo(); } else { editor.getUndoManager().redo(); } } } } /** * */ @SuppressWarnings("serial") public static class FontStyleAction extends AbstractAction { /** * */ protected boolean bold; /** * */ public FontStyleAction(boolean bold) { this.bold = bold; } /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); Component editorComponent = null; if (graphComponent.getCellEditor() instanceof mxCellEditor) { editorComponent = ((mxCellEditor) graphComponent .getCellEditor()).getEditor(); } if (editorComponent instanceof JEditorPane) { JEditorPane editorPane = (JEditorPane) editorComponent; int start = editorPane.getSelectionStart(); int ende = editorPane.getSelectionEnd(); String text = editorPane.getSelectedText(); if (text == null) { text = ""; } try { HTMLEditorKit editorKit = new HTMLEditorKit(); HTMLDocument document = (HTMLDocument) editorPane .getDocument(); document.remove(start, (ende - start)); editorKit.insertHTML(document, start, ((bold) ? "<b>" : "<i>") + text + ((bold) ? "</b>" : "</i>"), 0, 0, (bold) ? HTML.Tag.B : HTML.Tag.I); } catch (Exception ex) { ex.printStackTrace(); } editorPane.requestFocus(); editorPane.select(start, ende); } else { mxIGraphModel model = graphComponent.getGraph().getModel(); model.beginUpdate(); try { graphComponent.stopEditing(false); graphComponent.getGraph().toggleCellStyleFlags( mxConstants.STYLE_FONTSTYLE, (bold) ? mxConstants.FONT_BOLD : mxConstants.FONT_ITALIC); } finally { model.endUpdate(); } } } } } /** * */ @SuppressWarnings("serial") public static class WarningAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); Object[] cells = graphComponent.getGraph().getSelectionCells(); if (cells != null && cells.length > 0) { String warning = JOptionPane.showInputDialog(mxResources .get("enterWarningMessage")); for (int i = 0; i < cells.length; i++) { graphComponent.setCellWarning(cells[i], warning); } } else { JOptionPane.showMessageDialog(graphComponent, mxResources.get("noCellSelected")); } } } } /** * */ @SuppressWarnings("serial") public static class NewAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { BasicGraphEditor editor = getEditor(e); if (editor != null) { if (!editor.isModified() || JOptionPane.showConfirmDialog(editor, mxResources.get("loseChanges")) == JOptionPane.YES_OPTION) { ((VariamosGraphEditor) editor).resetView(); } } } } /** * */ @SuppressWarnings("serial") public static class ImportAction extends AbstractAction { /** * */ protected String lastDir; /** * Loads and registers the shape as a new shape in mxGraphics2DCanvas * and adds a new entry to use that shape in the specified palette * * @param palette * The palette to add the shape to. * @param nodeXml * The raw XML of the shape * @param path * The path to the directory the shape exists in * @return the string name of the shape */ public static String addStencilShape(EditorPalette palette, String nodeXml, String path) { // Some editors place a 3 byte BOM at the start of files // Ensure the first char is a "<" int lessthanIndex = nodeXml.indexOf("<"); nodeXml = nodeXml.substring(lessthanIndex); mxStencilShape newShape = new mxStencilShape(nodeXml); String name = newShape.getName(); ImageIcon icon = null; if (path != null) { String iconPath = path + newShape.getIconPath(); icon = new ImageIcon(iconPath); } // Registers the shape in the canvas shape registry mxGraphics2DCanvas.putShape(name, newShape); if (palette != null && icon != null) { palette.addTemplate(name, icon, "shape=" + name, 80, 80, ""); } return name; } /** * */ public void actionPerformed(ActionEvent e) { BasicGraphEditor editor = getEditor(e); if (editor != null) { String wd = (lastDir != null) ? lastDir : System .getProperty("user.dir"); JFileChooser fc = new JFileChooser(wd); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); // Adds file filter for Dia shape import fc.addChoosableFileFilter(new DefaultFileFilter(".shape", "Dia Shape " + mxResources.get("file") + " (.shape)")); int rc = fc.showDialog(null, mxResources.get("importStencil")); if (rc == JFileChooser.APPROVE_OPTION) { lastDir = fc.getSelectedFile().getParent(); try { if (fc.getSelectedFile().isDirectory()) { EditorPalette palette = editor.insertPalette(fc .getSelectedFile().getName()); for (File f : fc.getSelectedFile().listFiles( new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith( ".shape"); } })) { String nodeXml = mxUtils.readFile(f .getAbsolutePath()); addStencilShape(palette, nodeXml, f.getParent() + File.separator); } JComponent scrollPane = (JComponent) palette .getParent().getParent(); editor.getLibraryPane().setSelectedComponent( scrollPane); // FIXME: Need to update the size of the palette to // force a layout // update. Re/in/validate of palette or parent does // not work. // editor.getLibraryPane().revalidate(); } else { String nodeXml = mxUtils.readFile(fc .getSelectedFile().getAbsolutePath()); String name = addStencilShape(null, nodeXml, null); JOptionPane.showMessageDialog(editor, mxResources .get("stencilImported", new String[] { name })); } } catch (IOException e1) { e1.printStackTrace(); } } } } } /** * */ @SuppressWarnings("serial") public static class OpenAction extends AbstractAction { /** * */ protected String lastDir; /** * */ protected void resetEditor(VariamosGraphEditor editor) { editor.setVisibleModel(0, -1); editor.setDefaultButton(); editor.updateView(); editor.setModified(false); editor.getUndoManager().clear(); editor.getGraphComponent().zoomAndCenter(); } /** * Reads XML+PNG format. */ protected void openXmlPng(VariamosGraphEditor editor, File file) throws IOException { Map<String, String> text = mxPngTextDecoder .decodeCompressedText(new FileInputStream(file)); if (text != null) { String value = text.get("mxGraphModel"); if (value != null) { Document document = mxXmlUtils.parseXml(URLDecoder.decode( value, "UTF-8")); mxCodec codec = new mxCodec(document); codec.decode(document.getDocumentElement(), editor .getGraphComponent().getGraph().getModel()); editor.setCurrentFile(file); resetEditor(editor); return; } } JOptionPane.showMessageDialog(editor, mxResources.get("imageContainsNoDiagramData")); } /** * @throws IOException * */ protected void openGD(BasicGraphEditor editor, File file, String gdText) { mxGraph graph = editor.getGraphComponent().getGraph(); // Replaces file extension with .mxe String filename = file.getName(); filename = filename.substring(0, filename.length() - 4) + ".mxe"; if (new File(filename).exists() && JOptionPane.showConfirmDialog(editor, mxResources.get("overwriteExistingFile")) != JOptionPane.YES_OPTION) { return; } ((mxGraphModel) graph.getModel()).clear(); mxGdCodec.decode(gdText, graph); editor.getGraphComponent().zoomAndCenter(); editor.setCurrentFile(new File(lastDir + "/" + filename)); } /** * */ public void actionPerformed(ActionEvent e) { BasicGraphEditor editor = getEditor(e); if (editor != null) { ((MainFrame)editor.getFrame()).waitingCursor(true); if (!editor.isModified() || JOptionPane.showConfirmDialog(editor, mxResources.get("loseChanges")) == JOptionPane.YES_OPTION) { mxGraph graph = editor.getGraphComponent().getGraph(); if (graph != null) { String wd = (lastDir != null) ? lastDir : System .getProperty("user.dir"); JFileChooser fc = new JFileChooser(wd); // Adds file filter for supported file format DefaultFileFilter defaultFilter = new DefaultFileFilter( ".mxe", mxResources.get("allSupportedFormats") + " (.mxe, .png, .vdx)") { public boolean accept(File file) { String lcase = file.getName().toLowerCase(); return super.accept(file) || lcase.endsWith(".png") || lcase.endsWith(".vdx"); } }; fc.addChoosableFileFilter(defaultFilter); fc.addChoosableFileFilter(new DefaultFileFilter(".mxe", "mxGraph Editor " + mxResources.get("file") + " (.mxe)")); fc.addChoosableFileFilter(new DefaultFileFilter(".png", "PNG+XML " + mxResources.get("file") + " (.png)")); // Adds file filter for VDX import fc.addChoosableFileFilter(new DefaultFileFilter(".vdx", "XML Drawing " + mxResources.get("file") + " (.vdx)")); // Adds file filter for GD import fc.addChoosableFileFilter(new DefaultFileFilter(".txt", "Graph Drawing " + mxResources.get("file") + " (.txt)")); fc.setFileFilter(defaultFilter); int rc = fc.showDialog(null, mxResources.get("openFile")); if (rc == JFileChooser.APPROVE_OPTION) { lastDir = fc.getSelectedFile().getParent(); try { if (fc.getSelectedFile().getAbsolutePath() .toLowerCase().endsWith(".png")) { openXmlPng((VariamosGraphEditor) editor, fc.getSelectedFile()); } else if (fc.getSelectedFile() .getAbsolutePath().toLowerCase() .endsWith(".txt")) { openGD(editor, fc.getSelectedFile(), mxUtils.readFile(fc .getSelectedFile() .getAbsolutePath())); } else { Document document = mxXmlUtils .parseXml(mxUtils.readFile(fc .getSelectedFile() .getAbsolutePath())); mxCodec codec = new mxCodec(document); codec.decode(document.getDocumentElement(), graph.getModel()); editor.setCurrentFile(fc.getSelectedFile()); VariamosGraphEditor variamosEditor = (VariamosGraphEditor) editor; SharedActions.afterSaveGraph(graph, variamosEditor); resetEditor((VariamosGraphEditor) editor); } } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog( editor.getGraphComponent(), ex.toString(), mxResources.get("error"), JOptionPane.ERROR_MESSAGE); } } } } ((MainFrame)editor.getFrame()).waitingCursor(false); } } } /** * */ @SuppressWarnings("serial") public static class ToggleAction extends AbstractAction { /** * */ protected String key; /** * */ protected boolean defaultValue; /** * * @param key */ public ToggleAction(String key) { this(key, false); } /** * * @param key */ public ToggleAction(String key, boolean defaultValue) { this.key = key; this.defaultValue = defaultValue; } /** * */ public void actionPerformed(ActionEvent e) { mxGraph graph = mxGraphActions.getGraph(e); if (graph != null) { graph.toggleCellStyles(key, defaultValue); } } } /** * */ @SuppressWarnings("serial") public static class SetLabelPositionAction extends AbstractAction { /** * */ protected String labelPosition, alignment; /** * * @param key */ public SetLabelPositionAction(String labelPosition, String alignment) { this.labelPosition = labelPosition; this.alignment = alignment; } /** * */ public void actionPerformed(ActionEvent e) { mxGraph graph = mxGraphActions.getGraph(e); if (graph != null && !graph.isSelectionEmpty()) { graph.getModel().beginUpdate(); try { // Checks the orientation of the alignment to use the // correct constants if (labelPosition.equals(mxConstants.ALIGN_LEFT) || labelPosition.equals(mxConstants.ALIGN_CENTER) || labelPosition.equals(mxConstants.ALIGN_RIGHT)) { graph.setCellStyles(mxConstants.STYLE_LABEL_POSITION, labelPosition); graph.setCellStyles(mxConstants.STYLE_ALIGN, alignment); } else { graph.setCellStyles( mxConstants.STYLE_VERTICAL_LABEL_POSITION, labelPosition); graph.setCellStyles(mxConstants.STYLE_VERTICAL_ALIGN, alignment); } } finally { graph.getModel().endUpdate(); } } } } /** * */ @SuppressWarnings("serial") public static class SetStyleAction extends AbstractAction { /** * */ protected String value; /** * * @param key */ public SetStyleAction(String value) { this.value = value; } /** * */ public void actionPerformed(ActionEvent e) { mxGraph graph = mxGraphActions.getGraph(e); if (graph != null && !graph.isSelectionEmpty()) { graph.setCellStyle(value); } } } /** * */ @SuppressWarnings("serial") public static class KeyValueAction extends AbstractAction { /** * */ protected String key, value; /** * * @param key */ public KeyValueAction(String key) { this(key, null); } /** * * @param key */ public KeyValueAction(String key, String value) { this.key = key; this.value = value; } /** * */ public void actionPerformed(ActionEvent e) { mxGraph graph = mxGraphActions.getGraph(e); if (graph != null && !graph.isSelectionEmpty()) { graph.setCellStyles(key, value); } } } /** * */ @SuppressWarnings("serial") public static class PromptValueAction extends AbstractAction { /** * */ protected String key, message; /** * * @param key */ public PromptValueAction(String key, String message) { this.key = key; this.message = message; } /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof Component) { mxGraph graph = mxGraphActions.getGraph(e); if (graph != null && !graph.isSelectionEmpty()) { String value = (String) JOptionPane.showInputDialog( (Component) e.getSource(), mxResources.get("value"), message, JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null) { if (value.equals(mxConstants.NONE)) { value = null; } graph.setCellStyles(key, value); } } } } } /** * */ @SuppressWarnings("serial") public static class AlignCellsAction extends AbstractAction { /** * */ protected String align; /** * * @param key */ public AlignCellsAction(String align) { this.align = align; } /** * */ public void actionPerformed(ActionEvent e) { mxGraph graph = mxGraphActions.getGraph(e); if (graph != null && !graph.isSelectionEmpty()) { graph.alignCells(align); } } } /** * */ @SuppressWarnings("serial") public static class AutosizeAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { mxGraph graph = mxGraphActions.getGraph(e); if (graph != null && !graph.isSelectionEmpty()) { Object[] cells = graph.getSelectionCells(); mxIGraphModel model = graph.getModel(); model.beginUpdate(); try { for (int i = 0; i < cells.length; i++) { graph.updateCellSize(cells[i]); } } finally { model.endUpdate(); } } } } /** * */ @SuppressWarnings("serial") public static class ColorAction extends AbstractAction { /** * */ protected String name, key; /** * * @param key */ public ColorAction(String name, String key) { this.name = name; this.key = key; } /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); mxGraph graph = graphComponent.getGraph(); if (!graph.isSelectionEmpty()) { Color newColor = JColorChooser.showDialog(graphComponent, name, null); if (newColor != null) { graph.setCellStyles(key, mxUtils.hexString(newColor)); } } } } } /** * */ @SuppressWarnings("serial") public static class BackgroundImageAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); String value = (String) JOptionPane.showInputDialog( graphComponent, mxResources.get("backgroundImage"), "URL", JOptionPane.PLAIN_MESSAGE, null, null, "http://www.callatecs.com/images/background2.JPG"); if (value != null) { if (value.length() == 0) { graphComponent.setBackgroundImage(null); } else { Image background = mxUtils.loadImage(value); // Incorrect URLs will result in no image. // TODO provide feedback that the URL is not correct if (background != null) { graphComponent.setBackgroundImage(new ImageIcon( background)); } } // Forces a repaint of the outline graphComponent.getGraph().repaint(); } } } } /** * */ @SuppressWarnings("serial") public static class BackgroundAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); Color newColor = JColorChooser.showDialog(graphComponent, mxResources.get("background"), null); if (newColor != null) { graphComponent.getViewport().setOpaque(true); graphComponent.getViewport().setBackground(newColor); } // Forces a repaint of the outline graphComponent.getGraph().repaint(); } } } /** * */ @SuppressWarnings("serial") public static class PageBackgroundAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); Color newColor = JColorChooser.showDialog(graphComponent, mxResources.get("pageBackground"), null); if (newColor != null) { graphComponent.setPageBackgroundColor(newColor); } // Forces a repaint of the component graphComponent.repaint(); } } } /** * */ @SuppressWarnings("serial") public static class StyleAction extends AbstractAction { /** * */ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) e .getSource(); mxGraph graph = graphComponent.getGraph(); String initial = graph.getModel().getStyle( graph.getSelectionCell()); String value = (String) JOptionPane.showInputDialog( graphComponent, mxResources.get("style"), mxResources.get("style"), JOptionPane.PLAIN_MESSAGE, null, null, initial); if (value != null) { graph.setCellStyle(value); } } } } }
sebasMonsalve/VARIAMOS
com.variamos.gui/src/com/variamos/gui/refas/editor/actions/EditorActions.java
Java
gpl-2.0
48,399
/* * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/> * Copyright (C) 2008 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2008-2014 Hellground <http://hellground.net/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Common.h" #include "Language.h" #include "WorldPacket.h" #include "WorldSession.h" #include "World.h" #include "ObjectMgr.h" #include "Log.h" #include "Opcodes.h" #include "Guild.h" #include "ArenaTeam.h" #include "MapManager.h" #include "GossipDef.h" #include "SocialMgr.h" #include "GuildMgr.h" /*enum PetitionType // dbc data { PETITION_TYPE_GUILD = 1, PETITION_TYPE_ARENA_TEAM = 3 };*/ // Charters ID in item_template #define GUILD_CHARTER 5863 #define GUILD_CHARTER_COST 1000 // 10 S #define ARENA_TEAM_CHARTER_2v2 23560 #define ARENA_TEAM_CHARTER_2v2_COST 800000 // 80 G #define ARENA_TEAM_CHARTER_3v3 23561 #define ARENA_TEAM_CHARTER_3v3_COST 1200000 // 120 G #define ARENA_TEAM_CHARTER_5v5 23562 #define ARENA_TEAM_CHARTER_5v5_COST 2000000 // 200 G void WorldSession::HandlePetitionBuyOpcode(WorldPacket & recv_data) { CHECK_PACKET_SIZE(recv_data, 8+8+4+1+5*8+2+1+4+4); sLog.outDebug("Received opcode CMSG_PETITION_BUY"); //recv_data.hexlike(); uint64 guidNPC; uint64 unk1, unk3, unk4, unk5, unk6, unk7; uint32 unk2; std::string name; uint16 unk8; uint8 unk9; uint32 unk10; // selected index uint32 unk11; recv_data >> guidNPC; // NPC GUID recv_data >> unk1; // 0 recv_data >> unk2; // 0 recv_data >> name; // name // recheck CHECK_PACKET_SIZE(recv_data, 8+8+4+(name.size()+1)+5*8+2+1+4+4); recv_data >> unk3; // 0 recv_data >> unk4; // 0 recv_data >> unk5; // 0 recv_data >> unk6; // 0 recv_data >> unk7; // 0 recv_data >> unk8; // 0 recv_data >> unk9; // 0 recv_data >> unk10; // index recv_data >> unk11; // 0 sLog.outDebug("Petitioner with GUID %u tried sell petition: name %s", GUID_LOPART(guidNPC), name.c_str()); // prevent cheating Creature *pCreature = GetPlayer()->GetNPCIfCanInteractWith(guidNPC, UNIT_NPC_FLAG_PETITIONER); if (!pCreature) { sLog.outDebug("WORLD: HandlePetitionBuyOpcode - Unit (GUID: %u) not found or you can't interact with him.", GUID_LOPART(guidNPC)); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); uint32 charterid = 0; uint32 cost = 0; uint32 type = 0; if (pCreature->isTabardDesigner()) { // if tabard designer, then trying to buy a guild charter. // do not let if already in guild. if (_player->GetGuildId()) return; charterid = GUILD_CHARTER; cost = GUILD_CHARTER_COST; type = 9; } else { // TODO: find correct opcode if (_player->getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)) { SendNotification(LANG_ARENA_ONE_TOOLOW, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)); return; } switch (unk10) { case 1: charterid = ARENA_TEAM_CHARTER_2v2; cost = ARENA_TEAM_CHARTER_2v2_COST; type = 2; // 2v2 break; case 2: charterid = ARENA_TEAM_CHARTER_3v3; cost = ARENA_TEAM_CHARTER_3v3_COST; type = 3; // 3v3 break; case 3: charterid = ARENA_TEAM_CHARTER_5v5; cost = ARENA_TEAM_CHARTER_5v5_COST; type = 5; // 5v5 break; default: sLog.outDebug("unknown selection at buy petition: %u", unk10); return; } if (_player->GetArenaTeamId(unk10-1)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ALREADY_IN_ARENA_TEAM); return; } } if (type == 9) { if (sGuildMgr.GetGuildByName(name)) { SendGuildCommandResult(GUILD_CREATE_S, name, GUILD_NAME_EXISTS); return; } if (sObjectMgr.IsReservedName(name) || !ObjectMgr::IsValidCharterName(name)) { SendGuildCommandResult(GUILD_CREATE_S, name, GUILD_NAME_INVALID); return; } } else { if (sObjectMgr.GetArenaTeamByName(name)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_EXISTS_S); return; } if (sObjectMgr.IsReservedName(name) || !ObjectMgr::IsValidCharterName(name)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_INVALID); return; } } ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(charterid); if (!pProto) { _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, charterid, 0); return; } if (_player->GetMoney() < cost) { //player hasn't got enough money _player->SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, charterid, 0); return; } ItemPosCountVec dest; uint8 msg = _player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, charterid, pProto->BuyCount); if (msg != EQUIP_ERR_OK) { _player->SendBuyError(msg, pCreature, charterid, 0); return; } _player->ModifyMoney(-(int32)cost); Item *charter = _player->StoreNewItem(dest, charterid, true); if (!charter) return; charter->SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1, charter->GetGUIDLow()); // ITEM_FIELD_ENCHANTMENT_1_1 is guild/arenateam id // ITEM_FIELD_ENCHANTMENT_1_1+1 is current signatures count (showed on item) charter->SetState(ITEM_CHANGED, _player); _player->SendNewItem(charter, 1, true, false); // a petition is invalid, if both the owner and the type matches // we checked above, if this player is in an arenateam, so this must be // datacorruption QueryResultAutoPtr result = RealmDataDatabase.PQuery("SELECT petitionguid FROM petition WHERE ownerguid = '%u' AND type = '%u'", _player->GetGUIDLow(), type); std::ostringstream ssInvalidPetitionGUIDs; if (result) { do { Field *fields = result->Fetch(); ssInvalidPetitionGUIDs << "'" << fields[0].GetUInt32() << "' , "; } while (result->NextRow()); } // delete petitions with the same guid as this one ssInvalidPetitionGUIDs << "'" << charter->GetGUIDLow() << "'"; sLog.outDebug("Invalid petition GUIDs: %s", ssInvalidPetitionGUIDs.str().c_str()); RealmDataDatabase.escape_string(name); RealmDataDatabase.BeginTransaction(); RealmDataDatabase.PExecute("DELETE FROM petition WHERE petitionguid IN (%s)", ssInvalidPetitionGUIDs.str().c_str()); RealmDataDatabase.PExecute("DELETE FROM petition_sign WHERE petitionguid IN (%s)", ssInvalidPetitionGUIDs.str().c_str()); RealmDataDatabase.PExecute("INSERT INTO petition (ownerguid, petitionguid, name, type) VALUES ('%u', '%u', '%s', '%u')", _player->GetGUIDLow(), charter->GetGUIDLow(), name.c_str(), type); RealmDataDatabase.CommitTransaction(); } void WorldSession::HandlePetitionShowSignOpcode(WorldPacket & recv_data) { CHECK_PACKET_SIZE(recv_data, 8); // ok sLog.outDebug("Received opcode CMSG_PETITION_SHOW_SIGNATURES"); //recv_data.hexlike(); uint8 signs = 0; uint64 petitionguid; recv_data >> petitionguid; // petition guid // solve (possible) some strange compile problems with explicit use GUID_LOPART(petitionguid) at some GCC versions (wrong code optimization in compiler?) uint32 petitionguid_low = GUID_LOPART(petitionguid); QueryResultAutoPtr result = RealmDataDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", petitionguid_low); if (!result) { sLog.outLog(LOG_DEFAULT, "ERROR: any petition on server..."); return; } Field *fields = result->Fetch(); uint32 type = fields[0].GetUInt32(); // if guild petition and has guild => error, return; if (type==9 && _player->GetGuildId()) return; result = RealmDataDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", petitionguid_low); // result==NULL also correct in case no sign yet if (result) signs = result->GetRowCount(); sLog.outDebug("CMSG_PETITION_SHOW_SIGNATURES petition entry: '%u'", petitionguid_low); WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8+8+4+1+signs*12)); data << petitionguid; // petition guid data << _player->GetGUID(); // owner guid data << petitionguid_low; // guild guid (in Trinity always same as GUID_LOPART(petitionguid) data << signs; // sign's count for (uint8 i = 1; i <= signs; i++) { Field *fields2 = result->Fetch(); uint64 plguid = fields2[0].GetUInt64(); data << plguid; // Player GUID data << (uint32)0; // there 0 ... result->NextRow(); } SendPacket(&data); } void WorldSession::HandlePetitionQueryOpcode(WorldPacket & recv_data) { CHECK_PACKET_SIZE(recv_data, 4+8); sLog.outDebug("Received opcode CMSG_PETITION_QUERY"); // ok //recv_data.hexlike(); uint32 guildguid; uint64 petitionguid; recv_data >> guildguid; // in Trinity always same as GUID_LOPART(petitionguid) recv_data >> petitionguid; // petition guid sLog.outDebug("CMSG_PETITION_QUERY Petition GUID %u Guild GUID %u", GUID_LOPART(petitionguid), guildguid); SendPetitionQueryOpcode(petitionguid); } void WorldSession::SendPetitionQueryOpcode(uint64 petitionguid) { uint64 ownerguid = 0; uint32 type; std::string name = "NO_NAME_FOR_GUID"; uint8 signs = 0; QueryResultAutoPtr result = RealmDataDatabase.PQuery( "SELECT ownerguid, name, " " (SELECT COUNT(playerguid) FROM petition_sign WHERE petition_sign.petitionguid = '%u') AS signs, " " type " "FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid), GUID_LOPART(petitionguid)); if (result) { Field* fields = result->Fetch(); ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER); name = fields[1].GetCppString(); signs = fields[2].GetUInt8(); type = fields[3].GetUInt32(); } else { sLog.outDebug("CMSG_PETITION_QUERY failed for petition (GUID: %u)", GUID_LOPART(petitionguid)); return; } WorldPacket data(SMSG_PETITION_QUERY_RESPONSE, (4+8+name.size()+1+1+4*13)); data << GUID_LOPART(petitionguid); // guild/team guid (in Trinity always same as GUID_LOPART(petition guid) data << ownerguid; // charter owner guid data << name; // name (guild/arena team) data << uint8(0); // 1 if (type == 9) { data << uint32(9); data << uint32(9); data << uint32(0); // bypass client - side limitation, a different value is needed here for each petition } else { data << type-1; data << type-1; data << type; // bypass client - side limitation, a different value is needed here for each petition } data << uint32(0); // 5 data << uint32(0); // 6 data << uint32(0); // 7 data << uint32(0); // 8 data << uint16(0); // 9 2 bytes field data << uint32(0); // 10 data << uint32(0); // 11 data << uint32(0); // 13 count of next strings? data << uint32(0); // 14 if (type == 9) data << uint32(0); // 15 0 - guild, 1 - arena team else data << uint32(1); SendPacket(&data); } void WorldSession::HandlePetitionRenameOpcode(WorldPacket & recv_data) { CHECK_PACKET_SIZE(recv_data, 8+1); sLog.outDebug("Received opcode MSG_PETITION_RENAME"); // ok //recv_data.hexlike(); uint64 petitionguid; uint32 type; std::string newname; recv_data >> petitionguid; // guid recv_data >> newname; // new name Item *item = _player->GetItemByGuid(petitionguid); if (!item) return; QueryResultAutoPtr result = RealmDataDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); if (result) { Field* fields = result->Fetch(); type = fields[0].GetUInt32(); } else { sLog.outDebug("CMSG_PETITION_QUERY failed for petition (GUID: %u)", GUID_LOPART(petitionguid)); return; } if (type == 9) { if (sGuildMgr.GetGuildByName(newname)) { SendGuildCommandResult(GUILD_CREATE_S, newname, GUILD_NAME_EXISTS); return; } if (sObjectMgr.IsReservedName(newname) || !ObjectMgr::IsValidCharterName(newname)) { SendGuildCommandResult(GUILD_CREATE_S, newname, GUILD_NAME_INVALID); return; } } else { if (sObjectMgr.GetArenaTeamByName(newname)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, newname, "", ERR_ARENA_TEAM_NAME_EXISTS_S); return; } if (sObjectMgr.IsReservedName(newname) || !ObjectMgr::IsValidCharterName(newname)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, newname, "", ERR_ARENA_TEAM_NAME_INVALID); return; } } std::string db_newname = newname; RealmDataDatabase.escape_string(db_newname); RealmDataDatabase.PExecute("UPDATE petition SET name = '%s' WHERE petitionguid = '%u'", db_newname.c_str(), GUID_LOPART(petitionguid)); sLog.outDebug("Petition (GUID: %u) renamed to '%s'", GUID_LOPART(petitionguid), newname.c_str()); WorldPacket data(MSG_PETITION_RENAME, (8+newname.size()+1)); data << petitionguid; data << newname; SendPacket(&data); } void WorldSession::HandlePetitionSignOpcode(WorldPacket & recv_data) { CHECK_PACKET_SIZE(recv_data, 8+1); sLog.outDebug("Received opcode CMSG_PETITION_SIGN"); // ok //recv_data.hexlike(); Field *fields; uint64 petitionguid; uint8 unk; recv_data >> petitionguid; // petition guid recv_data >> unk; QueryResultAutoPtr result = RealmDataDatabase.PQuery( "SELECT ownerguid, " " (SELECT COUNT(playerguid) FROM petition_sign WHERE petition_sign.petitionguid = '%u') AS signs, " " type " "FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid), GUID_LOPART(petitionguid)); if (!result) { sLog.outLog(LOG_DEFAULT, "ERROR: any petition on server..."); return; } fields = result->Fetch(); uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER); uint8 signs = fields[1].GetUInt8(); uint32 type = fields[2].GetUInt32(); uint32 plguidlo = _player->GetGUIDLow(); if (GUID_LOPART(ownerguid) == plguidlo) return; // not let enemies sign guild charter if (!sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && GetPlayer()->GetTeam() != sObjectMgr.GetPlayerTeamByGUID(ownerguid)) { if (type != 9) SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", "", ERR_ARENA_TEAM_NOT_ALLIED); else SendGuildCommandResult(GUILD_CREATE_S, "", GUILD_NOT_ALLIED); return; } if (type != 9) { if (_player->getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, "", _player->GetName(), ERR_ARENA_TEAM_PLAYER_TO_LOW); return; } uint8 slot = ArenaTeam::GetSlotByType(type); if (slot >= MAX_ARENA_SLOT) return; if (_player->GetArenaTeamId(slot)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_IN_ARENA_TEAM_S); return; } if (_player->GetArenaTeamIdInvited()) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_INVITED_TO_ARENA_TEAM_S); return; } } else { if (_player->GetGuildId()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ALREADY_IN_GUILD); return; } if (_player->GetGuildIdInvited()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ALREADY_INVITED_TO_GUILD); return; } } if (++signs > type) // client signs maximum return; //client doesn't allow to sign petition two times by one character, but not check sign by another character from same account //not allow sign another player from already sign player account result = RealmDataDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE player_account = '%u' AND petitionguid = '%u'", GetAccountId(), GUID_LOPART(petitionguid)); if (result) { WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8+8+4)); data << petitionguid; data << _player->GetGUID(); data << (uint32)PETITION_SIGN_ALREADY_SIGNED; // close at signer side SendPacket(&data); // update for owner if online if (Player *owner = sObjectMgr.GetPlayer(ownerguid)) owner->SendPacketToSelf(&data); return; } RealmDataDatabase.PExecute("INSERT INTO petition_sign (ownerguid,petitionguid, playerguid, player_account) VALUES ('%u', '%u', '%u','%u')", GUID_LOPART(ownerguid),GUID_LOPART(petitionguid), plguidlo,GetAccountId()); sLog.outDebug("PETITION SIGN: GUID %u by player: %s (GUID: %u Account: %u)", GUID_LOPART(petitionguid), _player->GetName(),plguidlo,GetAccountId()); WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8+8+4)); data << petitionguid; data << _player->GetGUID(); data << (uint32)PETITION_SIGN_OK; // close at signer side SendPacket(&data); // update signs count on charter, required testing... //Item *item = _player->GetItemByGuid(petitionguid)); //if(item) // item->SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1+1, signs); // update for owner if online if (Player *owner = sObjectMgr.GetPlayer(ownerguid)) owner->SendPacketToSelf(&data); } void WorldSession::HandlePetitionDeclineOpcode(WorldPacket & recv_data) { CHECK_PACKET_SIZE(recv_data, 8); sLog.outDebug("Received opcode MSG_PETITION_DECLINE"); // ok //recv_data.hexlike(); uint64 petitionguid; uint64 ownerguid; recv_data >> petitionguid; // petition guid sLog.outDebug("Petition %u declined by %u", GUID_LOPART(petitionguid), _player->GetGUIDLow()); QueryResultAutoPtr result = RealmDataDatabase.PQuery("SELECT ownerguid FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); if (!result) return; Field *fields = result->Fetch(); ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER); Player *owner = sObjectMgr.GetPlayer(ownerguid); if (owner) // petition owner online { WorldPacket data(MSG_PETITION_DECLINE, 8); data << _player->GetGUID(); owner->SendPacketToSelf(&data); } } void WorldSession::HandleOfferPetitionOpcode(WorldPacket & recv_data) { CHECK_PACKET_SIZE(recv_data, 4+8+8); sLog.outDebug("Received opcode CMSG_OFFER_PETITION"); // ok //recv_data.hexlike(); uint8 signs = 0; uint64 petitionguid, plguid; uint32 type, junk; Player *player; recv_data >> junk; // this is not petition type! recv_data >> petitionguid; // petition guid recv_data >> plguid; // player guid player = ObjectAccessor::FindPlayer(plguid); if (!player) return; QueryResultAutoPtr result = RealmDataDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); if (!result) return; Field *fields = result->Fetch(); type = fields[0].GetUInt32(); sLog.outDebug("OFFER PETITION: type %u, GUID1 %u, to player id: %u", type, GUID_LOPART(petitionguid), GUID_LOPART(plguid)); if (!sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && GetPlayer()->GetTeam() != player->GetTeam()) { if (type != 9) SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", "", ERR_ARENA_TEAM_NOT_ALLIED); else SendGuildCommandResult(GUILD_CREATE_S, "", GUILD_NOT_ALLIED); return; } if (type != 9) { if (player->getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL)) { // player is too low level to join an arena team SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, player->GetName(), "", ERR_ARENA_TEAM_PLAYER_TO_LOW); return; } uint8 slot = ArenaTeam::GetSlotByType(type); if (slot >= MAX_ARENA_SLOT) return; if (player->GetArenaTeamId(slot)) { // player is already in an arena team SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, player->GetName(), "", ERR_ALREADY_IN_ARENA_TEAM_S); return; } if (player->GetArenaTeamIdInvited()) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_INVITED_TO_ARENA_TEAM_S); return; } } else { if (player->GetGuildId()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ALREADY_IN_GUILD); return; } if (player->GetGuildIdInvited()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ALREADY_INVITED_TO_GUILD); return; } } result = RealmDataDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); // result==NULL also correct charter without signs if (result) signs = result->GetRowCount(); WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8+8+4+signs+signs*12)); data << petitionguid; // petition guid data << _player->GetGUID(); // owner guid data << GUID_LOPART(petitionguid); // guild guid (in Trinity always same as GUID_LOPART(petition guid) data << signs; // sign's count for (uint8 i = 1; i <= signs; i++) { Field *fields2 = result->Fetch(); uint64 plguid = fields2[0].GetUInt64(); data << plguid; // Player GUID data << (uint32)0; // there 0 ... result->NextRow(); } player->SendPacketToSelf(&data); } void WorldSession::HandleTurnInPetitionOpcode(WorldPacket & recv_data) { CHECK_PACKET_SIZE(recv_data, 8); sLog.outDebug("Received opcode CMSG_TURN_IN_PETITION"); // ok //recv_data.hexlike(); WorldPacket data; uint64 petitionguid; uint32 ownerguidlo; uint32 type; std::string name; recv_data >> petitionguid; sLog.outDebug("Petition %u turned in by %u", GUID_LOPART(petitionguid), _player->GetGUIDLow()); // data QueryResultAutoPtr result = RealmDataDatabase.PQuery("SELECT ownerguid, name, type FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); if (result) { Field *fields = result->Fetch(); ownerguidlo = fields[0].GetUInt32(); name = fields[1].GetCppString(); type = fields[2].GetUInt32(); } else { sLog.outLog(LOG_DEFAULT, "ERROR: petition table has broken data!"); return; } if (type == 9) { if (_player->GetGuildId()) { data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); data << (uint32)PETITION_TURN_ALREADY_IN_GUILD; // already in guild _player->SendPacketToSelf(&data); return; } } else { uint8 slot = ArenaTeam::GetSlotByType(type); if (slot >= MAX_ARENA_SLOT) return; if (_player->GetArenaTeamId(slot)) { //data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); //data << (uint32)PETITION_TURN_ALREADY_IN_GUILD; // already in guild //_player->BroadcastPacketToSelf(&data); SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ALREADY_IN_ARENA_TEAM); return; } } if (_player->GetGUIDLow() != ownerguidlo) return; // signs uint8 signs; result = RealmDataDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); if (result) signs = result->GetRowCount(); else signs = 0; uint32 count; //if(signs < sWorld.getConfig(CONFIG_MIN_PETITION_SIGNS)) if (type == 9) count = sWorld.getConfig(CONFIG_MIN_PETITION_SIGNS); else count = type-1; if (signs < count) { data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); data << (uint32)PETITION_TURN_NEED_MORE_SIGNATURES; // need more signatures... SendPacket(&data); return; } if (type == 9) { if (sGuildMgr.GetGuildByName(name)) { SendGuildCommandResult(GUILD_CREATE_S, name, GUILD_NAME_EXISTS); return; } } else { if (sObjectMgr.GetArenaTeamByName(name)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_EXISTS_S); return; } } // and at last charter item check Item *item = _player->GetItemByGuid(petitionguid); if (!item) return; // OK! // delete charter item _player->DestroyItem(item->GetBagSlot(),item->GetSlot(), true); if (type == 9) // create guild { Guild* guild = new Guild; if (!guild->create(_player->GetGUID(), name)) { delete guild; return; } // register guild and add guildmaster sGuildMgr.AddGuild(guild); // add members for (uint8 i = 0; i < signs; ++i) { Field* fields = result->Fetch(); guild->AddMember(fields[0].GetUInt64(), guild->GetLowestRank()); result->NextRow(); } } else // or arena team { ArenaTeam* at = new ArenaTeam; if (!at->Create(_player->GetGUID(), type, name)) { sLog.outLog(LOG_DEFAULT, "ERROR: PetitionsHandler: arena team create failed."); delete at; return; } CHECK_PACKET_SIZE(recv_data, 8+5*4); uint32 icon, iconcolor, border, bordercolor, backgroud; recv_data >> backgroud >> icon >> iconcolor >> border >> bordercolor; at->SetEmblem(backgroud, icon, iconcolor, border, bordercolor); // register team and add captain sObjectMgr.AddArenaTeam(at); sLog.outDebug("PetitonsHandler: arena team added to objmrg"); // add members for (uint8 i = 0; i < signs; ++i) { Field* fields = result->Fetch(); uint64 memberGUID = fields[0].GetUInt64(); sLog.outDebug("PetitionsHandler: adding arena member %u", GUID_LOPART(memberGUID)); at->AddMember(memberGUID); result->NextRow(); } } RealmDataDatabase.BeginTransaction(); RealmDataDatabase.PExecute("DELETE FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); RealmDataDatabase.PExecute("DELETE FROM petition_sign WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); RealmDataDatabase.CommitTransaction(); // created sLog.outDebug("TURN IN PETITION GUID %u", GUID_LOPART(petitionguid)); data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); data << (uint32)PETITION_TURN_OK; SendPacket(&data); } void WorldSession::HandlePetitionShowListOpcode(WorldPacket & recv_data) { CHECK_PACKET_SIZE(recv_data, 8); sLog.outDebug("Received CMSG_PETITION_SHOWLIST"); // ok //recv_data.hexlike(); uint64 guid; recv_data >> guid; SendPetitionShowList(guid); } void WorldSession::SendPetitionShowList(uint64 guid) { Creature *pCreature = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_PETITIONER); if (!pCreature) { sLog.outDebug("WORLD: HandlePetitionShowListOpcode - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); uint8 count = 0; if (pCreature->isTabardDesigner()) count = 1; else count = 3; WorldPacket data(SMSG_PETITION_SHOWLIST, 8+1+4*6); data << guid; // npc guid data << count; // count if (count == 1) { data << uint32(1); // index data << uint32(GUILD_CHARTER); // charter entry data << uint32(16161); // charter display id data << uint32(GUILD_CHARTER_COST); // charter cost data << uint32(0); // unknown data << uint32(9); // required signs? } else { // 2v2 data << uint32(1); // index data << uint32(ARENA_TEAM_CHARTER_2v2); // charter entry data << uint32(16161); // charter display id data << uint32(ARENA_TEAM_CHARTER_2v2_COST); // charter cost data << uint32(2); // unknown data << uint32(2); // required signs? // 3v3 data << uint32(2); // index data << uint32(ARENA_TEAM_CHARTER_3v3); // charter entry data << uint32(16161); // charter display id data << uint32(ARENA_TEAM_CHARTER_3v3_COST); // charter cost data << uint32(3); // unknown data << uint32(3); // required signs? // 5v5 data << uint32(3); // index data << uint32(ARENA_TEAM_CHARTER_5v5); // charter entry data << uint32(16161); // charter display id data << uint32(ARENA_TEAM_CHARTER_5v5_COST); // charter cost data << uint32(5); // unknown data << uint32(5); // required signs? } //for (uint8 i = 0; i < count; i++) //{ // data << uint32(i); // index // data << uint32(GUILD_CHARTER); // charter entry // data << uint32(16161); // charter display id // data << uint32(GUILD_CHARTER_COST+i); // charter cost // data << uint32(0); // unknown // data << uint32(9); // required signs? //} SendPacket(&data); sLog.outDebug("Sent SMSG_PETITION_SHOWLIST"); }
superwow/hell.core
src/game/PetitionsHandler.cpp
C++
gpl-2.0
34,383
<?php /* +----------------------------------------------------------------+ | | | WordPress Plugin: WP-PostRatings | | Copyright (c) 2012 Lester "GaMerZ" Chan | | | | File Written By: | | - Lester "GaMerZ" Chan | | - http://lesterchan.net | | | | File Information: | | - Manage Post Ratings Logs | | - wp-content/plugins/wp-postratings/postratings-manager.php | | | +----------------------------------------------------------------+ */ // Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) exit; // Check Whether User Can Manage Ratings if ( ! current_user_can( 'manage_ratings' ) ) die( 'Access Denied' ); $base_name = plugin_basename( 'wp-postratings/postratings-manager.php' ); $base_page = admin_url( 'admin.php?page=' . urlencode( $base_name ) ); $postratings_sort_url = ''; $postratings_sortby_text = ''; $postratings_sortorder_text = ''; $ratings_image = get_option( 'postratings_image' ); $ratings_max = intval( get_option( 'postratings_max' ) ); // Handle $_GET values $postratings_filterid = isset( $_GET['id'] ) ? intval( $_GET['id'] ) : 0; $postratings_filterrating = isset( $_GET['rating'] ) ? intval( $_GET['rating'] ) : 0; $postratings_filteruser = isset( $_GET['user'] ) ? sanitize_text_field( $_GET['user'] ) : ''; $postratings_log_perpage = isset( $_GET['perpage'] ) ? intval( $_GET['perpage'] ) : 20; $postratings_page = ! empty( $_GET['ratingpage'] ) ? intval( $_GET['ratingpage'] ) : 1; $postratings_sortby = 'rating_timestamp'; $postratings_sortorder = 'DESC'; // For BY and ORDER, only accept data from a finite list of known and trusted values. if ( isset( $_GET['by'] ) && in_array( $_GET['by'], array( 'date', 'host', 'id', 'ip', 'postid', 'posttitle', 'rating', 'username', ) ) ) $postratings_sortby = $_GET['by']; if ( isset( $_GET['order'] ) && in_array( $_GET['order'], array( 'asc', 'desc', ) ) ) $postratings_sortorder = $_GET['order']; ### Form Processing if ( ! empty( $_POST['do'] ) ) { check_admin_referer('wp-postratings_logs'); $delete_datalog = isset( $_POST['delete_datalog'] ) ? (int) $_POST['delete_datalog'] : 1; $post_ids = ''; $post_ids_list = array(); $ratings_postmeta = array( 'ratings_users', 'ratings_score', 'ratings_average', ); // delete_postid is either a comma-separated list of integers, or "all". if ( ! empty( $_POST['delete_postid'] ) ) { // "all" is the only string value accepted if ( $_POST['delete_postid'] != 'all' ) { $post_ids_list = wp_parse_id_list( $_POST['delete_postid'] ); $post_ids = implode( ',', $post_ids_list ); } else { $post_ids = 'all'; } } switch($delete_datalog) { case 1: if($post_ids == 'all') { $delete_logs = $wpdb->query("DELETE FROM $wpdb->ratings"); if($delete_logs) { $text = '<font color="green">'.__('All Post Ratings Logs Have Been Deleted.', 'wp-postratings').'</font>'; } else { $text = '<font color="red">'.__('An Error Has Occured While Deleting All Post Ratings Logs.', 'wp-postratings').'</font>'; } } else { $delete_logs = $wpdb->query( "DELETE FROM {$wpdb->ratings} WHERE rating_postid IN (" . $post_ids . ')' ); if($delete_logs) { $text = '<font color="green">'.sprintf(__('All Post Ratings Logs For Post ID(s) %s Have Been Deleted.', 'wp-postratings'), $post_ids).'</font>'; } else { $text = '<font color="red">'.sprintf(__('An Error Has Occured While Deleting All Post Ratings Logs For Post ID(s) %s.', 'wp-postratings'), $post_ids).'</font>'; } } break; case 2: // @todo Deleting meta records like will not clear the post's object cache if($post_ids == 'all') { foreach($ratings_postmeta as $postmeta) { $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->postmeta} WHERE meta_key = %s", $postmeta ) ); $text .= '<font color="green">'.sprintf(__('Rating Data "%s" Has Been Deleted.', 'wp-postratings'), "<strong><em>$postmeta</em></strong>").'</font><br />'; } } else { foreach ( $post_ids_list as $the_post_id ) { foreach( $ratings_postmeta as $meta_key ) { delete_post_meta( $the_post_id, $meta_key ); $text .= '<font color="green">'.sprintf(__('Rating Data "%s" For Post ID(s) %s Has Been Deleted.', 'wp-postratings'), "<strong><em>$meta_key</em></strong>", $post_ids).'</font><br />'; } } } break; case 3: if($post_ids == 'all') { $delete_logs = $wpdb->query("DELETE FROM $wpdb->ratings"); if($delete_logs) { $text = '<font color="green">'.__('All Post Ratings Logs Have Been Deleted.', 'wp-postratings').'</font><br />'; } else { $text = '<font color="red">'.__('An Error Has Occured While Deleting All Post Ratings Logs.', 'wp-postratings').'</font><br />'; } // @todo Deleting meta records like will not clear the post's object cache foreach($ratings_postmeta as $postmeta) { $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->postmeta} WHERE meta_key = %s", $postmeta ) ); $text .= '<font color="green">'.sprintf(__('Rating Data "%s" Has Been Deleted.', 'wp-postratings'), "<strong><em>$postmeta</em></strong>").'</font><br />'; } } else { $delete_logs = $wpdb->query( "DELETE FROM {$wpdb->ratings} WHERE rating_postid IN (" . $post_ids . ')' ); if($delete_logs) { $text = '<font color="green">'.sprintf(__('All Post Ratings Logs For Post ID(s) %s Have Been Deleted.', 'wp-postratings'), $post_ids).'</font><br />'; } else { $text = '<font color="red">'.sprintf(__('An Error Has Occured While Deleting All Post Ratings Logs For Post ID(s) %s.', 'wp-postratings'), $post_ids).'</font><br />'; } foreach ( $post_ids_list as $the_post_id ) { foreach( $ratings_postmeta as $meta_key ) { delete_post_meta( $the_post_id, $meta_key ); $text .= '<font color="green">'.sprintf(__('Rating Data "%s" For Post ID(s) %s Has Been Deleted.', 'wp-postratings'), "<strong><em>$meta_key</em></strong>", $post_ids).'</font><br />'; } } } break; } } // if ( ! empty( $_POST['do'] ) ) ### Form Sorting URL // @todo Use add_query_arg() for these if(!empty($postratings_filterid)) { $postratings_sort_url .= '&amp;id='.$postratings_filterid; } if(!empty($postratings_filteruser)) { $postratings_sort_url .= '&amp;user='.urlencode( $postratings_filteruser ); } if ( ! empty( $postratings_filterrating ) ) { $postratings_sort_url .= '&amp;rating='.$postratings_filterrating; } if(!empty($postratings_sortby)) { $postratings_sort_url .= '&amp;by='.urlencode( $postratings_sortby ); } if(!empty($postratings_sortorder)) { $postratings_sort_url .= '&amp;order='.urlencode( $postratings_sortorder ); } if(!empty($postratings_log_perpage)) { $postratings_sort_url .= '&amp;perpage='.$postratings_log_perpage; } ### Get Order By switch($postratings_sortby) { case 'id': $postratings_sortby = 'rating_id'; $postratings_sortby_text = __('ID', 'wp-postratings'); break; case 'username': $postratings_sortby = 'rating_username'; $postratings_sortby_text = __('Username', 'wp-postratings'); break; case 'rating': $postratings_sortby = 'rating_rating'; $postratings_sortby_text = __('Rating', 'wp-postratings'); break; case 'postid': $postratings_sortby = 'rating_postid'; $postratings_sortby_text = __('Post ID', 'wp-postratings'); break; case 'posttitle': $postratings_sortby = 'rating_posttitle'; $postratings_sortby_text = __('Post Title', 'wp-postratings'); break; case 'ip': $postratings_sortby = 'rating_ip'; $postratings_sortby_text = __('IP', 'wp-postratings'); break; case 'host': $postratings_sortby = 'rating_host'; $postratings_sortby_text = __('Host', 'wp-postratings'); break; case 'date': default: $postratings_sortby = 'rating_timestamp'; $postratings_sortby_text = __('Date', 'wp-postratings'); } ### Get Sort Order if ( $postratings_sortorder == 'ASC' ) $postratings_sortorder_text = __('Ascending', 'wp-postratings'); else $postratings_sortorder_text = __('Descending', 'wp-postratings'); // Where $postratings_where = ''; if ( $postratings_filterid ) $postratings_where = $wpdb->prepare( "AND rating_postid = %d", $postratings_filterid );; if ( ! empty( $postratings_filteruser ) ) $postratings_where .= $wpdb->prepare( " AND rating_username = %s", $postratings_filteruser ); if ( ! empty( $postratings_filterrating ) ) $postratings_where .= $wpdb->prepare( " AND rating_rating = %d", $postratings_filterrating ); // Get Post Ratings Logs Data $total_ratings = $wpdb->get_var("SELECT COUNT(rating_id) FROM $wpdb->ratings WHERE 1=1 $postratings_where"); $total_users = $wpdb->get_var("SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = 'ratings_users'"); $total_score = $wpdb->get_var("SELECT SUM((meta_value+0.00)) FROM $wpdb->postmeta WHERE meta_key = 'ratings_score'"); $ratings_custom = intval(get_option('postratings_customrating')); if($total_users == 0) { $total_average = 0; } else { $total_average = $total_score/$total_users; } // Determin $offset $offset = ($postratings_page-1) * $postratings_log_perpage; // Determine Max Number Of Ratings To Display On Page if(($offset + $postratings_log_perpage) > $total_ratings) { $max_on_page = $total_ratings; } else { $max_on_page = ($offset + $postratings_log_perpage); } // Determine Number Of Ratings To Display On Page if (($offset + 1) > ($total_ratings)) { $display_on_page = $total_ratings; } else { $display_on_page = ($offset + 1); } // Determing Total Amount Of Pages $total_pages = ceil($total_ratings / $postratings_log_perpage); // Get The Logs $postratings_logs = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->ratings} WHERE 1=1 {$postratings_where} ORDER BY {$postratings_sortby} {$postratings_sortorder} LIMIT %d, %d", $offset, $postratings_log_perpage ) ); ?> <?php if(!empty($text)) { echo '<!-- Last Action --><div id="message" class="updated fade"><p>'.$text.'</p></div>'; } ?> <!-- Manage Post Ratings --> <div class="wrap"> <h2><?php _e('Manage Ratings', 'wp-postratings'); ?></h2> <h3><?php _e('Post Ratings Logs', 'wp-postratings'); ?></h3> <p><?php printf(__('Displaying <strong>%s</strong> to <strong>%s</strong> of <strong>%s</strong> Post Ratings log entries.', 'wp-postratings'), number_format_i18n($display_on_page), number_format_i18n($max_on_page), number_format_i18n($total_ratings)); ?></p> <p><?php printf(__('Sorted by <strong>%s</strong> in <strong>%s</strong> order.', 'wp-postratings'), $postratings_sortby_text, $postratings_sortorder_text); ?></p> <table class="widefat"> <thead> <tr> <th width="2%"><?php _e('ID', 'wp-postratings'); ?></th> <th width="10%"><?php _e('Username', 'wp-postratings'); ?></th> <th width="10%"><?php _e('Rating', 'wp-postratings'); ?></th> <th width="8%"><?php _e('Post ID', 'wp-postratings'); ?></th> <th width="25%"><?php _e('Post Title', 'wp-postratings'); ?></th> <th width="20%"><?php _e('Date / Time', 'wp-postratings'); ?></th> <th width="25%"><?php _e('IP / Host', 'wp-postratings'); ?></th> </tr> </thead> <tbody> <?php if($postratings_logs) { $i = 0; foreach($postratings_logs as $postratings_log) { if($i%2 == 0) { $style = 'class="alternate"'; } else { $style = ''; } $postratings_id = intval($postratings_log->rating_id); $postratings_username = stripslashes($postratings_log->rating_username); $postratings_rating = intval($postratings_log->rating_rating); $postratings_postid = intval($postratings_log->rating_postid); $postratings_posttitle = stripslashes($postratings_log->rating_posttitle); $postratings_date = mysql2date(sprintf(__('%s @ %s', 'wp-postratings'), get_option('date_format'), get_option('time_format')), gmdate('Y-m-d H:i:s', $postratings_log->rating_timestamp)); $postratings_ip = $postratings_log->rating_ip; $postratings_host = $postratings_log->rating_host; echo "<tr $style>\n"; echo '<td>'.$postratings_id.'</td>'."\n"; echo "<td>$postratings_username</td>\n"; echo '<td nowrap="nowrap">'; if($ratings_custom && $ratings_max == 2) { if($postratings_rating > 0) { $postratings_rating = '+'.$postratings_rating; } echo $postratings_rating; } else { if('rtl' == $text_direction && file_exists(WP_PLUGIN_DIR.'/wp-postratings/images/'.$ratings_image.'/rating_start-rtl.'.RATINGS_IMG_EXT)) { echo '<img src="'.plugins_url('wp-postratings/images/'.$ratings_image.'/rating_start-rtl.'.RATINGS_IMG_EXT).'" alt="" class="post-ratings-image" />'; } elseif(file_exists(WP_PLUGIN_DIR.'/wp-postratings/images/'.$ratings_image.'/rating_start.'.RATINGS_IMG_EXT)) { echo '<img src="'.plugins_url('wp-postratings/images/'.$ratings_image.'/rating_start.'.RATINGS_IMG_EXT).'" alt="" class="post-ratings-image" />'; } if($ratings_custom) { for($j=1; $j <= $ratings_max; $j++) { if($j <= $postratings_rating) { echo '<img src="'.plugins_url('wp-postratings/images/'.$ratings_image.'/rating_'.$j.'_on.'.RATINGS_IMG_EXT).'" alt="'.sprintf(_n('User Rate This Post %s Star', 'User Rate This Post %s Stars', $postratings_rating, 'wp-postratings'), $postratings_rating).__(' Out Of ', 'wp-postratings').$ratings_max.'" title="'.sprintf(_n('User Rate This Post %s Star', 'User Rate This Post %s Stars', $postratings_rating, 'wp-postratings'), $postratings_rating).__(' Out Of ', 'wp-postratings').$ratings_max.'" class="post-ratings-image" />'; } else { echo '<img src="'.plugins_url('wp-postratings/images/'.$ratings_image.'/rating_'.$j.'_off.'.RATINGS_IMG_EXT).'" alt="'.sprintf(_n('User Rate This Post %s Star', 'User Rate This Post %s Stars', $postratings_rating, 'wp-postratings'), $postratings_rating).__(' Out Of ', 'wp-postratings').$ratings_max.'" title="'.sprintf(_n('User Rate This Post %s Star', 'User Rate This Post %s Stars', $postratings_rating, 'wp-postratings'), $postratings_rating).__(' Out Of ', 'wp-postratings').$ratings_max.'" class="post-ratings-image" />'; } } } else { for($j=1; $j <= $ratings_max; $j++) { if($j <= $postratings_rating) { echo '<img src="'.plugins_url('wp-postratings/images/'.$ratings_image.'/rating_on.'.RATINGS_IMG_EXT).'" alt="'.sprintf(_n('User Rate This Post %s Star', 'User Rate This Post %s Stars', $postratings_rating, 'wp-postratings'), $postratings_rating).__(' Out Of ', 'wp-postratings').$ratings_max.'" title="'.sprintf(_n('User Rate This Post %s Star', 'User Rate This Post %s Stars', $postratings_rating, 'wp-postratings'), $postratings_rating).__(' Out Of ', 'wp-postratings').$ratings_max.'" class="post-ratings-image" />'; } else { echo '<img src="'.plugins_url('wp-postratings/images/'.$ratings_image.'/rating_off.'.RATINGS_IMG_EXT).'" alt="'.sprintf(_n('User Rate This Post %s Star', 'User Rate This Post %s Stars', $postratings_rating, 'wp-postratings'), $postratings_rating).__(' Out Of ', 'wp-postratings').$ratings_max.'" title="'.sprintf(_n('User Rate This Post %s Star', 'User Rate This Post %s Stars', $postratings_rating, 'wp-postratings'), $postratings_rating).__(' Out Of ', 'wp-postratings').$ratings_max.'" class="post-ratings-image" />'; } } } if('rtl' == $text_direction && file_exists(WP_PLUGIN_DIR.'/wp-postratings/images/'.$ratings_image.'/rating_end-rtl.'.RATINGS_IMG_EXT)) { echo '<img src="'.plugins_url('wp-postratings/images/'.$ratings_image.'/rating_end-rtl.'.RATINGS_IMG_EXT).'" alt="" class="post-ratings-image" />'; } elseif(file_exists(WP_PLUGIN_DIR.'/wp-postratings/images/'.$ratings_image.'/rating_end.'.RATINGS_IMG_EXT)) { echo '<img src="'.plugins_url('wp-postratings/images/'.$ratings_image.'/rating_end.'.RATINGS_IMG_EXT).'" alt="" class="post-ratings-image" />'; } } echo '</td>'."\n"; echo '<td>'.number_format_i18n($postratings_postid).'</td>'."\n"; echo "<td>$postratings_posttitle</td>\n"; echo "<td>$postratings_date</td>\n"; echo "<td>$postratings_ip / $postratings_host</td>\n"; echo '</tr>'; $i++; } } else { echo '<tr><td colspan="7" align="center"><strong>'.__('No Post Ratings Logs Found', 'wp-postratings').'</strong></td></tr>'; } ?> </tbody> </table> <!-- <Paging> --> <?php if($total_pages > 1) { ?> <br /> <table class="widefat"> <tr> <td align="<?php echo ('rtl' == $text_direction) ? 'right' : 'left'; ?>" width="50%"> <?php if($postratings_page > 1 && ((($postratings_page*$postratings_log_perpage)-($postratings_log_perpage-1)) <= $total_ratings)) { echo '<strong>&laquo;</strong> <a href="'.$base_page.'&amp;ratingpage='.($postratings_page-1).$postratings_sort_url.'" title="&laquo; '.__('Previous Page', 'wp-postratings').'">'.__('Previous Page', 'wp-postratings').'</a>'; } else { echo '&nbsp;'; } ?> </td> <td align="<?php echo ('rtl' == $text_direction) ? 'left' : 'right'; ?>" width="50%"> <?php if($postratings_page >= 1 && ((($postratings_page*$postratings_log_perpage)+1) <= $total_ratings)) { echo '<a href="'.$base_page.'&amp;ratingpage='.($postratings_page+1).$postratings_sort_url.'" title="'.__('Next Page', 'wp-postratings').' &raquo;">'.__('Next Page', 'wp-postratings').'</a> <strong>&raquo;</strong>'; } else { echo '&nbsp;'; } ?> </td> </tr> <tr class="alternate"> <td colspan="2" align="center"> <?php printf(__('Pages (%s): ', 'wp-postratings'), number_format_i18n($total_pages)); ?> <?php if ($postratings_page >= 4) { echo '<strong><a href="'.$base_page.'&amp;ratingpage=1'.$postratings_sort_url.$postratings_sort_url.'" title="'.__('Go to First Page', 'wp-postratings').'">&laquo; '.__('First', 'wp-postratings').'</a></strong> ... '; } if($postratings_page > 1) { echo ' <strong><a href="'.$base_page.'&amp;ratingpage='.($postratings_page-1).$postratings_sort_url.'" title="&laquo; '.__('Go to Page', 'wp-postratings').' '.number_format_i18n($postratings_page-1).'">&laquo;</a></strong> '; } for($i = $postratings_page - 2 ; $i <= $postratings_page +2; $i++) { if ($i >= 1 && $i <= $total_pages) { if($i == $postratings_page) { echo '<strong>['.number_format_i18n($i).']</strong> '; } else { echo '<a href="'.$base_page.'&amp;ratingpage='.($i).$postratings_sort_url.'" title="'.__('Page', 'wp-postratings').' '.number_format_i18n($i).'">'.number_format_i18n($i).'</a> '; } } } if($postratings_page < $total_pages) { echo ' <strong><a href="'.$base_page.'&amp;ratingpage='.($postratings_page+1).$postratings_sort_url.'" title="'.__('Go to Page', 'wp-postratings').' '.number_format_i18n($postratings_page+1).' &raquo;">&raquo;</a></strong> '; } if (($postratings_page+2) < $total_pages) { echo ' ... <strong><a href="'.$base_page.'&amp;ratingpage='.($total_pages).$postratings_sort_url.'" title="'.__('Go to Last Page', 'wp-postratings').'">'.__('Last', 'wp-postratings').' &raquo;</a></strong>'; } ?> </td> </tr> </table> <!-- </Paging> --> <?php } ?> <br /> <form action="<?php echo esc_url( $base_page ); ?>" method="get"> <input type="hidden" name="page" value="<?php echo $base_name; ?>" /> <table class="widefat"> <tr> <th><?php _e('Filter Options:', 'wp-postratings'); ?></th> <td> <?php _e('Post ID:', 'wp-postratings'); ?>&nbsp;<input type="text" name="id" value="<?php echo $postratings_filterid; ?>" size="5" maxlength="5" /> &nbsp;&nbsp;&nbsp; <select name="user" size="1"> <option value=""></option> <?php $filter_users = $wpdb->get_results( $wpdb->prepare( "SELECT DISTINCT rating_username, rating_userid FROM {$wpdb->ratings} WHERE rating_username != %s ORDER BY rating_userid ASC, rating_username ASC", __(' Guest', 'wp-postratings' ) ) ); if($filter_users) { foreach($filter_users as $filter_user) { $rating_username = stripslashes($filter_user->rating_username); $rating_userid = intval($filter_user->rating_userid); if($rating_userid > 0) { $prefix = __('Registered User: ', 'wp-postratings'); } else { $prefix = __('Comment Author: ', 'wp-postratings'); } if($rating_username == $postratings_filteruser) { echo '<option value="'.esc_attr($rating_username).'" selected="selected">'.$prefix.' '.$rating_username.'</option>'."\n"; } else { echo '<option value="'.esc_attr($rating_username).'">'.$prefix.' '.$rating_username.'</option>'."\n"; } } } ?> </select> &nbsp;&nbsp;&nbsp; <select name="rating" size="1"> <option value=""></option> <?php $filter_ratings = $wpdb->get_results("SELECT DISTINCT rating_rating FROM $wpdb->ratings ORDER BY rating_rating ASC"); if($filter_ratings) { foreach($filter_ratings as $filter_rating) { $rating_rating = $filter_rating->rating_rating; $prefix = __('Rating: ', 'wp-postratings'); if($rating_rating == $postratings_filterrating) { echo '<option value="'.$rating_rating.'" selected="selected">'.$prefix.' '.number_format_i18n($rating_rating).'</option>'."\n"; } else { echo '<option value="'.$rating_rating.'">'.$prefix.' '.number_format_i18n($rating_rating).'</option>'."\n"; } } } ?> </select> </td> </tr> <tr class="alternate"> <th><?php _e('Sort Options:', 'wp-postratings'); ?></th> <td> <select name="by" size="1"> <option value="id"<?php if($postratings_sortby == 'rating_id') { echo ' selected="selected"'; }?>><?php _e('ID', 'wp-postratings'); ?></option> <option value="username"<?php if($postratings_sortby == 'rating_username') { echo ' selected="selected"'; }?>><?php _e('UserName', 'wp-postratings'); ?></option> <option value="rating"<?php if($postratings_sortby == 'rating_rating') { echo ' selected="selected"'; }?>><?php _e('Rating', 'wp-postratings'); ?></option> <option value="postid"<?php if($postratings_sortby == 'rating_postid') { echo ' selected="selected"'; }?>><?php _e('Post ID', 'wp-postratings'); ?></option> <option value="posttitle"<?php if($postratings_sortby == 'rating_posttitle') { echo ' selected="selected"'; }?>><?php _e('Post Title', 'wp-postratings'); ?></option> <option value="date"<?php if($postratings_sortby == 'rating_timestamp') { echo ' selected="selected"'; }?>><?php _e('Date', 'wp-postratings'); ?></option> <option value="ip"<?php if($postratings_sortby == 'rating_ip') { echo ' selected="selected"'; }?>><?php _e('IP', 'wp-postratings'); ?></option> <option value="host"<?php if($postratings_sortby == 'rating_host') { echo ' selected="selected"'; }?>><?php _e('Host', 'wp-postratings'); ?></option> </select> &nbsp;&nbsp;&nbsp; <select name="order" size="1"> <option value="asc"<?php if($postratings_sortorder == 'asc') { echo ' selected="selected"'; }?>><?php _e('Ascending', 'wp-postratings'); ?></option> <option value="desc"<?php if($postratings_sortorder == 'desc') { echo ' selected="selected"'; } ?>><?php _e('Descending', 'wp-postratings'); ?></option> </select> &nbsp;&nbsp;&nbsp; <select name="perpage" size="1"> <?php for($i=10; $i <= 100; $i+=10) { if($postratings_log_perpage == $i) { echo "<option value=\"$i\" selected=\"selected\">".__('Per Page', 'wp-postratings').": ".number_format_i18n($i)."</option>\n"; } else { echo "<option value=\"$i\">".__('Per Page', 'wp-postratings').": ".number_format_i18n($i)."</option>\n"; } } ?> </select> </td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="<?php _e('Go', 'wp-postratings'); ?>" class="button" /></td> </tr> </table> </form> </div> <p>&nbsp;</p> <!-- Post Ratings Stats --> <div class="wrap"> <h3><?php _e('Post Ratings Logs Stats', 'wp-postratings'); ?></h3> <br style="clear" /> <table class="widefat"> <tr> <th><?php _e('Total Users Voted:', 'wp-postratings'); ?></th> <td><?php echo number_format_i18n($total_users); ?></td> </tr> <tr class="alternate"> <th><?php _e('Total Score:', 'wp-postratings'); ?></th> <td><?php echo number_format_i18n($total_score); ?></td> </tr> <tr> <th><?php _e('Total Average:', 'wp-postratings'); ?></th> <td><?php echo number_format_i18n($total_average, 2); ?></td> </tr> </table> </div> <p>&nbsp;</p> <!-- Delete Post Ratings Logs --> <div class="wrap"> <h3><?php _e('Delete Post Ratings Data/Logs', 'wp-postratings'); ?></h3> <br style="clear" /> <div align="center"> <form method="post" action="<?php echo esc_url( $base_page ); ?>"> <?php wp_nonce_field('wp-postratings_logs'); ?> <table class="widefat"> <tr> <td valign="top"><b><?php _e('Delete Type: ', 'wp-postratings'); ?></b></td> <td valign="top"> <select size="1" name="delete_datalog"> <option value="1"><?php _e('Logs Only', 'wp-postratings'); ?></option> <option value="2"><?php _e('Data Only', 'wp-postratings'); ?></option> <option value="3"><?php _e('Logs And Data', 'wp-postratings'); ?></option> </select> </td> </tr> <tr> <td valign="top"><b><?php _e('Post ID(s):', 'wp-postratings'); ?></b></td> <td valign="top"> <input type="text" name="delete_postid" size="20" dir="ltr" /> <p><?php _e('Seperate each Post ID with a comma.', 'wp-postratings'); ?></p> <p><?php _e('To delete ratings data/logs from Post ID 2, 3 and 4. Just type in: <b>2,3,4</b>', 'wp-postratings'); ?></p> <p><?php _e('To delete ratings data/logs for all posts. Just type in: <b>all</b>', 'wp-postratings'); ?></p> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" name="do" value="<?php _e('Delete Data/Logs', 'wp-postratings'); ?>" class="button" onclick="return confirm('<?php _e('You Are About To Delete Post Ratings Data/Logs.\nThis Action Is Not Reversible.\n\n Choose \\\'Cancel\\\' to stop, \\\'OK\\\' to delete.', 'wp-postratings'); ?>')" /> </td> </tr> </table> </form> </div> <h3><?php _e('Note:', 'wp-postratings'); ?></h3> <ul> <li><?php _e('\'Logs Only\' means the logs generated when a user rates a post.', 'wp-postratings'); ?></li> <li><?php _e('\'Data Only\' means the rating data for the post.', 'wp-postratings'); ?></li> <li><?php _e('\'Logs And Data\' means both the logs generated and the rating data for the post.', 'wp-postratings'); ?></li> <li><?php _e('If your logging method is by IP and Cookie or by Cookie, users may still be unable to rate if they have voted before as the cookie is still stored in their computer.', 'wp-postratings'); ?></li> </ul> </div>
the-wilhelm/chicagostorage
wp-content/plugins/wp-postratings/postratings-manager.php
PHP
gpl-2.0
27,209
<?php use Ctct\ConstantContact; use Ctct\Components\Contacts\Contact; use Ctct\Components\Contacts\Address; use Ctct\Components\Contacts\CustomField; use Ctct\Components\Contacts\Note; use Ctct\Components\Contacts\ContactList; use Ctct\Components\Contacts\EmailAddress; use Ctct\Exceptions\CtctException; class CTCT_Admin_Contacts extends CTCT_Admin_Page { var $errors; var $id; var $can_edit = true; var $can_add = true; var $component = 'Contact'; protected function getKey() { return "constant-contact-contacts"; } protected function getTitle( $value = '' ) { if ( empty( $value ) && $this->isEdit() || $value == 'edit' ) { return __( "Edit Contact", 'ctct' ); } if ( empty( $value ) && $this->isSingle() || $value == 'single' ) { return __( 'Contact', 'ctct' ); } if ( empty( $value ) && $this->isAdd() || $value == 'add' ) { return __( 'Add a Contact', 'ctct' ); } return __( 'Contacts', 'ctct' ); } protected function getNavTitle() { return __( 'Contacts', 'ctct' ); } protected function add() { $data = esc_attr_recursive( (array) $_POST ); $Contact = new KWSContact( $data ); include( CTCT_DIR_PATH . 'views/admin/view.contact-addedit.php' ); } protected function processForms() { // check if the form was submitted if ( isset( $_POST['email_addresses'] ) && ! empty( $_POST['email_addresses'] ) ) { $action = "Getting Contact By Email Address"; try { $data = $_POST; $returnContact = $this->cc->addUpdateContact( $data ); // create a new contact if one does not exist if ( $returnContact && ! is_wp_error( $returnContact ) ) { wp_redirect( add_query_arg( array( 'page' => $this->getKey(), 'view' => $returnContact->id ), admin_url( 'admin.php' ) ) ); // update the existing contact if address already existed } else { $this->errors[] = $returnContact; } // catch any exceptions thrown during the process and print the errors to screen } catch ( CtctException $ex ) { r( $ex, true, $action . ' Exception' ); $this->errors = $ex; } } } protected function edit() { if ( empty( $this->id ) ) { esc_html_e( 'You have not specified a Contact to edit', 'ctct' ); return; } $Contact = $this->cc->getContact( CTCT_ACCESS_TOKEN, $this->id ); // The fetching of the contact failed. if ( is_null( $Contact->id ) ) { return; } $Contact = new KWSContact( $Contact ); include( CTCT_DIR_PATH . 'views/admin/view.contact-addedit.php' ); } protected function single() { $id = $this->id; if ( empty( $id ) ) { esc_html_e( 'You have not specified a Contact to view', 'ctct' ); return; } if ( $refresh = get_option( 'ctct_refresh_contact_' . $id ) ) { delete_option( 'ctct_refresh_contact_' . $id ); add_filter( 'ctct_cache', '__return_false' ); } $Contact = $this->cc->getContact( CTCT_ACCESS_TOKEN, $id ); // The fetching of the contact failed. if ( is_null( $Contact->id ) ) { return; } $Contact = new KWSContact( $Contact ); $summary = $this->cc->getContactSummaryReport( CTCT_ACCESS_TOKEN, $Contact->get( 'id' ) ); include( CTCT_DIR_PATH . 'views/admin/view.contact-view.php' ); } protected function view() { add_filter( 'ctct_cachekey', function () { return isset( $_GET['status'] ) ? false : 'ctct_all_contacts'; } ); if ( ! empty( $_GET['refresh'] ) && $_GET['refresh'] === 'contacts' ) { do_action( 'ctct_flush_contacts' ); } $Contacts = $this->cc->getAllContacts(); kws_print_subsub( 'status', array( array( 'val' => '', 'text' => 'All' ), array( 'val' => 'ACTIVE', 'text' => 'Active' ), array( 'val' => 'UNCONFIRMED', 'text' => 'Unconfirmed' ), array( 'val' => 'OPTOUT', 'text' => 'Opt-Out' ), array( 'val' => 'REMOVED', 'text' => 'Removed' ), array( 'val' => 'NON_SUBSCRIBER', 'text' => 'Non-Subscriber' ), ) ); if ( empty( $Contacts ) ) { esc_html_e( 'Your account has no contacts.', 'ctct' ); } else { include( CTCT_DIR_PATH . 'views/admin/view.contacts-view.php' ); } } } new CTCT_Admin_Contacts;
johnmanlove/JMMC_Corp-Site
wp-content/plugins/constant-contact-api/admin/contacts.php
PHP
gpl-2.0
4,096
<?php namespace Phalcon\Mvc\Collection; /** * Phalcon\Mvc\Collection\Manager * This components controls the initialization of models, keeping record of relations * between the different models of the application. * A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\Di. * <code> * $di = new \Phalcon\Di(); * $di->set('collectionManager', function(){ * return new \Phalcon\Mvc\Collection\Manager(); * }); * $robot = new Robots($di); * </code> */ class Manager implements \Phalcon\Di\InjectionAwareInterface, \Phalcon\Events\EventsAwareInterface { protected $_dependencyInjector; protected $_initialized; protected $_lastInitialized; protected $_eventsManager; protected $_customEventsManager; protected $_connectionServices; protected $_implicitObjectsIds; protected $_behaviors; /** * Sets the DependencyInjector container * * @param mixed $dependencyInjector */ public function setDI(\Phalcon\DiInterface $dependencyInjector) {} /** * Returns the DependencyInjector container * * @return \Phalcon\DiInterface */ public function getDI() {} /** * Sets the event manager * * @param mixed $eventsManager */ public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} /** * Returns the internal event manager * * @return \Phalcon\Events\ManagerInterface */ public function getEventsManager() {} /** * Sets a custom events manager for a specific model * * @param mixed $model * @param mixed $eventsManager */ public function setCustomEventsManager(\Phalcon\Mvc\CollectionInterface $model, \Phalcon\Events\ManagerInterface $eventsManager) {} /** * Returns a custom events manager related to a model * * @param mixed $model * @param \Phalcon\Mvc\CollectionInterface $$model * @return \Phalcon\Events\ManagerInterface */ public function getCustomEventsManager(\Phalcon\Mvc\CollectionInterface $model) {} /** * Initializes a model in the models manager * * @param mixed $model */ public function initialize(\Phalcon\Mvc\CollectionInterface $model) {} /** * Check whether a model is already initialized * * @param string $modelName * @return bool */ public function isInitialized($modelName) {} /** * Get the latest initialized model * * @return \Phalcon\Mvc\CollectionInterface */ public function getLastInitialized() {} /** * Sets a connection service for a specific model * * @param mixed $model * @param string $connectionService */ public function setConnectionService(\Phalcon\Mvc\CollectionInterface $model, $connectionService) {} /** * Sets whether a model must use implicit objects ids * * @param mixed $model * @param bool $useImplicitObjectIds */ public function useImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model, $useImplicitObjectIds) {} /** * Checks if a model is using implicit object ids * * @param mixed $model * @return bool */ public function isUsingImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model) {} /** * Returns the connection related to a model * * @param mixed $model * @param \Phalcon\Mvc\CollectionInterface $$model * @return \Mongo */ public function getConnection(\Phalcon\Mvc\CollectionInterface $model) {} /** * Receives events generated in the models and dispatches them to a events-manager if available * Notify the behaviors that are listening in the model * * @param string $eventName * @param mixed $model */ public function notifyEvent($eventName, \Phalcon\Mvc\CollectionInterface $model) {} /** * Dispatch a event to the listeners and behaviors * This method expects that the endpoint listeners/behaviors returns true * meaning that a least one was implemented * * @param mixed $model * @param string $eventName * @param mixed $data * @return bool */ public function missingMethod(\Phalcon\Mvc\CollectionInterface $model, $eventName, $data) {} /** * Binds a behavior to a model * * @param mixed $model * @param mixed $behavior */ public function addBehavior(\Phalcon\Mvc\CollectionInterface $model, \Phalcon\Mvc\Collection\BehaviorInterface $behavior) {} }
mattm479/mafiakingz
vendor/phalcon/src/Phalcon/mvc/collection/Manager.php
PHP
gpl-2.0
4,617
# -*- coding: utf-8 -*- # Copyright (C) 2010 Holoscopio Tecnologia # Author: Marcelo Jorge Vieira <metal@holoscopio.com> # Author: Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import gobject import pygst pygst.require("0.10") import gst from core import Input, INPUT_TYPE_VIDEO CAPABILITIES = INPUT_TYPE_VIDEO class VideoTestInput(Input): def __init__(self): Input.__init__(self, CAPABILITIES) self.video_src = gst.element_factory_make("videotestsrc", "video_src") self.video_src.set_property("is-live", True) self.add(self.video_src) self.capsfilter = gst.element_factory_make("capsfilter", "capsfilter") self.add(self.capsfilter) gst.element_link_many(self.video_src, self.capsfilter) self.video_pad.set_target(self.capsfilter.src_pads().next()) def config(self, dict): self.video_src.set_property("pattern", int(dict["pattern"])) caps = gst.caps_from_string( "video/x-raw-yuv, width=%d, height=%d;" "video/x-raw-rgb, width=%d, height=%d" % ( int(dict["width"]), int(dict["height"]), int(dict["width"]), int(dict["height"]) ) ) self.capsfilter.set_property("caps", caps)
landell/landell
sltv/input/videotestinput.py
Python
gpl-2.0
1,971
/* PowerDNS Versatile Database Driven Nameserver Copyright (C) 2002 - 2013 PowerDNS.COM BV This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation Additionally, the license of this program contains a special exception which allows to distribute the program in binary form when it is linked against OpenSSL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "packetcache.hh" #include <cstdio> #include <signal.h> #include <cstring> #include <cstdlib> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <iostream> #include <string> #include <sys/stat.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include <pthread.h> #include <unistd.h> #include <sys/mman.h> #include <fcntl.h> #include <fstream> #include <boost/algorithm/string.hpp> #ifdef HAVE_LIBSODIUM #include <sodium.h> #endif #include "opensslsigners.hh" #include "dns.hh" #include "dnsbackend.hh" #include "ueberbackend.hh" #include "dnspacket.hh" #include "nameserver.hh" #include "distributor.hh" #include "logger.hh" #include "arguments.hh" #include "packethandler.hh" #include "statbag.hh" #include "tcpreceiver.hh" #include "misc.hh" #include "dynlistener.hh" #include "dynhandler.hh" #include "communicator.hh" #include "dnsproxy.hh" #include "utility.hh" #include "common_startup.hh" #include "dnsrecords.hh" #include "version.hh" time_t s_starttime; string s_programname="pdns"; // used in packethandler.cc const char *funnytext= "*****************************************************************************\n"\ "Ok, you just ran pdns_server through 'strings' hoping to find funny messages.\n"\ "Well, you found one. \n"\ "Two ions are flying through their particle accelerator, says the one to the\n" "other 'I think I've lost an electron!' \n"\ "So the other one says, 'Are you sure?'. 'YEAH! I'M POSITIVE!'\n"\ " the pdns crew - pdns@powerdns.com\n" "*****************************************************************************\n"; // start (sys)logging /** \var Logger L \brief All logging is done via L, a Logger instance */ /** \file receiver.cc \brief The main loop of powerdns This file is where it all happens - main is here, as are the two pivotal threads qthread() and athread() */ void daemonize(void) { if(fork()) exit(0); // bye bye setsid(); int i=open("/dev/null",O_RDWR); /* open stdin */ if(i < 0) L<<Logger::Critical<<"Unable to open /dev/null: "<<stringerror()<<endl; else { dup2(i,0); /* stdin */ dup2(i,1); /* stderr */ dup2(i,2); /* stderr */ close(i); } } static int cpid; static void takedown(int i) { if(cpid) { L<<Logger::Error<<"Guardian is killed, taking down children with us"<<endl; kill(cpid,SIGKILL); exit(0); } } static void writePid(void) { if(!::arg().mustDo("write-pid")) return; string fname=::arg()["socket-dir"]; if (::arg()["socket-dir"].empty()) { if (::arg()["chroot"].empty()) fname = LOCALSTATEDIR; else fname = ::arg()["chroot"] + "/"; } else if (!::arg()["socket-dir"].empty() && !::arg()["chroot"].empty()) { fname = ::arg()["chroot"] + ::arg()["socket-dir"]; } fname += + "/" + s_programname + ".pid"; ofstream of(fname.c_str()); if(of) of<<getpid()<<endl; else L<<Logger::Error<<"Writing pid for "<<getpid()<<" to "<<fname<<" failed: "<<strerror(errno)<<endl; } int g_fd1[2], g_fd2[2]; FILE *g_fp; pthread_mutex_t g_guardian_lock = PTHREAD_MUTEX_INITIALIZER; // The next two methods are not in dynhandler.cc because they use a few items declared in this file. static string DLCycleHandler(const vector<string>&parts, pid_t ppid) { kill(cpid, SIGKILL); // why? kill(cpid, SIGKILL); // why? sleep(1); return "ok"; } static string DLRestHandler(const vector<string>&parts, pid_t ppid) { string line; for(vector<string>::const_iterator i=parts.begin();i!=parts.end();++i) { if(i!=parts.begin()) line.append(1,' '); line.append(*i); } line.append(1,'\n'); Lock l(&g_guardian_lock); try { writen2(g_fd1[1],line.c_str(),line.size()+1); } catch(PDNSException &ae) { return "Error communicating with instance: "+ae.reason; } char mesg[512]; string response; while(fgets(mesg,sizeof(mesg),g_fp)) { if(*mesg=='\0') break; response+=mesg; } boost::trim_right(response); return response; } static int guardian(int argc, char **argv) { if(isGuarded(argv)) return 0; int infd=0, outfd=1; DynListener dlg(s_programname); dlg.registerFunc("QUIT",&DLQuitHandler, "quit daemon"); dlg.registerFunc("CYCLE",&DLCycleHandler, "restart instance"); dlg.registerFunc("PING",&DLPingHandler, "ping guardian"); dlg.registerFunc("STATUS",&DLStatusHandler, "get instance status from guardian"); dlg.registerRestFunc(&DLRestHandler); dlg.go(); string progname=argv[0]; bool first=true; cpid=0; pthread_mutex_lock(&g_guardian_lock); for(;;) { int pid; setStatus("Launching child"); if(pipe(g_fd1)<0 || pipe(g_fd2)<0) { L<<Logger::Critical<<"Unable to open pipe for coprocess: "<<strerror(errno)<<endl; exit(1); } if(!(g_fp=fdopen(g_fd2[0],"r"))) { L<<Logger::Critical<<"Unable to associate a file pointer with pipe: "<<stringerror()<<endl; exit(1); } setbuf(g_fp,0); // no buffering please, confuses select if(!(pid=fork())) { // child signal(SIGTERM, SIG_DFL); signal(SIGHUP, SIG_DFL); signal(SIGUSR1, SIG_DFL); signal(SIGUSR2, SIG_DFL); char **const newargv=new char*[argc+2]; int n; if(::arg()["config-name"]!="") { progname+="-"+::arg()["config-name"]; L<<Logger::Error<<"Virtual configuration name: "<<::arg()["config-name"]<<endl; } newargv[0]=strdup(const_cast<char *>((progname+"-instance").c_str())); for(n=1;n<argc;n++) { newargv[n]=argv[n]; } newargv[n]=0; L<<Logger::Error<<"Guardian is launching an instance"<<endl; close(g_fd1[1]); fclose(g_fp); // this closes g_fd2[0] for us if(g_fd1[0]!= infd) { dup2(g_fd1[0], infd); close(g_fd1[0]); } if(g_fd2[1]!= outfd) { dup2(g_fd2[1], outfd); close(g_fd2[1]); } if(execvp(argv[0], newargv)<0) { L<<Logger::Error<<"Unable to execvp '"<<argv[0]<<"': "<<strerror(errno)<<endl; char **p=newargv; while(*p) L<<Logger::Error<<*p++<<endl; exit(1); } L<<Logger::Error<<"execvp returned!!"<<endl; // never reached } else if(pid>0) { // parent close(g_fd1[0]); close(g_fd2[1]); if(first) { first=false; signal(SIGTERM, takedown); signal(SIGHUP, SIG_IGN); signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, SIG_IGN); writePid(); } pthread_mutex_unlock(&g_guardian_lock); int status; cpid=pid; for(;;) { int ret=waitpid(pid,&status,WNOHANG); if(ret<0) { L<<Logger::Error<<"In guardian loop, waitpid returned error: "<<strerror(errno)<<endl; L<<Logger::Error<<"Dying"<<endl; exit(1); } else if(ret) // something exited break; else { // child is alive // execute some kind of ping here if(DLQuitPlease()) takedown(1); // needs a parameter.. setStatus("Child running on pid "+itoa(pid)); sleep(1); } } pthread_mutex_lock(&g_guardian_lock); close(g_fd1[1]); fclose(g_fp); g_fp=0; if(WIFEXITED(status)) { int ret=WEXITSTATUS(status); if(ret==99) { L<<Logger::Error<<"Child requested a stop, exiting"<<endl; exit(1); } setStatus("Child died with code "+itoa(ret)); L<<Logger::Error<<"Our pdns instance exited with code "<<ret<<", respawning"<<endl; sleep(1); continue; } if(WIFSIGNALED(status)) { int sig=WTERMSIG(status); setStatus("Child died because of signal "+itoa(sig)); L<<Logger::Error<<"Our pdns instance ("<<pid<<") exited after signal "<<sig<<endl; #ifdef WCOREDUMP if(WCOREDUMP(status)) L<<Logger::Error<<"Dumped core"<<endl; #endif L<<Logger::Error<<"Respawning"<<endl; sleep(1); continue; } L<<Logger::Error<<"No clue what happened! Respawning"<<endl; } else { L<<Logger::Error<<"Unable to fork: "<<strerror(errno)<<endl; exit(1); } } } static void UNIX_declareArguments() { ::arg().set("config-dir","Location of configuration directory (pdns.conf)")=SYSCONFDIR; ::arg().set("config-name","Name of this virtual configuration - will rename the binary image")=""; ::arg().set("socket-dir",string("Where the controlsocket will live, ")+LOCALSTATEDIR+" when unset and not chrooted" )=""; ::arg().set("module-dir","Default directory for modules")=PKGLIBDIR; ::arg().set("chroot","If set, chroot to this directory for more security")=""; ::arg().set("logging-facility","Log under a specific facility")=""; ::arg().set("daemon","Operate as a daemon")="no"; } static void loadModules() { if(!::arg()["load-modules"].empty()) { vector<string>modules; stringtok(modules,::arg()["load-modules"],", "); for(vector<string>::const_iterator i=modules.begin();i!=modules.end();++i) { bool res; const string &module=*i; if(module.find(".")==string::npos) res=UeberBackend::loadmodule(::arg()["module-dir"]+"/lib"+module+"backend.so"); else if(module[0]=='/' || (module[0]=='.' && module[1]=='/') || (module[0]=='.' && module[1]=='.')) // absolute or current path res=UeberBackend::loadmodule(module); else res=UeberBackend::loadmodule(::arg()["module-dir"]+"/"+module); if(res==false) { L<<Logger::Error<<"Receiver unable to load module "<<module<<endl; exit(1); } } } } #ifdef __GLIBC__ #include <execinfo.h> static void tbhandler(int num) { L<<Logger::Critical<<"Got a signal "<<num<<", attempting to print trace: "<<endl; void *array[20]; //only care about last 17 functions (3 taken with tracing support) size_t size; char **strings; size_t i; size = backtrace (array, 20); strings = backtrace_symbols (array, size); //Need -rdynamic gcc (linker) flag for this to work for (i = 0; i < size; i++) //skip useless functions L<<Logger::Error<<strings[i]<<endl; signal(SIGABRT, SIG_DFL); abort();//hopefully will give core } #endif //! The main function of pdns, the pdns process int main(int argc, char **argv) { versionSetProduct(ProductAuthoritative); reportAllTypes(); // init MOADNSParser s_programname="pdns"; s_starttime=time(0); #ifdef __GLIBC__ signal(SIGSEGV,tbhandler); signal(SIGFPE,tbhandler); signal(SIGABRT,tbhandler); signal(SIGILL,tbhandler); #endif #if __GNUC__ >= 3 std::ios_base::sync_with_stdio(false); #endif L.toConsole(Logger::Warning); try { declareArguments(); UNIX_declareArguments(); ::arg().laxParse(argc,argv); // do a lax parse if(::arg().mustDo("version")) { showProductVersion(); showBuildConfiguration(); exit(99); } if(::arg()["config-name"]!="") s_programname+="-"+::arg()["config-name"]; (void)theL(s_programname); string configname=::arg()["config-dir"]+"/"+s_programname+".conf"; cleanSlashes(configname); if(!::arg().mustDo("config") && !::arg().mustDo("no-config")) // "config" == print a configuration file ::arg().laxFile(configname.c_str()); ::arg().laxParse(argc,argv); // reparse so the commandline still wins if(!::arg()["logging-facility"].empty()) { int val=logFacilityToLOG(::arg().asNum("logging-facility") ); if(val >= 0) theL().setFacility(val); else L<<Logger::Error<<"Unknown logging facility "<<::arg().asNum("logging-facility") <<endl; } L.setLoglevel((Logger::Urgency)(::arg().asNum("loglevel"))); L.toConsole((Logger::Urgency)(::arg().asNum("loglevel"))); if(::arg().mustDo("help") || ::arg().mustDo("config")) { ::arg().set("daemon")="no"; ::arg().set("guardian")="no"; } if(::arg().mustDo("guardian") && !isGuarded(argv)) { if(::arg().mustDo("daemon")) { L.toConsole(Logger::Critical); daemonize(); } guardian(argc, argv); // never get here, guardian will reinvoke process cerr<<"Um, we did get here!"<<endl; } // we really need to do work - either standalone or as an instance #ifdef __GLIBC__ if(!::arg().mustDo("traceback-handler")) { L<<Logger::Warning<<"Disabling traceback handler"<<endl; signal(SIGSEGV,SIG_DFL); signal(SIGFPE,SIG_DFL); signal(SIGABRT,SIG_DFL); signal(SIGILL,SIG_DFL); } #endif seedRandom(::arg()["entropy-source"]); #ifdef HAVE_LIBSODIUM if (sodium_init() == -1) { cerr<<"Unable to initialize sodium crypto library"<<endl; exit(99); } #endif openssl_thread_setup(); openssl_seed(); loadModules(); BackendMakers().launch(::arg()["launch"]); // vrooooom! if(!::arg().getCommands().empty()) { cerr<<"Fatal: non-option on the command line, perhaps a '--setting=123' statement missed the '='?"<<endl; exit(99); } if(::arg().mustDo("help")) { cout<<"syntax:"<<endl<<endl; cout<<::arg().helpstring(::arg()["help"])<<endl; exit(0); } if(::arg().mustDo("config")) { cout<<::arg().configstring()<<endl; exit(99); } if(::arg().mustDo("list-modules")) { auto modules = BackendMakers().getModules(); cout<<"Modules available:"<<endl; for(const auto& m : modules) cout<< m <<endl; _exit(99); } if(!::arg().asNum("local-port")) { L<<Logger::Error<<"Unable to launch, binding to no port or port 0 makes no sense"<<endl; exit(99); // this isn't going to fix itself either } if(!BackendMakers().numLauncheable()) { L<<Logger::Error<<"Unable to launch, no backends configured for querying"<<endl; exit(99); // this isn't going to fix itself either } if(::arg().mustDo("daemon")) { L.toConsole(Logger::None); if(!isGuarded(argv)) daemonize(); } if(isGuarded(argv)) { L<<Logger::Warning<<"This is a guarded instance of pdns"<<endl; dl=new DynListener; // listens on stdin } else { L<<Logger::Warning<<"This is a standalone pdns"<<endl; if(::arg().mustDo("control-console")) dl=new DynListener(); else dl=new DynListener(s_programname); writePid(); } DynListener::registerFunc("SHOW",&DLShowHandler, "show a specific statistic or * to get a list", "<statistic>"); DynListener::registerFunc("RPING",&DLPingHandler, "ping instance"); DynListener::registerFunc("QUIT",&DLRQuitHandler, "quit daemon"); DynListener::registerFunc("UPTIME",&DLUptimeHandler, "get instance uptime"); DynListener::registerFunc("NOTIFY-HOST",&DLNotifyHostHandler, "notify host for specific domain", "<domain> <host>"); DynListener::registerFunc("NOTIFY",&DLNotifyHandler, "queue a notification", "<domain>"); DynListener::registerFunc("RELOAD",&DLReloadHandler, "reload all zones"); DynListener::registerFunc("REDISCOVER",&DLRediscoverHandler, "discover any new zones"); DynListener::registerFunc("VERSION",&DLVersionHandler, "get instance version"); DynListener::registerFunc("PURGE",&DLPurgeHandler, "purge entries from packet cache", "[<record>]"); DynListener::registerFunc("CCOUNTS",&DLCCHandler, "get cache statistics"); DynListener::registerFunc("QTYPES", &DLQTypesHandler, "get QType statistics"); DynListener::registerFunc("RESPSIZES", &DLRSizesHandler, "get histogram of response sizes"); DynListener::registerFunc("REMOTES", &DLRemotesHandler, "get top remotes"); DynListener::registerFunc("SET",&DLSettingsHandler, "set config variables", "<var> <value>"); DynListener::registerFunc("RETRIEVE",&DLNotifyRetrieveHandler, "retrieve slave domain", "<domain>"); DynListener::registerFunc("CURRENT-CONFIG",&DLCurrentConfigHandler, "retrieve the current configuration"); DynListener::registerFunc("LIST-ZONES",&DLListZones, "show list of zones", "[master|slave|native]"); DynListener::registerFunc("POLICY",&DLPolicy, "interact with policy engine", "[policy command]"); DynListener::registerFunc("TOKEN-LOGIN", &DLTokenLogin, "Login to a PKCS#11 token", "<module> <slot> <pin>"); if(!::arg()["tcp-control-address"].empty()) { DynListener* dlTCP=new DynListener(ComboAddress(::arg()["tcp-control-address"], ::arg().asNum("tcp-control-port"))); dlTCP->go(); } // reparse, with error checking if(!::arg().mustDo("no-config")) ::arg().file(configname.c_str()); ::arg().parse(argc,argv); if(::arg()["server-id"].empty()) { char tmp[128]; gethostname(tmp, sizeof(tmp)-1); ::arg().set("server-id")=tmp; } UeberBackend::go(); N=new UDPNameserver; // this fails when we are not root, throws exception if(!::arg().mustDo("disable-tcp")) TN=new TCPNameserver; } catch(const ArgException &A) { L<<Logger::Error<<"Fatal error: "<<A.reason<<endl; exit(1); } declareStats(); DLOG(L<<Logger::Warning<<"Verbose logging in effect"<<endl); showProductVersion(); try { mainthread(); } catch(PDNSException &AE) { if(!::arg().mustDo("daemon")) cerr<<"Exiting because: "<<AE.reason<<endl; L<<Logger::Error<<"Exiting because: "<<AE.reason<<endl; } catch(std::exception &e) { if(!::arg().mustDo("daemon")) cerr<<"Exiting because of STL error: "<<e.what()<<endl; L<<Logger::Error<<"Exiting because of STL error: "<<e.what()<<endl; } catch(...) { cerr<<"Uncaught exception of unknown type - sorry"<<endl; } exit(1); }
nlyan/pdns
pdns/receiver.cc
C++
gpl-2.0
18,867
/* * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "SpellAuraEffects.h" #include "ulduar.h" #include "Vehicle.h" #include "Player.h" /* ScriptData SDName: boss_kologarn SD%Complete: 90 SDComment: @todo Achievements SDCategory: Ulduar EndScriptData */ enum Spells { SPELL_ARM_DEAD_DAMAGE = 63629, SPELL_TWO_ARM_SMASH = 63356, SPELL_ONE_ARM_SMASH = 63573, SPELL_ARM_SWEEP = 63766, SPELL_STONE_SHOUT = 63716, SPELL_PETRIFY_BREATH = 62030, SPELL_STONE_GRIP = 62166, SPELL_STONE_GRIP_CANCEL = 65594, SPELL_SUMMON_RUBBLE = 63633, SPELL_FALLING_RUBBLE = 63821, SPELL_ARM_ENTER_VEHICLE = 65343, SPELL_ARM_ENTER_VISUAL = 64753, SPELL_SUMMON_FOCUSED_EYEBEAM = 63342, SPELL_FOCUSED_EYEBEAM_PERIODIC = 63347, SPELL_FOCUSED_EYEBEAM_VISUAL = 63369, SPELL_FOCUSED_EYEBEAM_VISUAL_LEFT = 63676, SPELL_FOCUSED_EYEBEAM_VISUAL_RIGHT = 63702, // Passive SPELL_KOLOGARN_REDUCE_PARRY = 64651, SPELL_KOLOGARN_PACIFY = 63726, SPELL_KOLOGARN_UNK_0 = 65219, // Not found in DBC SPELL_BERSERK = 47008 // guess }; enum NPCs { NPC_RUBBLE_STALKER = 33809, NPC_ARM_SWEEP_STALKER = 33661 }; enum Events { EVENT_NONE = 0, EVENT_INSTALL_ACCESSORIES, EVENT_MELEE_CHECK, EVENT_SMASH, EVENT_SWEEP, EVENT_STONE_SHOUT, EVENT_STONE_GRIP, EVENT_FOCUSED_EYEBEAM, EVENT_RESPAWN_LEFT_ARM, EVENT_RESPAWN_RIGHT_ARM, EVENT_ENRAGE, }; enum Yells { SAY_AGGRO = 0, SAY_SLAY = 1, SAY_LEFT_ARM_GONE = 2, SAY_RIGHT_ARM_GONE = 3, SAY_SHOCKWAVE = 4, SAY_GRAB_PLAYER = 5, SAY_DEATH = 6, SAY_BERSERK = 7, EMOTE_STONE_GRIP = 8 }; class boss_kologarn : public CreatureScript { public: boss_kologarn() : CreatureScript("boss_kologarn") { } struct boss_kologarnAI : public BossAI { boss_kologarnAI(Creature* creature) : BossAI(creature, BOSS_KOLOGARN), vehicle(creature->GetVehicleKit()), left(false), right(false) { ASSERT(vehicle); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); DoCast(SPELL_KOLOGARN_REDUCE_PARRY); SetCombatMovement(false); Reset(); } Vehicle* vehicle; bool left, right; ObjectGuid eyebeamTarget; void EnterCombat(Unit* /*who*/) override { Talk(SAY_AGGRO); events.ScheduleEvent(EVENT_MELEE_CHECK, 6000); events.ScheduleEvent(EVENT_SMASH, 5000); events.ScheduleEvent(EVENT_SWEEP, 19000); events.ScheduleEvent(EVENT_STONE_GRIP, 25000); events.ScheduleEvent(EVENT_FOCUSED_EYEBEAM, 21000); events.ScheduleEvent(EVENT_ENRAGE, 600000); for (uint8 i = 0; i < 2; ++i) if (Unit* arm = vehicle->GetPassenger(i)) arm->ToCreature()->SetInCombatWithZone(); _EnterCombat(); } void Reset() override { _Reset(); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); eyebeamTarget.Clear(); } void JustDied(Unit* /*killer*/) override { Talk(SAY_DEATH); DoCast(SPELL_KOLOGARN_PACIFY); me->GetMotionMaster()->MoveTargetedHome(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->SetCorpseDelay(604800); // Prevent corpse from despawning. _JustDied(); } void KilledUnit(Unit* who) override { if (who->GetTypeId() == TYPEID_PLAYER) Talk(SAY_SLAY); } void PassengerBoarded(Unit* who, int8 /*seatId*/, bool apply) override { bool isEncounterInProgress = instance->GetBossState(BOSS_KOLOGARN) == IN_PROGRESS; if (who->GetEntry() == NPC_LEFT_ARM) { left = apply; if (!apply && isEncounterInProgress) { Talk(SAY_LEFT_ARM_GONE); events.ScheduleEvent(EVENT_RESPAWN_LEFT_ARM, 40000); } } else if (who->GetEntry() == NPC_RIGHT_ARM) { right = apply; if (!apply && isEncounterInProgress) { Talk(SAY_RIGHT_ARM_GONE); events.ScheduleEvent(EVENT_RESPAWN_RIGHT_ARM, 40000); } } if (!isEncounterInProgress) return; if (!apply) { who->CastSpell(me, SPELL_ARM_DEAD_DAMAGE, true); if (Creature* rubbleStalker = who->FindNearestCreature(NPC_RUBBLE_STALKER, 70.0f)) { rubbleStalker->CastSpell(rubbleStalker, SPELL_FALLING_RUBBLE, true); rubbleStalker->CastSpell(rubbleStalker, SPELL_SUMMON_RUBBLE, true); who->ToCreature()->DespawnOrUnsummon(); } if (!right && !left) events.ScheduleEvent(EVENT_STONE_SHOUT, 5000); instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, CRITERIA_DISARMED); } else { events.CancelEvent(EVENT_STONE_SHOUT); who->ToCreature()->SetInCombatWithZone(); } } void JustSummoned(Creature* summon) override { switch (summon->GetEntry()) { case NPC_FOCUSED_EYEBEAM: summon->CastSpell(me, SPELL_FOCUSED_EYEBEAM_VISUAL_LEFT, true); break; case NPC_FOCUSED_EYEBEAM_RIGHT: summon->CastSpell(me, SPELL_FOCUSED_EYEBEAM_VISUAL_RIGHT, true); break; case NPC_RUBBLE: summons.Summon(summon); // absence of break intended default: return; } summon->CastSpell(summon, SPELL_FOCUSED_EYEBEAM_PERIODIC, true); summon->CastSpell(summon, SPELL_FOCUSED_EYEBEAM_VISUAL, true); summon->SetReactState(REACT_PASSIVE); // One of the above spells is a channeled spell, we need to clear this unit state for MoveChase to work summon->ClearUnitState(UNIT_STATE_CASTING); // Victim gets 67351 if (eyebeamTarget) { if (Unit* target = ObjectAccessor::GetUnit(*summon, eyebeamTarget)) { summon->Attack(target, false); summon->GetMotionMaster()->MoveChase(target); } } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_MELEE_CHECK: if (!me->IsWithinMeleeRange(me->GetVictim())) DoCast(SPELL_PETRIFY_BREATH); events.ScheduleEvent(EVENT_MELEE_CHECK, 1 * IN_MILLISECONDS); break; case EVENT_SWEEP: if (left) DoCast(me->FindNearestCreature(NPC_ARM_SWEEP_STALKER, 500.0f, true), SPELL_ARM_SWEEP, true); events.ScheduleEvent(EVENT_SWEEP, 25 * IN_MILLISECONDS); break; case EVENT_SMASH: if (left && right) DoCastVictim(SPELL_TWO_ARM_SMASH); else if (left || right) DoCastVictim(SPELL_ONE_ARM_SMASH); events.ScheduleEvent(EVENT_SMASH, 15 * IN_MILLISECONDS); break; case EVENT_STONE_SHOUT: DoCast(SPELL_STONE_SHOUT); events.ScheduleEvent(EVENT_STONE_SHOUT, 2 * IN_MILLISECONDS); break; case EVENT_ENRAGE: DoCast(SPELL_BERSERK); Talk(SAY_BERSERK); break; case EVENT_RESPAWN_LEFT_ARM: case EVENT_RESPAWN_RIGHT_ARM: { if (vehicle) { int8 seat = eventId == EVENT_RESPAWN_LEFT_ARM ? 0 : 1; uint32 entry = eventId == EVENT_RESPAWN_LEFT_ARM ? NPC_LEFT_ARM : NPC_RIGHT_ARM; vehicle->InstallAccessory(entry, seat, true, TEMPSUMMON_MANUAL_DESPAWN, 0); } break; } case EVENT_STONE_GRIP: { if (right) { DoCast(SPELL_STONE_GRIP); Talk(SAY_GRAB_PLAYER); Talk(EMOTE_STONE_GRIP); } events.ScheduleEvent(EVENT_STONE_GRIP, 25 * IN_MILLISECONDS); break; } case EVENT_FOCUSED_EYEBEAM: if (Unit* eyebeamTargetUnit = SelectTarget(SELECT_TARGET_FARTHEST, 0, 0, true)) { eyebeamTarget = eyebeamTargetUnit->GetGUID(); DoCast(me, SPELL_SUMMON_FOCUSED_EYEBEAM, true); } events.ScheduleEvent(EVENT_FOCUSED_EYEBEAM, urand(15, 35) * IN_MILLISECONDS); break; } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<boss_kologarnAI>(creature); } }; class spell_ulduar_rubble_summon : public SpellScriptLoader { public: spell_ulduar_rubble_summon() : SpellScriptLoader("spell_ulduar_rubble_summon") { } class spell_ulduar_rubble_summonSpellScript : public SpellScript { PrepareSpellScript(spell_ulduar_rubble_summonSpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if (!caster) return; ObjectGuid originalCaster = caster->GetInstanceScript() ? caster->GetInstanceScript()->GetGuidData(BOSS_KOLOGARN) : ObjectGuid::Empty; uint32 spellId = GetEffectValue(); for (uint8 i = 0; i < 5; ++i) caster->CastSpell(caster, spellId, true, NULL, NULL, originalCaster); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_ulduar_rubble_summonSpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_ulduar_rubble_summonSpellScript(); } }; // predicate function to select non main tank target class StoneGripTargetSelector : public std::unary_function<Unit*, bool> { public: StoneGripTargetSelector(Creature* me, Unit const* victim) : _me(me), _victim(victim) { } bool operator()(WorldObject* target) { if (target == _victim && _me->getThreatManager().getThreatList().size() > 1) return true; if (target->GetTypeId() != TYPEID_PLAYER) return true; return false; } Creature* _me; Unit const* _victim; }; class spell_ulduar_stone_grip_cast_target : public SpellScriptLoader { public: spell_ulduar_stone_grip_cast_target() : SpellScriptLoader("spell_ulduar_stone_grip_cast_target") { } class spell_ulduar_stone_grip_cast_target_SpellScript : public SpellScript { PrepareSpellScript(spell_ulduar_stone_grip_cast_target_SpellScript); bool Load() override { if (GetCaster()->GetTypeId() != TYPEID_UNIT) return false; return true; } void FilterTargetsInitial(std::list<WorldObject*>& unitList) { // Remove "main tank" and non-player targets unitList.remove_if(StoneGripTargetSelector(GetCaster()->ToCreature(), GetCaster()->GetVictim())); // Maximum affected targets per difficulty mode uint32 maxTargets = 1; if (GetSpellInfo()->Id == 63981) maxTargets = 3; // Return a random amount of targets based on maxTargets while (maxTargets < unitList.size()) { std::list<WorldObject*>::iterator itr = unitList.begin(); advance(itr, urand(0, unitList.size()-1)); unitList.erase(itr); } // For subsequent effects _unitList = unitList; } void FillTargetsSubsequential(std::list<WorldObject*>& unitList) { unitList = _unitList; } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ulduar_stone_grip_cast_target_SpellScript::FilterTargetsInitial, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ulduar_stone_grip_cast_target_SpellScript::FillTargetsSubsequential, EFFECT_1, TARGET_UNIT_SRC_AREA_ENEMY); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ulduar_stone_grip_cast_target_SpellScript::FillTargetsSubsequential, EFFECT_2, TARGET_UNIT_SRC_AREA_ENEMY); } private: // Shared between effects std::list<WorldObject*> _unitList; }; SpellScript* GetSpellScript() const override { return new spell_ulduar_stone_grip_cast_target_SpellScript(); } }; class spell_ulduar_cancel_stone_grip : public SpellScriptLoader { public: spell_ulduar_cancel_stone_grip() : SpellScriptLoader("spell_ulduar_cancel_stone_grip") { } class spell_ulduar_cancel_stone_gripSpellScript : public SpellScript { PrepareSpellScript(spell_ulduar_cancel_stone_gripSpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { Unit* target = GetHitUnit(); if (!target || !target->GetVehicle()) return; switch (target->GetMap()->GetDifficulty()) { case RAID_DIFFICULTY_10MAN_NORMAL: target->RemoveAura(GetSpellInfo()->Effects[EFFECT_0].CalcValue()); break; case RAID_DIFFICULTY_25MAN_NORMAL: target->RemoveAura(GetSpellInfo()->Effects[EFFECT_1].CalcValue()); break; default: break; } } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_ulduar_cancel_stone_gripSpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_ulduar_cancel_stone_gripSpellScript(); } }; class spell_ulduar_squeezed_lifeless : public SpellScriptLoader { public: spell_ulduar_squeezed_lifeless() : SpellScriptLoader("spell_ulduar_squeezed_lifeless") { } class spell_ulduar_squeezed_lifeless_SpellScript : public SpellScript { PrepareSpellScript(spell_ulduar_squeezed_lifeless_SpellScript); void HandleInstaKill(SpellEffIndex /*effIndex*/) { if (!GetHitPlayer() || !GetHitPlayer()->GetVehicle()) return; //! Proper exit position does not work currently, //! See documentation in void Unit::ExitVehicle(Position const* exitPosition) Position pos; pos.m_positionX = 1756.25f + irand(-3, 3); pos.m_positionY = -8.3f + irand(-3, 3); pos.m_positionZ = 448.8f; pos.SetOrientation(float(M_PI)); GetHitPlayer()->DestroyForNearbyPlayers(); GetHitPlayer()->ExitVehicle(&pos); GetHitPlayer()->UpdateObjectVisibility(false); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_ulduar_squeezed_lifeless_SpellScript::HandleInstaKill, EFFECT_1, SPELL_EFFECT_INSTAKILL); } }; SpellScript* GetSpellScript() const override { return new spell_ulduar_squeezed_lifeless_SpellScript(); } }; class spell_ulduar_stone_grip_absorb : public SpellScriptLoader { public: spell_ulduar_stone_grip_absorb() : SpellScriptLoader("spell_ulduar_stone_grip_absorb") { } class spell_ulduar_stone_grip_absorb_AuraScript : public AuraScript { PrepareAuraScript(spell_ulduar_stone_grip_absorb_AuraScript); //! This will be called when Right Arm (vehicle) has sustained a specific amount of damage depending on instance mode //! What we do here is remove all harmful aura's related and teleport to safe spot. void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (GetTargetApplication()->GetRemoveMode() != AURA_REMOVE_BY_ENEMY_SPELL) return; if (!GetOwner()->ToCreature()) return; uint32 rubbleStalkerEntry = (GetOwner()->GetMap()->GetDifficulty() == DUNGEON_DIFFICULTY_NORMAL ? 33809 : 33942); Creature* rubbleStalker = GetOwner()->FindNearestCreature(rubbleStalkerEntry, 200.0f, true); if (rubbleStalker) rubbleStalker->CastSpell(rubbleStalker, SPELL_STONE_GRIP_CANCEL, true); } void Register() override { AfterEffectRemove += AuraEffectRemoveFn(spell_ulduar_stone_grip_absorb_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_SCHOOL_ABSORB, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const override { return new spell_ulduar_stone_grip_absorb_AuraScript(); } }; class spell_ulduar_stone_grip : public SpellScriptLoader { public: spell_ulduar_stone_grip() : SpellScriptLoader("spell_ulduar_stone_grip") { } class spell_ulduar_stone_grip_AuraScript : public AuraScript { PrepareAuraScript(spell_ulduar_stone_grip_AuraScript); void OnRemoveStun(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { if (Player* owner = GetOwner()->ToPlayer()) owner->RemoveAurasDueToSpell(aurEff->GetAmount()); } void OnRemoveVehicle(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { PreventDefaultAction(); Unit* caster = GetCaster(); if (!caster) return; Position exitPosition; exitPosition.m_positionX = 1750.0f; exitPosition.m_positionY = -7.5f + frand(-3.0f, 3.0f); exitPosition.m_positionZ = 457.9322f; // Remove pending passengers before exiting vehicle - might cause an Uninstall GetTarget()->GetVehicleKit()->RemovePendingEventsForPassenger(caster); caster->_ExitVehicle(&exitPosition); caster->RemoveAurasDueToSpell(GetId()); // Temporarily relocate player to vehicle exit dest serverside to send proper fall movement // beats me why blizzard sends these 2 spline packets one after another instantly Position oldPos = caster->GetPosition(); caster->Relocate(exitPosition); caster->GetMotionMaster()->MoveFall(); caster->Relocate(oldPos); } void Register() override { OnEffectRemove += AuraEffectRemoveFn(spell_ulduar_stone_grip_AuraScript::OnRemoveVehicle, EFFECT_0, SPELL_AURA_CONTROL_VEHICLE, AURA_EFFECT_HANDLE_REAL); AfterEffectRemove += AuraEffectRemoveFn(spell_ulduar_stone_grip_AuraScript::OnRemoveStun, EFFECT_2, SPELL_AURA_MOD_STUN, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const override { return new spell_ulduar_stone_grip_AuraScript(); } }; class spell_kologarn_stone_shout : public SpellScriptLoader { public: spell_kologarn_stone_shout() : SpellScriptLoader("spell_kologarn_stone_shout") { } class spell_kologarn_stone_shout_SpellScript : public SpellScript { PrepareSpellScript(spell_kologarn_stone_shout_SpellScript); void FilterTargets(std::list<WorldObject*>& unitList) { unitList.remove_if(PlayerOrPetCheck()); } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_kologarn_stone_shout_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); } }; SpellScript* GetSpellScript() const override { return new spell_kologarn_stone_shout_SpellScript(); } }; class spell_kologarn_summon_focused_eyebeam : public SpellScriptLoader { public: spell_kologarn_summon_focused_eyebeam() : SpellScriptLoader("spell_kologarn_summon_focused_eyebeam") { } class spell_kologarn_summon_focused_eyebeam_SpellScript : public SpellScript { PrepareSpellScript(spell_kologarn_summon_focused_eyebeam_SpellScript); void HandleForceCast(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); GetCaster()->CastSpell(GetCaster(), GetSpellInfo()->Effects[effIndex].TriggerSpell, true); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_kologarn_summon_focused_eyebeam_SpellScript::HandleForceCast, EFFECT_0, SPELL_EFFECT_FORCE_CAST); OnEffectHitTarget += SpellEffectFn(spell_kologarn_summon_focused_eyebeam_SpellScript::HandleForceCast, EFFECT_1, SPELL_EFFECT_FORCE_CAST); } }; SpellScript* GetSpellScript() const override { return new spell_kologarn_summon_focused_eyebeam_SpellScript(); } }; void AddSC_boss_kologarn() { new boss_kologarn(); new spell_ulduar_rubble_summon(); new spell_ulduar_squeezed_lifeless(); new spell_ulduar_cancel_stone_grip(); new spell_ulduar_stone_grip_cast_target(); new spell_ulduar_stone_grip_absorb(); new spell_ulduar_stone_grip(); new spell_kologarn_stone_shout(); new spell_kologarn_summon_focused_eyebeam(); }
HevdavDEV/DeathCore_3.3.5a
src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp
C++
gpl-2.0
25,778
/* ============================================================================== // ZenDebug.cpp // Part of the Zentropia JUCE Collection // Zentropia is hosted on Github at [https://github.com/SonicZentropy] // @author Casey Bailey (<a href="SonicZentropy@gmail.com">email</a>) // @version 0.1 // @date 2015/08/30 // Copyright (C) 2015 by Casey Bailey // Provided under the GNU license // // Details: Static Utility Class for Debug-related code ================================================================================*/ #include "ZenDebug.h" clock_t ZenDebug::inTime = clock(); int ZenDebug::numSecondsBetweenDebugPrints = 1; void ZenDebug::setSecondsBetweenDebugPrints(const int& inSeconds) { numSecondsBetweenDebugPrints = inSeconds; } int ZenDebug::getSecondsBetweenDebugPrints() { return numSecondsBetweenDebugPrints; } bool ZenDebug::isPrintTimerThresholdReached() { if (((clock() - inTime) / CLOCKS_PER_SEC) > numSecondsBetweenDebugPrints) { inTime = clock(); return true; } return false; }
SonicZentropy/ZenTool
Source/zen_utils/ZenDebug.cpp
C++
gpl-2.0
1,033
<?php /** * @version $Id: str_ireplace.php 23 2014-01-11 08:24:20Z thongta $ * @package utf8 * @subpackage strings */ //--------------------------------------------------------------- /** * UTF-8 aware alternative to str_ireplace * Case-insensitive version of str_replace * Note: requires utf8_strtolower * Note: it's not fast and gets slower if $search / $replace is array * Notes: it's based on the assumption that the lower and uppercase * versions of a UTF-8 character will have the same length in bytes * which is currently true given the hash table to strtolower * * @param string * * @return string * @see http://www.php.net/str_ireplace * @see utf8_strtolower * @package utf8 * @subpackage strings */ function utf8_ireplace( $search, $replace, $str, $count = NULL ) { if ( ! is_array( $search ) ) { $slen = strlen( $search ); if ( $slen == 0 ) { return $str; } $lendif = strlen( $replace ) - strlen( $search ); $search = utf8_strtolower( $search ); $search = preg_quote( $search, '/' ); $lstr = utf8_strtolower( $str ); $i = 0; $matched = 0; while ( preg_match( '/(.*)' . $search . '/Us', $lstr, $matches ) ) { if ( $i === $count ) { break; } $mlen = strlen( $matches[0] ); $lstr = substr( $lstr, $mlen ); $str = substr_replace( $str, $replace, $matched + strlen( $matches[1] ), $slen ); $matched += $mlen + $lendif; $i ++; } return $str; } else { foreach ( array_keys( $search ) as $k ) { if ( is_array( $replace ) ) { if ( array_key_exists( $k, $replace ) ) { $str = utf8_ireplace( $search[$k], $replace[$k], $str, $count ); } else { $str = utf8_ireplace( $search[$k], '', $str, $count ); } } else { $str = utf8_ireplace( $search[$k], $replace, $str, $count ); } } return $str; } }
AhmedSayedAhmed/MM_Portal
wp-content/plugins/wp-pipes/includes/phputf8/str_ireplace.php
PHP
gpl-2.0
1,864
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2007-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.dao.support; import java.util.SortedMap; import org.opennms.netmgt.dao.api.NodeDao; import org.opennms.netmgt.filter.FilterDao; import org.opennms.netmgt.model.EntityVisitor; import org.opennms.netmgt.model.OnmsNode; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; /** * <p>FilterWalker class.</p> * * @author <a href="mailto:dj@opennms.org">DJ Gregor</a> * @version $Id: $ */ public class FilterWalker implements InitializingBean { private NodeDao m_nodeDao; private FilterDao m_filterDao; private String m_filter; private EntityVisitor m_visitor; /** * <p>walk</p> */ public void walk() { SortedMap<Integer, String> map = getFilterDao().getNodeMap(m_filter); if (map != null) { for (final Integer nodeId : map.keySet()) { final OnmsNode node = getNodeDao().load(nodeId); m_visitor.visitNode(node); } } } /** * <p>afterPropertiesSet</p> */ @Override public void afterPropertiesSet() { Assert.state(m_visitor != null, "property visitor must be set to a non-null value"); Assert.state(m_filterDao != null, "property filterDao must be set to a non-null value"); Assert.state(m_nodeDao != null, "property nodeDao must be set to a non-null value"); Assert.state(m_filter != null, "property filter must be set to a non-null value"); } /** * @return the nodeDao */ public NodeDao getNodeDao() { return m_nodeDao; } /** * @param nodeDao the nodeDao to set */ public void setNodeDao(NodeDao nodeDao) { this.m_nodeDao = nodeDao; } /** * <p>getVisitor</p> * * @return a {@link org.opennms.netmgt.model.ResourceVisitor} object. */ public EntityVisitor getVisitor() { return m_visitor; } /** * <p>setVisitor</p> * * @param visitor a {@link org.opennms.netmgt.model.ResourceVisitor} object. */ public void setVisitor(EntityVisitor visitor) { m_visitor = visitor; } /** * <p>getFilterDao</p> * * @return a {@link org.opennms.netmgt.filter.FilterDao} object. */ public FilterDao getFilterDao() { return m_filterDao; } /** * <p>setFilterDao</p> * * @param filterDao a {@link org.opennms.netmgt.filter.FilterDao} object. */ public void setFilterDao(FilterDao filterDao) { m_filterDao = filterDao; } /** * <p>getFilter</p> * * @return a {@link java.lang.String} object. */ public String getFilter() { return m_filter; } /** * <p>setFilter</p> * * @param filter a {@link java.lang.String} object. */ public void setFilter(String filter) { m_filter = filter; } }
rfdrake/opennms
opennms-dao/src/main/java/org/opennms/netmgt/dao/support/FilterWalker.java
Java
gpl-2.0
4,106
/*************************************************************************** qgslayertreeembeddedwidgetsimpl.h -------------------------------------- Date : May 2016 Copyright : (C) 2016 by Martin Dobias Email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgslayertreeembeddedwidgetsimpl.h" #include <QHBoxLayout> #include <QLabel> #include <QSlider> #include <QTimer> #include "qgsrasterlayer.h" #include "qgsrasterrenderer.h" #include "qgsvectorlayer.h" ///@cond PRIVATE QgsLayerTreeOpacityWidget::QgsLayerTreeOpacityWidget( QgsMapLayer *layer ) : mLayer( layer ) { setAutoFillBackground( true ); // override the content from model QLabel *l = new QLabel( QStringLiteral( "Opacity" ), this ); mSlider = new QSlider( Qt::Horizontal, this ); mSlider->setRange( 0, 1000 ); QHBoxLayout *lay = new QHBoxLayout(); lay->addWidget( l ); lay->addWidget( mSlider ); setLayout( lay ); // timer for delayed transparency update - for more responsive GUI mTimer = new QTimer( this ); mTimer->setSingleShot( true ); mTimer->setInterval( 100 ); connect( mTimer, &QTimer::timeout, this, &QgsLayerTreeOpacityWidget::updateOpacityFromSlider ); connect( mSlider, &QAbstractSlider::valueChanged, this, &QgsLayerTreeOpacityWidget::sliderValueChanged ); // init from layer switch ( mLayer->type() ) { case QgsMapLayerType::VectorLayer: { QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( mLayer ); mSlider->setValue( vl->opacity() * 1000.0 ); connect( vl, &QgsVectorLayer::opacityChanged, this, &QgsLayerTreeOpacityWidget::layerTrChanged ); break; } case QgsMapLayerType::RasterLayer: { mSlider->setValue( 1000 - qobject_cast<QgsRasterLayer *>( mLayer )->renderer()->opacity() * 1000 ); // TODO: there is no signal for raster layers break; } case QgsMapLayerType::PluginLayer: case QgsMapLayerType::MeshLayer: break; } } QSize QgsLayerTreeOpacityWidget::sizeHint() const { return QWidget::sizeHint(); //return QSize(200,200); // horizontal seems ignored, vertical is used for spacing } void QgsLayerTreeOpacityWidget::sliderValueChanged( int value ) { Q_UNUSED( value ); if ( mTimer->isActive() ) return; mTimer->start(); } void QgsLayerTreeOpacityWidget::updateOpacityFromSlider() { int value = mSlider->value(); switch ( mLayer->type() ) { case QgsMapLayerType::VectorLayer: { qobject_cast<QgsVectorLayer *>( mLayer )->setOpacity( value / 1000.0 ); break; } case QgsMapLayerType::RasterLayer: { qobject_cast<QgsRasterLayer *>( mLayer )->renderer()->setOpacity( 1 - value / 1000.0 ); break; } case QgsMapLayerType::PluginLayer: case QgsMapLayerType::MeshLayer: break; } mLayer->triggerRepaint(); } void QgsLayerTreeOpacityWidget::layerTrChanged() { mSlider->blockSignals( true ); mSlider->setValue( qobject_cast<QgsVectorLayer *>( mLayer )->opacity() * 1000.0 ); mSlider->blockSignals( false ); } // QString QgsLayerTreeOpacityWidget::Provider::id() const { return QStringLiteral( "transparency" ); } QString QgsLayerTreeOpacityWidget::Provider::name() const { return tr( "Opacity slider" ); } QgsLayerTreeOpacityWidget *QgsLayerTreeOpacityWidget::Provider::createWidget( QgsMapLayer *layer, int widgetIndex ) { Q_UNUSED( widgetIndex ); return new QgsLayerTreeOpacityWidget( layer ); } bool QgsLayerTreeOpacityWidget::Provider::supportsLayer( QgsMapLayer *layer ) { switch ( layer->type() ) { case QgsMapLayerType::VectorLayer: case QgsMapLayerType::RasterLayer: return true; case QgsMapLayerType::MeshLayer: case QgsMapLayerType::PluginLayer: return false; } return false; } ///@endcond
m-kuhn/QGIS
src/gui/layertree/qgslayertreeembeddedwidgetsimpl.cpp
C++
gpl-2.0
4,418
/** * WonderPlugin Carousel Skin Options * Copyright 2014 Magic Hills Pty Ltd - http://www.wonderplugin.com */ var WONDERPLUGIN_CAROUSEL_SKIN_OPTIONS = { classic : { width:240, height:180, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:100, navheight:16, random:false, showbottomshadow:false, arrowheight:32, itembackgroundimagewidth:100, skin:"classic", responsive:true, bottomshadowimage:"bottomshadow-110-95-0.png", enabletouchswipe:true, navstyle:"bullets", backgroundimagetop:-40, arrowstyle:"always", bottomshadowimagetop:95, hoveroverlayimage:"hoveroverlay-64-64-3.png", itembottomshadowimage:"itembottomshadow-100-100-5.png", showitembottomshadow:false, transitioneasing:"easeOutExpo", showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-32-32-2.png", direction:"horizontal", navimage:"bullet-16-16-0.png", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:48, showplayvideo:true, spacing:18, scrollitems:1, showhoveroverlay:true, scrollmode:"page", navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", autoplay:true, arrowwidth:32, pauseonmouseover:true, navmode:"page", interval:3000, backgroundimagewidth:110, navspacing:8, playvideoimage:"playvideo-64-64-0.png", visibleitems:3, navswitchonmouseover:false, bottomshadowimagewidth:110, screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:16, loop:0, transitionduration:1000 }, gallery: { width:240, height:180, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:99, navheight:16, random:false, showbottomshadow:false, arrowheight:48, itembackgroundimagewidth:100, skin:"gallery", responsive:true, bottomshadowimage:"bottomshadow-110-95-0.png", enabletouchswipe:true, navstyle:"bullets", backgroundimagetop:-40, arrowstyle:"always", bottomshadowimagetop:95, hoveroverlayimage:"hoveroverlay-64-64-5.png", itembottomshadowimage:"itembottomshadow-100-98-3.png", showitembottomshadow:false, transitioneasing:"easeOutExpo", showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-48-48-2.png", direction:"horizontal", navimage:"bullet-16-16-0.png", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:48, showplayvideo:true, spacing:4, scrollitems:1, showhoveroverlay:true, scrollmode:"page", navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", autoplay:true, arrowwidth:48, pauseonmouseover:true, navmode:"page", interval:3000, backgroundimagewidth:110, navspacing:8, playvideoimage:"playvideo-64-64-0.png", visibleitems:3, navswitchonmouseover:false, bottomshadowimagewidth:110, screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:16, loop:0, transitionduration:1000 }, highlight: { width:240, height:180, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:99, navheight:16, random:false, showbottomshadow:false, arrowheight:48, itembackgroundimagewidth:100, skin:"highlight", responsive:true, bottomshadowimage:"bottomshadow-110-95-0.png", enabletouchswipe:true, navstyle:"bullets", backgroundimagetop:-40, arrowstyle:"always", bottomshadowimagetop:95, hoveroverlayimage:"hoveroverlay-64-64-5.png", itembottomshadowimage:"itembottomshadow-100-98-3.png", showitembottomshadow:true, transitioneasing:"easeOutExpo", showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-48-48-2.png", direction:"horizontal", navimage:"bullet-16-16-0.png", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:48, showplayvideo:true, spacing:4, scrollitems:1, showhoveroverlay:true, scrollmode:"page", navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", autoplay:true, arrowwidth:48, pauseonmouseover:true, navmode:"page", interval:3000, backgroundimagewidth:110, navspacing:8, playvideoimage:"playvideo-64-64-0.png", visibleitems:3, navswitchonmouseover:false, bottomshadowimagewidth:110, screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:16, loop:0, transitionduration:1000 }, list: { width:240, height:180, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:99, navheight:12, random:false, showbottomshadow:false, arrowheight:28, itembackgroundimagewidth:100, skin:"list", responsive:true, bottomshadowimage:"bottomshadow-110-95-0.png", enabletouchswipe:true, navstyle:"bullets", backgroundimagetop:-40, arrowstyle:"always", bottomshadowimagetop:95, hoveroverlayimage:"hoveroverlay-64-64-5.png", itembottomshadowimage:"itembottomshadow-100-98-3.png", showitembottomshadow:false, transitioneasing:"easeOutExpo", showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-28-28-0.png", direction:"vertical", navimage:"bullet-12-12-1.png", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:48, showplayvideo:true, spacing:8, scrollitems:1, showhoveroverlay:true, scrollmode:"page", navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", autoplay:true, arrowwidth:28, pauseonmouseover:true, navmode:"page", interval:3000, backgroundimagewidth:110, navspacing:4, playvideoimage:"playvideo-64-64-0.png", visibleitems:3, navswitchonmouseover:false, bottomshadowimagewidth:110, screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:12, loop:0, transitionduration:1000 }, navigator: { width:240, height:180, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:99, navheight:12, random:false, showbottomshadow:false, arrowheight:28, itembackgroundimagewidth:100, skin:"navigator", responsive:true, bottomshadowimage:"bottomshadow-110-95-0.png", enabletouchswipe:true, navstyle:"bullets", backgroundimagetop:-40, arrowstyle:"always", bottomshadowimagetop:95, hoveroverlayimage:"hoveroverlay-64-64-5.png", itembottomshadowimage:"itembottomshadow-100-98-3.png", showitembottomshadow:false, transitioneasing:"easeOutExpo", showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-28-28-0.png", direction:"horizontal", navimage:"bullet-12-12-1.png", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:48, showplayvideo:true, spacing:4, scrollitems:1, showhoveroverlay:true, scrollmode:"page", navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", autoplay:true, arrowwidth:28, pauseonmouseover:true, navmode:"page", interval:3000, backgroundimagewidth:110, navspacing:4, playvideoimage:"playvideo-64-64-0.png", visibleitems:2, navswitchonmouseover:false, bottomshadowimagewidth:110, screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:12, loop:0, transitionduration:1000 }, showcase: { width:240, height:180, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:99, navheight:16, random:false, showbottomshadow:false, arrowheight:32, itembackgroundimagewidth:100, skin:"showcase", responsive:true, bottomshadowimage:"bottomshadow-110-95-0.png", enabletouchswipe:true, navstyle:"bullets", backgroundimagetop:-40, arrowstyle:"none", bottomshadowimagetop:95, hoveroverlayimage:"hoveroverlay-64-64-5.png", itembottomshadowimage:"itembottomshadow-100-98-3.png", showitembottomshadow:false, transitioneasing:"easeOutExpo", showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-32-32-4.png", direction:"vertical", navimage:"bullet-16-16-0.png", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:48, showplayvideo:true, spacing:8, scrollitems:1, showhoveroverlay:true, scrollmode:"page", navdirection:"vertical", itembottomshadowimagewidth:100, backgroundimage:"", autoplay:true, arrowwidth:32, pauseonmouseover:true, navmode:"page", interval:3000, backgroundimagewidth:110, navspacing:8, playvideoimage:"playvideo-64-64-0.png", visibleitems:1, navswitchonmouseover:true, bottomshadowimagewidth:110, screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:16, loop:0, transitionduration:1000 }, simplicity: { width:240, height:180, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:100, navheight:16, random:false, showbottomshadow:false, arrowheight:32, itembackgroundimagewidth:100, skin:"simplicity", responsive:true, bottomshadowimage:"bottomshadow-110-95-0.png", enabletouchswipe:true, navstyle:"none", backgroundimagetop:-40, arrowstyle:"always", bottomshadowimagetop:95, hoveroverlayimage:"hoveroverlay-64-64-6.png", itembottomshadowimage:"itembottomshadow-100-100-5.png", showitembottomshadow:false, transitioneasing:"easeOutExpo", showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-32-32-1.png", direction:"horizontal", navimage:"bullet-16-16-0.png", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:48, showplayvideo:true, spacing:4, scrollitems:1, showhoveroverlay:true, scrollmode:"page", navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", autoplay:true, arrowwidth:32, pauseonmouseover:true, navmode:"page", interval:3000, backgroundimagewidth:110, navspacing:8, playvideoimage:"playvideo-64-64-0.png", visibleitems:3, navswitchonmouseover:false, bottomshadowimagewidth:110, screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:16, loop:0, transitionduration:1000 }, stylish: { width:240, height:180, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:100, navheight:24, random:false, showbottomshadow:true, arrowheight:32, itembackgroundimagewidth:100, skin:"stylish", responsive:true, bottomshadowimage:"bottomshadow-110-100-5.png", enabletouchswipe:false, navstyle:"bullets", backgroundimagetop:-40, arrowstyle:"always", bottomshadowimagetop:100, hoveroverlayimage:"hoveroverlay-64-64-4.png", itembottomshadowimage:"itembottomshadow-100-100-5.png", showitembottomshadow:false, transitioneasing:"easeOutExpo", showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-32-32-0.png", direction:"horizontal", navimage:"bullet-24-24-0.png", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:48, showplayvideo:true, spacing:8, scrollitems:1, showhoveroverlay:true, scrollmode:"page", navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", autoplay:true, arrowwidth:32, pauseonmouseover:true, navmode:"page", interval:3000, backgroundimagewidth:110, navspacing:4, playvideoimage:"playvideo-64-64-0.png", visibleitems:3, navswitchonmouseover:false, bottomshadowimagewidth:110, screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:24, loop:0, transitionduration:1000 }, thumbnail: { width:240, height:180, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:99, navheight:16, random:false, showbottomshadow:false, arrowheight:28, itembackgroundimagewidth:100, skin:"thumbnail", responsive:true, bottomshadowimage:"bottomshadow-110-95-0.png", enabletouchswipe:true, navstyle:"none", backgroundimagetop:-40, arrowstyle:"always", bottomshadowimagetop:95, hoveroverlayimage:"hoveroverlay-64-64-5.png", itembottomshadowimage:"itembottomshadow-100-98-3.png", showitembottomshadow:false, transitioneasing:"easeOutExpo", showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-28-28-0.png", direction:"horizontal", navimage:"bullet-16-16-0.png", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:48, showplayvideo:true, spacing:8, scrollitems:1, showhoveroverlay:true, scrollmode:"page", navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", autoplay:true, arrowwidth:28, pauseonmouseover:true, navmode:"page", interval:3000, backgroundimagewidth:110, navspacing:8, playvideoimage:"playvideo-64-64-0.png", visibleitems:1, navswitchonmouseover:false, bottomshadowimagewidth:110, screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:16, loop:0, transitionduration:750 }, vertical: { width:240, height:180, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:100, navheight:24, random:false, showbottomshadow:false, arrowheight:32, itembackgroundimagewidth:100, skin:"vertical", responsive:true, bottomshadowimage:"bottomshadow-110-100-5.png", enabletouchswipe:true, navstyle:"none", backgroundimagetop:-40, arrowstyle:"always", bottomshadowimagetop:100, hoveroverlayimage:"hoveroverlay-64-64-4.png", itembottomshadowimage:"itembottomshadow-100-100-5.png", showitembottomshadow:false, transitioneasing:"easeOutExpo", showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-32-32-4.png", direction:"vertical", navimage:"bullet-24-24-0.png", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:48, showplayvideo:true, spacing:12, scrollitems:1, showhoveroverlay:true, scrollmode:"page", navdirection:"vertical", itembottomshadowimagewidth:100, backgroundimage:"", autoplay:true, arrowwidth:32, pauseonmouseover:true, navmode:"page", interval:3000, backgroundimagewidth:110, navspacing:4, playvideoimage:"playvideo-64-64-0.png", visibleitems:2, navswitchonmouseover:false, bottomshadowimagewidth:110, screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:24, loop:0, transitionduration:1000 }, testimonial: { width:360, height:270, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:99, donotcrop:false, navheight:12, random:false, showhoveroverlay:true, height:270, arrowheight:32, itembackgroundimagewidth:100, skin:"testimonial", responsive:true, bottomshadowimage:"bottomshadow-110-95-0.png", navstyle:"none", enabletouchswipe:true, backgroundimagetop:-40, arrowstyle:"mouseover", bottomshadowimagetop:95, transitionduration:1000, lightboxshowtitle:true, hoveroverlayimage:"hoveroverlay-64-64-5.png", itembottomshadowimage:"itembottomshadow-100-98-3.png", lightboxshowdescription:false, width:360, showitembottomshadow:false, showhoveroverlayalways:false, navimage:"bullet-12-12-1.png", lightboxtitlebottomcss:"{color:#333; font-size:14px; font-family:Armata,sans-serif,Arial; overflow:hidden; text-align:left;}", lightboxshownavigation:false, showitembackgroundimage:false, itembackgroundimage:"", backgroundimagewidth:110, playvideoimagepos:"center", circular:true, arrowimage:"arrows-32-32-2.png", scrollitems:1, showbottomshadow:false, lightboxdescriptionbottomcss:"{color:#333; font-size:12px; font-family:Arial,Helvetica,sans-serif; overflow:hidden; text-align:left; margin:4px 0px 0px; padding: 0px;}", supportiframe:false, transitioneasing:"easeOutExpo", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:64, showplayvideo:true, spacing:4, lightboxthumbwidth:80, scrollmode:"item", navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", lightboxthumbtopmargin:12, arrowwidth:32, transparent:false, navmode:"page", lightboxthumbbottommargin:8, interval:2000, lightboxthumbheight:60, navspacing:4, pauseonmouseover:false, imagefillcolor:"FFFFFF", playvideoimage:"playvideo-64-64-0.png", visibleitems:1, navswitchonmouseover:false, direction:"horizontal", usescreenquery:false, bottomshadowimagewidth:110, screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:12, loop:0, autoplay:true }, fashion: { width:300, height:300, skinsfoldername:"", arrowhideonmouseleave:1000, itembottomshadowimagetop:100, donotcrop:false, navheight:16, random:false, showhoveroverlay:false, height:300, arrowheight:60, itembackgroundimagewidth:100, skin:"fashion", responsive:true, bottomshadowimage:"bottomshadow-110-95-0.png", navstyle:"bullets", enabletouchswipe:true, backgroundimagetop:-40, arrowstyle:"mouseover", bottomshadowimagetop:95, transitionduration:1000, lightboxshowtitle:true, hoveroverlayimage:"hoveroverlay-64-64-4.png", itembottomshadowimage:"itembottomshadow-100-100-5.png", lightboxshowdescription:false, width:300, showitembottomshadow:false, showhoveroverlayalways:false, navimage:"bullet-16-16-1.png", lightboxtitlebottomcss:"{color:#333; font-size:14px; font-family:Armata,sans-serif,Arial; overflow:hidden; text-align:left;}", lightboxshownavigation:false, showitembackgroundimage:false, itembackgroundimage:"", backgroundimagewidth:110, playvideoimagepos:"center", circular:true, arrowimage:"arrows-42-60-0.png", scrollitems:1, showbottomshadow:false, lightboxdescriptionbottomcss:"{color:#333; font-size:12px; font-family:Arial,Helvetica,sans-serif; overflow:hidden; text-align:left; margin:4px 0px 0px; padding: 0px;}", supportiframe:false, transitioneasing:"easeOutExpo", itembackgroundimagetop:0, showbackgroundimage:false, lightboxbarheight:64, showplayvideo:true, spacing:0, lightboxthumbwidth:80, scrollmode:"page", navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", lightboxthumbtopmargin:12, arrowwidth:42, transparent:false, navmode:"page", lightboxthumbbottommargin:8, interval:3000, lightboxthumbheight:60, navspacing:8, pauseonmouseover:true, imagefillcolor:"FFFFFF", playvideoimage:"playvideo-64-64-0.png", visibleitems:3, navswitchonmouseover:false, direction:"horizontal", usescreenquery:false, bottomshadowimagewidth:110, screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:16, loop:0, autoplay:true }, rotator: { width:200, height:200, skinsfoldername:"", interval:3000, itembottomshadowimagetop:100, donotcrop:false, random:false, showhoveroverlay:true, arrowheight:36, showbottomshadow:false, itembackgroundimagewidth:100, skin:"Rotator", responsive:true, lightboxtitlebottomcss:"{color:#333; font-size:14px; font-family:Armata,sans-serif,Arial; overflow:hidden; text-align:left;}", enabletouchswipe:true, navstyle:"none", backgroundimagetop:-40, arrowstyle:"mouseover", bottomshadowimagetop:100, transitionduration:1000, itembackgroundimagetop:0, hoveroverlayimage:"hoveroverlay-64-64-9.png", itembottomshadowimage:"itembottomshadow-100-100-5.png", lightboxshowdescription:false, navswitchonmouseover:false, showhoveroverlayalways:false, transitioneasing:"easeOutExpo", lightboxshownavigation:false, showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-36-36-1.png", scrollitems:1, direction:"vertical", lightboxdescriptionbottomcss:"{color:#333; font-size:12px; font-family:Arial,Helvetica,sans-serif; overflow:hidden; text-align:left; margin:4px 0px 0px; padding: 0px;}", supportiframe:false, navimage:"bullet-24-24-0.png", backgroundimagewidth:110, showbackgroundimage:false, lightboxbarheight:64, showplayvideo:true, spacing:8, lightboxthumbwidth:80, navdirection:"vertical", itembottomshadowimagewidth:100, backgroundimage:"", lightboxthumbtopmargin:12, autoplay:true, arrowwidth:36, transparent:false, bottomshadowimage:"bottomshadow-110-100-5.png", scrollmode:"page", navmode:"page", lightboxshowtitle:true, lightboxthumbbottommargin:8, arrowhideonmouseleave:1000, showitembottomshadow:false, lightboxthumbheight:60, navspacing:4, pauseonmouseover:true, imagefillcolor:"FFFFFF", playvideoimage:"playvideo-64-64-0.png", visibleitems:2, usescreenquery:false, bottomshadowimagewidth:110, screenquery:'{\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:24, loop:0, navheight:24 }, testimonialcarousel: { width:280, height:240, skinsfoldername:"", interval:3000, itembottomshadowimagetop:99, donotcrop:false, random:false, showhoveroverlay:false, arrowheight:32, showbottomshadow:false, itembackgroundimagewidth:100, skin:"TestimonialCarousel", responsive:true, lightboxtitlebottomcss:"{color:#333; font-size:14px; font-family:Armata,sans-serif,Arial; overflow:hidden; text-align:left;}", enabletouchswipe:true, navstyle:"bullets", backgroundimagetop:-40, arrowstyle:"mouseover", bottomshadowimagetop:95, transitionduration:1000, itembackgroundimagetop:0, hoveroverlayimage:"hoveroverlay-64-64-9.png", itembottomshadowimage:"itembottomshadow-100-98-3.png", lightboxshowdescription:false, navswitchonmouseover:false, showhoveroverlayalways:false, transitioneasing:"easeOutExpo", lightboxshownavigation:false, showitembackgroundimage:false, itembackgroundimage:"", playvideoimagepos:"center", circular:true, arrowimage:"arrows-32-32-2.png", scrollitems:1, direction:"horizontal", lightboxdescriptionbottomcss:"{color:#333; font-size:12px; font-family:Arial,Helvetica,sans-serif; overflow:hidden; text-align:left; margin:4px 0px 0px; padding: 0px;}", supportiframe:false, navimage:"bullet-16-16-1.png", backgroundimagewidth:110, showbackgroundimage:false, lightboxbarheight:64, showplayvideo:true, spacing:4, lightboxthumbwidth:80, navdirection:"horizontal", itembottomshadowimagewidth:100, backgroundimage:"", lightboxthumbtopmargin:12, autoplay:true, arrowwidth:32, transparent:false, bottomshadowimage:"bottomshadow-110-95-0.png", scrollmode:"page", navmode:"page", lightboxshowtitle:true, lightboxthumbbottommargin:8, arrowhideonmouseleave:600, showitembottomshadow:false, lightboxthumbheight:60, navspacing:4, pauseonmouseover:false, imagefillcolor:"FFFFFF", playvideoimage:"playvideo-64-64-0.png", visibleitems:3, usescreenquery:false, bottomshadowimagewidth:110, screenquery:'{\n "tablet": {\n "screenwidth": 900,\n "visibleitems": 2\n },\n "mobile": {\n "screenwidth": 600,\n "visibleitems": 1\n }\n}', navwidth:16, loop:0, navheight:16 } };
master777/tap
wp-content/plugins/wonderplugin-carousel/engine/wonderplugincarouselskins.js
JavaScript
gpl-2.0
28,810
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_GoogleBase * @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Google Base Attributes resource model * * @deprecated after 1.5.1.0 * @category Mage * @package Mage_GoogleBase * @author Magento Core Team <core@magentocommerce.com> */ class Mage_GoogleBase_Model_Resource_Attribute extends Mage_Core_Model_Resource_Db_Abstract { /** * Resource initialization * */ protected function _construct() { $this->_init('googlebase/attributes', 'id'); } }
miguelangelramirez/magento.dev
app/code/core/Mage/GoogleBase/Model/Resource/Attribute.php
PHP
gpl-2.0
1,413
(function ($, Drupal) { 'use strict'; Drupal.behaviors.chosen = { attach: function (context, settings) { settings.chosen = settings.chosen || drupalSettings.chosen; // Prepare selector and add unwantend selectors. var selector = settings.chosen.selector; var options; // Function to prepare all the options together for the chosen() call. var getElementOptions = function (element) { options = $.extend({}, settings.chosen.options); // The width default option is considered the minimum width, so this // must be evaluated for every option. if (settings.chosen.minimum_width > 0) { if ($(element).width() < settings.chosen.minimum_width) { options.width = settings.chosen.minimum_width + 'px'; } else { options.width = $(element).width() + 'px'; } } // Some field widgets have cardinality, so we must respect that. // @see chosen_pre_render_select() if ($(element).attr('multiple') && $(element).data('cardinality')) { options.max_selected_options = $(element).data('cardinality'); } return options; }; // Process elements that have opted-in for Chosen. $('select.chosen-enable', context).once('chosen').each(function () { options = getElementOptions(this); $(this).chosen(options); }); $(selector, context) // Disabled on: // - Field UI // - WYSIWYG elements // - Tabledrag weights // - Elements that have opted-out of Chosen // - Elements already processed by Chosen .not('#field-ui-field-storage-add-form select, #entity-form-display-edit-form select, #entity-view-display-edit-form select, .wysiwyg, .draggable select[name$="[weight]"], .draggable select[name$="[position]"], .locale-translate-filter-form select, .chosen-disable, .chosen-processed') .filter(function () { // Filter out select widgets that do not meet the minimum number of // options. var minOptions = $(this).attr('multiple') ? settings.chosen.minimum_multiple : settings.chosen.minimum_single; if (!minOptions) { // Zero value means no minimum. return true; } else { return $(this).find('option').length >= minOptions; } }) .once('chosen').each(function () { options = getElementOptions(this); $(this).chosen(options); }); } }; })(jQuery, Drupal);
SeeyaSia/www
web/modules/contrib/chosen/js/chosen.js
JavaScript
gpl-2.0
2,592
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Parse and analyse a SQL query * * @package PhpMyAdmin */ if (! defined('PHPMYADMIN')) { exit; } /** * */ $GLOBALS['unparsed_sql'] = $sql_query; $parsed_sql = PMA_SQP_parse($sql_query); $analyzed_sql = PMA_SQP_analyze($parsed_sql); // for bug 780516: now that we use case insensitive preg_match // or flags from the analyser, do not put back the reformatted query // into $sql_query, to make this kind of query work without // capitalizing keywords: // // CREATE TABLE SG_Persons ( // id int(10) unsigned NOT NULL auto_increment, // first varchar(64) NOT NULL default '', // PRIMARY KEY (`id`) // ) // Fills some variables from the analysed SQL // A table has to be created, renamed, dropped: // the navigation panel should be reloaded $reload = isset($analyzed_sql[0]['queryflags']['reload']); // check for drop database $drop_database = isset($analyzed_sql[0]['queryflags']['drop_database']); // for the presence of EXPLAIN $is_explain = isset($analyzed_sql[0]['queryflags']['is_explain']); // for the presence of DELETE $is_delete = isset($analyzed_sql[0]['queryflags']['is_delete']); // for the presence of UPDATE, DELETE or INSERT|LOAD DATA|REPLACE $is_affected = isset($analyzed_sql[0]['queryflags']['is_affected']); // for the presence of REPLACE $is_replace = isset($analyzed_sql[0]['queryflags']['is_replace']); // for the presence of INSERT $is_insert = isset($analyzed_sql[0]['queryflags']['is_insert']); // for the presence of CHECK|ANALYZE|REPAIR|OPTIMIZE|CHECKSUM TABLE $is_maint = isset($analyzed_sql[0]['queryflags']['is_maint']); // for the presence of SHOW $is_show = isset($analyzed_sql[0]['queryflags']['is_show']); // for the presence of PROCEDURE ANALYSE $is_analyse = isset($analyzed_sql[0]['queryflags']['is_analyse']); // for the presence of INTO OUTFILE $is_export = isset($analyzed_sql[0]['queryflags']['is_export']); // for the presence of GROUP BY|HAVING|SELECT DISTINCT $is_group = isset($analyzed_sql[0]['queryflags']['is_group']); // for the presence of SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND $is_func = isset($analyzed_sql[0]['queryflags']['is_func']); // for the presence of SELECT COUNT $is_count = isset($analyzed_sql[0]['queryflags']['is_count']); // check for a real SELECT ... FROM $is_select = isset($analyzed_sql[0]['queryflags']['select_from']); // the query contains a subquery $is_subquery = isset($analyzed_sql[0]['queryflags']['is_subquery']); // check for CALL // Since multiple query execution is anyway handled, // ignore the WHERE clause of the first sql statement // which might contain a phrase like 'call ' if (isset($analyzed_sql[0]['queryflags']['is_procedure']) && empty($analyzed_sql[0]['where_clause']) ) { $is_procedure = true; } else { $is_procedure = false; } // aggregates all the results into one array $analyzed_sql_results = array( "parsed_sql" => $parsed_sql, "analyzed_sql" => $analyzed_sql, "reload" => $reload, "drop_database" => $drop_database, "is_explain" => $is_explain, "is_delete" => $is_delete, "is_affected" => $is_affected, "is_replace" => $is_replace, "is_insert" => $is_insert, "is_maint" => $is_maint, "is_show" => $is_show, "is_analyse" => $is_analyse, "is_export" => $is_export, "is_group" => $is_group, "is_func" => $is_func, "is_count" => $is_count, "is_select" => $is_select, "is_procedure" => $is_procedure, "is_subquery" => $is_subquery ); // If the query is a Select, extract the db and table names and modify // $db and $table, to have correct page headers, links and left frame. // db and table name may be enclosed with backquotes, db is optional, // query may contain aliases. /** * @todo if there are more than one table name in the Select: * - do not extract the first table name * - do not show a table name in the page header * - do not display the sub-pages links) */ if ($is_select) { $prev_db = $db; if (isset($analyzed_sql[0]['table_ref'][0]['table_true_name'])) { $table = $analyzed_sql[0]['table_ref'][0]['table_true_name']; } if (isset($analyzed_sql[0]['table_ref'][0]['db']) && /*overload*/mb_strlen($analyzed_sql[0]['table_ref'][0]['db']) ) { $db = $analyzed_sql[0]['table_ref'][0]['db']; } else { $db = $prev_db; } // Don't change reload, if we already decided to reload in import if (empty($reload) && empty($GLOBALS['is_ajax_request'])) { $reload = ($db == $prev_db) ? 0 : 1; } } ?>
rakeshkaundilya/phpmyadmin
libraries/parse_analyze.inc.php
PHP
gpl-2.0
4,562
# -*- coding: utf-8 -*- """ /*************************************************************************** Rasterize.py ------------------- begin : 2016-10-05 copyright : (C) 2016 by OPENGIS.ch email : matthias@opengis.ch ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ """ from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm from qgis.PyQt.QtGui import QImage, QPainter from qgis.PyQt.QtCore import QSize from qgis.core import ( QgsMapSettings, QgsMapRendererCustomPainterJob, QgsRectangle, QgsProject, QgsProcessingException, QgsProcessingParameterExtent, QgsProcessingParameterString, QgsProcessingParameterNumber, QgsProcessingParameterMapLayer, QgsProcessingParameterRasterDestination, QgsRasterFileWriter ) import qgis import osgeo.gdal import os import tempfile import math __author__ = 'Matthias Kuhn' __date__ = '2016-10-05' __copyright__ = '(C) 2016 by OPENGIS.ch' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' class RasterizeAlgorithm(QgisAlgorithm): """Processing algorithm renders map canvas to a raster file. It's possible to choose the following parameters: - Map theme to render - Layer to render - The minimum extent to render - The tile size - Map unit per pixel - The output (can be saved to a file or to a temporary file and automatically opened as layer in qgis) """ # Constants used to refer to parameters and outputs. They will be # used when calling the algorithm from another algorithm, or when # calling from the QGIS console. OUTPUT = 'OUTPUT' MAP_THEME = 'MAP_THEME' LAYER = 'LAYER' EXTENT = 'EXTENT' TILE_SIZE = 'TILE_SIZE' MAP_UNITS_PER_PIXEL = 'MAP_UNITS_PER_PIXEL' def __init__(self): super().__init__() def initAlgorithm(self, config=None): """Here we define the inputs and output of the algorithm, along with some other properties. """ # The parameters self.addParameter( QgsProcessingParameterExtent(self.EXTENT, description=self.tr( 'Minimum extent to render'))) self.addParameter( QgsProcessingParameterNumber( self.TILE_SIZE, self.tr('Tile size'), defaultValue=1024, minValue=64)) self.addParameter(QgsProcessingParameterNumber( self.MAP_UNITS_PER_PIXEL, self.tr( 'Map units per ' 'pixel'), defaultValue=100, minValue=0, type=QgsProcessingParameterNumber.Double )) map_theme_param = QgsProcessingParameterString( self.MAP_THEME, description=self.tr( 'Map theme to render'), defaultValue=None, optional=True) map_theme_param.setMetadata( {'widget_wrapper': { 'class': 'processing.gui.wrappers_map_theme.MapThemeWrapper'}}) self.addParameter(map_theme_param) self.addParameter( QgsProcessingParameterMapLayer( self.LAYER, description=self.tr( 'Single layer to render'), optional=True)) # We add a raster layer as output self.addParameter(QgsProcessingParameterRasterDestination( self.OUTPUT, self.tr( 'Output layer'))) def name(self): # Unique (non-user visible) name of algorithm return 'rasterize' def displayName(self): # The name that the user will see in the toolbox return self.tr('Convert map to raster') def group(self): return self.tr('Raster tools') def tags(self): return self.tr('layer,raster,convert,file,map themes,tiles,render').split(',') # def processAlgorithm(self, progress): def processAlgorithm(self, parameters, context, feedback): """Here is where the processing itself takes place.""" # The first thing to do is retrieve the values of the parameters # entered by the user map_theme = self.parameterAsString( parameters, self.MAP_THEME, context) layer = self.parameterAsLayer( parameters, self.LAYER, context) extent = self.parameterAsExtent( parameters, self.EXTENT, context) tile_size = self.parameterAsInt( parameters, self.TILE_SIZE, context) mupp = self.parameterAsDouble( parameters, self.MAP_UNITS_PER_PIXEL, context) output_layer = self.parameterAsOutputLayer( parameters, self.OUTPUT, context) tile_set = TileSet(map_theme, layer, extent, tile_size, mupp, output_layer, qgis.utils.iface.mapCanvas().mapSettings()) tile_set.render(feedback) return {self.OUTPUT: output_layer} class TileSet(): """ A set of tiles """ def __init__(self, map_theme, layer, extent, tile_size, mupp, output, map_settings): """ :param map_theme: :param extent: :param layer: :param tile_size: :param mupp: :param output: :param map_settings: Map canvas map settings used for some fallback values and CRS """ self.extent = extent self.mupp = mupp self.tile_size = tile_size driver = self.getDriverForFile(output) if not driver: raise QgsProcessingException( u'Could not load GDAL driver for file {}'.format(output)) crs = map_settings.destinationCrs() self.x_tile_count = math.ceil(extent.width() / mupp / tile_size) self.y_tile_count = math.ceil(extent.height() / mupp / tile_size) xsize = self.x_tile_count * tile_size ysize = self.y_tile_count * tile_size self.dataset = driver.Create(output, xsize, ysize, 3) # 3 bands self.dataset.SetProjection(str(crs.toWkt())) self.dataset.SetGeoTransform( [extent.xMinimum(), mupp, 0, extent.yMaximum(), 0, -mupp]) self.image = QImage(QSize(tile_size, tile_size), QImage.Format_ARGB32) self.settings = QgsMapSettings() self.settings.setOutputDpi(self.image.logicalDpiX()) self.settings.setOutputImageFormat(QImage.Format_ARGB32) self.settings.setDestinationCrs(crs) self.settings.setOutputSize(self.image.size()) self.settings.setFlag(QgsMapSettings.Antialiasing, True) self.settings.setFlag(QgsMapSettings.RenderMapTile, True) if QgsProject.instance().mapThemeCollection().hasMapTheme(map_theme): self.settings.setLayers( QgsProject.instance().mapThemeCollection( ).mapThemeVisibleLayers( map_theme)) self.settings.setLayerStyleOverrides( QgsProject.instance().mapThemeCollection( ).mapThemeStyleOverrides( map_theme)) elif layer: self.settings.setLayers([layer]) else: self.settings.setLayers(map_settings.layers()) def render(self, feedback): for x in range(self.x_tile_count): for y in range(self.y_tile_count): if feedback.isCanceled(): return cur_tile = x * self.y_tile_count + y num_tiles = self.x_tile_count * self.y_tile_count self.renderTile(x, y, feedback) feedback.setProgress(int((cur_tile / num_tiles) * 100)) def renderTile(self, x, y, feedback): """ Render one tile :param x: The x index of the current tile :param y: The y index of the current tile """ painter = QPainter(self.image) self.settings.setExtent(QgsRectangle( self.extent.xMinimum() + x * self.mupp * self.tile_size, self.extent.yMaximum() - (y + 1) * self.mupp * self.tile_size, self.extent.xMinimum() + (x + 1) * self.mupp * self.tile_size, self.extent.yMaximum() - y * self.mupp * self.tile_size)) job = QgsMapRendererCustomPainterJob(self.settings, painter) job.renderSynchronously() painter.end() # Needs not to be deleted or Windows will kill it too early... tmpfile = tempfile.NamedTemporaryFile(suffix='.png', delete=False) try: self.image.save(tmpfile.name) src_ds = osgeo.gdal.Open(tmpfile.name) self.dataset.WriteRaster(x * self.tile_size, y * self.tile_size, self.tile_size, self.tile_size, src_ds.ReadRaster(0, 0, self.tile_size, self.tile_size)) except Exception as e: feedback.reportError(str(e)) finally: del src_ds tmpfile.close() os.unlink(tmpfile.name) def getDriverForFile(self, filename): """ Get the GDAL driver for a filename, based on its extension. (.gpkg, .mbtiles...) """ _, extension = os.path.splitext(filename) # If no extension is set, use .tif as default if extension == '': extension = '.tif' driver_name = QgsRasterFileWriter.driverForExtension(extension[1:]) return osgeo.gdal.GetDriverByName(driver_name)
GeoCat/QGIS
python/plugins/processing/algs/qgis/Rasterize.py
Python
gpl-2.0
10,479
<?php if (!defined('APPLICATION')) exit(); /* Copyright 2008, 2009 Vanilla Forums Inc. This file is part of Garden. Garden 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. Garden 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 Garden. If not, see <http://www.gnu.org/licenses/>. Contact Vanilla Forums Inc. at support [at] vanillaforums [dot] com */ /** * Renders recently active bookmarked discussions */ class BookmarkedModule extends Gdn_Module { public function GetData($Limit = 10) { $this->Data = FALSE; if (Gdn::Session()->IsValid() && C('Vanilla.Modules.ShowBookmarkedModule', TRUE)) { $BookmarkIDs = Gdn::SQL() ->Select('DiscussionID') ->From('UserDiscussion') ->Where('UserID', Gdn::Session()->UserID) ->Where('Bookmarked', 1) ->Get()->ResultArray(); $BookmarkIDs = ConsolidateArrayValuesByKey($BookmarkIDs, 'DiscussionID'); if (count($BookmarkIDs)) { $DiscussionModel = new DiscussionModel(); DiscussionModel::CategoryPermissions(); $DiscussionModel->SQL->WhereIn('d.DiscussionID', $BookmarkIDs); $this->Data = $DiscussionModel->Get( 0, $Limit ); } else { $this->Data = FALSE; } } } public function AssetTarget() { return 'Panel'; } public function ToString() { if (!isset($this->Data)) $this->GetData(); if (is_object($this->Data) && $this->Data->NumRows() > 0) return parent::ToString(); return ''; } }
Curter29/Vanilla-mod
applications/vanilla/modules/class.bookmarkedmodule.php
PHP
gpl-2.0
2,066
/** * Desarrollado por: Judelvis Antonio Rivas Perdomo * Fecha Creacion: 09 de Noviembre de 2014 */ $(function() { $('#tabs').tabs(); listar_pendientes(); listar_procesando(); listar_procesado(); listar_rechazo_cliente(); listar_rechazo_admin(); }); function listar_pendientes(){ var datos = "estatus=0&panel=1"; $("#resp1").html(''); alert(sUrlP); $.ajax({ url : sUrlP + "listar_pedidos_pendientes", data: datos, type : "POST", dataType : "json", success : function(json) {//alert(json); if(json['resp']==1){ var Grid1 = new TGrid(json, 'resp1','Pedidos Pendientes por Depositar'); Grid1.SetNumeracion(true); Grid1.SetName("PDepositar"); Grid1.SetDetalle(); Grid1.Generar(); }else $("#resp1").html("No posee Pedidos Pendientes por Depositar"); } }); } function listar_procesando(){ var datos = "estatus=1"; $("#resp2").html(''); //alert(sUrlP + "listar_pedidos_cliente"); $.ajax({ url : sUrlP + "listar_pedidos_cliente", data: datos, type : "POST", dataType : "json", success : function(json) {//alert(json); if(json['resp']==1){ var Grid2 = new TGrid(json, 'resp2','Pedidos Pendientes por Aprobar'); Grid2.SetNumeracion(true); Grid2.SetName("procesando"); Grid2.SetDetalle(); Grid2.Generar(); }else $("#resp2").html("No posee Pedidos Pendientes por Aprobar"); } }); } function listar_procesado(){ var datos = "estatus=2"; $("#resp3").html(''); alert(sUrlP); $.ajax({ url : sUrlP + "listar_pedidos_cliente", data: datos, type : "POST", dataType : "json", success : function(json) {//alert(json); if(json['resp']==1){ var Grid3 = new TGrid(json, 'resp3','Pedidos Aprobados'); Grid3.SetNumeracion(true); Grid3.SetName("Procesado"); Grid3.SetDetalle(); Grid3.Generar(); }else $("#resp3").html("No posee Pedidos Aprobados"); } }); } function listar_rechazo_cliente(){ var datos = "estatus=3"; $("#resp4").html(''); $.ajax({ url : sUrlP + "listar_pedidos_cliente", data: datos, type : "POST", dataType : "json", success : function(json) {//alert(json); if(json['resp']==1){ var Grid4 = new TGrid(json, 'resp4','Pedidos Rechazados Por Cliente'); Grid4.SetNumeracion(true); Grid4.SetName("Rcliente"); Grid4.SetDetalle(); Grid4.Generar(); }else $("#resp4").html("No posee Pedidos Rechazados por Cliente"); } }); } function listar_rechazo_admin(){ var datos = "estatus=4"; $("#resp5").html(''); $.ajax({ url : sUrlP + "listar_pedidos_cliente", data: datos, type : "POST", dataType : "json", success : function(json) {//alert(json); if(json['resp']==1){ var Grid5 = new TGrid(json, 'resp5','Pedidos rechazados por administrador'); Grid5.SetNumeracion(true); Grid5.SetName("Radmin"); Grid5.SetDetalle(); Grid5.Generar(); }else $("#resp5").html("No posee Pedidos Rechazados por Administrador"); } }); }
judelvis/jpa-garte
system/js/panel/principal.js
JavaScript
gpl-2.0
2,919
""" Page functions for Host Aggregates pages """ import attr from navmazing import NavigateToAttribute from widgetastic_patternfly import BootstrapNav from widgetastic_patternfly import BreadCrumb from widgetastic_patternfly import Button from widgetastic_patternfly import Dropdown from widgetastic_patternfly import View from cfme.base.ui import BaseLoggedInPage from cfme.common import Taggable from cfme.common import TaggableCollection from cfme.exceptions import ItemNotFound from cfme.modeling.base import BaseCollection from cfme.modeling.base import BaseEntity from cfme.utils.appliance.implementations.ui import CFMENavigateStep from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.appliance.implementations.ui import navigator from cfme.utils.providers import get_crud_by_name from widgetastic_manageiq import Accordion from widgetastic_manageiq import BaseEntitiesView from widgetastic_manageiq import ItemsToolBarViewSelector from widgetastic_manageiq import ManageIQTree from widgetastic_manageiq import PaginationPane from widgetastic_manageiq import Search from widgetastic_manageiq import SummaryTable from widgetastic_manageiq import Text class HostAggregatesView(BaseLoggedInPage): @property def in_host_aggregates(self): return ( self.logged_in_as_current_user and self.navigation.currently_selected == ['Compute', 'Clouds', 'Host Aggregates'] ) class HostAggregatesToolBar(View): policy = Dropdown('Policy') download = Dropdown('Download') configuration = Dropdown('Configuration') view_selector = View.nested(ItemsToolBarViewSelector) class HostAggregatesEntities(BaseEntitiesView): pass class HostAggregatesDetailsToolBar(View): policy = Dropdown('Policy') download = Button(title='Print or export summary') configuration = Dropdown('Configuration') class HostAggregatesDetailsAccordion(View): @View.nested class properties(Accordion): # noqa tree = ManageIQTree() @View.nested class relationships(Accordion): # noqa tree = ManageIQTree() class HostAggregatesDetailsEntities(View): breadcrumb = BreadCrumb() title = Text('//div[@id="main-content"]//h1') properties = SummaryTable(title='Properties') relationships = SummaryTable(title='Relationships') smart_management = SummaryTable(title='Smart Management') class HostAggregatesAllView(HostAggregatesView): toolbar = HostAggregatesToolBar() paginator = PaginationPane() search = View.nested(Search) including_entities = View.include(HostAggregatesEntities, use_parent=True) @View.nested class my_filters(Accordion): # noqa ACCORDION_NAME = "My Filters" navigation = BootstrapNav('.//div/ul') tree = ManageIQTree() @property def is_displayed(self): return ( self.in_host_aggregates and self.entities.title.text == 'Host Aggregates') class HostAggregatesDetailsView(HostAggregatesView): @property def is_displayed(self): obj = self.context['object'] return ( self.in_host_aggregates and self.entities.title.text == obj.expected_details_title and self.entities.breadcrumb.active_location == obj.expected_details_breadcrumb and self.entities.relationships.get_text_of('Cloud Provider') == obj.provider.name ) toolbar = HostAggregatesDetailsToolBar() sidebar = HostAggregatesDetailsAccordion() entities = HostAggregatesDetailsEntities() @attr.s class HostAggregates(BaseEntity, Taggable): """ Host Aggregates class to support navigation """ _param_name = "HostAggregate" name = attr.ib() provider = attr.ib() ram = attr.ib(default=None) vcpus = attr.ib(default=None) disk = attr.ib(default=None) swap = attr.ib(default=None) rxtx = attr.ib(default=None) is_public = attr.ib(default=True) tenant = attr.ib(default=None) def refresh(self): """Refresh provider relationships and browser""" self.provider.refresh_provider_relationships() self.browser.refresh() @property def instance_count(self): """ number of instances using host aggregates. Returns: :py:class:`int` instance count. """ view = navigate_to(self, 'Details') return int(view.entities.relationships.get_text_of('Instances')) @attr.s class HostAggregatesCollection(BaseCollection, TaggableCollection): ENTITY = HostAggregates def all(self): provider = self.filters.get('provider') # None if no filter, need for entity instantiation view = navigate_to(self, 'All') result = [] flavors = view.entities.get_all(surf_pages=True) for flavor in flavors: if provider is not None: if flavor.data['cloud_provider'] == provider.name: entity = self.instantiate(flavor.data['name'], provider) else: entity = self.instantiate(flavor.data['name'], get_crud_by_name(flavor.data['cloud_provider'])) result.append(entity) return result @navigator.register(HostAggregatesCollection, 'All') class HostAggregatesAll(CFMENavigateStep): VIEW = HostAggregatesAllView prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn') def step(self, *args, **kwargs): self.prerequisite_view.navigation.select('Compute', 'Clouds', 'Host Aggregates') @navigator.register(HostAggregates, 'Details') class HostAggregatesDetails(CFMENavigateStep): VIEW = HostAggregatesDetailsView prerequisite = NavigateToAttribute('parent', 'All') def step(self, *args, **kwargs): self.prerequisite_view.toolbar.view_selector.select('List View') try: row = self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True) except ItemNotFound: raise ItemNotFound('Could not locate host aggregate "{}" on provider {}' .format(self.obj.name, self.obj.provider.name)) row.click()
nachandr/cfme_tests
cfme/cloud/host_aggregates.py
Python
gpl-2.0
6,202
#! /usr/bin/env python # @ORIGINAL_AUTHOR: Robert Muth # # python.org has useful info about the Python programming language # # The Python library is described here: http://docs.python.org/lib/lib.html # An the index for the library here: http://docs.python.org/lib/genindex.html import sys import os import getopt import re import string import copy ####################################################################### # Version ####################################################################### def Version(): (l,v,x) = string.split('$Revision: 1.5 $') return v ####################################################################### # Usage ####################################################################### def Usage(): print "Usage: flowgraph.py [OPTION]+ assembler-listing edge-profile" print print "flowgraph converts a disassembled routine into a flowgraph which can be rendered using vcg" print print "assembler-listing is a textual disassembler listing generated with" print "objdump-routine.csh or directly with objdump" print print "edge-profile is a profile generated with the edgcnt Pin tool" return -1 ####################################################################### # Messages ####################################################################### def Info(str): print >> sys.stderr,"I:",str return def Warning(str): print >> sys.stderr,"W:", str return def Error(str): print >> sys.stderr, "E:",str sys.exit(-1) ####################################################################### # ####################################################################### # 402d05: 41 56 push %r14 PatternNoFallthrough = re.compile(r'call|ret|jmp') PatternCall = re.compile(r'call') class INS: def __init__(self, addr, opcode ): self._addr = addr self._opcode = opcode self._next = None self._leader = 0 self._bbl = None return def get_opcode(self): return self._opcode def set_next(self,next): self._next = next return def get_next(self): return self._next def get_addr(self): return self._addr def get_leader(self): return self._leader def set_leader(self,leader): self._leader = leader def get_bbl(self): return self._bbl def set_bbl(self,bbl): self._bbl = bbl def has_no_fallthru(self): return PatternNoFallthrough.search(self._opcode) def is_call(self): return PatternCall.search(self._opcode) ####################################################################### ## ####################################################################### ALL_INS = {} PatternAssemler = re.compile(r'^\s*([0-9a-fA-F]+):\s*(?:[0-9a-fA-F][0-9a-fA-F] )+\s*(.+)$') def ProcessAssemblerListing(lines): last_ins = None for l in lines: match = PatternAssemler.match(l) if not match: # print "bad line ",l continue addr = long(match.group(1),16) ins = INS( addr, match.group(2) ) ALL_INS[addr] = ins if last_ins: last_ins.set_next(ins) last_ins = ins return ####################################################################### # 0x0000000000400366 0x0000000000402300 2182 PatternEdge2 = re.compile(r'^\s*0x([0-9a-fA-F]+)\s+0x([0-9a-fA-F]+)\s+([0-9]+)\s*$') PatternEdge3 = re.compile(r'^\s*0x([0-9a-fA-F]+)\s+0x([0-9a-fA-F]+)\s+([a-zA-Z])\s+([0-9]+)\s*$') def ProcessEdgProfile(lines): version = string.split(lines[0]) if version[0] != "EDGCOUNT": Error("files is not an edge profile") if version[1] == "2.0": v = 2 elif version[1] == "3.0": v = 3 else: Error("unsupported edge profile version") edg_list = [] for l in lines[1:]: if v == 2: match = PatternEdge2.match(l) elif v==3: match = PatternEdge3.match(l) if not match: continue if v == 2: src = long(match.group(1),16) dst = long(match.group(2),16) count = long(match.group(3)) type = "u" elif v == 3: src = long(match.group(1),16) dst = long(match.group(2),16) type = match.group(3) count = long(match.group(4)) if ALL_INS.has_key(src): next = ALL_INS[src].get_next() if next: next.set_leader(1) if ALL_INS.has_key(dst): ins = ALL_INS[dst] ins.set_leader(1) if ALL_INS.has_key(src) or ALL_INS.has_key(dst): edg_list.append( (src,dst,count,type) ) return edg_list ####################################################################### # ####################################################################### class EDG: def __init__(self,src,dst,count, type): self._src = src self._dst = dst self._count = count self._type = type return def is_fallthru(self): return self._fallthru def StringVCG(self, threshold = 100000000000L): s = "" if self._count > threshold: s += "\t" + "nearedge:\n" else: s += "\t" + "edge:\n" s += "\t{\n" s += "\t\t" + "sourcename: \"" + hex(self._src._start) + "\"\n" s += "\t\t" + "targetname: \"" + hex(self._dst._start) + "\"\n" if self._type == "F" or self._type == "L": s += "\t\t" + "thickness: 4\n" else: s += "\t\t" + "thickness: 2\n" s += "\t\t" + "label: \"%s(%d)\"\n" % (self._type,self._count) # s += "\t\t" + "priority: %d\n" % self._count s += "\t}\n" return s ####################################################################### class BBL: def __init__(self,start): self._start = start self._ins = [] self._in = [] self._out = [] self._count = 0 self._in_count = 0 self._out_count = 0 self._next = None return def add_ins(self,ins): self._ins.append(ins) self._end = ins.get_addr() return def set_count(self,count): assert( self._count == 0 ) self._count = count return def add_out_edg(self, edg ): self._out.append(edg) return def add_in_edg(self, edg ): self._in.append(edg) return def add_in_count(self, count ): self._in_count += count return def add_out_count(self, count ): self._out_count += count return def count_in(self): count = self._in_count for e in self._in: count += e._count return count def count_out(self): count = self._out_count for e in self._out: count += e._count return count def set_next(self,next): self._next = next return def get_next(self): return self._next def get_start(self): return self._start def is_call(self): return self._ins[-1].is_call() def has_no_fallthru(self): return self._ins[-1].has_no_fallthru() def String(self): s = "BBL at %x count %d (i: %d o: %d)\n" % (self._start, self._count, self._in_count, self._out_count) s += "i: " for edg in self._in: s += "%x (%d) " % (edg._src.get_start(),edg._count) s += "\n" s += "o: " for edg in self._out: s += "%x (%d) " % (edg._dst.get_start(),edg._count) s += "\n" for ins in self._ins: s += "%x %s\n" % (ins.get_addr(),ins.get_opcode()) return s def StringVCG(self,threshold=1000): s = "\t" + "node:\n" s += "\t" + "{\n" if self._count > threshold: s += "\t\t" + "color: red\n" s += "\t\t" + "title: \"" + hex(self._start) + "\"\n" s += "\t\t" + "label: \"" + hex(self._start) + " (" + str(self._count) + ")\\n" for ins in self._ins: s += "%x: %s\\n" % (ins.get_addr(),ins.get_opcode()) s += "\"\n" s += "\t" + "}\n" return s ####################################################################### # ####################################################################### ALL_BBL = {} ALL_EDG = [] ####################################################################### # ####################################################################### def CreateCFG(edg_list): no_interproc_edges = 1 ins_list = ALL_INS.items() ins_list.sort() # by addr bbl_list = [] Info("BBL create") last = None for (a,ins) in ins_list: if ins.get_leader(): start = ins.get_addr() bbl = BBL(start) bbl_list.append(bbl) ALL_BBL[start] = bbl if last: last.set_next( bbl ) last = bbl last.add_ins( ins ) ins.set_bbl( last ) if ins.has_no_fallthru(): next = ins.get_next() if next: next.set_leader(1) Info( "Created %d bbls" % len(bbl_list)) # for bbl in bbl_list: print bbl.String() Info( "EDG create") for (src,dst,count,type) in edg_list: if ALL_INS.has_key(src): bbl_src = ALL_INS[src].get_bbl() else: assert( ALL_BBL.has_key(dst) ) if no_interproc_edges: ALL_BBL[dst].add_in_count(count) continue bbl_src = BBL(src) ALL_BBL[src] = bbl_src if ALL_BBL.has_key(dst): bbl_dst = ALL_BBL[dst] else: if no_interproc_edges: bbl_src.add_out_count(count) continue bbl_dst = BBL(dst) ALL_BBL[dst] = bbl_dst edg = EDG( bbl_src, bbl_dst, count, type) ALL_EDG.append( edg ) bbl_src.add_out_edg( edg ) bbl_dst.add_in_edg( edg ) Info("propagate counts and add fallthrus") for bbl in bbl_list: count = bbl.count_in() bbl.set_count(count) count -= bbl.count_out() if count < 0: Warning("negative fallthru count") count = 0 next = bbl.get_next() if count > 0: if bbl.has_no_fallthru(): Info("losing flow %d\n" % count) elif next: edg = EDG(bbl,next,count,"F") ALL_EDG.append( edg ) bbl.add_out_edg( edg ) next.add_in_edg( edg ) if bbl.is_call() and next: edg = EDG(bbl,next, 0,"L") ALL_EDG.append( edg ) bbl.add_out_edg( edg ) next.add_in_edg( edg ) # for bbl in bbl_list: print bbl.String() return bbl_list def DumpVCG(): start = 0 end = 0 print "// ###################################################################################" print "// VCG Flowgraph for %x - %x" % (start,end) print "// ###################################################################################" print "graph:" print "{"; print "title: \"Control Flow Graph for rtn %x - %x \"" % (start,end); print "label: \"Control Flow Graph for rtn %x - %x \"" % (start,end); print "display_edge_labels: yes" print "layout_downfactor: 100" print "layout_nearfactor: 10" print "layout_upfactor: 1" # print "dirty_edge_labels: yes" print "layout_algorithm: mindepth" print "manhatten_edges: yes" print "edge.arrowsize: 15" print "late_edge_labels: yes" for e in ALL_EDG: print e.StringVCG() bbl_list = ALL_BBL.items() bbl_list.sort() for (x,b) in bbl_list: print b.StringVCG() print "}"; print "// eof" return ####################################################################### # Main ####################################################################### def Main(argv): if len(argv) != 2: Usage() return -1 Info( "Reading listing") filename = argv[0] try: input = open(filename, "r") lines = input.readlines() input.close() except: Error("cannot read data " + filename) ProcessAssemblerListing(lines) Info( "Reading edges") filename = argv[1] try: input = open(filename, "r") lines = input.readlines() input.close() except: Error("cannot read data " + filename) edg_list = ProcessEdgProfile(lines) Info("Read %d edges" % len(edg_list)) bbl_list = CreateCFG( edg_list) Info("Dump VCG to stdout") DumpVCG() return 0 ####################################################################### # ####################################################################### if __name__ == "__main__": sys.exit( Main( sys.argv[1:]) ) ####################################################################### # eof #######################################################################
cyjseagull/SHMA
zsim-nvmain/pin_kit/source/tools/SimpleExamples/flowgraph.py
Python
gpl-2.0
13,531
/* * steghide 0.5.1 - a steganography program * Copyright (C) 1999-2003 Stefan Hetzl <shetzl@chello.at> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include <cstdlib> #include <cmath> #include "common.h" #include "JpegSampleValue.h" JpegSampleValue::JpegSampleValue (int c) : SampleValue(), DctCoeff (c) { Key = (UWORD32) DctCoeff ; EValue = calcEValue (DctCoeff) ; } SampleValue *JpegSampleValue::getNearestTargetSampleValue (EmbValue t) const { SWORD16 minvalue = 0, maxvalue = 0 ; if (DctCoeff > 0) { minvalue = 1 ; maxvalue = SWORD16_MAX ; } else if (DctCoeff < 0) { minvalue = SWORD16_MIN ; maxvalue = -1 ; } else { myassert(false) ; } SWORD16 dctc_up = DctCoeff, dctc_down = DctCoeff, dctc_new = 0 ; bool found = false ; do { if (dctc_up < maxvalue) { dctc_up++ ; } if (dctc_down > minvalue) { dctc_down-- ; } if (calcEValue(dctc_up) == t && calcEValue(dctc_down) == t) { if (RndSrc.getBool()) { dctc_new = dctc_up ; } else { dctc_new = dctc_down ; } found = true ; } else if (calcEValue(dctc_up) == t) { dctc_new = dctc_up ; found = true ; } else if (calcEValue(dctc_down) == t) { dctc_new = dctc_down ; found = true ; } } while (!found) ; return ((SampleValue *) new JpegSampleValue (dctc_new)) ; } UWORD32 JpegSampleValue::calcDistance (const SampleValue *s) const { const JpegSampleValue *sample = (const JpegSampleValue*) s ; /* If s is not a JpegSampleValue then we get into real trouble here. But calcDistance is called very often, a dynamic_cast costs a lot of time and it does not make sense to pass anything but a JpegSampleValue as s anyway. */ int d = DctCoeff - sample->DctCoeff ; return ((d >= 0) ? ((UWORD32) d) : ((UWORD32) -d)) ; } std::string JpegSampleValue::getName (void) const { char buf[128] ; sprintf (buf, "%d", DctCoeff) ; return std::string (buf) ; }
erykrutkowski/Steghide-GUI
steghide-src/JpegSampleValue.cc
C++
gpl-2.0
2,573
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Mike Brown (SNL) ------------------------------------------------------------------------- */ #include "math.h" #include "stdio.h" #include "string.h" #include "fix_nve_asphere.h" #include "math_extra.h" #include "atom.h" #include "atom_vec.h" #include "force.h" #include "update.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ FixNVEAsphere::FixNVEAsphere(LAMMPS *lmp, int narg, char **arg) : FixNVE(lmp, narg, arg) { inertia = memory->create_2d_double_array(atom->ntypes+1,3,"fix_nve_asphere:inertia"); // error checks if (!atom->angmom_flag || !atom->quat_flag || !atom->torque_flag || !atom->avec->shape_type) error->all("Fix nve/asphere requires atom attributes " "angmom, quat, torque, shape"); if (atom->radius_flag || atom->rmass_flag) error->all("Fix nve/asphere cannot be used with atom attributes " "diameter or rmass"); } /* ---------------------------------------------------------------------- */ FixNVEAsphere::~FixNVEAsphere() { memory->destroy_2d_double_array(inertia); } /* ---------------------------------------------------------------------- */ void FixNVEAsphere::init() { // check that all particles are finite-size // no point particles allowed, spherical is OK double **shape = atom->shape; int *type = atom->type; int *mask = atom->mask; int nlocal = atom->nlocal; if (igroup == atom->firstgroup) nlocal = atom->nfirst; for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) if (shape[type[i]][0] == 0.0) error->one("Fix nve/asphere requires extended particles"); FixNVE::init(); calculate_inertia(); } /* ---------------------------------------------------------------------- */ void FixNVEAsphere::initial_integrate(int vflag) { double dtfm; double **x = atom->x; double **v = atom->v; double **f = atom->f; double **quat = atom->quat; double **angmom = atom->angmom; double **torque = atom->torque; double *mass = atom->mass; int *type = atom->type; int *mask = atom->mask; int nlocal = atom->nlocal; if (igroup == atom->firstgroup) nlocal = atom->nfirst; // set timestep here since dt may have changed or come via rRESPA dtq = 0.5 * dtv; for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) { dtfm = dtf / mass[type[i]]; v[i][0] += dtfm * f[i][0]; v[i][1] += dtfm * f[i][1]; v[i][2] += dtfm * f[i][2]; x[i][0] += dtv * v[i][0]; x[i][1] += dtv * v[i][1]; x[i][2] += dtv * v[i][2]; // update angular momentum by 1/2 step // update quaternion a full step via Richardson iteration // returns new normalized quaternion angmom[i][0] += dtf * torque[i][0]; angmom[i][1] += dtf * torque[i][1]; angmom[i][2] += dtf * torque[i][2]; richardson(quat[i],angmom[i],inertia[type[i]]); } } /* ---------------------------------------------------------------------- */ void FixNVEAsphere::final_integrate() { double dtfm; double **v = atom->v; double **f = atom->f; double **angmom = atom->angmom; double **torque = atom->torque; double *mass = atom->mass; int *type = atom->type; int *mask = atom->mask; int nlocal = atom->nlocal; if (igroup == atom->firstgroup) nlocal = atom->nfirst; for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) { dtfm = dtf / mass[type[i]]; v[i][0] += dtfm * f[i][0]; v[i][1] += dtfm * f[i][1]; v[i][2] += dtfm * f[i][2]; angmom[i][0] += dtf * torque[i][0]; angmom[i][1] += dtf * torque[i][1]; angmom[i][2] += dtf * torque[i][2]; } } /* ---------------------------------------------------------------------- Richardson iteration to update quaternion accurately ------------------------------------------------------------------------- */ void FixNVEAsphere::richardson(double *q, double *m, double *moments) { // compute omega at 1/2 step from m at 1/2 step and q at 0 double w[3]; omega_from_mq(q,m,moments,w); // full update from dq/dt = 1/2 w q double wq[4]; MathExtra::multiply_vec_quat(w,q,wq); double qfull[4]; qfull[0] = q[0] + dtq * wq[0]; qfull[1] = q[1] + dtq * wq[1]; qfull[2] = q[2] + dtq * wq[2]; qfull[3] = q[3] + dtq * wq[3]; MathExtra::normalize4(qfull); // 1st half of update from dq/dt = 1/2 w q double qhalf[4]; qhalf[0] = q[0] + 0.5*dtq * wq[0]; qhalf[1] = q[1] + 0.5*dtq * wq[1]; qhalf[2] = q[2] + 0.5*dtq * wq[2]; qhalf[3] = q[3] + 0.5*dtq * wq[3]; MathExtra::normalize4(qhalf); // re-compute omega at 1/2 step from m at 1/2 step and q at 1/2 step // recompute wq omega_from_mq(qhalf,m,moments,w); MathExtra::multiply_vec_quat(w,qhalf,wq); // 2nd half of update from dq/dt = 1/2 w q qhalf[0] += 0.5*dtq * wq[0]; qhalf[1] += 0.5*dtq * wq[1]; qhalf[2] += 0.5*dtq * wq[2]; qhalf[3] += 0.5*dtq * wq[3]; MathExtra::normalize4(qhalf); // corrected Richardson update q[0] = 2.0*qhalf[0] - qfull[0]; q[1] = 2.0*qhalf[1] - qfull[1]; q[2] = 2.0*qhalf[2] - qfull[2]; q[3] = 2.0*qhalf[3] - qfull[3]; MathExtra::normalize4(q); } /* ---------------------------------------------------------------------- compute omega from angular momentum w = omega = angular velocity in space frame wbody = angular velocity in body frame project space-frame angular momentum onto body axes and divide by principal moments ------------------------------------------------------------------------- */ void FixNVEAsphere::omega_from_mq(double *q, double *m, double *moments, double *w) { double rot[3][3]; MathExtra::quat_to_mat(q,rot); double wbody[3]; MathExtra::transpose_times_column3(rot,m,wbody); wbody[0] /= moments[0]; wbody[1] /= moments[1]; wbody[2] /= moments[2]; MathExtra::times_column3(rot,wbody,w); } /* ---------------------------------------------------------------------- principal moments of inertia for ellipsoids ------------------------------------------------------------------------- */ void FixNVEAsphere::calculate_inertia() { double *mass = atom->mass; double **shape = atom->shape; for (int i = 1; i <= atom->ntypes; i++) { inertia[i][0] = 0.2*mass[i] * (shape[i][1]*shape[i][1]+shape[i][2]*shape[i][2]); inertia[i][1] = 0.2*mass[i] * (shape[i][0]*shape[i][0]+shape[i][2]*shape[i][2]); inertia[i][2] = 0.2*mass[i] * (shape[i][0]*shape[i][0]+shape[i][1]*shape[i][1]); } }
nchong/icliggghts
src/ASPHERE/fix_nve_asphere.cpp
C++
gpl-2.0
7,251
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class Replace { /** * REPLACE. * * @param mixed $oldText The text string value to modify * @param mixed $start Integer offset for start character of the replacement * @param mixed $chars Integer number of characters to replace from the start offset * @param mixed $newText String to replace in the defined position */ public static function replace($oldText, $start, $chars, $newText): string { $oldText = Functions::flattenSingleValue($oldText); $start = Functions::flattenSingleValue($start); $chars = Functions::flattenSingleValue($chars); $newText = Functions::flattenSingleValue($newText); $left = Extract::left($oldText, $start - 1); $right = Extract::right($oldText, Text::length($oldText) - ($start + $chars) + 1); return $left . $newText . $right; } /** * SUBSTITUTE. * * @param mixed $text The text string value to modify * @param mixed $fromText The string value that we want to replace in $text * @param mixed $toText The string value that we want to replace with in $text * @param mixed $instance Integer instance Number for the occurrence of frmText to change */ public static function substitute($text = '', $fromText = '', $toText = '', $instance = 0): string { $text = Functions::flattenSingleValue($text); $fromText = Functions::flattenSingleValue($fromText); $toText = Functions::flattenSingleValue($toText); $instance = floor(Functions::flattenSingleValue($instance)); if ($instance == 0) { return str_replace($fromText, $toText, $text); } $pos = -1; while ($instance > 0) { $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8'); if ($pos === false) { break; } --$instance; } if ($pos !== false) { return self::REPLACE($text, ++$pos, mb_strlen($fromText, 'UTF-8'), $toText); } return $text; } }
egbot/Symbiota
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Replace.php
PHP
gpl-2.0
2,182
/* * This is the source code of Telegram for Android v. 3.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2016. */ package org.telegram.messenger; import android.app.Activity; import android.app.AlarmManager; import android.app.Application; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.res.Configuration; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import android.os.PowerManager; import android.util.Base64; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.SerializedData; import org.telegram.tgnet.TLRPC; import org.telegram.ui.Components.ForegroundDetector; import java.io.File; import java.io.RandomAccessFile; public class ApplicationLoader extends Application { private static Drawable cachedWallpaper; private static int selectedColor; private static boolean isCustomTheme; private static final Object sync = new Object(); public static volatile Context applicationContext; public static volatile Handler applicationHandler; private static volatile boolean applicationInited = false; public static volatile boolean isScreenOn = false; public static volatile boolean mainInterfacePaused = true; public static boolean isCustomTheme() { return isCustomTheme; } public static int getSelectedColor() { return selectedColor; } public static void reloadWallpaper() { cachedWallpaper = null; loadWallpaper(); } public static void loadWallpaper() { if (cachedWallpaper != null) { return; } Utilities.searchQueue.postRunnable(new Runnable() { @Override public void run() { synchronized (sync) { int selectedColor = 0; try { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); int selectedBackground = preferences.getInt("selectedBackground", 1000001); selectedColor = preferences.getInt("selectedColor", 0); if (selectedColor == 0) { if (selectedBackground == 1000001) { cachedWallpaper = applicationContext.getResources().getDrawable(R.drawable.background_hd); isCustomTheme = false; } else { File toFile = new File(getFilesDirFixed(), "wallpaper.jpg"); if (toFile.exists()) { cachedWallpaper = Drawable.createFromPath(toFile.getAbsolutePath()); isCustomTheme = true; } else { cachedWallpaper = applicationContext.getResources().getDrawable(R.drawable.background_hd); isCustomTheme = false; } } } } catch (Throwable throwable) { //ignore } if (cachedWallpaper == null) { if (selectedColor == 0) { selectedColor = -2693905; } cachedWallpaper = new ColorDrawable(selectedColor); } } } }); } public static Drawable getCachedWallpaper() { synchronized (sync) { return cachedWallpaper; } } private static void convertConfig() { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("dataconfig", Context.MODE_PRIVATE); if (preferences.contains("currentDatacenterId")) { SerializedData buffer = new SerializedData(32 * 1024); buffer.writeInt32(2); buffer.writeBool(preferences.getInt("datacenterSetId", 0) != 0); buffer.writeBool(true); buffer.writeInt32(preferences.getInt("currentDatacenterId", 0)); buffer.writeInt32(preferences.getInt("timeDifference", 0)); buffer.writeInt32(preferences.getInt("lastDcUpdateTime", 0)); buffer.writeInt64(preferences.getLong("pushSessionId", 0)); buffer.writeBool(false); buffer.writeInt32(0); try { String datacentersString = preferences.getString("datacenters", null); if (datacentersString != null) { byte[] datacentersBytes = Base64.decode(datacentersString, Base64.DEFAULT); if (datacentersBytes != null) { SerializedData data = new SerializedData(datacentersBytes); buffer.writeInt32(data.readInt32(false)); buffer.writeBytes(datacentersBytes, 4, datacentersBytes.length - 4); data.cleanup(); } } } catch (Exception e) { FileLog.e("tmessages", e); } try { File file = new File(getFilesDirFixed(), "tgnet.dat"); RandomAccessFile fileOutputStream = new RandomAccessFile(file, "rws"); byte[] bytes = buffer.toByteArray(); fileOutputStream.writeInt(Integer.reverseBytes(bytes.length)); fileOutputStream.write(bytes); fileOutputStream.close(); } catch (Exception e) { FileLog.e("tmessages", e); } buffer.cleanup(); preferences.edit().clear().commit(); } } public static File getFilesDirFixed() { for (int a = 0; a < 10; a++) { File path = ApplicationLoader.applicationContext.getFilesDir(); if (path != null) { return path; } } try { ApplicationInfo info = applicationContext.getApplicationInfo(); File path = new File(info.dataDir, "files"); path.mkdirs(); return path; } catch (Exception e) { FileLog.e("tmessages", e); } return new File("/data/data/org.telegram.messenger/files"); } public static void postInitApplication() { if (applicationInited) { return; } applicationInited = true; convertConfig(); try { LocaleController.getInstance(); } catch (Exception e) { e.printStackTrace(); } try { final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); final BroadcastReceiver mReceiver = new ScreenReceiver(); applicationContext.registerReceiver(mReceiver, filter); } catch (Exception e) { e.printStackTrace(); } try { PowerManager pm = (PowerManager)ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE); isScreenOn = pm.isScreenOn(); FileLog.e("tmessages", "screen state = " + isScreenOn); } catch (Exception e) { FileLog.e("tmessages", e); } UserConfig.loadConfig(); String deviceModel; String langCode; String appVersion; String systemVersion; String configPath = getFilesDirFixed().toString(); try { langCode = LocaleController.getLocaleString(LocaleController.getInstance().getSystemDefaultLocale()); deviceModel = Build.MANUFACTURER + Build.MODEL; PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0); appVersion = pInfo.versionName + " (" + pInfo.versionCode + ")"; systemVersion = "SDK " + Build.VERSION.SDK_INT; } catch (Exception e) { langCode = "en"; deviceModel = "Android unknown"; appVersion = "App version unknown"; systemVersion = "SDK " + Build.VERSION.SDK_INT; } if (langCode.trim().length() == 0) { langCode = "en"; } if (deviceModel.trim().length() == 0) { deviceModel = "Android unknown"; } if (appVersion.trim().length() == 0) { appVersion = "App version unknown"; } if (systemVersion.trim().length() == 0) { systemVersion = "SDK Unknown"; } MessagesController.getInstance(); ConnectionsManager.getInstance().init(BuildVars.BUILD_VERSION, TLRPC.LAYER, BuildVars.APP_ID, deviceModel, systemVersion, appVersion, langCode, configPath, FileLog.getNetworkLogPath(), UserConfig.getClientUserId()); if (UserConfig.getCurrentUser() != null) { MessagesController.getInstance().putUser(UserConfig.getCurrentUser(), true); ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone); MessagesController.getInstance().getBlockedUsers(true); SendMessagesHelper.getInstance().checkUnsentMessages(); } ApplicationLoader app = (ApplicationLoader)ApplicationLoader.applicationContext; app.initPlayServices(); FileLog.e("tmessages", "app initied"); ContactsController.getInstance().checkAppAccount(); MediaController.getInstance(); } @Override public void onCreate() { super.onCreate(); if (Build.VERSION.SDK_INT < 11) { java.lang.System.setProperty("java.net.preferIPv4Stack", "true"); java.lang.System.setProperty("java.net.preferIPv6Addresses", "false"); } applicationContext = getApplicationContext(); NativeLoader.initNativeLibs(ApplicationLoader.applicationContext); ConnectionsManager.native_setJava(Build.VERSION.SDK_INT == 14 || Build.VERSION.SDK_INT == 15); if (Build.VERSION.SDK_INT >= 14) { new ForegroundDetector(this); } applicationHandler = new Handler(applicationContext.getMainLooper()); startPushService(); } public static void startPushService() { SharedPreferences preferences = applicationContext.getSharedPreferences("Notifications", MODE_PRIVATE); if (preferences.getBoolean("pushService", true)) { applicationContext.startService(new Intent(applicationContext, NotificationsService.class)); if (android.os.Build.VERSION.SDK_INT >= 19) { // Calendar cal = Calendar.getInstance(); // PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0); // AlarmManager alarm = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE); // alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30000, pintent); PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0); AlarmManager alarm = (AlarmManager)applicationContext.getSystemService(Context.ALARM_SERVICE); alarm.cancel(pintent); } } else { stopPushService(); } } public static void stopPushService() { applicationContext.stopService(new Intent(applicationContext, NotificationsService.class)); PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0); AlarmManager alarm = (AlarmManager)applicationContext.getSystemService(Context.ALARM_SERVICE); alarm.cancel(pintent); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); try { LocaleController.getInstance().onDeviceConfigurationChange(newConfig); AndroidUtilities.checkDisplaySize(); } catch (Exception e) { e.printStackTrace(); } } private void initPlayServices() { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (checkPlayServices()) { if (UserConfig.pushString == null || UserConfig.pushString.length() == 0) { FileLog.d("tmessages", "GCM Registration not found."); Intent intent = new Intent(applicationContext, GcmRegistrationIntentService.class); startService(intent); } else { FileLog.d("tmessages", "GCM regId = " + UserConfig.pushString); } } else { FileLog.d("tmessages", "No valid Google Play Services APK found."); } } }, 1000); } private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); return resultCode == ConnectionResult.SUCCESS; /*if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i("tmessages", "This device is not supported."); } return false; } return true;*/ } }
7ShaYaN7/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/ApplicationLoader.java
Java
gpl-2.0
14,342
package enums; public enum ConnectionMode { WIFI, USB }
LorenK96/slide-desktop
src/main/java/enums/ConnectionMode.java
Java
gpl-2.0
65
<?php /** * @package CoursePress */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <h1 class="entry-title"><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h1> <?php if ( has_post_thumbnail() ) { echo '<div class="featured-image">'; the_post_thumbnail(); echo '</div>'; } ?> <?php if ( 'post' == get_post_type() ) : ?> <div class="entry-meta"> <?php coursepress_posted_on(); ?> </div><!-- .entry-meta --> <?php endif; ?> </header><!-- .entry-header --> <?php if ( is_search() ) : // Only display Excerpts for Search ?> <div class="entry-summary"> <?php the_excerpt(); ?> </div><!-- .entry-summary --> <?php else : ?> <div class="entry-content"> <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'cp' ) ); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'cp' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <?php endif; ?> <footer class="entry-meta"> <?php if ( 'post' == get_post_type() ) : // Hide category and tag text for pages on Search ?> <?php /* translators: used between list items, there is a space after the comma */ $categories_list = get_the_category_list( __( ', ', 'cp' ) ); if ( $categories_list && coursepress_categorized_blog() ) : ?> <span class="cat-links"> <?php printf( __( 'Posted in %1$s', 'cp' ), $categories_list ); ?> </span> <?php endif; // End if categories ?> <?php /* translators: used between list items, there is a space after the comma */ $tags_list = get_the_tag_list( '', __( ', ', 'cp' ) ); if ( $tags_list ) : ?> <span class="tags-links"> <?php printf( __( 'Tagged %1$s', 'cp' ), $tags_list ); ?> </span> <?php endif; // End if $tags_list ?> <?php endif; // End if 'post' == get_post_type() ?> <?php if ( ! post_password_required() && ( comments_open() || '0' != get_comments_number() ) ) : ?> <span class="comments-link"><?php comments_popup_link( __( 'Leave a comment', 'cp' ), __( '1 Comment', 'cp' ), __( '% Comments', 'cp' ) ); ?></span> <?php endif; ?> <?php edit_post_link( __( 'Edit', 'cp' ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-meta --> </article><!-- #post-## -->
eduardmokrov/study
wp-content/themes/coursepress/content.php
PHP
gpl-2.0
2,347
<?php class onActivityContentAfterUpdateApprove extends cmsAction { public function run($data){ $ctype_name = $data['ctype_name']; $item = $data['item']; // обновляем запись в ленте активности $this->updateEntry('content', "add.{$ctype_name}", $item['id'], array( 'subject_title' => $item['title'], 'subject_id' => $item['id'], 'subject_url' => href_to_rel($ctype_name, $item['slug'] . '.html'), 'is_private' => isset($item['is_private']) ? $item['is_private'] : 0, 'is_pub' => $item['is_pub'] )); return $data; } }
Val-Git/icms2
system/controllers/activity/hooks/content_after_update_approve.php
PHP
gpl-2.0
685
/* FailedPanel.java / MiniCopier Copyright (C) 2007-2009 Adrian Courrèges This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package minicopier.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import minicopier.i18n.Language; public class FailedPanel extends JPanel { private MainFrame mainFrame; protected QueueJButton retry; protected QueueJButton removeFailed; protected DefaultTableModel failedModel; protected JTable failedList; public FailedPanel(MainFrame f){ super(); this.mainFrame = f; this.retry = new QueueJButton("img/retry.gif"); this.retry.setToolTipText(Language.get("Tooltip.Failed.Retry")); this.removeFailed = new QueueJButton("img/delete.gif"); this.removeFailed.setToolTipText(Language.get("Tooltip.Failed.Clear")); failedModel = mainFrame.copier.failedItems.getTableModel(); failedList = new JTable(failedModel); //transferList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); failedList.getColumnModel().getColumn(1).setCellRenderer(new RightTableCellRenderer()); failedList.getColumnModel().getColumn(1).setMaxWidth(80); failedList.getColumnModel().getColumn(1).setMinWidth(80); this.setLayout(new BorderLayout()); JScrollPane jspFailed = new JScrollPane(failedList); jspFailed.setViewportView(failedList); jspFailed.setPreferredSize(new Dimension(40,40)); //transferList.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); //jspTransfer.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); //Subpanel (west) with queue management buttons JPanel queueButtonsPanel = new JPanel(); queueButtonsPanel.setLayout(new BoxLayout(queueButtonsPanel, BoxLayout.Y_AXIS)); queueButtonsPanel.setAlignmentX(Component.CENTER_ALIGNMENT); queueButtonsPanel.add(this.retry,Component.CENTER_ALIGNMENT); queueButtonsPanel.add(this.removeFailed); this.add(queueButtonsPanel,BorderLayout.WEST); this.add(jspFailed,BorderLayout.CENTER); } private class RightTableCellRenderer extends DefaultTableCellRenderer { public RightTableCellRenderer() { setHorizontalAlignment(RIGHT); setVerticalAlignment(CENTER); } } }
acourreges/minicopier
src/minicopier/gui/FailedPanel.java
Java
gpl-2.0
2,996
/* Mango - Open Source M2M - http://mango.serotoninsoftware.com Copyright (C) 2006-2011 Serotonin Software Technologies Inc. @author Matthew Lohbihler 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.serotonin.mango.vo.dataSource.jmx; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.List; import java.util.Map; import com.serotonin.json.JsonException; import com.serotonin.json.JsonObject; import com.serotonin.json.JsonReader; import com.serotonin.json.JsonRemoteEntity; import com.serotonin.json.JsonRemoteProperty; import com.serotonin.mango.Common; import com.serotonin.mango.rt.dataSource.DataSourceRT; import com.serotonin.mango.rt.dataSource.jmx.JmxDataSourceRT; import com.serotonin.mango.rt.event.AlarmLevels; import com.serotonin.mango.rt.event.type.AuditEventType; import com.serotonin.mango.rt.event.type.EventType; import com.serotonin.mango.util.ExportCodes; import com.serotonin.mango.vo.dataSource.DataSourceVO; import com.serotonin.mango.vo.event.EventTypeVO; import com.serotonin.util.SerializationHelper; import com.serotonin.util.StringUtils; import com.serotonin.web.dwr.DwrResponseI18n; import com.serotonin.web.i18n.LocalizableMessage; /** * @author Matthew Lohbihler */ @JsonRemoteEntity public class JmxDataSourceVO extends DataSourceVO<JmxDataSourceVO> { public static final Type TYPE = Type.JMX; @Override protected void addEventTypes(List<EventTypeVO> ets) { ets.add(createEventType(JmxDataSourceRT.DATA_SOURCE_EXCEPTION_EVENT, new LocalizableMessage( "event.ds.dataSource"), EventType.DuplicateHandling.IGNORE_SAME_MESSAGE, AlarmLevels.URGENT)); ets.add(createEventType(JmxDataSourceRT.POINT_READ_EXCEPTION_EVENT, new LocalizableMessage("event.ds.pointRead"))); ets.add(createEventType(JmxDataSourceRT.POINT_WRITE_EXCEPTION_EVENT, new LocalizableMessage( "event.ds.pointWrite"))); } private static final ExportCodes EVENT_CODES = new ExportCodes(); static { EVENT_CODES.addElement(JmxDataSourceRT.DATA_SOURCE_EXCEPTION_EVENT, "DATA_SOURCE_EXCEPTION"); EVENT_CODES.addElement(JmxDataSourceRT.POINT_READ_EXCEPTION_EVENT, "POINT_READ_EXCEPTION"); EVENT_CODES.addElement(JmxDataSourceRT.POINT_WRITE_EXCEPTION_EVENT, "POINT_WRITE_EXCEPTION"); } @Override public ExportCodes getEventCodes() { return EVENT_CODES; } @Override public Type getType() { return TYPE; } @Override public LocalizableMessage getConnectionDescription() { if (useLocalServer) return new LocalizableMessage("dsEdit.jmx.dsconn.local"); return new LocalizableMessage("dsEdit.jmx.dsconn.remote", remoteServerAddr); } @Override public DataSourceRT createDataSourceRT() { return new JmxDataSourceRT(this); } @Override public JmxPointLocatorVO createPointLocator() { return new JmxPointLocatorVO(); } @JsonRemoteProperty private boolean useLocalServer; @JsonRemoteProperty private String remoteServerAddr; private int updatePeriodType = Common.TimePeriods.MINUTES; @JsonRemoteProperty private int updatePeriods = 5; @JsonRemoteProperty private boolean quantize; public boolean isUseLocalServer() { return useLocalServer; } public void setUseLocalServer(boolean useLocalServer) { this.useLocalServer = useLocalServer; } public String getRemoteServerAddr() { return remoteServerAddr; } public void setRemoteServerAddr(String remoteServerAddr) { this.remoteServerAddr = remoteServerAddr; } public int getUpdatePeriodType() { return updatePeriodType; } public void setUpdatePeriodType(int updatePeriodType) { this.updatePeriodType = updatePeriodType; } public int getUpdatePeriods() { return updatePeriods; } public void setUpdatePeriods(int updatePeriods) { this.updatePeriods = updatePeriods; } public boolean isQuantize() { return quantize; } public void setQuantize(boolean quantize) { this.quantize = quantize; } @Override public void validate(DwrResponseI18n response) { super.validate(response); if (!useLocalServer && StringUtils.isEmpty(remoteServerAddr)) response.addContextualMessage("remoteServerAddr", "validate.required"); if (!Common.TIME_PERIOD_CODES.isValidId(updatePeriodType)) response.addContextualMessage("updatePeriodType", "validate.invalidValue"); if (updatePeriods <= 0) response.addContextualMessage("updatePeriods", "validate.greaterThanZero"); } @Override protected void addPropertiesImpl(List<LocalizableMessage> list) { AuditEventType.addPropertyMessage(list, "dsEdit.jmx.useLocalServer", useLocalServer); AuditEventType.addPropertyMessage(list, "dsEdit.jmx.remoteServerAddr", remoteServerAddr); AuditEventType.addPeriodMessage(list, "dsEdit.updatePeriod", updatePeriodType, updatePeriods); AuditEventType.addPropertyMessage(list, "dsEdit.quantize", quantize); } @Override protected void addPropertyChangesImpl(List<LocalizableMessage> list, JmxDataSourceVO from) { AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.jmx.useLocalServer", from.useLocalServer, useLocalServer); AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.jmx.remoteServerAddr", from.remoteServerAddr, remoteServerAddr); AuditEventType.maybeAddPeriodChangeMessage(list, "dsEdit.updatePeriod", from.updatePeriodType, from.updatePeriods, updatePeriodType, updatePeriods); AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.quantize", from.quantize, quantize); } // // // Serialization // private static final long serialVersionUID = -1; private static final int version = 1; private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(version); out.writeBoolean(useLocalServer); SerializationHelper.writeSafeUTF(out, remoteServerAddr); out.writeInt(updatePeriodType); out.writeInt(updatePeriods); out.writeBoolean(quantize); } private void readObject(ObjectInputStream in) throws IOException { int ver = in.readInt(); // Switch on the version of the class so that version changes can be elegantly handled. if (ver == 1) { useLocalServer = in.readBoolean(); remoteServerAddr = SerializationHelper.readSafeUTF(in); updatePeriodType = in.readInt(); updatePeriods = in.readInt(); quantize = in.readBoolean(); } } @Override public void jsonDeserialize(JsonReader reader, JsonObject json) throws JsonException { super.jsonDeserialize(reader, json); Integer value = deserializeUpdatePeriodType(json); if (value != null) updatePeriodType = value; } @Override public void jsonSerialize(Map<String, Object> map) { super.jsonSerialize(map); serializeUpdatePeriodType(map, updatePeriodType); } }
sdtabilit/Scada-LTS
src/com/serotonin/mango/vo/dataSource/jmx/JmxDataSourceVO.java
Java
gpl-2.0
7,962
/* This file is part of the KDE project Copyright (C) 2005 Jarosław Staniek <staniek@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kexicustompropertyfactory_p.h" #include <qlineedit.h> #include <kdebug.h> #include <koproperty/Property.h> #include <kexiutils/identifier.h> #if 0 //TODO KexiImagePropertyEdit::KexiImagePropertyEdit( KoProperty::Property *property, QWidget *parent) : KoProperty::PixmapEdit(property, parent) , m_id(0) { } KexiImagePropertyEdit::~KexiImagePropertyEdit() { } void KexiImagePropertyEdit::selectPixmap() { QString fileName(KoProperty::PixmapEdit::selectPixmapFileName()); if (fileName.isEmpty()) return; KexiBLOBBuffer::Handle h(KexiBLOBBuffer::self()->insertPixmap(KUrl(fileName))); setValue((uint)/*! @todo unsafe*/h.id()); #if 0 //will be reenabled for new image collection if (!m_manager->activeForm() || !property()) return; ObjectTreeItem *item = m_manager->activeForm()->objectTree()->lookup(m_manager->activeForm()->selectedWidget()->name()); QString name = item ? item->pixmapName(property()->name()) : ""; PixmapCollectionChooser dialog(m_manager->activeForm()->pixmapCollection(), name, topLevelWidget()); if (dialog.exec() == QDialog::Accepted) { setValue(dialog.pixmap(), true); item->setPixmapName(property()->name(), dialog.pixmapName()); } #endif } QVariant KexiImagePropertyEdit::value() const { return (uint)/*! @todo unsafe*/m_id; } void KexiImagePropertyEdit::setValue(const QVariant &value, bool emitChange) { m_id = value.toInt(); PixmapEdit::setValue(KexiBLOBBuffer::self()->objectForId(m_id).pixmap(), emitChange); } void KexiImagePropertyEdit::drawViewer(QPainter *p, const QColorGroup &cg, const QRect &r, const QVariant &value) { KexiBLOBBuffer::Handle h(KexiBLOBBuffer::self()->objectForId(value.toInt())); PixmapEdit::drawViewer(p, cg, r, h.pixmap()); } #endif //---------------------------------------------------------------- KexiIdentifierPropertyEdit::KexiIdentifierPropertyEdit(QWidget *parent) : KoProperty::StringEdit(parent) { KexiUtils::IdentifierValidator *val = new KexiUtils::IdentifierValidator(this); setValidator(val); val->setObjectName("KexiIdentifierPropertyEdit Validator"); } KexiIdentifierPropertyEdit::~KexiIdentifierPropertyEdit() { } void KexiIdentifierPropertyEdit::setValue(const QString &value) { if (value.isEmpty()) { kWarning() << "Value cannot be empty. This call has no effect."; return; } const QString identifier(KexiUtils::string2Identifier(value)); if (identifier != value) kDebug() << QString("String \"%1\" converted to identifier \"%2\".").arg(value).arg(identifier); KoProperty::StringEdit::setValue(identifier); } #include "kexicustompropertyfactory_p.moc"
TheTypoMaster/calligra-history
kexi/widget/kexicustompropertyfactory_p.cpp
C++
gpl-2.0
3,633
<?php get_header(); the_post(); ?> <div id="page-title" class="post-title"> <div class="container"> <div class="post-info"> <div class="date"> <em></em> <a href="<?php the_permalink() ?>"><?php print get_the_date() ?></a> </div> <div class="comments"> <em></em> <a href="#comments"><?php comments_number( __('No Comments', 'snapshot'), __('One Comment', 'snapshot'), __('% Comments', 'snapshot') ); ?></a> </div> <?php $category = get_the_category(); if(!empty($category)) : ?> <div class="category"> <em></em> <?php the_category(', '); ?> </div> <?php endif ?> </div> <h1> <?php the_title() ?> </h1> <div class="nav"> <?php previous_post_link('%link') ?> <?php next_post_link('%link') ?> </div> </div> </div> <?php get_template_part('viewer') ?> <div id="post-<?php the_ID() ?>" <?php post_class() ?>> <div class="container"> <div id="post-share"> <?php if(so_setting('social_display_share')) get_template_part('share') ?> </div> <div id="post-main"> <div class="entry-content"> <?php the_content() ?> <?php global $numpages; if(!empty($numpages) || get_the_tag_list() != '') : ?> <div class="clear"></div> <?php endif; ?> <?php wp_link_pages() ?> <?php the_tags() ?> </div> <div class="clear"></div> <div id="single-comments-wrapper"> <?php comments_template() ?> </div> </div> <div id="post-images"> <?php $children = get_children(array( 'post_mime_type' => 'image', 'post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' )); foreach($children as $child){ $exclude = get_post_meta($child->ID, 'sidebar_exclude', true); if(!empty($exclude)) continue; $src = wp_get_attachment_image_src($child->ID, 'single-large'); ?> <div class="image"> <?php print '<a href="'.get_attachment_link($child->ID).'" data-width="'.$src[1].'" data-height="'.$src[2].'">' ?> <?php print wp_get_attachment_image($child->ID, 'post-thumbnail', false, array('class' => 'thumbnail')); ?> <?php print '</a>' ?> </div> <?php } ?> </div> </div> <div class="clear"></div> </div> <?php get_footer() ?>
hsfoxman/198362
wp-content/themes/snapshot/single.php
PHP
gpl-2.0
2,381
package plugins; import com.sun.squawk.VM; import java.lang.Math; import sics.plugin.PlugInComponent; import sics.port.PluginPPort; public class LEDLighter extends PlugInComponent { public PluginPPort led; private int k; public LEDLighter(String[] args) { super(args); } public LEDLighter() { k = 0; } public static void main(String[] args) { // VM.println("LEDLighter.main()\r\n"); LEDLighter ledLighter = new LEDLighter(args); ledLighter.run(); // VM.println("LEDLighter-main done\r\n"); } // public void setSpeed(PluginPPort speed) { // this.speed = speed; // } // // public void setSteering(PluginPPort steering) { // this.steering = steering; // } public void init() { // Initiate PluginPPort led = new PluginPPort(this, "led"); VM.println("new pluginpport led"); } // public void iter(int p, int e) { // switch(p) { // case 1: // VM.println("a"); // break; // case 2: // VM.println("b"); // break; // default: // VM.println("c"); // } // } private void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { VM.println("Interrupted.\r\n"); } } public void doFunction2() { VM.println("2|1"); led.write("2|1"); } private void setled(String str) { led.write(str); // VM.println(str); sleep(500); } public void doFunction() { int i = 0; while (true) { i++; VM.println("1 cycle " + i); setled("1|0"); setled("2|0"); setled("3|0"); setled("1|1"); setled("2|1"); setled("3|1"); } } public void run() { init(); doFunction(); } }
sics-sse/moped
plugins/LEDLighter/src/main/java/plugins/LEDLighter.java
Java
gpl-2.0
1,710
/* AclEntry.java -- An entry in an ACL list. Copyright (C) 1998 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.security.acl; import java.security.Principal; import java.util.Enumeration; /** * This interface models an entry in an access control list (ACL). Java * ACL's consist of a list of entries, where each consists of a * <code>Principal</code> and a list of <code>Permission</code>'s which * have been granted to that <code>Principal</code>. An ACL can also * be <em>negative</em>, which indicates that the list of * <code>Permission</code>'s is a list of permissions that are <em>not</em> * granted to the <code>Principal</code>. A <code>Principal</code> can * have at most one regular (or positive) ACL entry and one negative * ACL entry. * * @version 0.0 * * @author Aaron M. Renn (arenn@urbanophile.com) */ public interface AclEntry extends Cloneable { /** * This method returns the <code>Principal</code> associated with this * ACL entry. * * @return The <code>Principal</code> for this ACL entry */ Principal getPrincipal(); /** * This method sets ths <code>Principal</code> associated with this * ACL entry. This operation will only succeed if there is not already * a <code>Principal</code> assigned. * * @param user The <code>Principal</code> for this ACL entry * * @return <code>true</code> if the <code>Principal</code> was successfully set or <code>false</code> if this entry already has a <code>Principal</code>. */ boolean setPrincipal(Principal user); /** * This method sets this ACL entry to be a <em>negative</em> entry, indicating * that it contains a list of permissions that are <em>not</em> granted * to the entry's <code>Principal</code>. Note that there is no way to * undo this operation. */ void setNegativePermissions(); /** * This method tests whether or not this ACL entry is a negative entry or not. * * @return <code>true</code> if this ACL entry is negative, <code>false</code> otherwise */ boolean isNegative(); /** * This method adds the specified permission to this ACL entry. * * @param perm The <code>Permission</code> to add * * @return <code>true</code> if the permission was added or <code>false</code> if it was already set for this entry */ boolean addPermission(Permission permission); /** * This method deletes the specified permission to this ACL entry. * * @param perm The <code>Permission</code> to delete from this ACL entry. * * @return <code>true</code> if the permission was successfully deleted or <code>false</code> if the permission was not part of this ACL to begin with */ boolean removePermission(Permission perm); /** * This method tests whether or not the specified permission is associated * with this ACL entry. * * @param perm The <code>Permission</code> to test * * @return <code>true</code> if this permission is associated with this entry or <code>false</code> otherwise */ boolean checkPermission(Permission permission); /** * This method returns a list of all <code>Permission</code> objects * associated with this ACL entry as an <code>Enumeration</code>. * * @return A list of permissions for this ACL entry */ Enumeration permissions(); /** * This method returns this object as a <code>String</code>. * * @return A <code>String</code> representation of this object */ String toString(); /** * This method returns a clone of this ACL entry * * @return A clone of this ACL entry */ Object clone(); }
aosm/gcc_40
libjava/java/security/acl/AclEntry.java
Java
gpl-2.0
5,258
namespace Server.Items { public class AnimatedWeaponScroll : SpellScroll { [Constructable] public AnimatedWeaponScroll() : this(1) { } [Constructable] public AnimatedWeaponScroll(int amount) : base(683, 0x2DA4, amount) { } public AnimatedWeaponScroll(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
Argalep/ServUO
Scripts/Items/Consumables/AnimatedWeaponScroll.cs
C#
gpl-2.0
752
# -*- coding: UTF-8 -*- __revision__ = '$Id$' # Written by Christian Sagmueller <christian@sagmueller.net> # based on PluginMovieIMDB.py, Copyright (c) 2005 Vasco Nunes # You may use and distribute this software under the terms of the # GNU General Public License, version 2 or later import gutils import movie,string,re plugin_name = "OFDb" plugin_description = "Online-Filmdatenbank" plugin_url = "www.ofdb.de" plugin_language = _("German") plugin_author = "Christian Sagmueller, Jessica Katharina Parth" plugin_author_email = "Jessica.K.P@women-at-work.org" plugin_version = "0.11" class Plugin(movie.Movie): def __init__(self, id): self.encode = 'utf-8' self.movie_id = id self.url = "http://www.ofdb.de/%s" % str(self.movie_id) def initialize(self): # OFDb didn't provide the runtime, studio and classification but it provide a link to the german imdb entry # lets use the imdb page, why not imdb_nr = gutils.trim(self.page, 'http://german.imdb.com/Title?', '"') if imdb_nr != '': self.imdb_page = self.open_page(url='http://www.imdb.de/Title?' + imdb_nr) else: imdb_nr = gutils.trim(self.page, 'http://www.imdb.com/Title?', '"') if imdb_nr != '': self.imdb_page = self.open_page(url='http://www.imdb.de/Title?' + imdb_nr) else: self.imdb_page = '' def get_image(self): self.image_url = "http://img.ofdb.de/film/" + gutils.trim(self.page, 'img src="http://img.ofdb.de/film/', '"' ) def get_o_title(self): self.o_title = gutils.clean(gutils.trim(self.page, 'Originaltitel:', '</tr>')) if self.o_title == '': self.o_title = string.replace(self.o_title, '&nbsp;', '' ) def get_title(self): self.title = gutils.trim(self.page,'size="3"><b>','<') def get_director(self): self.director = gutils.trim(self.page,"Regie:","</a><br>") def get_plot(self): self.plot = '' storyid = gutils.regextrim(self.page, '<a href="plot/', '(">|[&])') if not storyid is None: story_page = self.open_page(url="http://www.ofdb.de/plot/%s" % (storyid.encode('utf8'))) if story_page: self.plot = gutils.trim(story_page, "</b><br><br>","</") def get_year(self): self.year = gutils.trim(self.page,"Erscheinungsjahr:","</a>") self.year = gutils.strip_tags(self.year) def get_runtime(self): # from imdb self.runtime = gutils.after(gutils.regextrim(self.imdb_page, 'itemprop="duration"', ' (min|Min)'), '>') def get_genre(self): self.genre = gutils.trim(self.page,"Genre(s):","</table>") self.genre = string.replace(self.genre, "<br>", ", ") self.genre = gutils.strip_tags(self.genre) self.genre = string.replace(self.genre, "/", ", ") self.genre = gutils.clean(self.genre) self.genre = self.genre[0:-1] def get_cast(self): self.cast = '' movie_id_elements = string.split(self.movie_id, ',') movie_id_elements[0] = string.replace(movie_id_elements[0], "film/", "") cast_page = self.open_page(url="http://www.ofdb.de/view.php?page=film_detail&fid=%s" % str(movie_id_elements[0]) ) self.cast = gutils.trim(cast_page, 'Darsteller</i>', '</table>') self.cast = re.sub('(\n|\t|&nbsp;)', '', self.cast) self.cast = string.replace(self.cast, '\t', '') self.cast = string.replace(self.cast, 'class="Daten">', '>\n') self.cast = string.strip(gutils.strip_tags(self.cast)) self.cast = string.replace(self.cast, '... ', _(' as ')) self.cast = gutils.clean(self.cast) def get_classification(self): # from imdb self.classification = gutils.regextrim(gutils.regextrim(self.imdb_page, '(Altersfreigabe|Certification):', '</div>'), '(Deutschland|Germany):', '(&|[|])') def get_studio(self): # from imdb self.studio = gutils.regextrim(self.imdb_page, 'Production Co:', '(<span|</span>)') def get_o_site(self): self.o_site = gutils.trim(gutils.regextrim(self.imdb_page, 'Official Sites:', '(<span|</span>)'), 'href="', '"') def get_site(self): self.site = self.url def get_trailer(self): self.trailer = "" def get_country(self): self.country = gutils.trim(self.page,"Herstellungsland:","</a>") def get_rating(self): self.rating = gutils.trim(self.page,"<br>Note: ","&nbsp;") if self.rating == '': self.rating = "0" self.rating = str(round(float(self.rating))) class SearchPlugin(movie.SearchMovie): def __init__(self): self.original_url_search = "http://www.ofdb.de/view.php?page=suchergebnis&Kat=OTitel&SText=" self.translated_url_search = "http://www.ofdb.de/view.php?page=suchergebnis&Kat=DTitel&SText=" self.encode = 'utf-8' self.remove_accents = False def search(self,parent_window): if not self.open_search(parent_window): return None self.page = gutils.trim(self.page,"</b><br><br>", "<br><br><br>"); self.page = string.replace( self.page, "'", '"' ) self.page = string.replace( self.page, '<font size="1">', '' ) self.page = string.replace( self.page, '</font>', '' ) return self.page def get_searches(self): elements = string.split(self.page,"<br>") if (elements[0]<>''): for element in elements: elementid = gutils.trim(element,'<a href="','"') if not elementid is None and not elementid == '': self.ids.append(elementid) elementname = gutils.clean(element) p1 = string.find(elementname, '>') if p1 == -1: self.titles.append(elementname) else: self.titles.append(elementname[p1+1:]) # # Plugin Test # class SearchPluginTest(SearchPlugin): # # Configuration for automated tests: # dict { movie_id -> [ expected result count for original url, expected result count for translated url ] } # test_configuration = { 'Rocky Balboa' : [ 1, 1 ], 'Arahan' : [ 3, 2 ], 'glückliches' : [ 4, 2 ] } class PluginTest: # # Configuration for automated tests: # dict { movie_id -> dict { arribute -> value } } # # value: * True/False if attribute only should be tested for any value # * or the expected value # test_configuration = { 'film/103013,Rocky%20Balboa' : { 'title' : 'Rocky Balboa', 'o_title' : 'Rocky Balboa', 'director' : 'Sylvester Stallone', 'plot' : True, 'cast' : 'Sylvester Stallone' + _(' as ') + 'Rocky Balboa\n\ Burt Young' + _(' as ') + 'Paulie\n\ Antonio Tarver' + _(' as ') + 'Mason \'The Line\' Dixon\n\ Geraldine Hughes' + _(' as ') + 'Marie\n\ Milo Ventimiglia' + _(' as ') + 'Robert Jr.\n\ Tony Burton' + _(' as ') + 'Duke\n\ A.J. Benza' + _(' as ') + 'L.C.\n\ James Francis Kelly III' + _(' as ') + 'Steps\n\ Lou DiBella' + _(' as ') + 'Himself\n\ Mike Tyson' + _(' as ') + 'Himself\n\ Henry G. Sanders' + _(' as ') + 'Martin\n\ Pedro Lovell' + _(' as ') + 'Spider Rico\n\ Ana Gerena' + _(' as ') + 'Isabel\n\ Angela Boyd' + _(' as ') + 'Angie\n\ Louis Giansante\n\ Maureen Schilling\n\ Lahmard J. Tate\n\ Woody Paige\n\ Skip Bayless\n\ Jay Crawford\n\ Brian Kenny\n\ Dana Jacobson\n\ Charles Johnson\n\ James Binns\n\ Johnnie Hobbs Jr.\n\ Barney Fitzpatrick\n\ Jim Lampley\n\ Larry Merchant\n\ Max Kellerman\n\ LeRoy Neiman\n\ Bert Randolph Sugar\n\ Bernard Fernández\n\ Gunnar Peterson\n\ Yahya\n\ Marc Ratner\n\ Anthony Lato Jr.\n\ Jack Lazzarado\n\ Michael Buffer' + _(' as ') + 'Ring Announcer\n\ Joe Cortez' + _(' as ') + 'Referee\n\ Carter Mitchell\n\ Vinod Kumar\n\ Fran Pultro\n\ Frank Stallone als Frank Stallone Jr.' + _(' as ') + 'Dinner Patron \n\ Jody Giambelluca\n\ Tobias Segal' + _(' as ') + 'Robert\'s Friend\n\ Tim Carr' + _(' as ') + 'Robert\'s Friend \n\ Matt Frack\n\ Paul Dion Monte' + _(' as ') + 'Robert\'s Friend\n\ Kevin King Templeton\n\ Robert Michael Kelly\n\ Rick Buchborn\n\ Nick Baker\n\ Don Sherman' + _(' as ') + 'Andy\n\ Gary Compton\n\ Vale Anoai\n\ Sikander Malik\n\ Michael Ahl\n\ Andrew Aninsman\n\ Ben Bachelder\n\ Lacy Bevis\n\ Tim Brooks\n\ D.T. Carney\n\ Ricky Cavazos' + _(' as ') + 'Boxing Spectator (uncredited)\n\ Rennie Cowan\n\ Deon Derrico\n\ Jacob \'Stitch\' Duran\n\ Simon P. Edwards\n\ Ruben Fischman' + _(' as ') + 'High-Roller in Las Vegas (uncredited)\n\ David Gere\n\ Noah Jacobs\n\ Mark J. Kilbane\n\ Zach Klinefelter\n\ David Kneeream\n\ Dan Montero\n\ Keith Moyer' + _(' as ') + 'Bar Patron (uncredited)\n\ Carol Anne Mueller\n\ Jacqueline Olivia\n\ Brian H. Scott\n\ Keyon Smith\n\ Frank Traynor\n\ Ryan Tygh\n\ Kimberly Villanova', 'country' : 'USA', 'genre' : 'Action, Drama, Sportfilm', 'classification' : False, 'studio' : 'Metro-Goldwyn-Mayer (MGM), Columbia Pictures, Revolution Studios', 'o_site' : False, 'site' : 'http://www.ofdb.de/film/103013,Rocky%20Balboa', 'trailer' : False, 'year' : 2006, 'notes' : False, 'runtime' : 102, 'image' : True, 'rating' : 8 }, 'film/22489,Ein-Gl%C3%BCckliches-Jahr' : { 'title' : 'Glückliches Jahr, Ein', 'o_title' : 'Bonne année, La', 'director' : 'Claude Lelouch', 'plot' : False, 'cast' : 'Lino Ventura' + _(' as ') + 'Simon\n\ Françoise Fabian' + _(' as ') + 'Françoise\n\ Charles Gérard' + _(' as ') + 'Charlot\n\ André Falcon' + _(' as ') + 'Le bijoutier\n\ Mireille Mathieu\n\ Lilo\n\ Claude Mann\n\ Frédéric de Pasquale\n\ Gérard Sire\n\ Silvano Tranquilli' + _(' as ') + 'L\'amant italien\n\ André Barello\n\ Michel Bertay\n\ Norman de la Chesnaye\n\ Pierre Edeline\n\ Pierre Pontiche\n\ Michou\n\ Bettina Rheims\n\ Joseph Rythmann\n\ Georges Staquet\n\ Jacques Villedieu\n\ Harry Walter\n\ Elie Chouraqui', 'country' : 'Frankreich', 'genre' : 'Komödie, Krimi', 'classification' : False, 'studio' : 'Les Films 13, Rizzoli Film', 'o_site' : False, 'site' : 'http://www.ofdb.de/film/22489,Ein-Gl%C3%BCckliches-Jahr', 'trailer' : False, 'year' : 1973, 'notes' : False, 'runtime' : 115, 'image' : True, 'rating' : 6 }, 'film/54088,Arahan' : { 'title' : 'Arahan', 'o_title' : 'Arahan jangpung daejakjeon', 'director' : 'Ryoo Seung-wan', 'plot' : True, 'cast' : 'Ryoo Seung-beom\n\ Yoon Soy' + _(' as ') + 'Wi-jin\n\ Ahn Seong-gi' + _(' as ') + 'Ja-woon\n\ Jeong Doo-hong' + _(' as ') + 'Heuk-Woon\n\ Yoon Joo-sang' + _(' as ') + 'Moo-woon \n\ Kim Ji-yeong\n\ Baek Chan-gi\n\ Kim Jae-man\n\ Lee Dae-yeon\n\ Kim Dong-ju\n\ Kim Su-hyeon\n\ Geum Dong-hyeon\n\ Lee Jae-goo\n\ Ahn Kil-kang\n\ Bong Tae-gyu' + _(' as ') + 'Cameo\n\ Im Ha-ryong' + _(' as ') + 'Cameo\n\ Yoon Do-hyeon\n\ Lee Choon-yeon' + _(' as ') + 'Cameo\n\ Kim Yeong-in\n\ Park Yoon-bae\n\ Lee Won\n\ Kim Kyeong-ae\n\ Yoo Soon-cheol\n\ Hwang Hyo-eun\n\ Lee Jae-ho\n\ Yang Ik-joon\n\ Kwon Beom-taek\n\ Min Hye-ryeong\n\ Oh Soon-tae\n\ Lee Oi-soo', 'country' : 'Südkorea', 'genre' : 'Action, Fantasy, Komödie', 'classification' : False, 'studio' : 'Fun and Happiness, Good Movie Company', 'o_site' : 'http://www.arahan.co.kr/', 'site' : 'http://www.ofdb.de/film/54088,Arahan', 'trailer' : False, 'year' : 2004, 'notes' : False, 'runtime' : 114, 'image' : True, 'rating' : 7 } }
santiavenda2/griffith
lib/plugins/movie/PluginMovieOFDb.py
Python
gpl-2.0
12,757
define(['multi-download'], function (multiDownload) { 'use strict'; return { download: function (items) { multiDownload(items.map(function (item) { return item.url; })); } }; });
gsnerf/MediaBrowser
MediaBrowser.WebDashboard/dashboard-ui/bower_components/emby-webcomponents/filedownloader.js
JavaScript
gpl-2.0
251
/* * Copyright (c) 2012, 2015, 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. * * 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 org.graalvm.compiler.loop; import static org.graalvm.compiler.loop.MathUtil.add; import static org.graalvm.compiler.loop.MathUtil.sub; import org.graalvm.compiler.core.common.type.Stamp; import org.graalvm.compiler.debug.GraalError; import org.graalvm.compiler.nodes.ValueNode; import org.graalvm.compiler.nodes.calc.AddNode; import org.graalvm.compiler.nodes.calc.BinaryArithmeticNode; import org.graalvm.compiler.nodes.calc.IntegerConvertNode; import org.graalvm.compiler.nodes.calc.NegateNode; import org.graalvm.compiler.nodes.calc.SubNode; public class DerivedOffsetInductionVariable extends DerivedInductionVariable { private final ValueNode offset; private final BinaryArithmeticNode<?> value; public DerivedOffsetInductionVariable(LoopEx loop, InductionVariable base, ValueNode offset, BinaryArithmeticNode<?> value) { super(loop, base); this.offset = offset; this.value = value; } public ValueNode getOffset() { return offset; } @Override public Direction direction() { return base.direction(); } @Override public ValueNode valueNode() { return value; } @Override public boolean isConstantInit() { return offset.isConstant() && base.isConstantInit(); } @Override public boolean isConstantStride() { return base.isConstantStride(); } @Override public long constantInit() { return op(base.constantInit(), offset.asJavaConstant().asLong()); } @Override public long constantStride() { if (value instanceof SubNode && base.valueNode() == value.getY()) { return -base.constantStride(); } return base.constantStride(); } @Override public ValueNode initNode() { return op(base.initNode(), offset); } @Override public ValueNode strideNode() { if (value instanceof SubNode && base.valueNode() == value.getY()) { return graph().addOrUniqueWithInputs(NegateNode.create(base.strideNode())); } return base.strideNode(); } @Override public ValueNode extremumNode(boolean assumePositiveTripCount, Stamp stamp) { return op(base.extremumNode(assumePositiveTripCount, stamp), IntegerConvertNode.convert(offset, stamp, graph())); } @Override public ValueNode exitValueNode() { return op(base.exitValueNode(), offset); } @Override public boolean isConstantExtremum() { return offset.isConstant() && base.isConstantExtremum(); } @Override public long constantExtremum() { return op(base.constantExtremum(), offset.asJavaConstant().asLong()); } private long op(long b, long o) { if (value instanceof AddNode) { return b + o; } if (value instanceof SubNode) { if (base.valueNode() == value.getX()) { return b - o; } else { assert base.valueNode() == value.getY(); return o - b; } } throw GraalError.shouldNotReachHere(); } private ValueNode op(ValueNode b, ValueNode o) { if (value instanceof AddNode) { return add(graph(), b, o); } if (value instanceof SubNode) { if (base.valueNode() == value.getX()) { return sub(graph(), b, o); } else { assert base.valueNode() == value.getY(); return sub(graph(), o, b); } } throw GraalError.shouldNotReachHere(); } @Override public void deleteUnusedNodes() { } @Override public String toString() { return String.format("DerivedOffsetInductionVariable base (%s) %s %s", base, value.getNodeClass().shortName(), offset); } }
mcberg2016/graal-core2
graal/org.graalvm.compiler.loop/src/org/graalvm/compiler/loop/DerivedOffsetInductionVariable.java
Java
gpl-2.0
4,905
"use strict"; (function main_default_js(g) { // - g is the global object. // - User callbacks called without 'this', global only if callee is non-strict. // - The names of function expressions are not required, but are used in stack // traces. We name them where useful to show up (fname:#line always shows). mp.msg = { log: mp.log }; mp.msg.verbose = mp.log.bind(null, "v"); var levels = ["fatal", "error", "warn", "info", "debug"]; levels.forEach(function(l) { mp.msg[l] = mp.log.bind(null, l) }); // same as {} but without inherited stuff, e.g. o["toString"] doesn't exist. // used where we try to fetch items by keys which we don't absolutely trust. function new_cache() { return Object.create(null, {}); } /********************************************************************** * event handlers, property observers, client messages, hooks *********************************************************************/ var ehandlers = new_cache() // items of event-name: array of {maybe cb: fn} mp.register_event = function(name, fn) { if (!ehandlers[name]) ehandlers[name] = []; ehandlers[name] = ehandlers[name].concat([{cb: fn}]); // replaces the arr return mp._request_event(name, true); } mp.unregister_event = function(fn) { for (var name in ehandlers) { ehandlers[name] = ehandlers[name].filter(function(h) { if (h.cb != fn) return true; delete h.cb; // dispatch could have a ref to h }); // replacing, not mutating the array if (!ehandlers[name].length) { delete ehandlers[name]; mp._request_event(name, false); } } } // call only pre-registered handlers, but not ones which got unregistered function dispatch_event(e) { var handlers = ehandlers[e.event]; if (handlers) { for (var len = handlers.length, i = 0; i < len; i++) { var cb = handlers[i].cb; // 'handlers' won't mutate, but unregister if (cb) // could remove cb from some items cb(e); } } } // ----- property observers ----- var next_oid = 1, observers = new_cache(); // items of id: fn mp.observe_property = function(name, format, fn) { var id = next_oid++; observers[id] = fn; return mp._observe_property(id, name, format || undefined); // allow null } mp.unobserve_property = function(fn) { for (var id in observers) { if (observers[id] == fn) { delete observers[id]; mp._unobserve_property(id); } } } function notify_observer(e) { var cb = observers[e.id]; if (cb) cb(e.name, e.data); } // ----- Client messages ----- var messages = new_cache(); // items of name: fn // overrides name. no libmpv API to reg/unreg specific messages. mp.register_script_message = function(name, fn) { messages[name] = fn; } mp.unregister_script_message = function(name) { delete messages[name]; } function dispatch_message(ev) { var cb = ev.args.length ? messages[ev.args[0]] : false; if (cb) cb.apply(null, ev.args.slice(1)); } // ----- hooks ----- var next_hid = 1, hooks = new_cache(); // items of id: fn function hook_run(id, cont) { var cb = hooks[id]; if (cb) cb(); mp.commandv("hook-ack", cont); } mp.add_hook = function add_hook(name, pri, fn) { if (next_hid == 1) // doesn't really matter if we do it once or always mp.register_script_message("hook_run", hook_run); var id = next_hid++; hooks[id] = fn; return mp.commandv("hook-add", name, id, pri); } /********************************************************************** * key bindings *********************************************************************/ // binds: items of (binding) name which are objects of: // {cb: fn, forced: bool, maybe input: str, repeatable: bool, complex: bool} var binds = new_cache(); function dispatch_key_binding(name, state) { var cb = binds[name] ? binds[name].cb : false; if (cb) // "script-binding [<script_name>/]<name>" command was invoked cb(state); } function update_input_sections() { var def = [], forced = []; for (var n in binds) // Array.join() will later skip undefined .input (binds[n].forced ? forced : def).push(binds[n].input); var sect = "input_" + mp.script_name; mp.commandv("define-section", sect, def.join("\n"), "default"); mp.commandv("enable-section", sect, "allow-hide-cursor+allow-vo-dragging"); sect = "input_forced_" + mp.script_name; mp.commandv("define-section", sect, forced.join("\n"), "force"); mp.commandv("enable-section", sect, "allow-hide-cursor+allow-vo-dragging"); } // name/opts maybe omitted. opts: object with optional bool members: repeatable, // complex, forced, or a string str which is evaluated as object {str: true}. var next_bid = 1; function add_binding(forced, key, name, fn, opts) { if (typeof name == "function") { // as if "name" is not part of the args opts = fn; fn = name; name = "__keybinding" + next_bid++; // new unique binding name } var key_data = {forced: forced}; switch (typeof opts) { // merge opts into key_data case "string": key_data[opts] = true; break; case "object": for (var o in opts) key_data[o] = opts[o]; } if (key_data.complex) { mp.register_script_message(name, function msg_cb() { fn({event: "press", is_mouse: false}); }); var KEY_STATES = { u: "up", d: "down", r: "repeat", p: "press" }; key_data.cb = function key_cb(state) { fn({ event: KEY_STATES[state[0]] || "unknown", is_mouse: state[1] == "m" }); } } else { mp.register_script_message(name, fn); key_data.cb = function key_cb(state) { // Emulate the semantics at input.c: mouse emits on up, kb on down. // Also, key repeat triggers the binding again. var e = state[0], emit = (state[1] == "m") ? (e == "u") : (e == "d"); if (emit || e == "p" || e == "r" && key_data.repeatable) fn(); } } if (key) key_data.input = key + " script-binding " + mp.script_name + "/" + name; binds[name] = key_data; // used by user and/or our (key) script-binding update_input_sections(); } mp.add_key_binding = add_binding.bind(null, false); mp.add_forced_key_binding = add_binding.bind(null, true); mp.remove_key_binding = function(name) { mp.unregister_script_message(name); delete binds[name]; update_input_sections(); } /********************************************************************** Timers: compatible HTML5 WindowTimers - set/clear Timeout/Interval - Spec: https://www.w3.org/TR/html5/webappapis.html#timers - Guaranteed to callback a-sync to [re-]insertion (event-loop wise). - Guaranteed to callback by expiration order, or, if equal, by insertion order. - Not guaranteed schedule accuracy, though intervals should have good average. *********************************************************************/ // pending 'timers' ordered by expiration: latest at index 0 (top fires first). // Earlier timers are quicker to handle - just push/pop or fewer items to shift. var next_tid = 1, timers = [], // while in process_timers, just insertion-ordered (push) tset_is_push = false, // signal set_timer that we're in process_timers tcanceled = false, // or object of items timer-id: true now = mp.get_time_ms; // just an alias function insert_sorted(arr, t) { for (var i = arr.length - 1; i >= 0 && t.when >= arr[i].when; i--) arr[i + 1] = arr[i]; // move up timers which fire earlier than t arr[i + 1] = t; // i is -1 or fires later than t } // args (is "arguments"): fn_or_str [,duration [,user_arg1 [, user_arg2 ...]]] function set_timer(repeat, args) { var fos = args[0], duration = Math.max(0, (args[1] || 0)), // minimum and default are 0 t = { id: next_tid++, when: now() + duration, interval: repeat ? duration : -1, callback: (typeof fos == "function") ? fos : Function(fos), args: (args.length < 3) ? false : [].slice.call(args, 2), }; if (tset_is_push) { timers.push(t); } else { insert_sorted(timers, t); } return t.id; } g.setTimeout = function setTimeout() { return set_timer(false, arguments) }; g.setInterval = function setInterval() { return set_timer(true, arguments) }; g.clearTimeout = g.clearInterval = function(id) { if (id < next_tid) { // must ignore if not active timer id. if (!tcanceled) tcanceled = {}; tcanceled[id] = true; } } // arr: ordered timers array. ret: -1: no timers, 0: due, positive: ms to wait function peek_wait(arr) { return arr.length ? Math.max(0, arr[arr.length - 1].when - now()) : -1; } // Callback all due non-canceled timers which were inserted before calling us. // Returns wait in ms till the next timer (possibly 0), or -1 if nothing pends. function process_timers() { var wait = peek_wait(timers); if (wait != 0) return wait; var actives = timers; // only process those already inserted by now timers = []; // we'll handle added new timers at the end of processing. tset_is_push = true; // signal set_timer to just push-insert do { var t = actives.pop(); if (tcanceled && tcanceled[t.id]) continue; if (t.args) { t.callback.apply(null, t.args); } else { (0, t.callback)(); // faster, nicer stack trace than t.cb.call() } if (t.interval >= 0) { // allow 20 ms delay/clock-resolution/gc before we skip and reset t.when = Math.max(now() - 20, t.when + t.interval); timers.push(t); // insertion order only } } while (peek_wait(actives) == 0); // new 'timers' are insertion-ordered. remains of actives are fully ordered timers.forEach(function(t) { insert_sorted(actives, t) }); timers = actives; // now we're fully ordered again, and with all timers tset_is_push = false; if (tcanceled) { timers = timers.filter(function(t) { return !tcanceled[t.id] }); tcanceled = false; } return peek_wait(timers); } /********************************************************************** CommonJS module/require Spec: http://wiki.commonjs.org/wiki/Modules/1.1.1 - All the mandatory requirements are implemented, all the unit tests pass. - The implementation makes the following exception: - Allows the chars [~@:\\] in module id for meta-dir/builtin/dos-drive/UNC. Implementation choices beyond the specification: - A module may assign to module.exports (rather than only to exports). - A module's 'this' is the global object, also if it sets strict mode. - No 'global'/'self'. Users can do "this.global = this;" before require(..) - A module has "privacy of its top scope", runs in its own function context. - No id identity with symlinks - a valid choice which others make too. - require("X") always maps to "X.js" -> require("foo.js") is file "foo.js.js". - Global modules search paths are 'scripts/modules.js/' in mpv config dirs. - A main script could e.g. require("./abc") to load a non-global module. - Module id supports mpv path enhancements, e.g. ~/foo, ~~/bar, ~~desktop/baz *********************************************************************/ // Internal meta top-dirs. Users should not rely on these names. var MODULES_META = "~~modules", SCRIPTDIR_META = "~~scriptdir", // relative script path -> meta absolute id main_script = mp.utils.split_path(mp.script_file); // -> [ path, file ] function resolve_module_file(id) { var sep = id.indexOf("/"), base = id.substring(0, sep), rest = id.substring(sep + 1) + ".js"; if (base == SCRIPTDIR_META) return mp.utils.join_path(main_script[0], rest); if (base == MODULES_META) { var path = mp.find_config_file("scripts/modules.js/" + rest); if (!path) throw(Error("Cannot find module file '" + rest + "'")); return path; } return id + ".js"; } // Delimiter '/', remove redundancies, prefix with modules meta-root if needed. // E.g. c:\x -> c:/x, or ./x//y/../z -> ./x/z, or utils/x -> ~~modules/utils/x . function canonicalize(id) { var path = id.replace(/\\/g,"/").split("/"), t = path[0], base = []; // if not strictly relative then must be top-level. figure out base/rest if (t != "." && t != "..") { // global module if it's not fs-root/home/dos-drive/builtin/meta-dir if (!(t == "" || t == "~" || t[1] == ":" || t == "@" || t.match(/^~~/))) path.unshift(MODULES_META); // add an explicit modules meta-root if (id.match(/^\\\\/)) // simple UNC handling, preserve leading \\srv path = ["\\\\" + path[2]].concat(path.slice(3)); // [ \\srv, shr..] if (t[1] == ":" && t.length > 2) { // path: [ "c:relative", "path" ] path[0] = t.substring(2); path.unshift(t[0] + ":."); // -> [ "c:.", "relative", "path" ] } base = [path.shift()]; } // path is now logically relative. base, if not empty, is its [meta] root. // normalize the relative part - always id-based (spec Module Id, 1.3.6). var cr = []; // canonicalized relative for (var i = 0; i < path.length; i++) { if (path[i] == "." || path[i] == "") continue; if (path[i] == ".." && cr.length && cr[cr.length - 1] != "..") { cr.pop(); continue; } cr.push(path[i]); } if (!base.length && cr[0] != "..") base = ["."]; // relative and not ../<stuff> so must start with ./ return base.concat(cr).join("/"); } function resolve_module_id(base_id, new_id) { new_id = canonicalize(new_id); if (!new_id.match(/^\.\/|^\.\.\//)) // doesn't start with ./ or ../ return new_id; // not relative, we don't care about base_id var combined = mp.utils.join_path(mp.utils.split_path(base_id)[0], new_id); return canonicalize(combined); } var req_cache = new_cache(); // global for all instances of require // ret: a require function instance which uses base_id to resolve relative id's function new_require(base_id) { return function require(id) { id = resolve_module_id(base_id, id); // id is now top-level if (req_cache[id]) return req_cache[id].exports; var new_module = {id: id, exports: {}}; req_cache[id] = new_module; try { var filename = resolve_module_file(id); // we need dedicated free vars + filename in traces + allow strict var str = "mp._req = function(require, exports, module) {" + mp.utils.read_file(filename) + "\n;}"; mp.utils.compile_js(filename, str)(); // only runs the assignment var tmp = mp._req; // we have mp._req, or else we'd have thrown delete mp._req; tmp.call(g, new_require(id), new_module.exports, new_module); } catch (e) { delete req_cache[id]; throw(e); } return new_module.exports; }; } g.require = new_require(SCRIPTDIR_META + "/" + main_script[1]); /********************************************************************** * various *********************************************************************/ g.print = mp.msg.info; // convenient alias mp.get_script_name = function() { return mp.script_name }; mp.get_script_file = function() { return mp.script_file }; mp.get_time = function() { return mp.get_time_ms() / 1000 }; mp.utils.getcwd = function() { return mp.get_property("working-directory") }; mp.dispatch_event = dispatch_event; mp.process_timers = process_timers; mp.get_opt = function(key, def) { var v = mp.get_property_native("options/script-opts")[key]; return (typeof v != "undefined") ? v : def; } mp.osd_message = function osd_message(text, duration) { mp.commandv("show_text", text, Math.round(1000 * (duration || -1))); } // ----- dump: like print, but expands objects/arrays recursively ----- function replacer(k, v) { var t = typeof v; if (t == "function" || t == "undefined") return "<" + t + ">"; if (Array.isArray(this) && t == "object" && v !== null) { // "safe" mode if (this.indexOf(v) >= 0) return "<VISITED>"; this.push(v); } return v; } function obj2str(v) { try { // can process objects more than once, but throws on cycles return JSON.stringify(v, replacer, 2); } catch (e) { // simple safe: exclude visited objects, even if not cyclic return JSON.stringify(v, replacer.bind([]), 2); } } g.dump = function dump() { var toprint = []; for (var i = 0; i < arguments.length; i++) { var v = arguments[i]; toprint.push((typeof v == "object") ? obj2str(v) : replacer(0, v)); } print.apply(null, toprint); } /********************************************************************** * main listeners and event loop *********************************************************************/ mp.keep_running = true; g.exit = function() { mp.keep_running = false }; // user-facing too mp.register_event("shutdown", g.exit); mp.register_event("property-change", notify_observer); mp.register_event("client-message", dispatch_message); mp.register_script_message("key-binding", dispatch_key_binding); g.mp_event_loop = function mp_event_loop() { var wait = 0; // seconds do { // distapch events as long as they arrive, then do the timers var e = mp.wait_event(wait); if (e.event != "none") { dispatch_event(e); wait = 0; // poll the next one } else { wait = process_timers() / 1000; } } while (mp.keep_running); }; })(this)
torque/mpv
player/javascript/defaults.js
JavaScript
gpl-2.0
18,251
'use strict'; require('../common'); const assert = require('assert'); const Buffer = require('buffer').Buffer; function FakeBuffer() { } Object.setPrototypeOf(FakeBuffer, Buffer); Object.setPrototypeOf(FakeBuffer.prototype, Buffer.prototype); const fb = new FakeBuffer(); assert.throws(function() { Buffer.from(fb); }, TypeError); assert.throws(function() { +Buffer.prototype; }, TypeError); assert.throws(function() { Buffer.compare(fb, Buffer.alloc(0)); }, TypeError); assert.throws(function() { fb.write('foo'); }, TypeError); assert.throws(function() { Buffer.concat([fb, fb]); }, TypeError); assert.throws(function() { fb.toString(); }, TypeError); assert.throws(function() { fb.equals(Buffer.alloc(0)); }, TypeError); assert.throws(function() { fb.indexOf(5); }, TypeError); assert.throws(function() { fb.readFloatLE(0); }, TypeError); assert.throws(function() { fb.writeFloatLE(0); }, TypeError); assert.throws(function() { fb.fill(0); }, TypeError);
domino-team/openwrt-cc
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/test/parallel/test-buffer-fakes.js
JavaScript
gpl-2.0
994
<?php /** * @package Layers */ /** * Add define Layers constants to be used around Layers themes, plugins etc. */ /** * The current version of the theme. Use a random number for SCRIPT_DEBUG mode */ define( 'LAYERS_VERSION', '1.2.2' ); define( 'LAYERS_TEMPLATE_URI' , get_template_directory_uri() ); define( 'LAYERS_TEMPLATE_DIR' , get_template_directory() ); define( 'LAYERS_THEME_TITLE' , 'Layers' ); define( 'LAYERS_THEME_SLUG' , 'layers' ); define( 'LAYERS_BUILDER_TEMPLATE' , 'builder.php' ); /** * Set the content width based on the theme's design and stylesheet. */ if ( ! isset( $content_width ) ) $content_width = 1080; /* pixels */ /** * Adjust the content width when the full width page template is being used */ function layers_set_content_width() { global $content_width; $left_sidebar_active = layers_can_show_sidebar( 'left-sidebar' ); $right_sidebar_active = layers_can_show_sidebar( 'right-sidebar' ); if( is_page_template( LAYERS_BUILDER_TEMPLATE ) ) { $content_width = 1080; } else if( is_page_template( 'template-both-sidebar.php' ) || is_page_template( 'template-left-sidebar.php' ) || is_page_template( 'template-right-sidebar.php' ) ){ $content_width = 660; } elseif ( is_page_template( 'template-blog.php' ) ) { $content_width = 1080; } elseif( $left_sidebar_active || $right_sidebar_active ){ $content_width = 660; } } add_action( 'template_redirect', 'layers_set_content_width' ); /* * Third Party Scripts */ require_once get_template_directory() . '/core/third-party/site-logo.php'; /* * Load Widgets */ require_once get_template_directory() . '/core/widgets/init.php'; /* * Load Customizer Support */ require_once get_template_directory() . '/core/customizer/init.php'; /* * Load Custom Post Meta */ require_once get_template_directory() . '/core/meta/init.php'; /* * Load Front-end helpers */ require_once get_template_directory() . '/core/helpers/color.php'; require_once get_template_directory() . '/core/helpers/custom-fonts.php'; require_once get_template_directory() . '/core/helpers/extensions.php'; require_once get_template_directory() . '/core/helpers/post.php'; require_once get_template_directory() . '/core/helpers/post-types.php'; require_once get_template_directory() . '/core/helpers/sanitization.php'; require_once get_template_directory() . '/core/helpers/template.php'; require_once get_template_directory() . '/core/helpers/woocommerce.php'; /* * Load Admin-specific files */ if( is_admin() ){ // Include form item class require_once get_template_directory() . '/core/helpers/forms.php'; // Include design bar class require_once get_template_directory() . '/core/helpers/design-bar.php'; // Include API class require_once get_template_directory() . '/core/helpers/api.php'; // Include widget export/import class require_once get_template_directory() . '/core/helpers/migrator.php'; //Load Options Panel require_once get_template_directory() . '/core/options-panel/init.php'; } if( ! function_exists( 'layers_setup' ) ) { function layers_setup(){ global $pagenow; /** * Add support for HTML5 */ add_theme_support('html5'); /** * Add support for Title Tags */ add_theme_support('title-tag'); /** * Add support for widgets inside the customizer */ add_theme_support('widget-customizer'); /** * Add support for WooCommerce */ add_theme_support( 'woocommerce' ); /** * Add support for featured images */ add_theme_support( 'post-thumbnails' ); // Set Large Image Sizes add_image_size( 'layers-square-large', 1000, 1000, true ); add_image_size( 'layers-portrait-large', 720, 1000, true ); add_image_size( 'layers-landscape-large', 1000, 720, true ); // Set Medium Image Sizes add_image_size( 'layers-square-medium', 480, 480, true ); add_image_size( 'layers-portrait-medium', 340, 480, true ); add_image_size( 'layers-landscape-medium', 480, 340, true ); /** * Add text domain */ load_theme_textdomain('layerswp', get_template_directory() . '/languages'); /** * Add theme support */ // Custom Site Logo add_theme_support( 'site-logo', array( 'header-text' => array( 'sitetitle', 'tagline', ), 'size' => 'medium', ) ); // Automatic Feed Links add_theme_support( 'automatic-feed-links' ); /** * Register nav menus */ register_nav_menus( array( LAYERS_THEME_SLUG . '-secondary-left' => __( 'Top Left Menu' , 'layerswp' ), LAYERS_THEME_SLUG . '-secondary-right' => __( 'Top Right Menu' , 'layerswp' ), LAYERS_THEME_SLUG . '-primary' => __( 'Header Menu' , 'layerswp' ), LAYERS_THEME_SLUG . '-primary-right' => __( 'Right Header Menu' , 'layerswp' ), LAYERS_THEME_SLUG . '-footer' => __( 'Footer Menu' , 'layerswp' ), ) ); /** * Welcome Redirect */ if( isset($_GET["activated"]) && $pagenow = "themes.php" ) { //&& '' == get_option( 'layers_welcome' ) update_option( 'layers_welcome' , 1); wp_safe_redirect( admin_url('admin.php?page=' . LAYERS_THEME_SLUG . '-get-started')); } } // function layers_setup } // if !function layers_setup add_action( 'after_setup_theme' , 'layers_setup', 10 ); /** * Enqueue front end styles and scripts */ if( ! function_exists( 'layers_register_standard_sidebars' ) ) { function layers_register_standard_sidebars(){ /** * Register Standard Sidebars */ register_sidebar( array( 'id' => LAYERS_THEME_SLUG . '-off-canvas-sidebar', 'name' => __( 'Mobile Sidebar' , 'layerswp' ), 'description' => __( 'This sidebar will only appear on mobile devices.' , 'layerswp' ), 'before_widget' => '<aside id="%1$s" class="content widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h5 class="section-nav-title">', 'after_title' => '</h5>', ) ); register_sidebar( array( 'id' => LAYERS_THEME_SLUG . '-left-sidebar', 'name' => __( 'Left Sidebar' , 'layerswp' ), 'before_widget' => '<aside id="%1$s" class="content well push-bottom-large widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h5 class="section-nav-title">', 'after_title' => '</h5>', ) ); register_sidebar( array( 'id' => LAYERS_THEME_SLUG . '-right-sidebar', 'name' => __( 'Right Sidebar' , 'layerswp' ), 'before_widget' => '<aside id="%1$s" class="content well push-bottom-large widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h5 class="section-nav-title">', 'after_title' => '</h5>', ) ); /** * Register Footer Sidebars */ for( $footer = 1; $footer < 5; $footer++ ) { register_sidebar( array( 'id' => LAYERS_THEME_SLUG . '-footer-' . $footer, 'name' => __( 'Footer ', 'layerswp' ) . $footer, 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h5 class="section-nav-title">', 'after_title' => '</h5>', ) ); } // for footers /** * Register WooCommerce Sidebars */ if( class_exists( 'WooCommerce' ) ) { register_sidebar( array( 'id' => LAYERS_THEME_SLUG . '-left-woocommerce-sidebar', 'name' => __( 'Left Shop Sidebar' , 'layerswp' ), 'description' => __( '' , 'layerswp' ), 'before_widget' => '<aside id="%1$s" class="content well push-bottom-large widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h5 class="section-nav-title">', 'after_title' => '</h5>', ) ); register_sidebar( array( 'id' => LAYERS_THEME_SLUG . '-right-woocommerce-sidebar', 'name' => __( 'Right Shop Sidebar' , 'layerswp' ), 'description' => __( '' , 'layerswp' ), 'before_widget' => '<aside id="%1$s" class="content well push-bottom-large widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h5 class="section-nav-title">', 'after_title' => '</h5>', ) ); } } } add_action( 'widgets_init' , 'layers_register_standard_sidebars' , 50 ); /** * Enqueue front end styles and scripts */ if( ! function_exists( 'layers_scripts' ) ) { function layers_scripts(){ /** * Front end Scripts */ wp_enqueue_script( LAYERS_THEME_SLUG . '-plugins-js' , get_template_directory_uri() . '/assets/js/plugins.js', array( 'jquery', ), LAYERS_VERSION ); // Sticky-Kit wp_enqueue_script( LAYERS_THEME_SLUG . '-framework-js' , get_template_directory_uri() . '/assets/js/layers.framework.js', array( 'jquery', ), LAYERS_VERSION, true ); // Framework if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } // Comment reply script /** * Front end Styles */ wp_enqueue_style( LAYERS_THEME_SLUG . '-framework' , get_template_directory_uri() . '/assets/css/framework.css', array() , LAYERS_VERSION ); wp_enqueue_style( LAYERS_THEME_SLUG . '-components', get_template_directory_uri() . '/assets/css/components.css', array(), LAYERS_VERSION ); // Compontents wp_enqueue_style( LAYERS_THEME_SLUG . '-responsive', get_template_directory_uri() . '/assets/css/responsive.css', array(), LAYERS_VERSION ); // Responsive wp_enqueue_style( LAYERS_THEME_SLUG . '-icon-fonts', get_template_directory_uri() . '/assets/css/layers-icons.css', array(), LAYERS_VERSION ); // Icon Font if( class_exists( 'WooCommerce' ) ) { wp_enqueue_style( LAYERS_THEME_SLUG . '-woocommerce', get_template_directory_uri() . '/assets/css/woocommerce.css', array(), LAYERS_VERSION ); // Woocommerce } wp_enqueue_style( LAYERS_THEME_SLUG . '-style' , get_stylesheet_uri(), array() , LAYERS_VERSION ); if( is_admin_bar_showing() ) { wp_enqueue_style( LAYERS_THEME_SLUG . '-admin', get_template_directory_uri() . '/core/assets/icons.css', array(), LAYERS_VERSION ); // Admin CSS } } } add_action( 'wp_enqueue_scripts' , 'layers_scripts' ); /** * Enqueue admin end styles and scripts */ if( ! function_exists( 'layers_admin_scripts' ) ) { function layers_admin_scripts(){ wp_enqueue_style( LAYERS_THEME_SLUG . '-admin', get_template_directory_uri() . '/core/assets/admin.css', array(), LAYERS_VERSION ); // Admin CSS wp_enqueue_style( LAYERS_THEME_SLUG . '-admin-editor', get_template_directory_uri() . '/core/assets/editor.css', array(), LAYERS_VERSION ); // Inline Editor wp_enqueue_style( LAYERS_THEME_SLUG . '-admin-font-awesome', get_template_directory_uri() . '/core/assets/font-awesome.min.css', array(), LAYERS_VERSION ); // Inline Editor wp_enqueue_script( LAYERS_THEME_SLUG . '-admin-editor' , get_template_directory_uri() . '/core/assets/editor.min.js' , array( 'jquery' ), LAYERS_VERSION, true ); // Inline Editor wp_enqueue_script( LAYERS_THEME_SLUG . '-admin-migrator' , get_template_directory_uri() . '/core/assets/migrator.js' , array( 'media-upload' ), LAYERS_VERSION, true ); wp_localize_script( LAYERS_THEME_SLUG . '-admin-migrator', 'migratori18n', array( 'loading_message' => __( 'Be patient while we import the widget data and images.' , 'layerswp' ), 'complete_message' => __( 'Import Complete' , 'layerswp' ), 'importing_message' => __( 'Importing Your Content' , 'layerswp' ), 'duplicate_complete_message' => __( 'Edit Your New Page' , 'layerswp' ) ) );// Migrator// Localize Scripts wp_localize_script( LAYERS_THEME_SLUG . '-admin-migrator', "layers_migrator_params", array( 'duplicate_layout_nonce' => wp_create_nonce( 'layers-migrator-duplicate' ), 'import_layout_nonce' => wp_create_nonce( 'layers-migrator-import' ), 'preset_layout_nonce' => wp_create_nonce( 'layers-migrator-preset-layouts' ), ) ); // Onboarding Process wp_enqueue_script( LAYERS_THEME_SLUG . '-admin-onboarding' , get_template_directory_uri() . '/core/assets/onboarding.js', array( 'jquery' ), LAYERS_VERSION, true ); // Onboarding JS wp_localize_script( LAYERS_THEME_SLUG . '-admin-onboarding' , "layers_onboarding_params", array( 'preset_layout_nonce' => wp_create_nonce( 'layers-migrator-preset-layouts' ), 'update_option_nonce' => wp_create_nonce( 'layers-onboarding-update-options' ), 'set_theme_mod_nonce' => wp_create_nonce( 'layers-onboarding-set-theme-mods' ), ) ); // Onboarding ajax parameters wp_localize_script( LAYERS_THEME_SLUG . '-admin-onboarding' , 'onboardingi18n', array( 'step_saving_message' => __( 'Saving...' , 'layerswp' ), 'step_done_message' => __( 'Done!' , 'layerswp' ) ) ); // Onboarding localization wp_enqueue_script( LAYERS_THEME_SLUG . '-admin' , get_template_directory_uri() . '/core/assets/admin.js', array( 'jquery', 'jquery-ui-sortable', 'wp-color-picker', ), LAYERS_VERSION, true ); // Admin JS wp_localize_script( LAYERS_THEME_SLUG . '-admin' , "layers_admin_params", array( 'backup_pages_nonce' => wp_create_nonce( 'layers-backup-pages' ), 'backup_pages_success_message' => __('Your pages have been successfully backed up!', 'layerswp' ) ) ); // Onboarding ajax parameters wp_enqueue_media(); } } add_action( 'customize_controls_print_footer_scripts' , 'layers_admin_scripts' ); add_action( 'admin_enqueue_scripts' , 'layers_admin_scripts' ); /** * Make sure that all excerpts have class="excerpt" */ if( !function_exists( 'layers_excerpt_class' ) ) { function layers_excerpt_class( $excerpt ) { return str_replace('<p', '<p class="excerpt"', $excerpt); } } // layers_excerpt_class add_filter( "the_excerpt", "layers_excerpt_class" ); add_filter( "get_the_excerpt", "layers_excerpt_class" );
haisuu111/shop
wp-content/themes/layerswp/functions.php
PHP
gpl-2.0
13,786
<?php /* * This file is part of EC-CUBE * * Copyright(c) 2000-2014 LOCKON CO.,LTD. All Rights Reserved. * * http://www.lockon.co.jp/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * テストケースで使う一般的なユーティリティを持つクラス. * * @author Hiroko Tamagawa * @version $Id: Test_Utils.php 23546 2014-06-12 14:47:59Z shutta $ */ class Test_Utils { /** * 連想配列から指定されたキーだけを抜き出したものを返します. * 入力の連想配列には変更を加えません. * * @static * @param input_array 入力の連想配列 * @param map_keys 出力結果に入れたいキーを配列で指定します * @return 指定したキーのみを持つ連想配列 */ public static function mapArray($input_array, $map_keys) { $output_array = array(); foreach ($map_keys as $index => $map_key) { $output_array[$map_key] = $input_array[$map_key]; } return $output_array; } /** * 配列の各要素(連想配列)から特定のキーだけを抜き出した配列を返します. * 入力の連想配列には変更を加えません. * * @static * @param input_array 入力の配列 * @param key 抽出対象のキー * @return 指定のキーだけを抜き出した配列 */ public static function mapCols($input_array, $key) { $output_array = array(); foreach ($input_array as $data) { $output_array[] = $data[$key]; } return $output_array; } /** * 配列に別の配列をappendします。 * $orig_arrayが直接変更されます。 * * @static * @param orig_array 追加先の配列 * @param new_array 追加要素を持つ配列 */ public static function array_append(&$orig_array, $new_array) { foreach ($new_array as $element) { $orig_array[] = $element; } } }
shoheiworks/Labo-EcCube
tests/class/test/util/Test_Utils.php
PHP
gpl-2.0
2,579
<?php /** * File containing the FragmentListenerFactory class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.07.0 */ namespace eZ\Bundle\EzPublishCoreBundle\Fragment; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\UriSigner; /** * Custom factory for Symfony FragmentListener. * Makes fragment paths SiteAccess aware (when in URI). */ class FragmentListenerFactory { /** * @var \Symfony\Component\HttpFoundation\Request */ private $request; public function setRequest( Request $request = null ) { $this->request = $request; } public function buildFragmentListener( UriSigner $uriSigner, $fragmentPath, $fragmentListenerClass ) { // Ensure that current pathinfo ends with configured fragment path. // If so, consider it as the fragment path. // This ensures to have URI siteaccess compatible fragment paths. $pathInfo = $this->request->getPathInfo(); if ( substr( $pathInfo, -strlen( $fragmentPath ) ) === $fragmentPath ) { $fragmentPath = $pathInfo; } $fragmentListener = new $fragmentListenerClass( $uriSigner, $fragmentPath ); return $fragmentListener; } }
tonvinh/ez
vendor/ezsystems/ezpublish-kernel/eZ/Bundle/EzPublishCoreBundle/Fragment/FragmentListenerFactory.php
PHP
gpl-2.0
1,381
#include "DataFactory.h" #include "Data/DataLoader.h" #include "Data/Image/Controller.h" #include "Data/Image/DataSource.h" #include "Data/Region/Region.h" #include "Data/Region/RegionFactory.h" #include "Data/Util.h" #include "CartaLib/Hooks/LoadRegion.h" #include "Globals.h" #include <QDebug> namespace Carta { namespace Data { DataFactory::DataFactory(){ } QString DataFactory::addData( Controller* controller, const QString& fileName, bool* success ){ QString result; *success = false; if ( controller ){ QFileInfo fileInfo( fileName ); bool dataFile = fileInfo.isFile(); if ( dataFile ){ bool regionFile = _isRegion( fileName ); //If we think it is a region, see if any of the region parsing //plugins can handle it. if ( regionFile ){ std::vector<std::shared_ptr<Region> > regions = _loadRegions( controller, fileName, success, result ); if ( regions.size() > 0 ){ controller->_addDataRegions( regions ); } } } //Try loading it as an image. if ( !(*success) ){ result = controller->_addDataImage( fileName, success ); } } else { result = "The data in "+fileName +" could not be added because no controller was specified."; } return result; } bool DataFactory::_isRegion( const QString& fileName ){ bool regionFile = false; if ( fileName.endsWith( DataLoader::CRTF) ){ regionFile = true; } else if ( fileName.endsWith( ".reg")){ regionFile = true; } else { QFile file( fileName ); if ( file.open( QIODevice::ReadOnly | QIODevice::Text)){ char buf[1024]; qint64 lineLength = file.readLine( buf, sizeof(buf)); if ( lineLength > 0 ){ QString line( buf ); if ( line.startsWith( "#CRTF") ){ regionFile = true; } else if ( line.startsWith( "# Region file format: DS9") ){ regionFile = true; } //Region files for unspecified plug-ins? else if ( line.contains( "region", Qt::CaseInsensitive) ){ regionFile = true; } } } } return regionFile; } std::vector<std::shared_ptr<Region> > DataFactory::_loadRegions( Controller* controller, const QString& fileName, bool* success, QString& errorMsg ){ std::vector< std::shared_ptr<Region> > regions; std::shared_ptr<DataSource> dataSource = controller->getDataSource(); if ( dataSource ){ std::shared_ptr<Carta::Lib::Image::ImageInterface> image = dataSource->_getImage(); auto result = Globals::instance()-> pluginManager() -> prepare <Carta::Lib::Hooks::LoadRegion>(fileName, image ); auto lam = /*[=]*/[&regions,fileName] ( const Carta::Lib::Hooks::LoadRegion::ResultType &data ) { int regionCount = data.size(); //Return whether to continue the loop or not. We continue until we //find the first plugin that can handle the region format and generate //one or more regions. bool continueLoop = true; if ( regionCount > 0 ){ continueLoop = false; } for ( int i = 0; i < regionCount; i++ ){ if ( data[i] ){ std::shared_ptr<Region> regionPtr = RegionFactory::makeRegion( data[i] ); regionPtr -> _setUserId( fileName, i ); regions.push_back( regionPtr ); } } return continueLoop; }; try { //Find the first plugin that can load the region. result.forEachCond( lam ); *success = true; } catch( char*& error ){ errorMsg = QString( error ); *success = false; } } return regions; } DataFactory::~DataFactory(){ } } }
Astroua/CARTAvis
carta/cpp/core/Data/Image/DataFactory.cpp
C++
gpl-2.0
4,125
package edu.stanford.nlp.coref.hybrid.sieve; import edu.stanford.nlp.util.logging.Redwood; import java.util.List; import java.util.Properties; import edu.stanford.nlp.coref.data.Dictionaries; import edu.stanford.nlp.coref.data.Document; import edu.stanford.nlp.coref.data.Mention; import edu.stanford.nlp.coref.data.Dictionaries.MentionType; public class OracleSieve extends Sieve { /** A logger for this class */ private static Redwood.RedwoodChannels log = Redwood.channels(OracleSieve.class); private static final long serialVersionUID = 3510248899162246138L; public OracleSieve(Properties props, String sievename) { super(props, sievename); this.classifierType = ClassifierType.ORACLE; } @Override public void findCoreferentAntecedent(Mention m, int mIdx, Document document, Dictionaries dict, Properties props, StringBuilder sbLog) throws Exception { for(int distance=0 ; distance <= m.sentNum ; distance++) { List<Mention> candidates = document.predictedMentions.get(m.sentNum-distance); for(Mention candidate : candidates) { if(!matchedMentionType(candidate, aTypeStr) || !matchedMentionType(m, mTypeStr)) continue; // if(!options.mType.contains(m.mentionType) || !options.aType.contains(candidate.mentionType)) continue; if(candidate == m) continue; if(distance==0 && m.appearEarlierThan(candidate)) continue; // ignore cataphora if(Sieve.isReallyCoref(document, m.mentionID, candidate.mentionID)) { if(m.mentionType==MentionType.LIST) { log.info("LIST MATCHING MENTION : "+m.spanToString()+"\tANT: "+candidate.spanToString()); } Sieve.merge(document, m.mentionID, candidate.mentionID); return; } } } } }
rupenp/CoreNLP
src/edu/stanford/nlp/coref/hybrid/sieve/OracleSieve.java
Java
gpl-2.0
1,774
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.6 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2015 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM is distributed in the hope that it will be useful, but | | WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | See the GNU Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * This class generates form components for processing a contribution. */ class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditPayment { /** * The id of the contribution that we are processing. * * @var int */ public $_id; /** * The id of the premium that we are processing. * * @var int */ public $_premiumID = NULL; /** * @var CRM_Contribute_DAO_ContributionProduct */ public $_productDAO = NULL; /** * The id of the note. * * @var int */ public $_noteID; /** * The id of the contact associated with this contribution. * * @var int */ public $_contactID; /** * The id of the pledge payment that we are processing. * * @var int */ public $_ppID; /** * The id of the pledge that we are processing. * * @var int */ public $_pledgeID; /** * Is this contribution associated with an online. * financial transaction * * @var boolean */ public $_online = FALSE; /** * Stores all product options. * * @var array */ public $_options; /** * Storage of parameters from form * * @var array */ public $_params; /** * Store the contribution Type ID * * @var array */ public $_contributionType; /** * The contribution values if an existing contribution */ public $_values; /** * The pledge values if this contribution is associated with pledge */ public $_pledgeValues; public $_contributeMode = 'direct'; public $_context; /** * Parameter with confusing name. * @todo what is it? * @var string */ public $_compContext; public $_compId; /** * Possible From email addresses * @var array */ public $_fromEmails; /** * ID of from email * @var integer */ public $fromEmailId; /** * Store the line items if price set used. */ public $_lineItems; /** * Line item * @todo explain why we use lineItem & lineItems * @var array */ public $_lineItem; /** * @var array soft credit info */ public $_softCreditInfo; protected $_formType; /** * @todo what on earth does cdType stand for???? * @var */ protected $_cdType; public $_honoreeProfileType; /** * Array of billing panes to be displayed by billingBlock.tpl. * Currently this is likely to look like * array('Credit Card' => ts('Credit Card') or * array('Direct Debit => ts('Direct Debit') * @todo billing details (address stuff) to be added when we stop hard coding the panes in billingBlock.tpl * * @var array */ public $billingPane = array(); /** * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata * * @var array */ public $_paymentFields = array(); /** * Logged in user's email. * @var string */ public $userEmail; /** * Price set ID * @var integer */ public $_priceSetId; /** * Price set as an array * @var array */ public $_priceSet; /** * Form defaults * @todo can we define this a as protected? can we define higher up the chain * @var array */ public $_defaults; /** * User display name * * @var string */ public $userDisplayName; /** * Set variables up before form is built. */ public function preProcess() { // Check permission for action. if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) { CRM_Core_Error::fatal(ts('You do not have permission to access this page.')); } // @todo - if anyone ever figures out what this _cdType subroutine is about // (or even if it still applies) please add comments!!!!!!!!!! $this->_cdType = CRM_Utils_Array::value('type', $_GET); $this->assign('cdType', FALSE); if ($this->_cdType) { $this->assign('cdType', TRUE); CRM_Custom_Form_CustomData::preProcess($this); return; } $this->_formType = CRM_Utils_Array::value('formType', $_GET); // Get price set id. $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET); $this->set('priceSetId', $this->_priceSetId); $this->assign('priceSetId', $this->_priceSetId); // Get the pledge payment id $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this); // Get the contact id $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this); // Get the action. $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add'); $this->assign('action', $this->_action); // Get the contribution id if update $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this); if (!empty($this->_id)) { $this->assign('contribID', $this->_id); } $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this); $this->assign('context', $this->_context); $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this); $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this); //set the contribution mode. $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this); $this->assign('contributionMode', $this->_mode); if ($this->_action & CRM_Core_Action::DELETE) { return; } $this->assign('showCheckNumber', TRUE); $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail(); $this->assignPaymentRelatedVariables(); if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) { $this->preProcessPledge(); } if ($this->_id) { $this->showRecordLinkMesssage($this->_id); } $this->_values = array(); // Current contribution id. if ($this->_id) { $this->assignPremiumProduct($this->_id); $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values); } // when custom data is included in this page if (!empty($_POST['hidden_custom'])) { $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id); } $this->_lineItems = array(); if ($this->_id) { if (!empty($this->_compId) && $this->_compContext == 'participant') { $this->assign('compId', $this->_compId); $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId); } else { $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE); } empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem; } $this->assign('lineItem', empty($this->_lineItems) ? FALSE : $this->_lineItems); // Set title if ($this->_mode) { $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution')); } else { $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution')); } if ($this->_id) { CRM_Contribute_Form_SoftCredit::preprocess($this); } } /** * Set default values. * * @return array */ public function setDefaultValues() { if ($this->_cdType) { // @todo document when this function would be called in this way // (and whether it is valid or an overloading of this form). return CRM_Custom_Form_CustomData::setDefaultValues($this); } $defaults = $this->_values; // Set defaults for pledge payment. if ($this->_ppID) { $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']); $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues); $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues); $defaults['option_type'] = 1; } if ($this->_action & CRM_Core_Action::DELETE) { return $defaults; } $defaults['frequency_interval'] = 1; $defaults['frequency_unit'] = 'month'; // Set soft credit defaults. CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this); if ($this->_mode) { $config = CRM_Core_Config::singleton(); // Set default country from config if no country set. if (empty($defaults["billing_country_id-{$this->_bltID}"])) { $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry; } if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) { $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince; } $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID); $defaults = array_merge($defaults, $billingDefaults); } if ($this->_id) { $this->_contactID = $defaults['contact_id']; } // Set $newCredit variable in template to control whether link to credit card mode is included. $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()); // Fix the display of the monetary value, CRM-4038. if (isset($defaults['total_amount'])) { if (!empty($defaults['tax_amount'])) { $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id); if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) { $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a'); } } else { $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'], NULL, '%a'); } } if (isset($defaults['non_deductible_amount'])) { $defaults['non_deductible_amount'] = CRM_Utils_Money::format($defaults['non_deductible_amount'], NULL, '%a'); } if (isset($defaults['fee_amount'])) { $defaults['fee_amount'] = CRM_Utils_Money::format($defaults['fee_amount'], NULL, '%a'); } if (isset($defaults['net_amount'])) { $defaults['net_amount'] = CRM_Utils_Money::format($defaults['net_amount'], NULL, '%a'); } if ($this->_contributionType) { $defaults['financial_type_id'] = $this->_contributionType; } if (empty($defaults['payment_instrument_id'])) { $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1')); } if (!empty($defaults['is_test'])) { $this->assign('is_test', TRUE); } $this->assign('showOption', TRUE); // For Premium section. if ($this->_premiumID) { $this->assign('showOption', FALSE); $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : ""; if (!$options) { $this->assign('showOption', TRUE); } $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options); if ($options_key) { $defaults['product_name'] = array($this->_productDAO->product_id, trim($options_key)); } else { $defaults['product_name'] = array($this->_productDAO->product_id); } if ($this->_productDAO->fulfilled_date) { list($defaults['fulfilled_date']) = CRM_Utils_Date::setDateDefaults($this->_productDAO->fulfilled_date); } } if (isset($this->userEmail)) { $this->assign('email', $this->userEmail); } if (!empty($defaults['is_pay_later'])) { $this->assign('is_pay_later', TRUE); } $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults)); $dates = array( 'receive_date', 'receipt_date', 'cancel_date', 'thankyou_date', ); foreach ($dates as $key) { if (!empty($defaults[$key])) { list($defaults[$key], $defaults[$key . '_time']) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults), 'activityDateTime'); } } if (!$this->_id && empty($defaults['receive_date'])) { list($defaults['receive_date'], $defaults['receive_date_time'] ) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime'); } $this->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $defaults), CRM_Utils_Array::value('receive_date_time', $defaults) )); $currency = CRM_Utils_Array::value('currency', $defaults); $this->assign('currency', $currency); // Hack to get currency info to the js layer. CRM-11440. CRM_Utils_Money::format(1); $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols)); $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults)); // Inherit campaign from pledge. if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) { $defaults['campaign_id'] = $this->_pledgeValues['campaign_id']; } $this->_defaults = $defaults; return $defaults; } /** * Build the form object. */ public function buildQuickForm() { //@todo document the purpose of cdType (if still in use) if ($this->_cdType) { CRM_Custom_Form_CustomData::buildQuickForm($this); return; } $allPanes = array(); //tax rate from financialType $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates())); $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled'))); // build price set form. $buildPriceSet = FALSE; $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); $this->assign('invoicing', $invoicing); // display tax amount on edit contribution page if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) { $this->assign('totalTaxAmount', $this->_values['tax_amount']); } if (empty($this->_lineItems) && ($this->_priceSetId || !empty($_POST['price_set_id'])) ) { $buildPriceSet = TRUE; $getOnlyPriceSetElements = TRUE; if (!$this->_priceSetId) { $this->_priceSetId = $_POST['price_set_id']; $getOnlyPriceSetElements = FALSE; } $this->set('priceSetId', $this->_priceSetId); CRM_Price_BAO_PriceSet::buildPriceSet($this); // get only price set form elements. if ($getOnlyPriceSetElements) { return; } } // use to build form during form rule. $this->assign('buildPriceSet', $buildPriceSet); $showAdditionalInfo = FALSE; $defaults = $this->_values; $additionalDetailFields = array( 'note', 'thankyou_date', 'invoice_id', 'non_deductible_amount', 'fee_amount', 'net_amount', ); foreach ($additionalDetailFields as $key) { if (!empty($defaults[$key])) { $defaults['hidden_AdditionalDetail'] = 1; break; } } if ($this->_productDAO) { if ($this->_productDAO->product_id) { $defaults['hidden_Premium'] = 1; } } if ($this->_noteID && isset($this->_values['note']) ) { $defaults['hidden_AdditionalDetail'] = 1; } $paneNames = array( ts('Additional Details') => 'AdditionalDetail', ); //Add Premium pane only if Premium is exists. $dao = new CRM_Contribute_DAO_Product(); $dao->is_active = 1; if ($dao->find(TRUE)) { $paneNames[ts('Premium Information')] = 'Premium'; } $billingPanes = array(); if ($this->_mode) { if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE) == TRUE) { $buildRecurBlock = TRUE; foreach ($this->billingPane as $name => $label) { if (!empty($this->billingFieldSets[$name]['fields'])) { // @todo reduce variation so we don't have to convert 'credit_card' to 'CreditCard' $billingPanes[$label] = $this->generatePane(CRM_Utils_String::convertStringToCamel($name), $defaults); } } } } foreach ($paneNames as $name => $type) { $allPanes[$name] = $this->generatePane($type, $defaults); } if (empty($this->_recurPaymentProcessors)) { $buildRecurBlock = FALSE; } if ($buildRecurBlock) { CRM_Contribute_Form_Contribution_Main::buildRecur($this); $this->setDefaults(array('is_recur' => 0)); } $this->assign('buildRecurBlock', $buildRecurBlock); $qfKey = $this->controller->_key; $this->assign('qfKey', $qfKey); $this->assign('billingPanes', $billingPanes); $this->assign('allPanes', $allPanes); $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this); if ($this->_formType) { $this->assign('formType', $this->_formType); return; } $this->applyFilter('__ALL__', 'trim'); if ($this->_action & CRM_Core_Action::DELETE) { $this->addButtons(array( array( 'type' => 'next', 'name' => ts('Delete'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => TRUE, ), array( 'type' => 'cancel', 'name' => ts('Cancel'), ), ) ); return; } //need to assign custom data type and subtype to the template $this->assign('customDataType', 'Contribution'); $this->assign('customDataSubType', $this->_contributionType); $this->assign('entityID', $this->_id); if ($this->_context == 'standalone') { $this->addEntityRef('contact_id', ts('Contact'), array( 'create' => TRUE, 'api' => array('extra' => array('email')), ), TRUE); } $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution'); $financialType = $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(), TRUE, array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );") ); $paymentInstrument = FALSE; if (!$this->_mode) { $paymentInstrument = $this->add('select', 'payment_instrument_id', ts('Paid By'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);") ); } $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']); //add receipt for offline contribution $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?')); $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails); $status = CRM_Contribute_PseudoConstant::contributionStatus(); // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169) $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); if ($this->_ppID) { foreach (array( 'Cancelled', 'Failed', 'In Progress', ) as $suppress) { unset($status[CRM_Utils_Array::key($suppress, $statusName)]); } } elseif ((!$this->_ppID && $this->_id) || !$this->_id) { $suppressFlag = FALSE; if ($this->_id) { $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id); if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) { $suppressFlag = TRUE; } } if (!$suppressFlag) { foreach (array( 'Overdue', 'In Progress', ) as $suppress) { unset($status[CRM_Utils_Array::key($suppress, $statusName)]); } } else { unset($status[CRM_Utils_Array::key('Overdue', $statusName)]); } } if ($this->_id) { $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id'); $name = CRM_Utils_Array::value($contributionStatus, $statusName); switch ($name) { case 'Completed': case 'Cancelled': case 'Refunded': unset($status[CRM_Utils_Array::key('In Progress', $statusName)]); unset($status[CRM_Utils_Array::key('Pending', $statusName)]); unset($status[CRM_Utils_Array::key('Failed', $statusName)]); break; case 'Pending': case 'In Progress': unset($status[CRM_Utils_Array::key('Refunded', $statusName)]); break; case 'Failed': foreach (array( 'Pending', 'Refunded', 'Completed', 'In Progress', 'Cancelled', ) as $suppress) { unset($status[CRM_Utils_Array::key($suppress, $statusName)]); } break; } } else { unset($status[CRM_Utils_Array::key('Refunded', $statusName)]); } $this->add('select', 'contribution_status_id', ts('Contribution Status'), $status, FALSE ); // add various dates $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime')); if ($this->_online) { $this->assign('hideCalender', TRUE); } $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']); $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime')); $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime')); $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']); $recurJs = NULL; if ($buildRecurBlock) { $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;"); } $element = $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, NULL, $recurJs ); if ($this->_online) { $element->freeze(); } $totalAmount = NULL; if (empty($this->_lineItems)) { $buildPriceSet = FALSE; $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute'); if (!empty($priceSets) && !$this->_ppID) { $buildPriceSet = TRUE; } // don't allow price set for contribution if it is related to participant, or if it is a pledge payment // and if we already have line items for that participant. CRM-5095 if ($buildPriceSet && $this->_id) { $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id); $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_id, 'id', 'contribution_id' ); if ($pledgePaymentId) { $buildPriceSet = FALSE; } if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) { $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID); if (!CRM_Utils_System::isNull($participantLI)) { $buildPriceSet = FALSE; } } } $hasPriceSets = FALSE; if ($buildPriceSet) { $hasPriceSets = TRUE; $element = $this->add('select', 'price_set_id', ts('Choose price set'), array( '' => ts('Choose price set'), ) + $priceSets, NULL, array('onchange' => "buildAmount( this.value );") ); if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) { $element->freeze(); } } $this->assign('hasPriceSets', $hasPriceSets); $currencyFreeze = FALSE; if (!($this->_action & CRM_Core_Action::UPDATE)) { if ($this->_online || $this->_ppID) { $attributes['total_amount'] = array_merge($attributes['total_amount'], array( 'READONLY' => TRUE, 'style' => "background-color:#EBECE4", )); $optionTypes = array( '1' => ts('Adjust Pledge Payment Schedule?'), '2' => ts('Adjust Total Pledge Amount?'), ); $this->addRadio('option_type', NULL, $optionTypes, array(), '<br/>' ); $currencyFreeze = TRUE; } } $totalAmount = $this->addMoney('total_amount', ts('Total Amount'), ($hasPriceSets) ? FALSE : TRUE, $attributes['total_amount'], TRUE, 'currency', NULL, $currencyFreeze ); } $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes)); // CRM-7362 --add campaigns. CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values)); CRM_Contribute_Form_SoftCredit::buildQuickForm($this); $js = NULL; if (!$this->_mode) { $js = array('onclick' => "return verify( );"); } $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mailing_backend' ); $this->assign('outBound_option', $mailingInfo['outBound_option']); $this->addButtons(array( array( 'type' => 'upload', 'name' => ts('Save'), 'js' => $js, 'isDefault' => TRUE, ), array( 'type' => 'upload', 'name' => ts('Save and New'), 'js' => $js, 'subName' => 'new', ), array( 'type' => 'cancel', 'name' => ts('Cancel'), ), ) ); // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type, // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail if ($this->_id && $this->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) { if ($totalAmount) { $totalAmount->freeze(); } $checkNumber->freeze(); $paymentInstrument->freeze(); $trxnId->freeze(); $financialType->freeze(); } // if contribution is related to membership or participant freeze Financial Type, Amount if ($this->_id && isset($this->_values['tax_amount'])) { $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id); if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) { if ($totalAmount) { $totalAmount->freeze(); } $financialType->freeze(); $this->assign('freezeFinancialType', TRUE); } } if ($this->_action & CRM_Core_Action::VIEW) { $this->freeze(); } } /** * Global form rule. * * @param array $fields * The input form values. * @param array $files * The uploaded files if any. * @param $self * * @return bool|array * true if no errors, else array of errors */ public static function formRule($fields, $files, $self) { $errors = array(); // Check for Credit Card Contribution. if ($self->_mode) { if (empty($fields['payment_processor_id'])) { $errors['payment_processor_id'] = ts('Payment Processor is a required field.'); } else { // validate payment instrument (e.g. credit card number) CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self); } } // Do the amount validations. if (empty($fields['total_amount']) && empty($self->_lineItems)) { if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) { CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors); } } $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self); if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) || !empty($fields['fee_amount']))) { $sum = CRM_Utils_Rule::cleanMoney($fields['net_amount']) + CRM_Utils_Rule::cleanMoney($fields['fee_amount']); // For taxable contribution we need to deduct taxable amount from // (net amount + fee amount) before comparing it with total amount if (!empty($self->_values['tax_amount'])) { $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($self->_id); if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) ) { $sum = CRM_Utils_Money::format($sum - $self->_values['tax_amount'], NULL, '%a'); } } if (CRM_Utils_Rule::cleanMoney($fields['total_amount']) != $sum) { $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount'); } } // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow if ($self->_id && $self->_values['contribution_status_id'] != $fields['contribution_status_id']) { CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors); } // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type if ($self->_id && $self->_values['financial_type_id'] != $fields['financial_type_id']) { CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors); } //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) { $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType; } // $trxn_id must be unique CRM-13919 if (!empty($fields['trxn_id'])) { $queryParams = array(1 => array($fields['trxn_id'], 'String')); $query = 'select count(*) from civicrm_contribution where trxn_id = %1'; if ($self->_id) { $queryParams[2] = array((int) $self->_id, 'Integer'); $query .= ' and id !=%2'; } $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams); if ($tCnt) { $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id'])); } } $errors = array_merge($errors, $softErrors); return $errors; } /** * Process the form submission. */ public function postProcess() { $sendReceipt = $pId = $contribution = $isRelatedId = FALSE; $softParams = $softIDs = array(); if ($this->_action & CRM_Core_Action::DELETE) { CRM_Contribute_BAO_Contribution::deleteContribution($this->_id); CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute" )); return; } // Get the submitted form values. $submittedValues = $this->controller->exportValues($this->_name); if (!empty($submittedValues['price_set_id']) && $this->_action & CRM_Core_Action::UPDATE) { $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution'); $lineID = key($line); $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id'); $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config'); if ($quickConfig) { CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution'); } } // Process price set and get total amount and line items. $lineItem = array(); $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues); if (empty($priceSetId) && !$this->_id) { $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name'); $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId)); $fieldID = key($this->_priceSet['fields']); $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']); $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount']; $submittedValues['price_' . $fieldID] = 1; } if ($priceSetId) { CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]); // Unset tax amount for offline 'is_quick_config' contribution. if ($this->_priceSet['is_quick_config'] && !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates()) ) { unset($submittedValues['tax_amount']); } $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues); } if ($this->_id) { if ($this->_compId) { if ($this->_context == 'participant') { $pId = $this->_compId; } elseif ($this->_context == 'membership') { $isRelatedId = TRUE; } else { $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id'); } } else { $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id); if (array_key_exists('membership', $contributionDetails)) { $isRelatedId = TRUE; } elseif (array_key_exists('participant', $contributionDetails)) { $pId = $contributionDetails['participant']; } } } if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) { // CRM-10117 update the line items for participants. if ($pId) { $entityTable = 'participant'; $entityID = $pId; $isRelatedId = FALSE; $participantParams = array( 'fee_amount' => $submittedValues['total_amount'], 'id' => $entityID, ); CRM_Event_BAO_Participant::add($participantParams); if (empty($this->_lineItems)) { $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1); } } else { $entityTable = 'contribution'; $entityID = $this->_id; } $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId); foreach (array_keys($lineItems) as $id) { $lineItems[$id]['id'] = $id; } $itemId = key($lineItems); if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) { $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id'); } if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) { $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues)); // Update line total and total amount with tax on edit. $financialItemsId = CRM_Core_PseudoConstant::getTaxRates(); if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) { $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']]; } else { $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = ""; $submittedValues['tax_amount'] = 'null'; } if ($lineItems[$itemId]['tax_rate']) { $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total']; $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount']; $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount']; } } // CRM-10117 update the line items for participants. if (!empty($lineItems[$itemId]['price_field_id'])) { $lineItem[$this->_priceSetId] = $lineItems; } } $isQuickConfig = 0; if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) { $isQuickConfig = 1; } //CRM-11529 for quick config back office transactions //when financial_type_id is passed in form, update the //line items with the financial type selected in form if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem) ) { foreach ($lineItem[$this->_priceSetId] as &$values) { $values['financial_type_id'] = $submittedValues['financial_type_id']; } } if (!isset($submittedValues['total_amount'])) { $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values); } $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE); if (!empty($submittedValues['pcp_made_through_id'])) { $pcp = array(); $fields = array( 'pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note', ); foreach ($fields as $f) { $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues); } } $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id'])); if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) { //Delete existing soft credit records if soft credit list is empty on update CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id)); } else { //build soft credit params foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) { if ($val && $submittedValues['soft_credit_amount'][$key]) { $softParams[$key]['contact_id'] = $val; $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($submittedValues['soft_credit_amount'][$key]); $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key]; if (!empty($submittedValues['soft_credit_id'][$key])) { $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key]; } } } } // set the contact, when contact is selected if (!empty($submittedValues['contact_id'])) { $this->_contactID = $submittedValues['contact_id']; } // Credit Card Contribution. if ($this->_mode) { $this->processCreditCard($submittedValues, $lineItem); } else { // Offline Contribution. $submittedValues = $this->unsetCreditCardFields($submittedValues); // get the required field value only. $formValues = $submittedValues; $params = $ids = array(); $params['contact_id'] = $this->_contactID; $params['currency'] = $this->getCurrency($submittedValues); $fields = array( 'financial_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number', ); foreach ($fields as $f) { $params[$f] = CRM_Utils_Array::value($f, $formValues); } if (!empty($pcp)) { $params['pcp'] = $pcp; } if (!empty($softParams)) { $params['soft_credit'] = $softParams; $params['soft_credit_ids'] = $softIDs; } // CRM-5740 if priceset is used, no need to cleanup money. if ($priceSetId) { $params['skipCleanMoney'] = 1; } $dates = array( 'receive_date', 'receipt_date', 'cancel_date', ); foreach ($dates as $d) { $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE); } if (!empty($formValues['is_email_receipt'])) { $params['receipt_date'] = date("Y-m-d"); } if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name') || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name') ) { if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) { $params['cancel_date'] = date('Y-m-d'); } } else { $params['cancel_date'] = $params['cancel_reason'] = 'null'; } // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) { $params['is_pay_later'] = 1; } elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) { $params['is_pay_later'] = 0; } $ids['contribution'] = $params['id'] = $this->_id; // Add Additional common information to formatted params. CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this); if ($pId) { $params['contribution_mode'] = 'participant'; $params['participant_id'] = $pId; $params['skipLineItem'] = 1; } elseif ($isRelatedId) { $params['contribution_mode'] = 'membership'; } $params['line_item'] = $lineItem; $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor); if (isset($submittedValues['tax_amount'])) { $params['tax_amount'] = $submittedValues['tax_amount']; } //create contribution. if ($isQuickConfig) { $params['is_quick_config'] = 1; } // CRM-11956 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] - // if non_deductible_amount does NOT exist - then calculate it depending on: // $ContributionType->is_deductible and whether there is a product (premium). if (empty($params['non_deductible_amount'])) { $contributionType = new CRM_Financial_DAO_FinancialType(); $contributionType->id = $params['financial_type_id']; if (!$contributionType->find(TRUE)) { CRM_Core_Error::fatal('Could not find a system table'); } if ($contributionType->is_deductible) { if (isset($formValues['product_name'][0])) { $selectProduct = $formValues['product_name'][0]; } // if there is a product - compare the value to the contribution amount if (isset($selectProduct)) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $selectProduct; $productDAO->find(TRUE); // product value exceeds contribution amount if ($params['total_amount'] < $productDAO->price) { $params['non_deductible_amount'] = $params['total_amount']; } // product value does NOT exceed contribution amount else { $params['non_deductible_amount'] = $productDAO->price; } } // contribution is deductible - but there is no product else { $params['non_deductible_amount'] = '0.00'; } } // contribution is NOT deductible else { $params['non_deductible_amount'] = $params['total_amount']; } } $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids); // process associated membership / participant, CRM-4395 $relatedComponentStatusMsg = NULL; if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) { $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values ), $contribution->receive_date ); } //process note if ($contribution->id && isset($formValues['note'])) { CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID); } //process premium if ($contribution->id && isset($formValues['product_name'][0])) { CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id, $this->_premiumID, $this->_options ); } // assign tax calculation for contribution receipts $taxRate = array(); $getTaxDetails = FALSE; $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); if ($invoicing) { if ($this->_action & CRM_Core_Action::ADD) { $line = $lineItem; } elseif ($this->_action & CRM_Core_Action::UPDATE) { $line = $this->_lineItems; } foreach ($line as $key => $value) { foreach ($value as $v) { if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) { $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v); } else { if (isset($v['tax_rate'])) { $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v); $getTaxDetails = TRUE; } } } } } if ($invoicing) { if ($this->_action & CRM_Core_Action::UPDATE) { if (isset($submittedValues['tax_amount'])) { $totalTaxAmount = $submittedValues['tax_amount']; } else { $totalTaxAmount = $this->_values['tax_amount']; } $this->assign('totalTaxAmount', $totalTaxAmount); $this->assign('dataArray', $taxRate); } else { if (!empty($submittedValues['price_set_id'])) { $this->assign('totalTaxAmount', $submittedValues['tax_amount']); $this->assign('getTaxDetails', $getTaxDetails); $this->assign('dataArray', $taxRate); $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings)); } else { $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues)); } } } //send receipt mail. if ($contribution->id && !empty($formValues['is_email_receipt'])) { $formValues['contact_id'] = $this->_contactID; $formValues['contribution_id'] = $contribution->id; $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id); // to get 'from email id' for send receipt $this->fromEmailId = $formValues['from_email_address']; $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues); } $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id' ); //update pledge payment status. if ((($this->_ppID && $contribution->id) && $this->_action & CRM_Core_Action::ADD) || (($pledgePaymentId) && $this->_action & CRM_Core_Action::UPDATE) ) { if ($this->_ppID) { //store contribution id in payment record. CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id); } else { $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id' ); $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'pledge_id', 'contribution_id' ); } $adjustTotalAmount = FALSE; if (CRM_Utils_Array::value('option_type', $formValues) == 2) { $adjustTotalAmount = TRUE; } $updatePledgePaymentStatus = FALSE; //do only if either the status or the amount has changed if ($this->_action & CRM_Core_Action::ADD) { $updatePledgePaymentStatus = TRUE; } elseif ($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $formValues['contribution_status_id']) || ($this->_defaults['total_amount'] != $formValues['total_amount'])) ) { $updatePledgePaymentStatus = TRUE; } if ($updatePledgePaymentStatus) { CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount, $adjustTotalAmount ); } } $statusMsg = ts('The contribution record has been saved.'); if (!empty($formValues['is_email_receipt']) && $sendReceipt) { $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.'); } if ($relatedComponentStatusMsg) { $statusMsg .= ' ' . $relatedComponentStatusMsg; } CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success'); //Offline Contribution ends. } $session = CRM_Core_Session::singleton(); $buttonName = $this->controller->getButtonName(); if ($this->_context == 'standalone') { if ($buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add', 'reset=1&action=add&context=standalone' )); } else { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute" )); } } elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}" )); } elseif ($buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}" )); } //store contribution ID if not yet set (on create) if (empty($this->_id) && !empty($contribution->id)) { $this->_id = $contribution->id; } } /** * Process credit card payment. * * @param array $submittedValues * @param array $lineItem * * @throws CRM_Core_Exception */ protected function processCreditCard($submittedValues, $lineItem) { $sendReceipt = $contribution = FALSE; $unsetParams = array( 'trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason', ); foreach ($unsetParams as $key) { if (isset($submittedValues[$key])) { unset($submittedValues[$key]); } } $isTest = ($this->_mode == 'test') ? 1 : 0; // CRM-12680 set $_lineItem if its not set if (empty($this->_lineItem) && !empty($lineItem)) { $this->_lineItem = $lineItem; } //Get the require fields value only. $params = $this->_params = $submittedValues; $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode ); // Get the payment processor id as per mode. $this->_params['payment_processor'] = $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id']; $now = date('YmdHis'); $fields = array(); // we need to retrieve email address if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) { list($this->userDisplayName, $this->userEmail ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID); $this->assign('displayName', $this->userDisplayName); } // Set email for primary location. $fields['email-Primary'] = 1; $params['email-Primary'] = $this->userEmail; // now set the values for the billing location. foreach (array_keys($this->_fields) as $name) { $fields[$name] = 1; } // also add location name to the array $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params); $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]); $fields["address_name-{$this->_bltID}"] = 1; $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type' ); $nameFields = array('first_name', 'middle_name', 'last_name'); foreach ($nameFields as $name) { $fields[$name] = 1; if (array_key_exists("billing_$name", $params)) { $params[$name] = $params["billing_{$name}"]; $params['preserveDBName'] = TRUE; } } if (!empty($params['source'])) { unset($params['source']); } $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, NULL, NULL, $ctype ); // add all the additional payment params we need if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) { $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]); } if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) { $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]); } $legacyCreditCardExpiryCheck = FALSE; if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD && !isset($this->_paymentFields)) { $legacyCreditCardExpiryCheck = TRUE; } if ($legacyCreditCardExpiryCheck || in_array('credit_card_exp_date', array_keys($this->_paymentFields))) { $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params); $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params); } $this->_params['ip_address'] = CRM_Utils_System::ipAddress(); $this->_params['amount'] = $this->_params['total_amount']; $this->_params['amount_level'] = 0; $this->_params['description'] = ts('Office Credit Card contribution'); $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, CRM_Core_Config::singleton()->defaultCurrency ); $this->_params['payment_action'] = 'Sale'; if (!empty($this->_params['receive_date'])) { $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']); } if (!empty($params['soft_credit_to'])) { $this->_params['soft_credit_to'] = $params['soft_credit_to']; $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id']; } $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params); $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params); $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params); //Add common data to formatted params CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this); if (empty($this->_params['invoice_id'])) { $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE)); } else { $this->_params['invoiceID'] = $this->_params['invoice_id']; } // At this point we've created a contact and stored its address etc // all the payment processors expect the name and address to be in the // so we copy stuff over to first_name etc. $paymentParams = $this->_params; $paymentParams['contactID'] = $this->_contactID; CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE); $contributionType = new CRM_Financial_DAO_FinancialType(); $contributionType->id = $params['financial_type_id']; // Add some financial type details to the params list // if folks need to use it. $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name; $paymentParams['contributionPageID'] = NULL; if (!empty($this->_params['is_email_receipt'])) { $paymentParams['email'] = $this->userEmail; $paymentParams['is_email_receipt'] = 1; } else { $paymentParams['is_email_receipt'] = 0; $this->_params['is_email_receipt'] = 0; } if (!empty($this->_params['receive_date'])) { $paymentParams['receive_date'] = $this->_params['receive_date']; } // For recurring contribution, create Contribution Record first. // Contribution ID, Recurring ID and Contact ID needed // When we get a callback from the payment processor, CRM-7115 if (!empty($paymentParams['is_recur'])) { $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, NULL, $this->_contactID, $contributionType, TRUE, FALSE, $isTest, $this->_lineItem ); $paymentParams['contributionID'] = $contribution->id; $paymentParams['contributionTypeID'] = $contribution->financial_type_id; $paymentParams['contributionPageID'] = $contribution->contribution_page_id; $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id; } $result = array(); if ($paymentParams['amount'] > 0.0) { // force a re-get of the payment processor in case the form changed it, CRM-7179 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE); try { $result = $payment->doPayment($paymentParams, 'contribute'); } catch (CRM_Core_Exception $e) { $message = ts("Payment Processor Error message") . $e->getMessage(); $this->cleanupDBAfterPaymentFailure($paymentParams, $message); // Set the contribution mode. $urlParams = "action=add&cid={$this->_contactID}"; if ($this->_mode) { $urlParams .= "&mode={$this->_mode}"; } if (!empty($this->_ppID)) { $urlParams .= "&context=pledge&ppid={$this->_ppID}"; } CRM_Core_Error::statusBounce($message, $urlParams, ts('Payment Processor Error')); } } $this->_params = array_merge($this->_params, $result); $this->_params['receive_date'] = $now; if (!empty($this->_params['is_email_receipt'])) { $this->_params['receipt_date'] = $now; } else { $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'], $params['receipt_date_time'], TRUE ); } $this->set('params', $this->_params); $this->assign('trxn_id', $result['trxn_id']); $this->assign('receive_date', $this->_params['receive_date']); // Result has all the stuff we need // lets archive it to a financial transaction if ($contributionType->is_deductible) { $this->assign('is_deductible', TRUE); $this->set('is_deductible', TRUE); } // Set source if not set if (empty($this->_params['source'])) { $userID = CRM_Core_Session::singleton()->get('userID'); $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name' ); $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName)); } // Build custom data getFields array $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, CRM_Utils_Array::value('financial_type_id', $params) ); $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE) ); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution' ); if (empty($paymentParams['is_recur'])) { $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, FALSE, $isTest, $this->_lineItem ); } // Send receipt mail. if ($contribution->id && !empty($this->_params['is_email_receipt'])) { $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result); $this->_params['contact_id'] = $this->_contactID; $this->_params['contribution_id'] = $contribution->id; $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE); } //process the note if ($contribution->id && isset($params['note'])) { CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL); } //process premium if ($contribution->id && isset($params['product_name'][0])) { CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options); } //update pledge payment status. if ($this->_ppID && $contribution->id) { // Store contribution id in payment record. CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id); CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount ); } if ($contribution->id) { $statusMsg = ts('The contribution record has been processed.'); if (!empty($this->_params['is_email_receipt']) && $sendReceipt) { $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.'); } CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success'); } } /** * Clean up DB after payment fails. * * This function removes related DB entries. Note that it has been agreed in principle, * but not implemented, that contributions should be retained as 'Failed' rather than * deleted. * * @todo it doesn't clean up line items. * * @param array $paymentParams * @param string $message */ public function cleanupDBAfterPaymentFailure($paymentParams, $message) { // Make sure to cleanup db for recurring case. if (!empty($paymentParams['contributionID'])) { CRM_Core_Error::debug_log_message($message . "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}"); CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']); } if (!empty($paymentParams['contributionRecurID'])) { CRM_Core_Error::debug_log_message($message . "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}"); CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']); } } /** * Generate the data to construct a snippet based pane. * * This form also assigns the showAdditionalInfo var based on historical code. * This appears to mean 'there is a pane to show'. * * @param string $type * Type of Pane - this is generally used to determine the function name used to build it * - e.g CreditCard, AdditionalDetail * @param array $defaults * * @return array * We aim to further refactor & simplify this but currently * - the panes array * - should additional info be shown? */ protected function generatePane($type, $defaults) { $urlParams = "snippet=4&formType={$type}"; if ($this->_mode) { $urlParams .= "&mode={$this->_mode}"; } $open = 'false'; if ($type == 'CreditCard' || $type == 'DirectDebit' ) { $open = 'true'; } $pane = array( 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams), 'open' => $open, 'id' => $type, ); // See if we need to include this paneName in the current form. if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) || CRM_Utils_Array::value("hidden_{$type}", $defaults) ) { $this->assign('showAdditionalInfo', TRUE); $pane['open'] = 'true'; } if ($type == 'CreditCard' || $type == 'DirectDebit') { // @todo would be good to align tpl name with form name... // @todo document why this hidden variable is required. $this->add('hidden', 'hidden_' . $type, 1); return $pane; } else { $additionalInfoFormFunction = 'build' . $type; CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this); return $pane; } } }
JMAConsulting/campaigntool
sites/all/modules/civicrm/CRM/Contribute/Form/Contribution.php
PHP
gpl-2.0
68,192
<?php /** * File containing the CountryList class * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.07.0 */ namespace eZ\Publish\Core\REST\Server\Values; use eZ\Publish\Core\REST\Common\Value as RestValue; /** * Country list view model */ class CountryList extends RestValue { /** * @var \eZ\Publish\API\Repository\Values\ContentType\Countries[] */ public $countries; /** * Construct * */ public function __construct( array $countries ) { $this->countries = $countries; } }
tonvinh/ez
vendor/ezsystems/ezpublish-kernel/eZ/Publish/Core/REST/Server/Values/CountryList.php
PHP
gpl-2.0
681
#include <lib/dvb/idvb.h> #include <dvbsi++/descriptor_tag.h> #include <dvbsi++/service_descriptor.h> #include <dvbsi++/satellite_delivery_system_descriptor.h> #include <dvbsi++/terrestrial_delivery_system_descriptor.h> #include <dvbsi++/cable_delivery_system_descriptor.h> #include <dvbsi++/ca_identifier_descriptor.h> #include <dvbsi++/registration_descriptor.h> #include <lib/dvb/specs.h> #include <lib/dvb/esection.h> #include <lib/dvb/scan.h> #include <lib/dvb/frontend.h> #include <lib/base/eenv.h> #include <lib/base/eerror.h> #include <lib/base/estring.h> #include <lib/dvb/dvb.h> #include <lib/dvb/db.h> #include <lib/python/python.h> #include <errno.h> #define SCAN_eDebug(x...) do { if (m_scan_debug) eDebug(x); } while(0) #define SCAN_eDebugNoNewLine(x...) do { if (m_scan_debug) eDebugNoNewLine(x); } while(0) DEFINE_REF(eDVBScan); eDVBScan::eDVBScan(iDVBChannel *channel, bool usePAT, bool debug) :m_channel(channel), m_channel_state(iDVBChannel::state_idle) ,m_ready(0), m_ready_all(usePAT ? (readySDT|readyPAT) : readySDT) ,m_pmt_running(false), m_abort_current_pmt(false), m_flags(0) ,m_usePAT(usePAT), m_scan_debug(debug), m_show_add_tsid_onid_check_failed_msg(true) { if (m_channel->getDemux(m_demux)) SCAN_eDebug("scan: failed to allocate demux!"); m_channel->connectStateChange(slot(*this, &eDVBScan::stateChange), m_stateChanged_connection); std::string filename = eEnv::resolve("${sysconfdir}/scan_tp_valid_check.py"); FILE *f = fopen(filename.c_str(), "r"); if (f) { char code[16384]; size_t rd = fread(code, 1, 16383, f); if (rd) { code[rd]=0; m_additional_tsid_onid_check_func = Py_CompileString(code, filename.c_str(), Py_file_input); } fclose(f); } } eDVBScan::~eDVBScan() { if (m_additional_tsid_onid_check_func) Py_DECREF(m_additional_tsid_onid_check_func); } int eDVBScan::isValidONIDTSID(int orbital_position, eOriginalNetworkID onid, eTransportStreamID tsid) { /* * Assume cable and terrestrial ONIDs/TSIDs are always valid, * don't check them against the satellite blacklist. */ if (orbital_position == 0xFFFF || orbital_position == 0xEEEE) return 1; int ret; switch (onid.get()) { case 0: case 0x1111: ret=0; break; case 0x13E: // workaround for 11258H and 11470V on hotbird with same ONID/TSID (0x13E/0x578) ret = orbital_position != 130 || tsid != 0x578; break; case 1: ret = orbital_position == 192; break; case 0x00B1: ret = tsid != 0x00B0; break; case 0x00eb: ret = tsid != 0x4321; break; case 0x0002: ret = abs(orbital_position-282) < 6 && tsid != 2019; // 12070H and 10936V have same tsid/onid.. but even the same services are provided break; case 0x2000: ret = tsid != 0x1000; break; case 0x5E: // Sirius 4.8E 12322V and 12226H ret = abs(orbital_position-48) < 3 && tsid != 1; break; case 10100: // Eutelsat W7 36.0E 11644V and 11652V ret = orbital_position != 360 || tsid != 10187; break; case 42: // Tuerksat 42.0E ret = orbital_position != 420 || ( tsid != 8 && // 11830V 12729V tsid != 5 && // 12679V 12685H tsid != 2 && // 11096V 12015H tsid != 55); // 11996V 11716V break; case 100: // Intelsat 10 68.5E 3808V 3796V 4012V, Amos 4.0W 10723V 11571H ret = (orbital_position != 685 && orbital_position != 3560) || tsid != 1; break; case 70: // Thor 0.8W 11862H 12341V ret = abs(orbital_position-3592) < 3 && tsid != 46; break; case 32: // NSS 806 (40.5W) 4059R, 3774L ret = orbital_position != 3195 || tsid != 21; break; default: ret = onid.get() < 0xFF00; break; } if (ret && m_additional_tsid_onid_check_func) { bool failed = true; ePyObject dict = PyDict_New(); extern void PutToDict(ePyObject &, const char *, long); PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins()); PutToDict(dict, "orbpos", orbital_position); PutToDict(dict, "tsid", tsid.get()); PutToDict(dict, "onid", onid.get()); ePyObject r = PyEval_EvalCode((PyCodeObject*)(PyObject*)m_additional_tsid_onid_check_func, dict, dict); if (r) { ePyObject o = PyDict_GetItemString(dict, "ret"); if (o) { if (PyInt_Check(o)) { ret = PyInt_AsLong(o); failed = false; } } Py_DECREF(r); } if (failed && m_show_add_tsid_onid_check_failed_msg) { eDebug("execing /etc/enigma2/scan_tp_valid_check failed!\n" "usable global variables in scan_tp_valid_check.py are 'orbpos', 'tsid', 'onid'\n" "the return value must be stored in a global var named 'ret'"); m_show_add_tsid_onid_check_failed_msg=false; } Py_DECREF(dict); } return ret; } eDVBNamespace eDVBScan::buildNamespace(eOriginalNetworkID onid, eTransportStreamID tsid, unsigned long hash) { // on valid ONIDs, ignore frequency ("sub network") part if (isValidONIDTSID((hash >> 16) & 0xFFFF, onid, tsid)) hash &= ~0xFFFF; return eDVBNamespace(hash); } void eDVBScan::stateChange(iDVBChannel *ch) { int state; if (ch->getState(state)) return; if (m_channel_state == state) return; if (state == iDVBChannel::state_ok) { startFilter(); m_channel_state = state; } else if (state == iDVBChannel::state_failed) { m_ch_unavailable.push_back(m_ch_current); nextChannel(); } /* unavailable will timeout, anyway. */ } RESULT eDVBScan::nextChannel() { ePtr<iDVBFrontend> fe; m_SDT = 0; m_PAT = 0; m_BAT = 0; m_NIT = 0, m_PMT = 0; m_ready = 0; m_pat_tsid = eTransportStreamID(); /* check what we need */ m_ready_all = readySDT; if (m_flags & scanNetworkSearch) m_ready_all |= readyNIT; if (m_flags & scanSearchBAT) m_ready_all |= readyBAT; if (m_usePAT) m_ready_all |= readyPAT; if (m_ch_toScan.empty()) { SCAN_eDebug("no channels left to scan."); SCAN_eDebug("%zd channels scanned, %zd were unavailable.", m_ch_scanned.size(), m_ch_unavailable.size()); SCAN_eDebug("%zd channels in database.", m_new_channels.size()); m_event(evtFinish); return -ENOENT; } m_ch_current = m_ch_toScan.front(); m_ch_toScan.pop_front(); if (m_channel->getFrontend(fe)) { m_event(evtFail); return -ENOTSUP; } m_chid_current = eDVBChannelID(); m_channel_state = iDVBChannel::state_idle; if (fe->tune(*m_ch_current)) return nextChannel(); m_event(evtUpdate); return 0; } RESULT eDVBScan::startFilter() { bool startSDT=true; ASSERT(m_demux); /* only start required filters filter */ if (m_ready_all & readyPAT) startSDT = m_ready & readyPAT; // m_ch_current is not set, when eDVBScan is just used for a SDT update if (!m_ch_current) { unsigned int channelFlags; m_channel->getCurrentFrontendParameters(m_ch_current); m_ch_current->getFlags(channelFlags); if (channelFlags & iDVBFrontendParameters::flagOnlyFree) m_flags |= scanOnlyFree; } m_SDT = 0; if (startSDT && (m_ready_all & readySDT)) { m_SDT = new eTable<ServiceDescriptionSection>; int tsid=-1; if (m_ready & readyPAT && m_ready & validPAT) { std::vector<ProgramAssociationSection*>::const_iterator i = m_PAT->getSections().begin(); ASSERT(i != m_PAT->getSections().end()); tsid = (*i)->getTableIdExtension(); // in PAT this is the transport stream id m_pat_tsid = eTransportStreamID(tsid); for (; i != m_PAT->getSections().end(); ++i) { const ProgramAssociationSection &pat = **i; ProgramAssociationConstIterator program = pat.getPrograms()->begin(); for (; program != pat.getPrograms()->end(); ++program) m_pmts_to_read.insert(std::pair<unsigned short, service>((*program)->getProgramNumber(), service((*program)->getProgramMapPid()))); } m_PMT = new eTable<ProgramMapSection>; CONNECT(m_PMT->tableReady, eDVBScan::PMTready); PMTready(-2); // KabelBW HACK ... on 618Mhz and 626Mhz the transport stream id in PAT and SDT is different { int type; m_ch_current->getSystem(type); if (type == iDVBFrontend::feCable) { eDVBFrontendParametersCable parm; m_ch_current->getDVBC(parm); if ((tsid == 0x00d7 && abs(parm.frequency-618000) < 2000) || (tsid == 0x00d8 && abs(parm.frequency-626000) < 2000)) tsid = -1; } } } if (tsid == -1) { if (m_SDT->start(m_demux, eDVBSDTSpec())) return -1; } else if (m_SDT->start(m_demux, eDVBSDTSpec(tsid, true))) return -1; CONNECT(m_SDT->tableReady, eDVBScan::SDTready); } if (!(m_ready & readyPAT)) { m_PAT = 0; if (m_ready_all & readyPAT) { m_PAT = new eTable<ProgramAssociationSection>; if (m_PAT->start(m_demux, eDVBPATSpec(4000))) return -1; CONNECT(m_PAT->tableReady, eDVBScan::PATready); } m_NIT = 0; if (m_ready_all & readyNIT) { m_NIT = new eTable<NetworkInformationSection>; if (m_NIT->start(m_demux, eDVBNITSpec(m_networkid))) return -1; CONNECT(m_NIT->tableReady, eDVBScan::NITready); } m_BAT = 0; if (m_ready_all & readyBAT) { m_BAT = new eTable<BouquetAssociationSection>; if (m_BAT->start(m_demux, eDVBBATSpec())) return -1; CONNECT(m_BAT->tableReady, eDVBScan::BATready); } } return 0; } void eDVBScan::SDTready(int err) { SCAN_eDebug("got sdt %d", err); m_ready |= readySDT; if (!err) m_ready |= validSDT; channelDone(); } void eDVBScan::NITready(int err) { SCAN_eDebug("got nit, err %d", err); m_ready |= readyNIT; if (!err) m_ready |= validNIT; channelDone(); } void eDVBScan::BATready(int err) { SCAN_eDebug("got bat"); m_ready |= readyBAT; if (!err) m_ready |= validBAT; channelDone(); } void eDVBScan::PATready(int err) { SCAN_eDebug("got pat"); m_ready |= readyPAT; if (!err) m_ready |= validPAT; startFilter(); // for starting the SDT filter } void eDVBScan::PMTready(int err) { SCAN_eDebug("got pmt %d", err); if (!err) { bool scrambled = false; bool have_audio = false; bool have_video = false; unsigned short pcrpid = 0xFFFF; std::vector<ProgramMapSection*>::const_iterator i; for (i = m_PMT->getSections().begin(); i != m_PMT->getSections().end(); ++i) { const ProgramMapSection &pmt = **i; if (pcrpid == 0xFFFF) pcrpid = pmt.getPcrPid(); else SCAN_eDebug("already have a pcrpid %04x %04x", pcrpid, pmt.getPcrPid()); ElementaryStreamInfoConstIterator es; for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es) { int isaudio = 0, isvideo = 0, is_scrambled = 0, forced_audio = 0, forced_video = 0; switch ((*es)->getType()) { case 0x1b: // AVC Video Stream (MPEG4 H264) case 0x10: // MPEG 4 Part 2 case 0x01: // MPEG 1 video case 0x02: // MPEG 2 video isvideo = 1; forced_video = 1; //break; fall through !!! case 0x03: // MPEG 1 audio case 0x04: // MPEG 2 audio case 0x0f: // MPEG 2 AAC case 0x11: // MPEG 4 AAC if (!isvideo) { forced_audio = 1; isaudio = 1; } case 0x06: // PES Private case 0x81: // user private case 0xEA: // TS_PSI_ST_SMPTE_VC1 for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin(); desc != (*es)->getDescriptors()->end(); ++desc) { uint8_t tag = (*desc)->getTag(); /* PES private can contain AC-3, DTS or lots of other stuff. check descriptors to get the exakt type. */ if (!forced_video && !forced_audio) { switch (tag) { case 0x1C: // TS_PSI_DT_MPEG4_Audio case 0x2B: // TS_PSI_DT_MPEG2_AAC case AAC_DESCRIPTOR: case AC3_DESCRIPTOR: case DTS_DESCRIPTOR: case AUDIO_STREAM_DESCRIPTOR: isaudio = 1; break; case 0x28: // TS_PSI_DT_AVC case 0x1B: // TS_PSI_DT_MPEG4_Video case VIDEO_STREAM_DESCRIPTOR: isvideo = 1; break; case REGISTRATION_DESCRIPTOR: /* some services don't have a separate AC3 descriptor */ { RegistrationDescriptor *d = (RegistrationDescriptor*)(*desc); switch (d->getFormatIdentifier()) { case 0x44545331 ... 0x44545333: // DTS1/DTS2/DTS3 case 0x41432d33: // == 'AC-3' case 0x42535344: // == 'BSSD' (LPCM) isaudio = 1; break; case 0x56432d31: // == 'VC-1' isvideo = 1; break; default: break; } } default: break; } } if (tag == CA_DESCRIPTOR) is_scrambled = 1; } default: break; } if (isvideo) have_video = true; else if (isaudio) have_audio = true; else continue; if (is_scrambled) scrambled = true; } for (DescriptorConstIterator desc = pmt.getDescriptors()->begin(); desc != pmt.getDescriptors()->end(); ++desc) { if ((*desc)->getTag() == CA_DESCRIPTOR) scrambled = true; } } m_pmt_in_progress->second.scrambled = scrambled; if ( have_video ) m_pmt_in_progress->second.serviceType = 1; else if ( have_audio ) m_pmt_in_progress->second.serviceType = 2; else m_pmt_in_progress->second.serviceType = 100; } if (err == -1) // timeout or removed by sdt m_pmts_to_read.erase(m_pmt_in_progress++); else if (m_pmt_running) ++m_pmt_in_progress; else { m_pmt_in_progress = m_pmts_to_read.begin(); m_pmt_running = true; } if (m_pmt_in_progress != m_pmts_to_read.end()) m_PMT->start(m_demux, eDVBPMTSpec(m_pmt_in_progress->second.pmtPid, m_pmt_in_progress->first, 4000)); else { m_PMT = 0; m_pmt_running = false; channelDone(); } } void eDVBScan::addKnownGoodChannel(const eDVBChannelID &chid, iDVBFrontendParameters *feparm) { /* add it to the list of known channels. */ if (chid) m_new_channels.insert(std::pair<eDVBChannelID,ePtr<iDVBFrontendParameters> >(chid, feparm)); } void eDVBScan::addChannelToScan(const eDVBChannelID &chid, iDVBFrontendParameters *feparm) { /* check if we don't already have that channel ... */ int type; feparm->getSystem(type); switch(type) { case iDVBFrontend::feSatellite: { eDVBFrontendParametersSatellite parm; feparm->getDVBS(parm); SCAN_eDebug("try to add %d %d %d %d %d %d", parm.orbital_position, parm.frequency, parm.symbol_rate, parm.polarisation, parm.fec, parm.modulation); break; } case iDVBFrontend::feCable: { eDVBFrontendParametersCable parm; feparm->getDVBC(parm); SCAN_eDebug("try to add %d %d %d %d", parm.frequency, parm.symbol_rate, parm.modulation, parm.fec_inner); break; } case iDVBFrontend::feTerrestrial: { eDVBFrontendParametersTerrestrial parm; feparm->getDVBT(parm); SCAN_eDebug("try to add %d %d %d %d %d %d %d %d", parm.frequency, parm.modulation, parm.transmission_mode, parm.hierarchy, parm.guard_interval, parm.code_rate_LP, parm.code_rate_HP, parm.bandwidth); break; } } int found_count=0; /* ... in the list of channels to scan */ for (std::list<ePtr<iDVBFrontendParameters> >::iterator i(m_ch_toScan.begin()); i != m_ch_toScan.end();) { if (sameChannel(*i, feparm)) { if (!found_count) { *i = feparm; // update SCAN_eDebug("update"); } else { SCAN_eDebug("remove dupe"); m_ch_toScan.erase(i++); continue; } ++found_count; } ++i; } if (found_count > 0) { SCAN_eDebug("already in todo list"); return; } /* ... in the list of successfully scanned channels */ for (std::list<ePtr<iDVBFrontendParameters> >::const_iterator i(m_ch_scanned.begin()); i != m_ch_scanned.end(); ++i) if (sameChannel(*i, feparm)) { SCAN_eDebug("successfully scanned"); return; } /* ... in the list of unavailable channels */ for (std::list<ePtr<iDVBFrontendParameters> >::const_iterator i(m_ch_unavailable.begin()); i != m_ch_unavailable.end(); ++i) if (sameChannel(*i, feparm, true)) { SCAN_eDebug("scanned but not available"); return; } /* ... on the current channel */ if (sameChannel(m_ch_current, feparm)) { SCAN_eDebug("is current"); return; } SCAN_eDebug("really add"); /* otherwise, add it to the todo list. */ m_ch_toScan.push_front(feparm); // better.. then the rotor not turning wild from east to west :) } int eDVBScan::sameChannel(iDVBFrontendParameters *ch1, iDVBFrontendParameters *ch2, bool exact) const { int diff; if (ch1->calculateDifference(ch2, diff, exact)) return 0; if (diff < 4000) // more than 4mhz difference? return 1; return 0; } void eDVBScan::channelDone() { if (m_ready & validSDT && (!(m_flags & scanOnlyFree) || !m_pmt_running)) { unsigned long hash = 0; m_ch_current->getHash(hash); eDVBNamespace dvbnamespace = buildNamespace( (**m_SDT->getSections().begin()).getOriginalNetworkId(), (**m_SDT->getSections().begin()).getTransportStreamId(), hash); SCAN_eDebug("SDT: "); std::vector<ServiceDescriptionSection*>::const_iterator i; for (i = m_SDT->getSections().begin(); i != m_SDT->getSections().end(); ++i) processSDT(dvbnamespace, **i); m_ready &= ~validSDT; } if (m_ready & validNIT) { int system; std::list<ePtr<iDVBFrontendParameters> > m_ch_toScan_backup; m_ch_current->getSystem(system); SCAN_eDebug("dumping NIT"); if (m_flags & clearToScanOnFirstNIT) { m_ch_toScan_backup = m_ch_toScan; m_ch_toScan.clear(); } std::vector<NetworkInformationSection*>::const_iterator i; for (i = m_NIT->getSections().begin(); i != m_NIT->getSections().end(); ++i) { const TransportStreamInfoList &tsinfovec = *(*i)->getTsInfo(); for (TransportStreamInfoConstIterator tsinfo(tsinfovec.begin()); tsinfo != tsinfovec.end(); ++tsinfo) { SCAN_eDebug("TSID: %04x ONID: %04x", (*tsinfo)->getTransportStreamId(), (*tsinfo)->getOriginalNetworkId()); eOriginalNetworkID onid = (*tsinfo)->getOriginalNetworkId(); eTransportStreamID tsid = (*tsinfo)->getTransportStreamId(); for (DescriptorConstIterator desc = (*tsinfo)->getDescriptors()->begin(); desc != (*tsinfo)->getDescriptors()->end(); ++desc) { switch ((*desc)->getTag()) { case CABLE_DELIVERY_SYSTEM_DESCRIPTOR: { if (system != iDVBFrontend::feCable) break; // when current locked transponder is no cable transponder ignore this descriptor CableDeliverySystemDescriptor &d = (CableDeliverySystemDescriptor&)**desc; ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters; eDVBFrontendParametersCable cable; cable.set(d); feparm->setDVBC(cable); unsigned long hash=0; feparm->getHash(hash); eDVBNamespace ns = buildNamespace(onid, tsid, hash); addChannelToScan( eDVBChannelID(ns, tsid, onid), feparm); break; } case TERRESTRIAL_DELIVERY_SYSTEM_DESCRIPTOR: { if (system != iDVBFrontend::feTerrestrial) break; // when current locked transponder is no terrestrial transponder ignore this descriptor TerrestrialDeliverySystemDescriptor &d = (TerrestrialDeliverySystemDescriptor&)**desc; ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters; eDVBFrontendParametersTerrestrial terr; terr.set(d); feparm->setDVBT(terr); unsigned long hash=0; feparm->getHash(hash); eDVBNamespace ns = buildNamespace(onid, tsid, hash); addChannelToScan( eDVBChannelID(ns, tsid, onid), feparm); break; } case SATELLITE_DELIVERY_SYSTEM_DESCRIPTOR: { if (system != iDVBFrontend::feSatellite) break; // when current locked transponder is no satellite transponder ignore this descriptor SatelliteDeliverySystemDescriptor &d = (SatelliteDeliverySystemDescriptor&)**desc; if (d.getFrequency() < 10000) break; ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters; eDVBFrontendParametersSatellite sat; sat.set(d); eDVBFrontendParametersSatellite p; m_ch_current->getDVBS(p); if ( abs(p.orbital_position - sat.orbital_position) < 5 ) sat.orbital_position = p.orbital_position; if ( abs(abs(3600 - p.orbital_position) - sat.orbital_position) < 5 ) { SCAN_eDebug("found transponder with incorrect west/east flag ... correct this"); sat.orbital_position = p.orbital_position; } feparm->setDVBS(sat); if ( p.orbital_position != sat.orbital_position) SCAN_eDebug("dropping this transponder, it's on another satellite."); else { unsigned long hash=0; feparm->getHash(hash); addChannelToScan( eDVBChannelID(buildNamespace(onid, tsid, hash), tsid, onid), feparm); } break; } default: SCAN_eDebug("descr<%x>", (*desc)->getTag()); break; } } } } /* a pitfall is to have the clearToScanOnFirstNIT-flag set, and having channels which have no or invalid NIT. this code will not erase the toScan list unless at least one valid entry has been found. This is not a perfect solution, as the channel could contain a partial NIT. Life's bad. */ if (m_flags & clearToScanOnFirstNIT) { if (m_ch_toScan.empty()) { eWarning("clearToScanOnFirstNIT was set, but NIT is invalid. Refusing to stop scan."); m_ch_toScan = m_ch_toScan_backup; } else m_flags &= ~clearToScanOnFirstNIT; } m_ready &= ~validNIT; } if (m_pmt_running || (m_ready & m_ready_all) != m_ready_all) { if (m_abort_current_pmt) { m_abort_current_pmt = false; PMTready(-1); } return; } SCAN_eDebug("channel done!"); /* if we had services on this channel, we declare this channels as "known good". add it. (TODO: not yet implemented) a NIT entry could have possible overridden our frontend data with more exact data. (TODO: not yet implemented) the tuning process could have lead to more exact data than the user entered. The channel id was probably corrected by the data written in the SDT. this is important, as "initial transponder lists" usually don't have valid CHIDs (and that's good). These are the reasons for adding the transponder here, and not before. */ int type; if (m_ch_current->getSystem(type)) type = -1; for (m_pmt_in_progress = m_pmts_to_read.begin(); m_pmt_in_progress != m_pmts_to_read.end();) { eServiceReferenceDVB ref; ePtr<eDVBService> service = new eDVBService; if (!m_chid_current) { unsigned long hash = 0; m_ch_current->getHash(hash); m_chid_current = eDVBChannelID( buildNamespace(eOriginalNetworkID(0), m_pat_tsid, hash), m_pat_tsid, eOriginalNetworkID(0)); } if (m_pmt_in_progress->second.serviceType == 1) SCAN_eDebug("SID %04x is VIDEO", m_pmt_in_progress->first); else if (m_pmt_in_progress->second.serviceType == 2) SCAN_eDebug("SID %04x is AUDIO", m_pmt_in_progress->first); else SCAN_eDebug("SID %04x is DATA", m_pmt_in_progress->first); ref.set(m_chid_current); ref.setServiceID(m_pmt_in_progress->first); ref.setServiceType(m_pmt_in_progress->second.serviceType); if (type != -1) { char sname[255]; char pname[255]; memset(pname, 0, sizeof(pname)); memset(sname, 0, sizeof(sname)); switch(type) { case iDVBFrontend::feSatellite: { eDVBFrontendParametersSatellite parm; m_ch_current->getDVBS(parm); snprintf(sname, 255, "%d%c SID 0x%02x", parm.frequency/1000, parm.polarisation ? 'V' : 'H', m_pmt_in_progress->first); snprintf(pname, 255, "%s %s %d%c %d.%d°%c", parm.system ? "DVB-S2" : "DVB-S", parm.modulation == 1 ? "QPSK" : "8PSK", parm.frequency/1000, parm.polarisation ? 'V' : 'H', parm.orbital_position/10, parm.orbital_position%10, parm.orbital_position > 0 ? 'E' : 'W'); break; } case iDVBFrontend::feTerrestrial: { eDVBFrontendParametersTerrestrial parm; m_ch_current->getDVBT(parm); snprintf(sname, 255, "%d SID 0x%02x", parm.frequency/1000, m_pmt_in_progress->first); break; } case iDVBFrontend::feCable: { eDVBFrontendParametersCable parm; m_ch_current->getDVBC(parm); snprintf(sname, 255, "%d SID 0x%02x", parm.frequency/1000, m_pmt_in_progress->first); break; } } SCAN_eDebug("name '%s', provider_name '%s'", sname, pname); service->m_service_name = convertDVBUTF8(sname); service->genSortName(); service->m_provider_name = convertDVBUTF8(pname); } if (!(m_flags & scanOnlyFree) || !m_pmt_in_progress->second.scrambled) { SCAN_eDebug("add not scrambled!"); std::pair<std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator, bool> i = m_new_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(ref, service)); if (i.second) { m_last_service = i.first; m_event(evtNewService); } } else SCAN_eDebug("dont add... is scrambled!"); m_pmts_to_read.erase(m_pmt_in_progress++); } if (!m_chid_current) eWarning("SCAN: the current channel's ID was not corrected - not adding channel."); else { addKnownGoodChannel(m_chid_current, m_ch_current); if (m_chid_current) { switch(type) { case iDVBFrontend::feSatellite: case iDVBFrontend::feTerrestrial: case iDVBFrontend::feCable: { ePtr<iDVBFrontend> fe; if (!m_channel->getFrontend(fe)) { ePyObject tp_dict = PyDict_New(); fe->getTransponderData(tp_dict, false); // eDebug("add tuner data for tsid %04x, onid %04x, ns %08x", // m_chid_current.transport_stream_id.get(), m_chid_current.original_network_id.get(), // m_chid_current.dvbnamespace.get()); m_tuner_data.insert(std::pair<eDVBChannelID, ePyObjectWrapper>(m_chid_current, tp_dict)); Py_DECREF(tp_dict); } } default: break; } } } m_ch_scanned.push_back(m_ch_current); for (std::list<ePtr<iDVBFrontendParameters> >::iterator i(m_ch_toScan.begin()); i != m_ch_toScan.end();) { if (sameChannel(*i, m_ch_current)) { SCAN_eDebug("remove dupe 2"); m_ch_toScan.erase(i++); continue; } ++i; } nextChannel(); } void eDVBScan::start(const eSmartPtrList<iDVBFrontendParameters> &known_transponders, int flags, int networkid) { m_flags = flags; m_networkid = networkid; m_ch_toScan.clear(); m_ch_scanned.clear(); m_ch_unavailable.clear(); m_new_channels.clear(); m_tuner_data.clear(); m_new_services.clear(); m_last_service = m_new_services.end(); for (eSmartPtrList<iDVBFrontendParameters>::const_iterator i(known_transponders.begin()); i != known_transponders.end(); ++i) { bool exist=false; for (std::list<ePtr<iDVBFrontendParameters> >::const_iterator ii(m_ch_toScan.begin()); ii != m_ch_toScan.end(); ++ii) { if (sameChannel(*i, *ii, true)) { exist=true; break; } } if (!exist) m_ch_toScan.push_back(*i); } nextChannel(); } void eDVBScan::insertInto(iDVBChannelList *db, bool backgroundscanresult) { if (m_flags & scanRemoveServices) { bool clearTerrestrial=false; bool clearCable=false; std::set<unsigned int> scanned_sat_positions; std::list<ePtr<iDVBFrontendParameters> >::iterator it(m_ch_scanned.begin()); for (;it != m_ch_scanned.end(); ++it) { if (m_flags & scanDontRemoveUnscanned) db->removeServices(&(*(*it))); else { int system; (*it)->getSystem(system); switch(system) { case iDVBFrontend::feSatellite: { eDVBFrontendParametersSatellite sat_parm; (*it)->getDVBS(sat_parm); scanned_sat_positions.insert(sat_parm.orbital_position); break; } case iDVBFrontend::feTerrestrial: { clearTerrestrial=true; break; } case iDVBFrontend::feCable: { clearCable=true; break; } } } } for (it=m_ch_unavailable.begin();it != m_ch_unavailable.end(); ++it) { if (m_flags & scanDontRemoveUnscanned) db->removeServices(&(*(*it))); else { int system; (*it)->getSystem(system); switch(system) { case iDVBFrontend::feSatellite: { eDVBFrontendParametersSatellite sat_parm; (*it)->getDVBS(sat_parm); scanned_sat_positions.insert(sat_parm.orbital_position); break; } case iDVBFrontend::feTerrestrial: { clearTerrestrial=true; break; } case iDVBFrontend::feCable: { clearCable=true; break; } } } } if (clearTerrestrial) { eDVBChannelID chid; chid.dvbnamespace=0xEEEE0000; db->removeServices(chid); } if (clearCable) { eDVBChannelID chid; chid.dvbnamespace=0xFFFF0000; db->removeServices(chid); } for (std::set<unsigned int>::iterator x(scanned_sat_positions.begin()); x != scanned_sat_positions.end(); ++x) { eDVBChannelID chid; if (m_flags & scanDontRemoveFeeds) chid.dvbnamespace = eDVBNamespace((*x)<<16); // eDebug("remove %d %08x", *x, chid.dvbnamespace.get()); db->removeServices(chid, *x); } } for (std::map<eDVBChannelID, ePtr<iDVBFrontendParameters> >::const_iterator ch(m_new_channels.begin()); ch != m_new_channels.end(); ++ch) { int system; ch->second->getSystem(system); std::map<eDVBChannelID, ePyObjectWrapper>::iterator it = m_tuner_data.find(ch->first); switch(system) { case iDVBFrontend::feTerrestrial: { eDVBFrontendParameters *p = (eDVBFrontendParameters*)&(*ch->second); eDVBFrontendParametersTerrestrial parm; int freq = PyInt_AsLong(PyDict_GetItemString(it->second, "frequency")); p->getDVBT(parm); // eDebug("corrected freq for tsid %04x, onid %04x, ns %08x is %d, old was %d", // ch->first.transport_stream_id.get(), ch->first.original_network_id.get(), // ch->first.dvbnamespace.get(), freq, parm.frequency); parm.frequency = freq; p->setDVBT(parm); break; } case iDVBFrontend::feSatellite: // no update of any transponder parameter yet case iDVBFrontend::feCable: break; } if (m_flags & scanOnlyFree) { eDVBFrontendParameters *ptr = (eDVBFrontendParameters*)&(*ch->second); ptr->setFlags(iDVBFrontendParameters::flagOnlyFree); } db->addChannelToList(ch->first, ch->second); } for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::const_iterator service(m_new_services.begin()); service != m_new_services.end(); ++service) { ePtr<eDVBService> dvb_service; if (!db->getService(service->first, dvb_service)) { if (dvb_service->m_flags & eDVBService::dxNoSDT) continue; if (!(dvb_service->m_flags & eDVBService::dxHoldName)) { dvb_service->m_service_name = service->second->m_service_name; dvb_service->m_service_name_sort = service->second->m_service_name_sort; } dvb_service->m_provider_name = service->second->m_provider_name; if (service->second->m_ca.size()) dvb_service->m_ca = service->second->m_ca; if (!backgroundscanresult) // do not remove new found flags when this is the result of a 'background scan' dvb_service->m_flags &= ~eDVBService::dxNewFound; } else { db->addService(service->first, service->second); if (!(m_flags & scanRemoveServices)) service->second->m_flags |= eDVBService::dxNewFound; } } if (!backgroundscanresult) { /* only create a 'Last Scanned' bouquet when this is not the result of a background scan */ std::string bouquetname = "userbouquet.LastScanned.tv"; std::string bouquetquery = "FROM BOUQUET \"" + bouquetname + "\" ORDER BY bouquet"; eServiceReference bouquetref(eServiceReference::idDVB, eServiceReference::flagDirectory, bouquetquery); bouquetref.setData(0, 1); /* set bouquet 'servicetype' to tv (even though we probably have both tv and radio channels) */ eBouquet *bouquet = NULL; eServiceReference rootref(eServiceReference::idDVB, eServiceReference::flagDirectory, "FROM BOUQUET \"bouquets.tv\" ORDER BY bouquet"); if (!db->getBouquet(bouquetref, bouquet) && bouquet) { /* bouquet already exists, empty it before we continue */ bouquet->m_services.clear(); } else { /* bouquet doesn't yet exist, create a new one */ if (!db->getBouquet(rootref, bouquet) && bouquet) { bouquet->m_services.push_back(bouquetref); bouquet->flushChanges(); } /* loading the bouquet seems to be the only way to add it to the bouquet list */ eDVBDB *dvbdb = eDVBDB::getInstance(); if (dvbdb) dvbdb->loadBouquet(bouquetname.c_str()); /* and now that it has been added to the list, we can find it */ db->getBouquet(bouquetref, bouquet); } if (bouquet) { bouquet->m_bouquet_name = "Last Scanned"; for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::const_iterator service(m_new_services.begin()); service != m_new_services.end(); ++service) { bouquet->m_services.push_back(service->first); } bouquet->flushChanges(); } else { eDebug("failed to create 'Last Scanned' bouquet!"); } } } RESULT eDVBScan::processSDT(eDVBNamespace dvbnamespace, const ServiceDescriptionSection &sdt) { const ServiceDescriptionList &services = *sdt.getDescriptions(); SCAN_eDebug("ONID: %04x", sdt.getOriginalNetworkId()); eDVBChannelID chid(dvbnamespace, sdt.getTransportStreamId(), sdt.getOriginalNetworkId()); /* save correct CHID for this channel */ m_chid_current = chid; for (ServiceDescriptionConstIterator s(services.begin()); s != services.end(); ++s) { unsigned short service_id = (*s)->getServiceId(); SCAN_eDebugNoNewLine("SID %04x: ", service_id); bool add = true; if (m_flags & scanOnlyFree) { std::map<unsigned short, service>::iterator it = m_pmts_to_read.find(service_id); if (it != m_pmts_to_read.end()) { if (it->second.scrambled) { SCAN_eDebug("is scrambled!"); add = false; } else SCAN_eDebug("is free"); } else { SCAN_eDebug("not found in PAT.. so we assume it is scrambled!!"); add = false; } } if (add) { eServiceReferenceDVB ref; ePtr<eDVBService> service = new eDVBService; ref.set(chid); ref.setServiceID(service_id); for (DescriptorConstIterator desc = (*s)->getDescriptors()->begin(); desc != (*s)->getDescriptors()->end(); ++desc) { switch ((*desc)->getTag()) { case SERVICE_DESCRIPTOR: { ServiceDescriptor &d = (ServiceDescriptor&)**desc; int servicetype = d.getServiceType(); /* NA scanning hack */ switch (servicetype) { /* DISH/BEV servicetypes: */ case 128: case 133: case 137: case 144: case 145: case 150: case 154: case 163: case 164: case 166: case 167: case 168: servicetype = 1; break; } /* */ ref.setServiceType(servicetype); service->m_service_name = convertDVBUTF8(d.getServiceName()); service->genSortName(); service->m_provider_name = convertDVBUTF8(d.getServiceProviderName()); SCAN_eDebug("name '%s', provider_name '%s'", service->m_service_name.c_str(), service->m_provider_name.c_str()); break; } case CA_IDENTIFIER_DESCRIPTOR: { CaIdentifierDescriptor &d = (CaIdentifierDescriptor&)**desc; const CaSystemIdList &caids = *d.getCaSystemIds(); SCAN_eDebugNoNewLine("CA "); for (CaSystemIdList::const_iterator i(caids.begin()); i != caids.end(); ++i) { SCAN_eDebugNoNewLine("%04x ", *i); service->m_ca.push_front(*i); } SCAN_eDebug(""); break; } default: SCAN_eDebug("descr<%x>", (*desc)->getTag()); break; } } std::pair<std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator, bool> i = m_new_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(ref, service)); if (i.second) { m_last_service = i.first; m_event(evtNewService); } } if (m_pmt_running && m_pmt_in_progress->first == service_id) m_abort_current_pmt = true; else m_pmts_to_read.erase(service_id); } return 0; } RESULT eDVBScan::connectEvent(const Slot1<void,int> &event, ePtr<eConnection> &connection) { connection = new eConnection(this, m_event.connect(event)); return 0; } void eDVBScan::getStats(int &transponders_done, int &transponders_total, int &services) { transponders_done = m_ch_scanned.size() + m_ch_unavailable.size(); transponders_total = m_ch_toScan.size() + transponders_done; services = m_new_services.size(); } void eDVBScan::getLastServiceName(std::string &last_service_name) { if (m_last_service == m_new_services.end()) last_service_name = ""; else last_service_name = m_last_service->second->m_service_name; } RESULT eDVBScan::getFrontend(ePtr<iDVBFrontend> &fe) { if (m_channel) return m_channel->getFrontend(fe); fe = 0; return -1; } RESULT eDVBScan::getCurrentTransponder(ePtr<iDVBFrontendParameters> &tp) { if (m_ch_current) { tp = m_ch_current; return 0; } tp = 0; return -1; }
digidudeofdw/enigma2
lib/dvb/scan.cpp
C++
gpl-2.0
36,702
/* * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* creature_movement Table alter table creature_movement add `textid1` int(11) NOT NULL default '0'; alter table creature_movement add `textid2` int(11) NOT NULL default '0'; alter table creature_movement add `textid3` int(11) NOT NULL default '0'; alter table creature_movement add `textid4` int(11) NOT NULL default '0'; alter table creature_movement add `textid5` int(11) NOT NULL default '0'; alter table creature_movement add `emote` int(10) unsigned default '0'; alter table creature_movement add `spell` int(5) unsigned default '0'; alter table creature_movement add `wpguid` int(11) default '0'; */ #include <ctime> #include "WaypointMovementGenerator.h" #include "ObjectMgr.h" #include "Creature.h" #include "DestinationHolderImp.h" #include "CreatureAI.h" #include "WaypointManager.h" #include "WorldPacket.h" #include "ScriptCalls.h" #include <cassert> //-----------------------------------------------// void WaypointMovementGenerator<Creature>::LoadPath(Creature &creature) { DETAIL_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "LoadPath: loading waypoint path for creature %u, %u", creature.GetGUIDLow(), creature.GetDBTableGUIDLow()); i_path = sWaypointMgr.GetPath(creature.GetDBTableGUIDLow()); // We may LoadPath() for several occasions: // 1: When creature.MovementType=2 // 1a) Path is selected by creature.guid == creature_movement.id // 1b) Path for 1a) does not exist and then use path from creature.GetEntry() == creature_movement_template.entry // 2: When creature_template.MovementType=2 // 2a) Creature is summoned and has creature_template.MovementType=2 // Creators need to be sure that creature_movement_template is always valid for summons. // Mob that can be summoned anywhere should not have creature_movement_template for example. // No movement found for guid if (!i_path) { i_path = sWaypointMgr.GetPathTemplate(creature.GetEntry()); // No movement found for entry if (!i_path) { sLog.outErrorDb("WaypointMovementGenerator::LoadPath: creature %s (Entry: %u GUID: %u) doesn't have waypoint path", creature.GetName(), creature.GetEntry(), creature.GetDBTableGUIDLow()); return; } } // We have to set the destination here (for the first point), right after Initialize. Without, we may not have valid xyz for GetResetPosition CreatureTraveller traveller(creature); if (creature.CanFly()) creature.AddSplineFlag(SPLINEFLAG_UNKNOWN7); const WaypointNode &node = i_path->at(i_currentNode); i_destinationHolder.SetDestination(traveller, node.x, node.y, node.z); i_nextMoveTime.Reset(i_destinationHolder.GetTotalTravelTime()); } void WaypointMovementGenerator<Creature>::Initialize(Creature &creature) { LoadPath(creature); creature.addUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE); } void WaypointMovementGenerator<Creature>::Finalize(Creature &creature) { creature.clearUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE); } void WaypointMovementGenerator<Creature>::Interrupt(Creature &creature) { creature.clearUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE); } void WaypointMovementGenerator<Creature>::Reset(Creature &creature) { SetStoppedByPlayer(false); i_nextMoveTime.Reset(0); creature.addUnitState(UNIT_STAT_ROAMING|UNIT_STAT_ROAMING_MOVE); } bool WaypointMovementGenerator<Creature>::Update(Creature &creature, const uint32 &diff) { if (!&creature) return true; // Waypoint movement can be switched on/off // This is quite handy for escort quests and other stuff if (creature.hasUnitState(UNIT_STAT_NOT_MOVE)) { creature.clearUnitState(UNIT_STAT_ROAMING_MOVE); return true; } // prevent a crash at empty waypoint path. if (!i_path || i_path->empty()) { creature.clearUnitState(UNIT_STAT_ROAMING_MOVE); return true; } if (i_currentNode >= i_path->size()) { sLog.outError("WaypointMovement currentNode (%u) is equal or bigger than path size (creature entry %u)", i_currentNode, creature.GetEntry()); i_currentNode = 0; } CreatureTraveller traveller(creature); i_nextMoveTime.Update(diff); if (i_destinationHolder.UpdateTraveller(traveller, diff, false, true)) { if (!IsActive(creature)) // force stop processing (movement can move out active zone with cleanup movegens list) return true; // not expire now, but already lost } // creature has been stopped in middle of the waypoint segment if (!i_destinationHolder.HasArrived() && creature.IsStopped()) { // Timer has elapsed, meaning this part controlled it if (i_nextMoveTime.Passed()) { SetStoppedByPlayer(false); creature.addUnitState(UNIT_STAT_ROAMING_MOVE); if (creature.CanFly()) creature.AddSplineFlag(SPLINEFLAG_UNKNOWN7); // Now we re-set destination to same node and start travel const WaypointNode &node = i_path->at(i_currentNode); i_destinationHolder.SetDestination(traveller, node.x, node.y, node.z); i_nextMoveTime.Reset(i_destinationHolder.GetTotalTravelTime()); } else // if( !i_nextMoveTime.Passed()) { // unexpected end of timer && creature stopped && not at end of segment if (!IsStoppedByPlayer()) { // Put 30 seconds delay i_destinationHolder.IncreaseTravelTime(STOP_TIME_FOR_PLAYER); i_nextMoveTime.Reset(STOP_TIME_FOR_PLAYER); SetStoppedByPlayer(true); // Mark we did it } } return true; // Abort here this update } if (creature.IsStopped()) { if (!m_isArrivalDone) { if (i_path->at(i_currentNode).orientation != 100) creature.SetOrientation(i_path->at(i_currentNode).orientation); if (i_path->at(i_currentNode).script_id) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature movement start script %u at point %u for creature %u (entry %u).", i_path->at(i_currentNode).script_id, i_currentNode, creature.GetDBTableGUIDLow(), creature.GetEntry()); creature.GetMap()->ScriptsStart(sCreatureMovementScripts, i_path->at(i_currentNode).script_id, &creature, &creature); } // We have reached the destination and can process behavior if (WaypointBehavior *behavior = i_path->at(i_currentNode).behavior) { if (behavior->emote != 0) creature.HandleEmote(behavior->emote); if (behavior->spell != 0) { creature.CastSpell(&creature, behavior->spell, false); if (!IsActive(creature)) // force stop processing (cast can change movegens list) return true; // not expire now, but already lost } if (behavior->model1 != 0) creature.SetDisplayId(behavior->model1); if (behavior->textid[0]) { // Not only one text is set if (behavior->textid[1]) { // Select one from max 5 texts (0 and 1 already checked) int i = 2; for(; i < MAX_WAYPOINT_TEXT; ++i) { if (!behavior->textid[i]) break; } creature.Say(behavior->textid[rand() % i], 0, 0); } else creature.Say(behavior->textid[0], 0, 0); } } // wpBehaviour found // Can only do this once for the node m_isArrivalDone = true; // Inform script MovementInform(creature); if (!IsActive(creature)) // force stop processing (movement can move out active zone with cleanup movegens list) return true; // not expire now, but already lost // prevent a crash at empty waypoint path. if (!i_path || i_path->empty() || i_currentNode >= i_path->size()) { creature.clearUnitState(UNIT_STAT_ROAMING_MOVE); return true; } } } // i_creature.IsStopped() // This is at the end of waypoint segment (incl. was previously stopped by player, extending the time) if (i_nextMoveTime.Passed()) { // If stopped then begin a new move segment if (creature.IsStopped()) { creature.addUnitState(UNIT_STAT_ROAMING_MOVE); if (creature.CanFly()) creature.AddSplineFlag(SPLINEFLAG_UNKNOWN7); if (WaypointBehavior *behavior = i_path->at(i_currentNode).behavior) { if (behavior->model2 != 0) creature.SetDisplayId(behavior->model2); creature.SetUInt32Value(UNIT_NPC_EMOTESTATE, 0); } // behavior for "departure" of the current node is done m_isArrivalDone = false; // Proceed with increment current node and then send to the next destination ++i_currentNode; // Oops, end of the line so need to start from the beginning if (i_currentNode >= i_path->size()) i_currentNode = 0; if (i_path->at(i_currentNode).orientation != 100) creature.SetOrientation(i_path->at(i_currentNode).orientation); const WaypointNode &node = i_path->at(i_currentNode); i_destinationHolder.SetDestination(traveller, node.x, node.y, node.z); i_nextMoveTime.Reset(i_destinationHolder.GetTotalTravelTime()); } else { // If not stopped then stop it creature.clearUnitState(UNIT_STAT_ROAMING_MOVE); SetStoppedByPlayer(false); // Set TimeTracker to waittime for the current node i_nextMoveTime.Reset(i_path->at(i_currentNode).delay); } } return true; } void WaypointMovementGenerator<Creature>::MovementInform(Creature &creature) { if (creature.AI()) creature.AI()->MovementInform(WAYPOINT_MOTION_TYPE, i_currentNode); } bool WaypointMovementGenerator<Creature>::GetResetPosition(Creature&, float& x, float& y, float& z) { return PathMovementBase<Creature, WaypointPath const*>::GetPosition(x,y,z); } //----------------------------------------------------// uint32 FlightPathMovementGenerator::GetPathAtMapEnd() const { if (i_currentNode >= i_path->size()) return i_path->size(); uint32 curMapId = (*i_path)[i_currentNode].mapid; for(uint32 i = i_currentNode; i < i_path->size(); ++i) { if ((*i_path)[i].mapid != curMapId) return i; } return i_path->size(); } void FlightPathMovementGenerator::Initialize(Player &player) { Reset(player); } void FlightPathMovementGenerator::Finalize(Player & player) { // remove flag to prevent send object build movement packets for flight state and crash (movement generator already not at top of stack) player.clearUnitState(UNIT_STAT_TAXI_FLIGHT); float x, y, z; i_destinationHolder.GetLocationNow(player.GetBaseMap(), x, y, z); player.SetPosition(x, y, z, player.GetOrientation()); player.Unmount(); player.RemoveFlag(UNIT_FIELD_FLAGS,UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT); if(player.m_taxi.empty()) { player.getHostileRefManager().setOnlineOfflineState(true); if(player.pvpInfo.inHostileArea) player.CastSpell(&player, 2479, true); // update z position to ground and orientation for landing point // this prevent cheating with landing point at lags // when client side flight end early in comparison server side player.StopMoving(); } } void FlightPathMovementGenerator::Interrupt(Player & player) { player.clearUnitState(UNIT_STAT_TAXI_FLIGHT); } void FlightPathMovementGenerator::Reset(Player & player) { player.getHostileRefManager().setOnlineOfflineState(false); player.addUnitState(UNIT_STAT_TAXI_FLIGHT); player.SetFlag(UNIT_FIELD_FLAGS,UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT); Traveller<Player> traveller(player); // do not send movement, it was sent already i_destinationHolder.SetDestination(traveller, (*i_path)[i_currentNode].x, (*i_path)[i_currentNode].y, (*i_path)[i_currentNode].z, false); player.SendMonsterMoveByPath(GetPath(),GetCurrentNode(),GetPathAtMapEnd(), SplineFlags(SPLINEFLAG_WALKMODE|SPLINEFLAG_FLYING)); } bool FlightPathMovementGenerator::Update(Player &player, const uint32 &diff) { if (MovementInProgress()) { Traveller<Player> traveller(player); if( i_destinationHolder.UpdateTraveller(traveller, diff, false) ) { if (!IsActive(player)) // force stop processing (movement can move out active zone with cleanup movegens list) return true; // not expire now, but already lost i_destinationHolder.ResetUpdate(FLIGHT_TRAVEL_UPDATE); if (i_destinationHolder.HasArrived()) { DoEventIfAny(player,(*i_path)[i_currentNode],false); uint32 curMap = (*i_path)[i_currentNode].mapid; ++i_currentNode; if (MovementInProgress()) { DoEventIfAny(player,(*i_path)[i_currentNode],true); DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "loading node %u for player %s", i_currentNode, player.GetName()); if ((*i_path)[i_currentNode].mapid == curMap) { // do not send movement, it was sent already i_destinationHolder.SetDestination(traveller, (*i_path)[i_currentNode].x, (*i_path)[i_currentNode].y, (*i_path)[i_currentNode].z, false); } return true; } } else return true; } else return true; } // we have arrived at the end of the path return false; } void FlightPathMovementGenerator::SetCurrentNodeAfterTeleport() { if (i_path->empty()) return; uint32 map0 = (*i_path)[0].mapid; for (size_t i = 1; i < i_path->size(); ++i) { if ((*i_path)[i].mapid != map0) { i_currentNode = i; return; } } } void FlightPathMovementGenerator::DoEventIfAny(Player& player, TaxiPathNodeEntry const& node, bool departure) { if (uint32 eventid = departure ? node.departureEventID : node.arrivalEventID) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Taxi %s event %u of node %u of path %u for player %s", departure ? "departure" : "arrival", eventid, node.index, node.path, player.GetName()); if (!Script->ProcessEventId(eventid, &player, &player, departure)) player.GetMap()->ScriptsStart(sEventScripts, eventid, &player, &player); } } // // Unique1's ASTAR Pathfinding Code... For future use & reference... // #ifdef __PATHFINDING__ int GetFCost(int to, int num, int parentNum, float *gcost); // Below... int ShortenASTARRoute(short int *pathlist, int number) { // Wrote this to make the routes a little smarter (shorter)... No point looping back to the same places... Unique1 short int temppathlist[MAX_PATHLIST_NODES]; int count = 0; // int count2 = 0; int temp, temp2; int link; int upto = 0; for (temp = number; temp >= 0; temp--) { qboolean shortened = qfalse; for (temp2 = 0; temp2 < temp; temp2++) { for (link = 0; link < nodes[pathlist[temp]].enodenum; link++) { if (nodes[pathlist[temp]].links[link].flags & PATH_BLOCKED) continue; //if ((bot->client->ps.eFlags & EF_TANK) && nodes[bot->current_node].links[link].flags & PATH_NOTANKS) //if this path is blocked, skip it // continue; //if (nodes[nodes[pathlist[temp]].links[link].targetNode].origin[2] > nodes[pathlist[temp]].origin[2] + 32) // continue; if (nodes[pathlist[temp]].links[link].targetNode == pathlist[temp2]) { // Found a shorter route... //if (OrgVisible(nodes[pathlist[temp2]].origin, nodes[pathlist[temp]].origin, -1)) { temppathlist[count] = pathlist[temp2]; temp = temp2; ++count; shortened = qtrue; } } } } if (!shortened) { temppathlist[count] = pathlist[temp]; ++count; } } upto = count; for (temp = 0; temp < count; temp++) { pathlist[temp] = temppathlist[upto]; --upto; } G_Printf("ShortenASTARRoute: Path size reduced from %i to %i nodes...n", number, count); return count; } /* =========================================================================== CreatePathAStar This function uses the A* pathfinding algorithm to determine the shortest path between any two nodes. It's fairly complex, so I'm not really going to explain it much. Look up A* and binary heaps for more info. pathlist stores the ideal path between the nodes, in reverse order, and the return value is the number of nodes in that path =========================================================================== */ int CreatePathAStar(gentity_t *bot, int from, int to, short int *pathlist) { //all the data we have to hold...since we can't do dynamic allocation, has to be MAX_NODES //we can probably lower this later - eg, the open list should never have more than at most a few dozen items on it short int openlist[MAX_NODES+1]; //add 1 because it's a binary heap, and they don't use 0 - 1 is the first used index float gcost[MAX_NODES]; int fcost[MAX_NODES]; char list[MAX_NODES]; //0 is neither, 1 is open, 2 is closed - char because it's the smallest data type short int parent[MAX_NODES]; short int numOpen = 0; short int atNode, temp, newnode=-1; qboolean found = qfalse; int count = -1; float gc; int i, u, v, m; vec3_t vec; //clear out all the arrays memset(openlist, 0, sizeof(short int)*(MAX_NODES+1)); memset(fcost, 0, sizeof(int)*MAX_NODES); memset(list, 0, sizeof(char)*MAX_NODES); memset(parent, 0, sizeof(short int)*MAX_NODES); memset(gcost, -1, sizeof(float)*MAX_NODES); //make sure we have valid data before calculating everything if ((from == NODE_INVALID) || (to == NODE_INVALID) || (from >= MAX_NODES) || (to >= MAX_NODES) || (from == to)) return -1; openlist[1] = from; //add the starting node to the open list ++numOpen; gcost[from] = 0; //its f and g costs are obviously 0 fcost[from] = 0; while (1) { if (numOpen != 0) //if there are still items in the open list { //pop the top item off of the list atNode = openlist[1]; list[atNode] = 2; //put the node on the closed list so we don't check it again --numOpen; openlist[1] = openlist[numOpen+1]; //move the last item in the list to the top position v = 1; //this while loop reorders the list so that the new lowest fcost is at the top again while (1) { u = v; if ((2*u+1) < numOpen) //if both children exist { if (fcost[openlist[u]] >= fcost[openlist[2*u]]) v = 2*u; if (fcost[openlist[v]] >= fcost[openlist[2*u+1]]) v = 2*u+1; } else { if ((2*u) < numOpen) //if only one child exists { if (fcost[openlist[u]] >= fcost[openlist[2*u]]) v = 2*u; } } if (u != v) //if they're out of order, swap this item with its parent { temp = openlist[u]; openlist[u] = openlist[v]; openlist[v] = temp; } else break; } for (i = 0; i < nodes[atNode].enodenum; ++i) //loop through all the links for this node { newnode = nodes[atNode].links[i].targetNode; //if this path is blocked, skip it if (nodes[atNode].links[i].flags & PATH_BLOCKED) continue; //if this path is blocked, skip it if (bot->client && (bot->client->ps.eFlags & EF_TANK) && nodes[atNode].links[i].flags & PATH_NOTANKS) continue; //skip any unreachable nodes if (bot->client && (nodes[newnode].type & NODE_ALLY_UNREACHABLE) && (bot->client->sess.sessionTeam == TEAM_ALLIES)) continue; if (bot->client && (nodes[newnode].type & NODE_AXIS_UNREACHABLE) && (bot->client->sess.sessionTeam == TEAM_AXIS)) continue; if (list[newnode] == 2) //if this node is on the closed list, skip it continue; if (list[newnode] != 1) //if this node is not already on the open list { openlist[++numOpen] = newnode; //add the new node to the open list list[newnode] = 1; parent[newnode] = atNode; //record the node's parent if (newnode == to) //if we've found the goal, don't keep computing paths! break; //this will break the 'for' and go all the way to 'if (list[to] == 1)' //store it's f cost value fcost[newnode] = GetFCost(to, newnode, parent[newnode], gcost); //this loop re-orders the heap so that the lowest fcost is at the top m = numOpen; while (m != 1) //while this item isn't at the top of the heap already { //if it has a lower fcost than its parent if (fcost[openlist[m]] <= fcost[openlist[m/2]]) { temp = openlist[m/2]; openlist[m/2] = openlist[m]; openlist[m] = temp; //swap them m /= 2; } else break; } } else //if this node is already on the open list { gc = gcost[atNode]; VectorSubtract(nodes[newnode].origin, nodes[atNode].origin, vec); gc += VectorLength(vec); //calculate what the gcost would be if we reached this node along the current path if (gc < gcost[newnode]) //if the new gcost is less (ie, this path is shorter than what we had before) { parent[newnode] = atNode; //set the new parent for this node gcost[newnode] = gc; //and the new g cost for (i = 1; i < numOpen; ++i) //loop through all the items on the open list { if (openlist[i] == newnode) //find this node in the list { //calculate the new fcost and store it fcost[newnode] = GetFCost(to, newnode, parent[newnode], gcost); //reorder the list again, with the lowest fcost item on top m = i; while (m != 1) { //if the item has a lower fcost than it's parent if (fcost[openlist[m]] < fcost[openlist[m/2]]) { temp = openlist[m/2]; openlist[m/2] = openlist[m]; openlist[m] = temp; //swap them m /= 2; } else break; } break; //exit the 'for' loop because we already changed this node } //if } //for } //if (gc < gcost[newnode]) } //if (list[newnode] != 1) --> else } //for (loop through links) } //if (numOpen != 0) else { found = qfalse; //there is no path between these nodes break; } if (list[to] == 1) //if the destination node is on the open list, we're done { found = qtrue; break; } } //while (1) if (found == qtrue) //if we found a path { //G_Printf("%s - path found!n", bot->client->pers.netname); count = 0; temp = to; //start at the end point while (temp != from) //travel along the path (backwards) until we reach the starting point { pathlist[count++] = temp; //add the node to the pathlist and increment the count temp = parent[temp]; //move to the parent of this node to continue the path } pathlist[count++] = from; //add the beginning node to the end of the pathlist #ifdef __BOT_SHORTEN_ROUTING__ count = ShortenASTARRoute(pathlist, count); // This isn't working... Dunno why.. Unique1 #endif //__BOT_SHORTEN_ROUTING__ } else { //G_Printf("^1*** ^4BOT DEBUG^5: (CreatePathAStar) There is no route between node ^7%i^5 and node ^7%i^5.n", from, to); count = CreateDumbRoute(from, to, pathlist); if (count > 0) { #ifdef __BOT_SHORTEN_ROUTING__ count = ShortenASTARRoute(pathlist, count); // This isn't working... Dunno why.. Unique1 #endif //__BOT_SHORTEN_ROUTING__ return count; } } return count; //return the number of nodes in the path, -1 if not found } /* =========================================================================== GetFCost Utility function used by A* pathfinding to calculate the cost to move between nodes towards a goal. Using the A* algorithm F = G + H, G here is the distance along the node paths the bot must travel, and H is the straight-line distance to the goal node. Returned as an int because more precision is unnecessary and it will slightly speed up heap access =========================================================================== */ int GetFCost(int to, int num, int parentNum, float *gcost) { float gc = 0; float hc = 0; vec3_t v; if (gcost[num] == -1) { if (parentNum != -1) { gc = gcost[parentNum]; VectorSubtract(nodes[num].origin, nodes[parentNum].origin, v); gc += VectorLength(v); } gcost[num] = gc; } else gc = gcost[num]; VectorSubtract(nodes[to].origin, nodes[num].origin, v); hc = VectorLength(v); return (int)(gc + hc); } #endif //__PATHFINDING__
Khira/La-Confrerie
src/game/WaypointMovementGenerator.cpp
C++
gpl-2.0
30,591
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dx.io; import com.android.dx.util.ByteInput; import com.android.dx.util.Leb128Utils; /** * SAX-style reader for encoded values. * TODO: convert this to a pull-style reader */ public class EncodedValueReader { public static final int ENCODED_BYTE = 0x00; public static final int ENCODED_SHORT = 0x02; public static final int ENCODED_CHAR = 0x03; public static final int ENCODED_INT = 0x04; public static final int ENCODED_LONG = 0x06; public static final int ENCODED_FLOAT = 0x10; public static final int ENCODED_DOUBLE = 0x11; public static final int ENCODED_STRING = 0x17; public static final int ENCODED_TYPE = 0x18; public static final int ENCODED_FIELD = 0x19; public static final int ENCODED_ENUM = 0x1b; public static final int ENCODED_METHOD = 0x1a; public static final int ENCODED_ARRAY = 0x1c; public static final int ENCODED_ANNOTATION = 0x1d; public static final int ENCODED_NULL = 0x1e; public static final int ENCODED_BOOLEAN = 0x1f; protected final ByteInput in; public EncodedValueReader(ByteInput in) { this.in = in; } public EncodedValueReader(EncodedValue in) { this(in.asByteInput()); } public final void readArray() { int size = Leb128Utils.readUnsignedLeb128(in); visitArray(size); for (int i = 0; i < size; i++) { readValue(); } } public final void readAnnotation() { int typeIndex = Leb128Utils.readUnsignedLeb128(in); int size = Leb128Utils.readUnsignedLeb128(in); visitAnnotation(typeIndex, size); for (int i = 0; i < size; i++) { visitAnnotationName(Leb128Utils.readUnsignedLeb128(in)); readValue(); } } public final void readValue() { int argAndType = in.readByte() & 0xff; int type = argAndType & 0x1f; int arg = (argAndType & 0xe0) >> 5; int size = arg + 1; switch (type) { case ENCODED_BYTE: case ENCODED_SHORT: case ENCODED_CHAR: case ENCODED_INT: case ENCODED_LONG: case ENCODED_FLOAT: case ENCODED_DOUBLE: visitPrimitive(argAndType, type, arg, size); break; case ENCODED_STRING: visitString(type, readIndex(in, size)); break; case ENCODED_TYPE: visitType(type, readIndex(in, size)); break; case ENCODED_FIELD: case ENCODED_ENUM: visitField(type, readIndex(in, size)); break; case ENCODED_METHOD: visitMethod(type, readIndex(in, size)); break; case ENCODED_ARRAY: visitArrayValue(argAndType); readArray(); break; case ENCODED_ANNOTATION: visitAnnotationValue(argAndType); readAnnotation(); break; case ENCODED_NULL: visitEncodedNull(argAndType); break; case ENCODED_BOOLEAN: visitEncodedBoolean(argAndType); break; } } protected void visitArray(int size) {} protected void visitAnnotation(int typeIndex, int size) {} protected void visitAnnotationName(int nameIndex) {} protected void visitPrimitive(int argAndType, int type, int arg, int size) { for (int i = 0; i < size; i++) { in.readByte(); } } protected void visitString(int type, int index) {} protected void visitType(int type, int index) {} protected void visitField(int type, int index) {} protected void visitMethod(int type, int index) {} protected void visitArrayValue(int argAndType) {} protected void visitAnnotationValue(int argAndType) {} protected void visitEncodedBoolean(int argAndType) {} protected void visitEncodedNull(int argAndType) {} private int readIndex(ByteInput in, int byteCount) { int result = 0; int shift = 0; for (int i = 0; i < byteCount; i++) { result += (in.readByte() & 0xff) << shift; shift += 8; } return result; } }
rex-xxx/mt6572_x201
dalvik/dx/src/com/android/dx/io/EncodedValueReader.java
Java
gpl-2.0
4,797
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.text; import java.util.Map; /** * Lookup a String key to a String value. * <p> * This class represents the simplest form of a string to string map. * It has a benefit over a map in that it can create the result on * demand based on the key. * <p> * This class comes complete with various factory methods. * If these do not suffice, you can subclass and implement your own matcher. * <p> * For example, it would be possible to implement a lookup that used the * key as a primary key, and looked up the value on demand from the database * * @author Apache Software Foundation * @since 2.2 * @version $Id$ */ public abstract class StrLookup<V> { /** * Lookup that always returns null. */ private static final StrLookup<?> NONE_LOOKUP; /** * Lookup that uses System properties. */ private static final StrLookup<Object> SYSTEM_PROPERTIES_LOOKUP; static { NONE_LOOKUP = new MapStrLookup(null); StrLookup lookup = null; try { lookup = new MapStrLookup(System.getProperties()); } catch (SecurityException ex) { lookup = NONE_LOOKUP; } SYSTEM_PROPERTIES_LOOKUP = lookup; } //----------------------------------------------------------------------- /** * Returns a lookup which always returns null. * * @return a lookup that always returns null, not null */ public static StrLookup<?> noneLookup() { return NONE_LOOKUP; } /** * Returns a lookup which uses {@link System#getProperties() System properties} * to lookup the key to value. * <p> * If a security manager blocked access to system properties, then null will * be returned from every lookup. * <p> * If a null key is used, this lookup will throw a NullPointerException. * * @return a lookup using system properties, not null */ public static StrLookup<Object> systemPropertiesLookup() { return SYSTEM_PROPERTIES_LOOKUP; } /** * Returns a lookup which looks up values using a map. * <p> * If the map is null, then null will be returned from every lookup. * The map result object is converted to a string using toString(). * * @param map the map of keys to values, may be null * @return a lookup using the map, not null */ public static <V> StrLookup mapLookup(Map<String, V> map) { return new MapStrLookup<V>(map); } //----------------------------------------------------------------------- /** * Constructor. */ protected StrLookup() { super(); } /** * Looks up a String key to a String value. * <p> * The internal implementation may use any mechanism to return the value. * The simplest implementation is to use a Map. However, virtually any * implementation is possible. * <p> * For example, it would be possible to implement a lookup that used the * key as a primary key, and looked up the value on demand from the database * Or, a numeric based implementation could be created that treats the key * as an integer, increments the value and return the result as a string - * converting 1 to 2, 15 to 16 etc. * * @param key the key to be looked up, may be null * @return the matching value, null if no match */ public abstract String lookup(String key); //----------------------------------------------------------------------- /** * Lookup implementation that uses a Map. */ static class MapStrLookup<V> extends StrLookup { /** Map keys are variable names and value. */ private final Map<String, V> map; /** * Creates a new instance backed by a Map. * * @param map the map of keys to values, may be null */ MapStrLookup(Map<String, V> map) { this.map = map; } /** * Looks up a String key to a String value using the map. * <p> * If the map is null, then null is returned. * The map result object is converted to a string using toString(). * * @param key the key to be looked up, may be null * @return the matching value, null if no match */ @Override public String lookup(String key) { if (map == null) { return null; } Object obj = map.get(key); if (obj == null) { return null; } return obj.toString(); } } }
SpoonLabs/astor
examples/lang_39/src/java/org/apache/commons/lang3/text/StrLookup.java
Java
gpl-2.0
5,459
/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** @file storage/perfschema/table_esgs_by_user_by_event_name.cc Table EVENTS_STAGES_SUMMARY_BY_USER_BY_EVENT_NAME (implementation). */ #include "my_global.h" #include "my_pthread.h" #include "pfs_instr_class.h" #include "pfs_column_types.h" #include "pfs_column_values.h" #include "table_esgs_by_user_by_event_name.h" #include "pfs_global.h" #include "pfs_account.h" #include "pfs_visitor.h" THR_LOCK table_esgs_by_user_by_event_name::m_table_lock; static const TABLE_FIELD_TYPE field_types[]= { { { C_STRING_WITH_LEN("USER") }, { C_STRING_WITH_LEN("char(16)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("EVENT_NAME") }, { C_STRING_WITH_LEN("varchar(128)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("COUNT_STAR") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("SUM_TIMER_WAIT") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("MIN_TIMER_WAIT") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("AVG_TIMER_WAIT") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} }, { { C_STRING_WITH_LEN("MAX_TIMER_WAIT") }, { C_STRING_WITH_LEN("bigint(20)") }, { NULL, 0} } }; TABLE_FIELD_DEF table_esgs_by_user_by_event_name::m_field_def= { 7, field_types, 0, (uint*) 0 }; PFS_engine_table_share table_esgs_by_user_by_event_name::m_share= { { C_STRING_WITH_LEN("events_stages_summary_by_user_by_event_name") }, &pfs_truncatable_acl, table_esgs_by_user_by_event_name::create, NULL, /* write_row */ table_esgs_by_user_by_event_name::delete_all_rows, NULL, /* get_row_count */ 1000, /* records */ sizeof(pos_esgs_by_user_by_event_name), &m_table_lock, &m_field_def, false /* checked */ }; PFS_engine_table* table_esgs_by_user_by_event_name::create(void) { return new table_esgs_by_user_by_event_name(); } int table_esgs_by_user_by_event_name::delete_all_rows(void) { reset_events_stages_by_thread(); reset_events_stages_by_account(); reset_events_stages_by_user(); return 0; } table_esgs_by_user_by_event_name::table_esgs_by_user_by_event_name() : PFS_engine_table(&m_share, &m_pos), m_row_exists(false), m_pos(), m_next_pos() {} void table_esgs_by_user_by_event_name::reset_position(void) { m_pos.reset(); m_next_pos.reset(); } int table_esgs_by_user_by_event_name::rnd_init(bool scan) { m_normalizer= time_normalizer::get(stage_timer); return 0; } int table_esgs_by_user_by_event_name::rnd_next(void) { PFS_user *user; PFS_stage_class *stage_class; for (m_pos.set_at(&m_next_pos); m_pos.has_more_user(); m_pos.next_user()) { user= &user_array[m_pos.m_index_1]; if (user->m_lock.is_populated()) { stage_class= find_stage_class(m_pos.m_index_2); if (stage_class) { make_row(user, stage_class); m_next_pos.set_after(&m_pos); return 0; } } } return HA_ERR_END_OF_FILE; } int table_esgs_by_user_by_event_name::rnd_pos(const void *pos) { PFS_user *user; PFS_stage_class *stage_class; set_position(pos); DBUG_ASSERT(m_pos.m_index_1 < user_max); user= &user_array[m_pos.m_index_1]; if (! user->m_lock.is_populated()) return HA_ERR_RECORD_DELETED; stage_class= find_stage_class(m_pos.m_index_2); if (stage_class) { make_row(user, stage_class); return 0; } return HA_ERR_RECORD_DELETED; } void table_esgs_by_user_by_event_name ::make_row(PFS_user *user, PFS_stage_class *klass) { pfs_lock lock; m_row_exists= false; user->m_lock.begin_optimistic_lock(&lock); if (m_row.m_user.make_row(user)) return; m_row.m_event_name.make_row(klass); PFS_connection_stage_visitor visitor(klass); PFS_connection_iterator::visit_user(user, true, true, & visitor); if (! user->m_lock.end_optimistic_lock(&lock)) return; m_row_exists= true; m_row.m_stat.set(m_normalizer, & visitor.m_stat); } int table_esgs_by_user_by_event_name ::read_row_values(TABLE *table, unsigned char *buf, Field **fields, bool read_all) { Field *f; if (unlikely(! m_row_exists)) return HA_ERR_RECORD_DELETED; /* Set the null bits */ DBUG_ASSERT(table->s->null_bytes == 1); buf[0]= 0; for (; (f= *fields) ; fields++) { if (read_all || bitmap_is_set(table->read_set, f->field_index)) { switch(f->field_index) { case 0: /* USER */ m_row.m_user.set_field(f); break; case 1: /* EVENT_NAME */ m_row.m_event_name.set_field(f); break; default: /* 2, ... COUNT/SUM/MIN/AVG/MAX */ m_row.m_stat.set_field(f->field_index - 2, f); break; } } } return 0; }
ottok/mariadb-galera-10.0
storage/perfschema/table_esgs_by_user_by_event_name.cc
C++
gpl-2.0
5,462
<?php namespace Xms\Core; use ErrorException; use DOMNode; use DOMNodeList; use DOMElement; use DOMDocument; use Closure; /* * XMS - Online Web Development * * Copyright (c) 2010 Cezar Lucan cezar.lucan@aws-dms.com * Licensed under GPL license. * http://www.aws-dms.com * * Date: 2010-10-24 */ //0.47 ::append,::prepend,::replaceWith,::before,::after - removed support for ->check() //0.46 $GLOBALS["XMS_SERVER_CONSOLE"] now observable instance property Xms::XMS_SERVER_CONSOLE //0.45 ::has fixed to return array when $commit = false //0.40 ::context moved here; ::setContext() and ::getContext() //0.40 ::siblings //0.37 ::elements(), __invoke direct call to return $obj->q() //0.37: removed elements operations like ::bind(),.. from versions 0.34-36; use ::elements() instead //0.36 ::detachAllEventHandlers(), ::detachEventHandler() //0.35 ::trigger(),::on() //0.34 ::bind(),::unbind(),::unbindAll() to support same XmsDomElement methods //0.31 updated comments - minimal changes //0.30 ::filter() , ::all(), ::find() to accept additional parameters to invoke the callback //0.29 ::prop($name,$value) to change properties of DOMNodes; only works on pi() and text() like ::prop("data","SOME DATA") //0.27 2015-03-14: properly commented //0.24 2015-03-14: ::find($selector,$callback[,$optionalArg1,$optionalArg2,]) //0.20 2015-03-12: ::filter() , ::all() , ::add(), ::has(selector) and ::has(selector,commit), ::lastQuery //0.20 2015-03-12: old version of ::filter() removed, ::each() simplified //0.20 2015-02-28: ::addClass(), ::removeClass(), ::hasClass(), ::has() //0.18 2015-02-27 ::remove(), ::cloneResults() //0.16 2015-02-27 ::append(),::prepend(),::before(),::after(),::replace(),::replaceContent() argumente parsate cu normalizeOperationsInput: EX: append(string) sau append(DOMNode) sau append(DOMNodeList) sau append(array(string,domNode,DOMNodeList,array)) //0.14 2015-02-26 ::each() - if callback is closure it passes first argument as $this of the callback //0.14 2015-02-26 trows exception on ::q() and ::e() malformed xpath or context //0.14 2015-02-25 extends XmsOverload //0.13 2015-1-30: replaceContent fixed not append if document fragment is empty //0.12 ::removeAttributes() //0.12 removed copyElement() //0.12 returns attr value of first item of results if only attr name specified //0.12 removed cssq() and csse() //0.11-2013-06-01: fixed call time pass by reference for append, prepend lambda functions //0.10-2010-11-03: dirty output fixes //0.9: ::filter(xpath) - query on a clone of $this; //0.9: check , filter(function) - works, filter(xpath) - works //0.8: ::each() - now support multiple arguments; these will be transmitted to the function; first arg will be always $el /* * Abstract class providing extended xml functionality */ abstract class CommonXml extends XmsOverload { const version = "0.46"; const releaseDate = "2015-05-03"; public $doc; public $results = array(); public $xpath; public $lastQuery; protected $context; private $check; /** * executes xpath query over the xml document * * @param string $query * @param DOMNode $context - optional - the context node if needed * @return CommonXml */ final public function q($query = ".", $context = FALSE) { $this->lastQuery = $query; if (!$context) $this->results = $this->normalizeOperationsInput($this->xpath->query($query, $this->context)); else $this->results = $this->normalizeOperationsInput($this->xpath->query($query, $context)); $this->topmost()->XMS_SERVER_CONSOLE = get_class($this) . "::" . __FUNCTION__ . " executing xpath query\t" . $query . "\n\t" . sizeof($this->results) . " results \n"; if ($this->results === FALSE) { $this->results = array(); throw new ErrorException("\n Expression is malformed or the contextnode is invalid in " . __FUNCTION__ . " of " . get_class($this) . "\n"); } return $this; } /** * evaluates xpath query over the xml document * * @param string $query * @param DOMNode $context - optional - the context node if needed * @return CommonXml */ final public function e($query = ".", $context = FALSE) { $this->lastQuery = $query; if (!$context) $this->results = $this->normalizeOperationsInput($this->xpath->evaluate($query, $this->context)); else $this->results = $this->normalizeOperationsInput($this->xpath->evaluate($query, $context)); $this->topmost()->XMS_SERVER_CONSOLE = get_class($this) . "::" . __FUNCTION__ . " executing xpath query\t" . $query . "\n\t" . sizeof($this->results) . " results \n"; if ($this->results === FALSE) { $this->results = array(); throw new ErrorException("\n Expression is malformed or the contextnode is invalid in " . __FUNCTION__ . " of " . get_class($this) . "\n"); } return $this; } /** * if invoked directly after instance created, execute q method with given parameters * * @param DOMNode $context * @return CommonXml */ function __invoke() { return call_user_func_array(array( $this, "q" ), func_get_args()); } function __clone() { $this->results = array(); $this->check = null; $this->context = null; } /** * sets the default query cotext * * @param DOMNode $context * @return CommonXml */ final public function setContext(&$context) { $this->context = $context; return $this; } /** * retrieve the default query context * * @return DOMNode */ final public function getContext() { return $this->context; } /** * executes a callback for each result * if $callback is closure $this is the current DOMElement * * @param callback $callback * @param mixed optional $params - extra parameters to pass to the $callback * @return CommonXml */ final public function each($callback) { //TODO: schimb each cu while if (func_num_args() > 0) { $params = func_get_args(); if (is_callable($callback)) { if (sizeof($this->results) > 0) foreach ($this->results as $result) { //& de mai jos e important altfel avem warning; $params[0] = &$result; $this->topmost()->XMS_SERVER_CONSOLE = get_class($this) . "::" . __FUNCTION__ . " executing callback " . ($params[0] instanceof DOMNode ? "on " . $params[0]->nodeName : "") . "\n"; //daca este closure if (Utils::is_closure($callback)) { //if($callback instanceof Closure) //si este definit parametrul 0 (aka $el) if (gettype($params[0]) == "object" && $params[0] instanceof DOMNode) { //apeleaza funtia cu $this = $el $callback = $callback->bindTo($params[0]); $this->topmost()->XMS_SERVER_CONSOLE = get_class($this) . "::" . __FUNCTION__ . " binding callback to " . $params[0]->nodeName . "\n"; } } else { $this->topmost()->XMS_SERVER_CONSOLE = get_class($this) . "::" . __FUNCTION__ . " NOT a closure\n"; } $fres = call_user_func_array($callback, $params); if ($fres === FALSE) $this->topmost()->XMS_SERVER_CONSOLE = get_class($this) . "::" . __FUNCTION__ . " was NOT ABLE TO EXECUTE given callback\n"; } } else { $this->topmost()->XMS_SERVER_CONSOLE = get_class($this) . "::" . __FUNCTION__ . " ERROR executing callback: NONE CALLABLE\n"; } } else { $this->topmost()->XMS_SERVER_CONSOLE = get_class($this) . "::" . __FUNCTION__ . " NO callback supplied\n"; } return $this; } /** * executes a callback with paramaters $this->results * if $callback is closure $this is the CommonXml object that filter methods belongs to * * @param callback $callback * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function all($callback) { $params = func_get_args(); if (is_callable($callback)) { if (Utils::is_closure($callback)) $callback = $callback->bindTo($this); $params[0] = &$this->results; $checkForResults = call_user_func_array($callback, $params); if ($checkForResults === FALSE) $this->topmost()->XMS_SERVER_CONSOLE = get_class($this) . "::" . __FUNCTION__ . " callback could not be executed\n"; } return $this; } /** * executes $toCheck callback before executing code in below methods; $toCheck needs to return TRUE for method to execute * used in methods like append, perpend, before, after, text, attr, removeAttr, replace, replaceContent, text, removeChilds * * @param callback $toCheck * @return CommonXml */ final public function check($toCheck) { if (is_callable($toCheck)) $this->check = $toCheck; else $this->check = FALSE; return $this; } /** * reduces results to the ones that pass the test of the $callback; * $callback returns TRUE to keep the element; * $callback can be either function, lambda or closure * $callback only argument is current result * if $callback is closure $this is the CommonXml object that filter methods belongs to * * @param callback $callback ($el,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::filter;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function filter($callback) { $params = func_get_args(); if (is_callable($callback)) { if (Utils::is_closure($callback)) $callback = $callback->bindTo($this); $theyDo = []; foreach ($this->results as $result) { if ($result instanceof DOMNode) { $params[0] = &$result; $checkForResults = call_user_func_array($callback, $params); if ($checkForResults === TRUE) $theyDo[] = $result; else { $this->topmost()->XMS_SERVER_CONSOLE = get_class($this) . "::" . __FUNCTION__ . " either the callback could not be executed or the element did not passed the test\n"; } } } $this->results = $theyDo; } return $this; } /** * executes the given callback for all nodes given by selector in the context of each Xml::results * if callback is closure $this is the current DOMElement * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function find($selector, $callback) { $params = func_get_args(); if ($selector && is_callable($callback)) { //only executes below if we have a $selector and a callable $callback $selector = trim($selector); //trim whitespace if any foreach ($this->results as $result) { //for each result if ($result instanceof DOMNode) { //if is DOMNode $checkForResults = $this->xpath->query($selector, $result); //find nodes given by $selector in context $result if ($checkForResults === FALSE) //if query returns FALSE throw new ErrorException("\n Expression is malformed or invalid context " . __FUNCTION__ . " of " . get_class($this) . "\n"); else if ($checkForResults instanceof DOMNodeList && $checkForResults->length > 0) { //if we have nodes in context $params[1] = &$result; //second parameter of our callback is the contextNode we run the query to $checkForResults = $this->normalizeOperationsInput($checkForResults); foreach ($checkForResults as $subquery_result) { //for each node in context $params[0] = &$subquery_result; if (Utils::is_closure($callback)) $callback = $callback->bindTo($subquery_result); //if is closure bind it to the Xml call_user_func_array($callback, $params); //and execute the callback } } } } } return $this; } /** * filters the results with the ones having elements to match the given @$selector * * @param string $selector * @param bool $commit if TRUE - the results of the subquery replace the result used as context; if FALSE returns an array with nodes matching $selector * @return CommonXml */ final public function has($selector, $commit = FALSE) { if ($selector) { $selector = trim($selector); $theyDo = []; foreach ($this->results as $result) { if ($result instanceof DOMNode) { $checkForResults = $this->xpath->query($selector, $result); if ($checkForResults === FALSE) throw new ErrorException("\n Expression is malformed or invalid context " . __FUNCTION__ . " of " . get_class($this) . "\n"); else if ($checkForResults instanceof DOMNodeList && $checkForResults->length > 0) { if ($commit) { foreach ($checkForResults as $subquery_result) $theyDo[] = $subquery_result; } else $theyDo[] = $result; } } } } if ($commit) { $this->results = $theyDo; return $this; } else return $theyDo; } /** * retrieve the $index element of the results * if $callback is given run it for the $index element of the results and return $this * * @param integer $index * @param callback $callback ($el,$results,$param1,$param2,....){$this is the DOMNode if $callback is closure;$param1,$param2,... are the optional ones} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml * @return DOMNode */ final public function get($index, $callback = null) { if (is_callable($callback)) { $params = func_get_args(); if ($callback instanceof Closure) $callback = $callback->bindTo($this->results[$index]); $params[0] = &$this->results[$index]; $params[1] = &$this->results; call_user_func_array($callback, $params); return $this; } else { if ($this->results[$index] instanceof DOMNode) return $this->results[$index]; } } /** * find if current node is matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function is($selector, $callback = null) { if (!is_callable($callback)) $this->has("self::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "self::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find any descendants or self matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function descendantsAndSelf($selector, $callback = null) { if (!is_callable($callback)) $this->has("descendant-or-self::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "descendant-or-self::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find any descendants matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function descendants($selector, $callback = null) { if (!is_callable($callback)) $this->has("descendant::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "descendant::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find parent nodes, including self, matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function parentsAndSelf($selector, $callback = null) { if (!is_callable($callback)) $this->has("ancestor-or-self::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "ancestor-or-self::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find parent nodes matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function parents($selector, $callback = null) { if (!is_callable($callback)) $this->has("ancestor::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "ancestor::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find child nodes matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function children($selector, $callback = null) { if (!is_callable($callback)) $this->has("child::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "child::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find following nodes matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function following($selector, $callback = null) { if (!is_callable($callback)) $this->has("following::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "following::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find preceding nodes matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function preceding($selector, $callback = null) { if (!is_callable($callback)) $this->has("preceding::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "preceding::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find the attribute nodes matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function attribute($selector, $callback = null) { if (!is_callable($callback)) $this->has("attribute::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "attribute::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find next siblings matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function next($selector, $callback = null) { if (!is_callable($callback)) $this->has("following-sibling::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "following-sibling::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find prev siblings matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function prev($selector, $callback = null) { if (!is_callable($callback)) $this->has("preceding-sibling::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "preceding-sibling::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * find siblings matching given selector; if a callback is provided, run it for each result, otherwise commit changes in CommonXml::results * applies to CommonXml::results and not CommonXml::context * * @param string $selector * @param callback $callback ($el,$context,$param1,$param2,....){$this is the DOMNode;$param1,$param2,... are the optional ones of ::find;} * @param mixed $param1,$param2,... additional parameters to invoke the callback with; * @return CommonXml */ final public function siblings($selector, $callback = null) { if (!is_callable($callback)) $this->has("preceding-sibling::" . $selector . "|" . "following-sibling::" . $selector, TRUE); else { $params = func_get_args(); $params[0] = "preceding-sibling::" . $selector . "|" . "following-sibling::" . $selector; call_user_func_array(array( $this, "find" ), $params); } return $this; } /** * adds the results of xpath query for selector to existing set of results * * @param string $selector * @return CommonXml */ final public function add($selector) { if ($selector) { $selector = trim($selector); $newResults = $this->xpath->query($selector); if ($newResults instanceof DOMNodeList && $newResults->length > 0) foreach ($newResults as $result) { if ($result instanceof DOMNode) $this->results[] = $result; } } return $this; } /** * changes a native property of DOMNode if possible, for each results * * @param string $name * @param string $value * @return CommonXml */ final public function prop($name, $value) { if (!empty($name)) { $name = trim($name); foreach ($this->results as $result) { if ($result instanceof DOMNode) $result->$name = $value; } } return $this; } /** * filters the results to the ones having given class * * @param string $c * @return CommonXml */ final public function hasClass($c) { if (!empty($c)) { $c = trim($c); $theyDo = []; foreach ($this->results as $result) { if ($result instanceof DOMNode && method_exists($result, "hasAttribute")) if ($result->hasAttribute("class")) { $attrVals = preg_split("/[\s,]+/", $result->getAttribute("class")); foreach ($attrVals as $class) if ($class == $c) $theyDo[] = $result; } } $this->results = $theyDo; } return $this; } /** * removes given class * * @param string $c * @param string $glue - default space character; used to implode the class names * @return CommonXml */ final public function removeClass($c, $glue = " ") { if (!$this->removeClass_helper instanceof Closure) $this->removeClass_helper = function(&$el, $class, $g) { $cs = array(); if ($this instanceof DOMNode && method_exists($this, "hasAttribute")) if ($this->hasAttribute("class")) { $attrVals = preg_split("/[\s,]+/", $this->getAttribute("class")); foreach ($attrVals as $c) if ($class != $c) $cs[] = $c; $this->setAttribute("class", implode($g, $cs)); } }; if (!empty($c)) { $c = trim($c); $this->each($this->removeClass_helper, $c, $glue); } return $this; } /** * adds given class * * @param string $c * @param string $glue - default space character * @return CommonXml */ final public function addClass($c, $glue = " ") { if (!$this->addClass_helper instanceof Closure) $this->addClass_helper = function(&$el, $class, $g) { if ($this instanceof DOMNode && method_exists($this, "hasAttribute")) { if ($this->getAttribute("class")) $attrVals = preg_split("/[\s,]+/", $this->getAttribute("class")); else $attrVals = []; if (!in_array($class, $attrVals)) { $attrVals[] = $class; $this->setAttribute("class", implode($g, $attrVals)); } } }; if (!empty($c)) { $c = trim($c); $this->each($this->addClass_helper, $c, $glue); } return $this; } /** * returns class instance for 2 arguments or attr value for one argument (attr name) * * @param string $name * @param string $value * @return CommonXml if both $name and $value are provided; * @return string if only $nameis provided */ final public function attr() { $attrName = func_get_arg(0); $attrValue = func_get_arg(1); if (!$this->attr_helper instanceof Closure) $this->attr_helper = function(&$el, $attrName, $attrValue) { if ($el->nodeType == 1) $el->setAttribute($attrName, $attrValue); }; if (func_num_args() == 2) { $this->each($this->attr_helper, $attrName, $attrValue); return $this; } else if (func_num_args() == 1) { if (gettype($this->get(0)) == "object" && $this->get(0) instanceof DOMNode) if ($this->get(0)->nodeType == 1) return $this->get(0)->getAttribute($attrName); } } /** * removes given attribute * * @param string $name * @return CommonXml */ final public function removeAttr($aN) { if (func_num_args() >= 1) { if (!$removeAttr_helper instanceof Closure) $removeAttr_helper = function(&$el, $attrName) { if ($el->nodeType == 1) if ($el->hasAttribute($attrName)) $el->removeAttribute($attrName); }; $this->each($removeAttr_helper, $aN); } return $this; } /** * removes all atributes * * @return CommonXml */ final public function removeAttributes() { if (!$this->removeAttributes_helper instanceof Closure) $this->removeAttributes_helper = function(&$el) { if ($el->nodeType == 1) while ($el->hasAttributes()) $el->removeAttributeNode($el->attributes->item(0)); }; $this->each($this->removeAttributes_helper, FALSE); return $this; } /** * creates an array of DOMNodes * * @param mixed $input - can be either string, DOMNode, DOMNodeList, array of them * @return array */ final public function normalizeOperationsInput($input) { $output = array(); $doc = $this->doc; if (sizeof(func_num_args()) > 0) { //folosesc DOMDocument daca a fost dat ca parametru al functiei if (sizeof(func_num_args()) > 1) if (!func_get_arg(1) instanceof DOMDocument) $doc = func_get_arg(1); switch (gettype($input)) { case "string" : //daca input ="" este tot string if (!empty($input)) { $df = $doc->createDocumentFragment(); $df->appendXML($input); $output[] = $df; } break; case "object" : //DOMNodeList DOMNode if ($input instanceof DOMNode) { $output[] = $input; } else if ($input instanceof DOMNodeList) { foreach ($input as $node) $output[] = $node; } break; case "array" : foreach ($input as $v) $output = array_merge($output, $this->normalizeOperationsInput($v)); break; } } return $output; } /** * clones all nodes in results * * @return array */ final public function cloneResults() { $output = []; foreach ($this->results as $res) $output[] = $res->cloneNode(TRUE); return $output; } /** * appends to all nodes in results * * @param mixed - can be either string, DOMNode, DOMNodeList, array of them * @return CommonXml */ final public function append($with) { if (func_num_args() >= 1) { $nodes = $this->normalizeOperationsInput($with); $append_helper = function(&$el, $df, $cloneNode) { if ($cloneNode) { if (method_exists($df, "cloneNode")) $newdf = $df->cloneNode(TRUE); else $newdf = $df; } else $newdf = $df; if ($newdf->ownerDocument !== $el->ownerDocument) if ($newdf instanceof DOMNode) $newdf = $el->ownerDocument->importNode($newdf, TRUE); if ($newdf instanceof DOMNode) $el->appendChild($newdf); }; foreach ($nodes as $node) $this->each($append_helper, $node, (sizeof($this->results) > 1 ? TRUE : FALSE)); } return $this; } /** * prepends to all nodes in results * * @param mixed - can be either string, DOMNode, DOMNodeList, array of them * @return CommonXml */ final public function prepend($with) { if (func_num_args() >= 1) { $nodes = $this->normalizeOperationsInput($with); if (!$prepend_helper instanceof Closure) $prepend_helper = function(&$el, $df, $cloneNode) { if ($cloneNode) { if (method_exists($df, "cloneNode")) $newdf = $df->cloneNode(TRUE); else $newdf = $df; } else $newdf = $df; if ($newdf->ownerDocument !== $el->ownerDocument) if ($newdf instanceof DOMNode) $newdf = $el->ownerDocument->importNode($newdf, TRUE); if ($el->hasChildNodes()) { if ($newdf instanceof DOMNode) $el->insertBefore($newdf, $el->firstChild); } else { if ($newdf instanceof DOMNode) $el->appendChild($newdf); } }; foreach ($nodes as $node) $this->each($prepend_helper, $node, (sizeof($this->results) > 1 ? TRUE : FALSE)); } return $this; } /** * inserts before all nodes in results * * @param $with - mixed - can be either string, DOMNode, DOMNodeList, array of them * @return CommonXml */ final public function before($with) { if (func_num_args() >= 1) { $nodes = $this->normalizeOperationsInput($with); if (!$before_helper instanceof Closure) $before_helper = function(&$el, $df, $cloneNode) { if ($cloneNode) { if (method_exists($df, "cloneNode")) $newdf = $df->cloneNode(TRUE); else $newdf = $df; } else $newdf = $df; if ($newdf->ownerDocument !== $el->ownerDocument) if ($newdf instanceof DOMNode) $newdf = $el->ownerDocument->importNode($newdf, TRUE); if ($newdf instanceof DOMNode) $el->parentNode->insertBefore($newdf, $el); }; foreach ($nodes as $node) $this->each($before_helper, $node, (sizeof($this->results) > 1 ? TRUE : FALSE)); } return $this; } /** * inserts after all nodes in results * * @param $with - mixed - can be either string, DOMNode, DOMNodeList, array of them * @return CommonXml */ final public function after($with) { if (func_num_args() >= 1) { $nodes = $this->normalizeOperationsInput($with); if (!$after_helper instanceof Closure) $after_helper = function(&$el, $df, $cloneNode) { if ($cloneNode) { if (method_exists($df, "cloneNode")) $newdf = $df->cloneNode(TRUE); else $newdf = $df; } else $newdf = $df; if ($newdf->ownerDocument !== $el->ownerDocument) if ($newdf instanceof DOMNode) $newdf = $el->ownerDocument->importNode($newdf, TRUE); if ($newdf instanceof DOMNode) $el->parentNode->insertBefore($newdf, $el->nextSibling); }; foreach ($nodes as $node) $this->each($after_helper, $node, (sizeof($this->results) > 1 ? TRUE : FALSE)); } return $this; } /** * replaces all nodes in results * * @param mixed - can be either string, DOMNode, DOMNodeList, array of them * @return CommonXml */ final public function replace() { if (func_num_args() == 1) { $df = $this->doc->createDocumentFragment(); $nodes = $this->normalizeOperationsInput(func_get_arg(0)); //creez document fragment din arg(0); fac clona si import daca e nevoie if (sizeof($this->results) > 1) //daca sunt mai multe elemente in results facem clone foreach ($nodes as $node) if ($node->ownerDocument === $this->doc) $df->appendChild($node->cloneNode(TRUE)); else $df->appendChild($this->doc->importNode($node->cloneNode(TRUE), TRUE)); else //avem doar un singur resultat al query foreach ($nodes as $node) if ($node->ownerDocument === $this->doc) $df->appendChild($node); else $df->appendChild($this->doc->importNode($node, TRUE)); //cu df creat, fac replace, clona daca sunt mai multe results df initial daca results->length = 1 if (sizeof($this->results) > 1) foreach ($this->results as $tor) $tor->parentNode->replaceChild($df->cloneNode(TRUE), $tor); else foreach ($this->results as $tor) $tor->parentNode->replaceChild($df, $tor); } return $this; } /** * replaces content of all nodes in results * * @param $with - mixed - can be either string, DOMNode, DOMNodeList, array of them * @return CommonXml */ final public function replaceContent($with) { if (func_num_args() >= 1) { $nodes = $this->normalizeOperationsInput($with); if (!$replaceContent_helper_removeContent instanceof Closure) $replaceContent_helper_removeContent = function(&$el) { while ($el->hasChildNodes()) $el->removeChild($el->firstChild); foreach ($nodes as $node) $el->appendChild($node->cloneNode(TRUE)); }; $this->each($replaceContent_helper_removeContent); } return $this; } /** * removes child nodes of all nodes in results * * @return CommonXml */ final public function removeChilds() { foreach ($this->results as $tor) if (method_exists($tor, "hasChildNodes")) while ($tor->hasChildNodes()) $tor->removeChild($tor->childNodes->item(0)); return $this; } /** * removes all nodes in results * * @return CommonXml */ final public function remove() { $this->each(function() { $this->parentNode->removeChild($this); }); return $this; } /** * retrive or set the text content of all nodes in results * * @param string to set the text * @return CommonXml */ final public function text() { if (func_num_args() == 1) { $textContent = func_get_arg(0); if (!$this->text_helper instanceof Closure) $this->text_helper = function(&$el, $check, $textContent) { if (!$check || ($check && is_callable($check) && call_user_func($check, $el))) { $done = false; if ($el->nodeType == XML_ELEMENT_NODE) { if ($el->hasChildNodes()) foreach ($el->childNodes as $child) if ($child->nodeType == XML_TEXT_NODE) { $child->replaceData(0, strlen($child->wholeText), $textContent); $done = true; } if (!$done) $el->appendChild($el->ownerDocument->createTextNode($textContent)); $done = false; } } }; if (function_exists($this->check)) $this->each($this->text_helper, $this->check, $textContent); else $this->each($this->text_helper, FALSE, $textContent); return $this; } else { $toReturn = ""; foreach ($this->results as $result) { //elemente if ($result->nodeType == XML_ELEMENT_NODE) $toReturn .= $result->textContent; } return $toReturn; } } /** * get a string of concatenated source of all DOMElements in results * * @param mixed - can be either string, DOMNode, DOMNodeList, array of them * @return CommonXml */ final public function resultsAsSource() { $toReturn = ""; foreach ($this->results as $result) { //elemente if ($result->nodeType == XML_ELEMENT_NODE) $toReturn .= $result->C14N(); } return $toReturn; } /** * get a string with concatenated source of all nodes in results * * @return string */ final public function xml() { $toReturn = ""; foreach ($this->results as $result) $toReturn .= $result->C14N(); return $toReturn; } /** * retrieve a documentFragment containing all nodes in results * * @return DOMDocumentFragment */ final public function resultsAsDocumentFragment() { $docFragment = $this->doc->createDocumentFragment(); foreach ($this->results as $result) $docFragment->appendChild($result); return $docFragment; } /** * use to call a method of a DOMElement with given args * * @param string $method * @param array $args - method arguments * @return CommonXml */ final public function elements($method, $args = array()) { if (!empty($method)) foreach ($this->results as $result) if ($result instanceof DOMElement) if (method_exists($result, $method)) call_user_func_array(array( $result, $method ), $args); else { trigger_error(get_class($result) . "::$method doesn't exists; trying if any callable property is available", E_USER_WARNING); if (is_callable(array( $result, $method ))) { trigger_error(get_class($result) . "::$method callable property found, executing", E_USER_NOTICE); call_user_func_array(array( $result, $method ), $args); } else trigger_error(get_class($result) . "::$method callable property not found either", E_USER_WARNING); } return $this; } /** * get the document root node * * @return DOMNode */ final public function getRootElement() { return $this->doc->documentElement; } /** * retrieve the results as array to a variable * * @param array $destination - name of the variable * @return CommonXml */ final public function to(&$destination) { $destination = $this->results; return $this; } /** * retrieve the first element of results * * @return DOMNode or FALSE */ final public function first() { if (gettype($this->results) == "array" && sizeof($this->results) > 0) { if (gettype($this->get(0)) == "object" && $this->get(0) instanceof DOMNode) return $this->get(0); } else return FALSE; } /** * retrieve the last element of results * * @return DOMNode or FALSE */ final public function last() { if (gettype($this->results) == "array" && sizeof($this->results) > 0) { if (gettype($this->get(sizeof($this->results) - 1)) == "object" && $this->get(sizeof($this->results) - 1) instanceof DOMNode) return $this->get(sizeof($this->results) - 1); } else return FALSE; } public function parentVersion() { return parent::version; } public function __version__() { return array( __CLASS__ => self::version, get_parent_class($this) => parent::version ); } }
igorwwwwwwwwwwwwwwwwwwww/test
includes/Xms/Core/CommonXml.php
PHP
gpl-2.0
49,814
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_CurrencySymbol * @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Currency Symbol helper * * @category Mage * @package Mage_CurrencySymbol * @author Magento Core Team <core@magentocommerce.com> */ class Mage_CurrencySymbol_Helper_Data extends Mage_Core_Helper_Data { /** * Get currency display options * * @param string $baseCode * @return array */ public function getCurrencyOptions($baseCode) { $currencyOptions = array(); $currencySymbol = Mage::getModel('currencysymbol/system_currencysymbol'); if($currencySymbol) { $customCurrencySymbol = $currencySymbol->getCurrencySymbol($baseCode); if ($customCurrencySymbol) { $currencyOptions['symbol'] = $customCurrencySymbol; $currencyOptions['display'] = Zend_Currency::USE_SYMBOL; } } return $currencyOptions; } }
miguelangelramirez/magento.dev
app/code/core/Mage/CurrencySymbol/Helper/Data.php
PHP
gpl-2.0
1,841
/* This file is part of the KDE project * Copyright (C) 2009 Jan Hambrecht <jaham@gmx.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "TestPointMergeCommand.h" #include "KoPathPointMergeCommand.h" #include "KoPathShape.h" #include "KoPathPoint.h" #include "KoPathPointData.h" #include <KDebug> void TestPointMergeCommand::closeSingleLinePath() { KoPathShape path1; path1.moveTo(QPointF(40, 0)); path1.lineTo(QPointF(60, 0)); path1.lineTo(QPointF(60, 30)); path1.lineTo(QPointF(0, 30)); path1.lineTo(QPointF(0, 0)); path1.lineTo(QPointF(20, 0)); KoPathPointIndex index1(0,0); KoPathPointIndex index2(0,5); KoPathPointData pd1(&path1, index1); KoPathPointData pd2(&path1, index2); KoPathPoint * p1 = path1.pointByIndex(index1); KoPathPoint * p2 = path1.pointByIndex(index2); QVERIFY(!path1.isClosedSubpath(0)); QCOMPARE(path1.subpathPointCount(0), 6); QCOMPARE(p1->point(), QPointF(40,0)); QCOMPARE(p2->point(), QPointF(20,0)); KoPathPointMergeCommand cmd1(pd1,pd2); cmd1.redo(); QVERIFY(path1.isClosedSubpath(0)); QCOMPARE(path1.subpathPointCount(0), 5); QCOMPARE(p2->point(), QPointF(30,0)); cmd1.undo(); QVERIFY(!path1.isClosedSubpath(0)); QCOMPARE(path1.subpathPointCount(0), 6); QCOMPARE(p1->point(), QPointF(40,0)); QCOMPARE(p2->point(), QPointF(20,0)); KoPathPointMergeCommand cmd2(pd2,pd1); cmd2.redo(); QVERIFY(path1.isClosedSubpath(0)); QCOMPARE(path1.subpathPointCount(0), 5); QCOMPARE(p2->point(), QPointF(30,0)); cmd2.undo(); QVERIFY(!path1.isClosedSubpath(0)); QCOMPARE(path1.subpathPointCount(0), 6); QCOMPARE(p1->point(), QPointF(40,0)); QCOMPARE(p2->point(), QPointF(20,0)); } void TestPointMergeCommand::closeSingleCurvePath() { KoPathShape path1; path1.moveTo(QPointF(40, 0)); path1.curveTo(QPointF(60, 0), QPointF(60,0), QPointF(60,60)); path1.lineTo(QPointF(0, 60)); path1.curveTo(QPointF(0, 0), QPointF(0,0), QPointF(20,0)); KoPathPointIndex index1(0,0); KoPathPointIndex index2(0,3); KoPathPointData pd1(&path1, index1); KoPathPointData pd2(&path1, index2); KoPathPoint * p1 = path1.pointByIndex(index1); KoPathPoint * p2 = path1.pointByIndex(index2); QVERIFY(!path1.isClosedSubpath(0)); QCOMPARE(path1.subpathPointCount(0), 4); QCOMPARE(p1->point(), QPointF(40,0)); QVERIFY(!p1->activeControlPoint1()); QCOMPARE(p2->point(), QPointF(20,0)); QVERIFY(!p2->activeControlPoint2()); KoPathPointMergeCommand cmd1(pd1,pd2); cmd1.redo(); QVERIFY(path1.isClosedSubpath(0)); QCOMPARE(path1.subpathPointCount(0), 3); QCOMPARE(p2->point(), QPointF(30,0)); QVERIFY(p2->activeControlPoint1()); QVERIFY(p2->activeControlPoint2()); cmd1.undo(); QVERIFY(!path1.isClosedSubpath(0)); QCOMPARE(path1.subpathPointCount(0), 4); QCOMPARE(p1->point(), QPointF(40,0)); QVERIFY(!p1->activeControlPoint1()); QCOMPARE(p2->point(), QPointF(20,0)); QVERIFY(!p2->activeControlPoint2()); KoPathPointMergeCommand cmd2(pd2,pd1); cmd2.redo(); QVERIFY(path1.isClosedSubpath(0)); QCOMPARE(path1.subpathPointCount(0), 3); QCOMPARE(p2->point(), QPointF(30,0)); QVERIFY(p2->activeControlPoint1()); QVERIFY(p2->activeControlPoint2()); cmd2.undo(); QVERIFY(!path1.isClosedSubpath(0)); QCOMPARE(path1.subpathPointCount(0), 4); QCOMPARE(p1->point(), QPointF(40,0)); QVERIFY(!p1->activeControlPoint1()); QCOMPARE(p2->point(), QPointF(20,0)); QVERIFY(!p2->activeControlPoint2()); } void TestPointMergeCommand::connectLineSubpaths() { KoPathShape path1; path1.moveTo(QPointF(0,0)); path1.lineTo(QPointF(10,0)); path1.moveTo(QPointF(20,0)); path1.lineTo(QPointF(30,0)); KoPathPointIndex index1(0,1); KoPathPointIndex index2(1,0); KoPathPointData pd1(&path1, index1); KoPathPointData pd2(&path1, index2); QCOMPARE(path1.subpathCount(), 2); QCOMPARE(path1.pointByIndex(index1)->point(), QPointF(10,0)); QCOMPARE(path1.pointByIndex(index2)->point(), QPointF(20,0)); KoPathPointMergeCommand cmd1(pd1, pd2); cmd1.redo(); QCOMPARE(path1.subpathCount(), 1); QCOMPARE(path1.pointByIndex(index1)->point(), QPointF(15,0)); cmd1.undo(); QCOMPARE(path1.subpathCount(), 2); QCOMPARE(path1.pointByIndex(index1)->point(), QPointF(10,0)); QCOMPARE(path1.pointByIndex(index2)->point(), QPointF(20,0)); KoPathPointMergeCommand cmd2(pd2, pd1); cmd2.redo(); QCOMPARE(path1.subpathCount(), 1); QCOMPARE(path1.pointByIndex(index1)->point(), QPointF(15,0)); cmd2.undo(); QCOMPARE(path1.subpathCount(), 2); QCOMPARE(path1.pointByIndex(index1)->point(), QPointF(10,0)); QCOMPARE(path1.pointByIndex(index2)->point(), QPointF(20,0)); } void TestPointMergeCommand::connectCurveSubpaths() { KoPathShape path1; path1.moveTo(QPointF(0,0)); path1.curveTo(QPointF(20,0),QPointF(0,20),QPointF(20,20)); path1.moveTo(QPointF(50,0)); path1.curveTo(QPointF(30,0), QPointF(50,20), QPointF(30,20)); KoPathPointIndex index1(0,1); KoPathPointIndex index2(1,1); KoPathPointData pd1(&path1, index1); KoPathPointData pd2(&path1, index2); QCOMPARE(path1.subpathCount(), 2); QCOMPARE(path1.pointByIndex(index1)->point(), QPointF(20,20)); QCOMPARE(path1.pointByIndex(index1)->controlPoint1(), QPointF(0,20)); QCOMPARE(path1.pointByIndex(index2)->point(), QPointF(30,20)); QCOMPARE(path1.pointByIndex(index2)->controlPoint1(), QPointF(50,20)); QVERIFY(path1.pointByIndex(index1)->activeControlPoint1()); QVERIFY(!path1.pointByIndex(index1)->activeControlPoint2()); KoPathPointMergeCommand cmd1(pd1, pd2); cmd1.redo(); QCOMPARE(path1.subpathCount(), 1); QCOMPARE(path1.pointByIndex(index1)->point(), QPointF(25,20)); QCOMPARE(path1.pointByIndex(index1)->controlPoint1(), QPointF(5,20)); QCOMPARE(path1.pointByIndex(index1)->controlPoint2(), QPointF(45,20)); QVERIFY(path1.pointByIndex(index1)->activeControlPoint1()); QVERIFY(path1.pointByIndex(index1)->activeControlPoint2()); cmd1.undo(); QCOMPARE(path1.subpathCount(), 2); QCOMPARE(path1.pointByIndex(index1)->point(), QPointF(20,20)); QCOMPARE(path1.pointByIndex(index1)->controlPoint1(), QPointF(0,20)); QCOMPARE(path1.pointByIndex(index2)->point(), QPointF(30,20)); QCOMPARE(path1.pointByIndex(index2)->controlPoint1(), QPointF(50,20)); QVERIFY(path1.pointByIndex(index1)->activeControlPoint1()); QVERIFY(!path1.pointByIndex(index1)->activeControlPoint2()); KoPathPointMergeCommand cmd2(pd2, pd1); cmd2.redo(); QCOMPARE(path1.subpathCount(), 1); QCOMPARE(path1.pointByIndex(index1)->point(), QPointF(25,20)); QCOMPARE(path1.pointByIndex(index1)->controlPoint1(), QPointF(5,20)); QCOMPARE(path1.pointByIndex(index1)->controlPoint2(), QPointF(45,20)); QVERIFY(path1.pointByIndex(index1)->activeControlPoint1()); QVERIFY(path1.pointByIndex(index1)->activeControlPoint2()); cmd2.undo(); QCOMPARE(path1.subpathCount(), 2); QCOMPARE(path1.pointByIndex(index1)->point(), QPointF(20,20)); QCOMPARE(path1.pointByIndex(index1)->controlPoint1(), QPointF(0,20)); QCOMPARE(path1.pointByIndex(index2)->point(), QPointF(30,20)); QCOMPARE(path1.pointByIndex(index2)->controlPoint1(), QPointF(50,20)); QVERIFY(path1.pointByIndex(index1)->activeControlPoint1()); QVERIFY(!path1.pointByIndex(index1)->activeControlPoint2()); } QTEST_MAIN(TestPointMergeCommand) #include <TestPointMergeCommand.moc>
wyuka/calligra
libs/flake/tests/TestPointMergeCommand.cpp
C++
gpl-2.0
8,389
/* SESC: Super ESCalar simulator Copyright (C) 2003 University of Illinois. Contributed by Jose Renau Milos Prvulovic This file is part of SESC. SESC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. SESC 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 SESC; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "RunningProcs.h" #include "GProcessor.h" #ifdef SESC_THERM #include "ReportTherm.h" #endif #ifdef TASKSCALAR #include "TaskContext.h" #endif RunningProcs::RunningProcs() { stayInLoop=true; } void RunningProcs::finishWorkNow() { stayInLoop=false; #ifdef SESC_THERM ReportTherm::stopCB(); #endif workingList.clear(); startProc =0; } void RunningProcs::workingListRemove(GProcessor *core) { ProcessorMultiSet::iterator availIt=availableProcessors.find(core); if (availIt==availableProcessors.end()) availableProcessors.insert(core); if (core->hasWork()) return; bool found=false; for(size_t i=0;i<workingList.size();i++) { if (workingList[i] == core) { found = true; continue; }else if (found) { I(i>0); workingList[i-1] = workingList[i]; } } workingList.pop_back(); startProc =0; stayInLoop=!workingList.empty(); } void RunningProcs::workingListAdd(GProcessor *core) { ProcessorMultiSet::iterator availIt=availableProcessors.find(core); if (availIt!=availableProcessors.end()) availableProcessors.erase(availIt); // TODO: Ein? I(core->hasWork()); for(size_t i=0;i<workingList.size();i++) { if (workingList[i] == core) return; } workingList.push_back(core); } void RunningProcs::run() { I(cpuVector.size() > 0 ); IS(currentCPU = 0); do{ if ( workingList.empty() ) { EventScheduler::advanceClock(); } #ifdef TASKSCALAR HVersionDomain::tryPropagateSafeTokenAll(); #endif while (hasWork()) { stayInLoop=true; startProc = 0; do{ // Loop duplicated so round-robin fetch starts on different // processor each cycle <><> for(size_t i=startProc ; i < workingList.size() ; i++) { if (workingList[i]->hasWork()) { currentCPU = workingList[i]; currentCPU->advanceClock(); }else{ workingListRemove(workingList[i]); } } for(size_t i=0 ; i < startProc ; i++) { if (workingList[i]->hasWork()) { currentCPU = workingList[i]; currentCPU->advanceClock(); }else{ workingListRemove(workingList[i]); } } startProc++; if (startProc >= workingList.size()) startProc = 0; IS(currentCPU = 0); EventScheduler::advanceClock(); }while(stayInLoop); #ifdef SESC_THERM ReportTherm::stopCB(); #endif } }while(!EventScheduler::empty()); } void RunningProcs::makeRunnable(ProcessId *proc) { // The process must be in the InvalidState I(proc->getState()==InvalidState); // Now the process is runnable (but still not running) ProcessId *victimProc=proc->becomeReady(); // Get the CPU where the process would like to run CPU_t cpu=proc->getCPU(); // If there is a preferred CPU, try to schedule there if(cpu>=0){ // Get the GProcessor of the CPU GProcessor *core=getProcessor(cpu); // Are there available flows on this CPU if(core->availableFlows()){ // There is an available flow, grab it switchIn(cpu,proc); return; } } // Could not run the process on the cpu it wanted // If the process is not pinned to that processor, try to find another cpu if(!proc->isPinned()){ // Find an available processor GProcessor *core=getAvailableProcessor(); // If available processor found, run there if(core){ switchIn(core->getId(),proc); return; } } // Could not run on an available processor // If there is a process to evict, switch it out and switch the new one in its place if(victimProc){ I(victimProc->getState()==RunningState); // get the processor where victim process is running cpu=victimProc->getCPU(); switchOut(cpu, victimProc); switchIn(cpu,proc); victimProc->becomeNonReady(); makeRunnable(victimProc); } // No free processor, no process to evict // The new process has to wait its turn } void RunningProcs::makeNonRunnable(ProcessId *proc) { // It should still be running or ready I((proc->getState()==RunningState)||(proc->getState()==ReadyState)); // If it is still running, remove it from the processor if(proc->getState()==RunningState){ // Find the CPU where it is running CPU_t cpu=proc->getCPU(); // Remove it from there switchOut(cpu, proc); // Set the state to InvalidState to make the process non-runnable proc->becomeNonReady(); // Find another process to run on this cpu ProcessId *newProc=ProcessId::queueGet(cpu); // If a process has been found, switch it in if(newProc){ switchIn(cpu,newProc); } }else{ // Just set the state to InvalidState to make it non-runnable proc->becomeNonReady(); } } void RunningProcs::setProcessor(CPU_t cpu, GProcessor *newCore) { if(cpu >= (CPU_t)size()) cpuVector.resize(cpu+1); GProcessor *oldCore=cpuVector[cpu]; cpuVector[cpu]=newCore; // Is there was an old core in this slot if(oldCore){ // Erase all instances of the old core from the available multiset size_t erased=availableProcessors.erase(oldCore); // Check whether we erased the right number of entries I(oldCore->getMaxFlows()==erased); } // If there is a new core in this slot if(newCore){ // Insert the new core into the available mulstiset // once for each of its available flows for(size_t i=0;i<newCore->getMaxFlows();i++) availableProcessors.insert(newCore); } #ifdef TRACE_DRIVEN // in trace-driven mode, all processor must have work in the beggining workingListAdd(newCore); #endif } void RunningProcs::switchIn(CPU_t id, ProcessId *proc) { GProcessor *core=getProcessor(id); workingListAdd(core); proc->switchIn(id); #ifdef TS_STALL core->setStallUntil(globalClock+5); #endif core->switchIn(proc->getPid()); // Must be the last thing because it can generate a switch } void RunningProcs::switchOut(CPU_t id, ProcessId *proc) { GProcessor *core=getProcessor(id); Pid_t pid = proc->getPid(); proc->switchOut(core->getAndClearnGradInsts(pid), core->getAndClearnWPathInsts(pid)); core->switchOut(pid); workingListRemove(core); } GProcessor *RunningProcs::getAvailableProcessor(void) { // Get the first processor in the avaialable multiset ProcessorMultiSet::iterator availIt=availableProcessors.begin(); if(availIt==availableProcessors.end()) { //UGLY UGLY fix for the bug, i'll fix it soon. --luis for(unsigned cpuId = 0; cpuId < size(); cpuId++) { if(getProcessor(cpuId)->availableFlows() > 0) return getProcessor(cpuId); } return 0; } // SMTs have multiple available processors. Give more priority to // empty cpus GProcessor *gproc = *availIt; while ((*availIt)->getMaxFlows() > (*availIt)->availableFlows()) { availIt++; if (availIt == availableProcessors.end()) return gproc; } I(availIt != availableProcessors.end()); return *availIt; }
dilawar/sesc
src_without_LF/libcore/RunningProcs.cpp
C++
gpl-2.0
7,893
<? include_once("lib/security_incident_lib.php"); include_once("lib/security_incident_classification_lib.php"); include_once("lib/security_services_lib.php"); include_once("lib/security_incident_service_lib.php"); include_once("lib/general_classification_lib.php"); include_once("lib/security_incident_status_lib.php"); include_once("lib/site_lib.php"); include_once("lib/tp_lib.php"); include_once("lib/asset_lib.php"); $section = $_GET["section"]; $subsection = $_GET["subsection"]; $action = $_GET["action"]; $security_incident_id = $_GET["security_incident_id"]; $base_url_list = build_base_url($section,"security_incident_list"); if (is_numeric($security_incident_id)) { $security_incident_item = lookup_security_incident("security_incident_id",$security_incident_id); } ?> <section id="content-wrapper"> <h3>Edit or Create a Security Incidents</h3> <span class="description">Use this form to create or edit Security Incidents</span> <div class="tab-wrapper"> <ul class="tabs"> <li class="first active"> <a href="tab1">General</a> <span class="right"></span> </li> </ul> <div class="tab-content"> <div class="tab" id="tab1"> <? echo " <form name=\"edit\" method=\"GET\" action=\"$base_url_list\">"; ?> <label for="name">Security Incident Title</label> <span class="description">Give the Security Incident a title, name or code so it's easily identified on the list list menu</span> <? echo " <input type=\"text\" class=\"filter-text\" name=\"security_incident_title\" id=\"security_incident_title\" value=\"$security_incident_item[security_incident_title]\"/>";?> <label for="description">Incident Description</label> <span class="description">Describe the Security Incident in detail (when, what, where, why, whom, how).</span> <? echo "<textarea name=\"security_incident_description\" class=\"filter-text\">$security_incident_item[security_incident_description]</textarea>";?> <label for="legalType">Third Parties Affected</label> <span class="description"></span> <select name="security_incident_tp_id" id="" class="chzn-select"> <option value="-1">Select the affected Third Party (If any)</option> <? list_drop_menu_tp($security_incident_item[security_incident_tp_id],"tp_name"); ?> </select> <label for="legalType">Incident Classification</label> <span class="description"></span> <select name="security_incident_classification_id" id="" class="chzn-select"> <option value="-1">Select the Incident Classification</option> <? list_drop_menu_security_incident_classification($security_incident_item[security_incident_classification_id],"security_incident_classification_id"); ?> </select> <label for="legalType">Compromised Asset</label> <span class="description">Describe an asset from the list of registered asset that best represents the assets being affected by this incident</span> <select name="security_incident_compromised_asset_id" id="" class="chzn-select"> <option value="-1">Select an Asset</option> <? list_drop_menu_asset($security_incident_item[security_incident_compromised_asset_id],"asset_id"); ?> </select> <label for="legalType">Compensating Controls</label> <span class="description">Select those controls involved on this incident</span> <select name="security_incident_service[]" id="" class="chzn-select" multiple="multiple"> <option value="-1">Select one or more Controls...</option> <? $pre_selected_security_services_list = list_security_incident_service_join(" WHERE security_incident_service_incident_id = \"$security_incident_item[security_incident_id]\""); $pre_selected_items = array(); foreach($pre_selected_security_services_list as $pre_selected_security_services_item) { array_push($pre_selected_items,$pre_selected_security_services_item[security_incident_service_service_id]); } list_drop_menu_security_services($pre_selected_items,"security_services_name"); ?> </select> <label for="description">Security Incident Owner</label> <span class="description">Describe who is assigned on this incident and is responsible for it's treatment</span> <? echo "<input type=\"text\" class=\"filter-text\" name=\"security_incident_owner_id\" id=\"security_incident_owner\" value=\"$security_incident_item[security_incident_owner_id]\"/>";?> <label for="description">Security Incident Reporter</label> <span class="description">Describe who reported the incident</span> <? echo "<input type=\"text\" class=\"filter-text\" name=\"security_incident_reporter_id\" id=\"security_incident_owner\" value=\"$security_incident_item[security_incident_reporter_id]\"/>";?> <label for="description">Security Incident Victim</label> <span class="description">Describe who was involved on this incident</span> <? echo "<input type=\"text\" class=\"filter-text\" name=\"security_incident_victim_id\" id=\"security_incident_victim_id\" value=\"$security_incident_item[security_incident_victim_id]\"/>";?> <label for="description">Security Incident Open Date</label> <span class="description">Describe the time when the Incident has been reported</span> <? echo "<input type=\"text\" class=\"filter-date datepicker\" name=\"security_incident_open_date\" id=\"security_incident_open_date\" value=\"$security_incident_item[security_incident_open_date]\"/>";?> <label for="description">Security Incident Closure Date</label> <span class="description">Describe the time when the Incident has been closed</span> <? echo "<input type=\"text\" class=\"filter-date datepicker\" name=\"security_incident_closure_date\" id=\"security_incident_closure_date\" value=\"$security_incident_item[security_incident_closure_date]\"/>";?> <label for="legalType">Incident Status</label> <span class="description"></span> <select name="security_incident_status_id" id="" class="chzn-select"> <option value="-1">Select the Incident Status</option> <? list_drop_menu_security_incident_status($security_incident_item[security_incident_status_id],"security_incident_status_id"); ?> </select> </div> <div class="tab" id="tab2"> advanced tab </div> </div> </div> <div class="controls-wrapper"> <INPUT type="hidden" name="action" value="edit"> <INPUT type="hidden" name="section" value="operations"> <INPUT type="hidden" name="subsection" value="security_incident_list"> <? echo " <INPUT type=\"hidden\" name=\"security_incident_id\" value=\"$security_incident_item[security_incident_id]\">"; ?> <a> <INPUT type="submit" value="Submit" class="add-btn"> </a> <? echo " <a href=\"$base_url_list\" class=\"cancel-btn\">"; ?> Cancel <span class="select-icon"></span> </a> </form> </div> <br class="clear"/> </section> </body> </html>
santu47/Eramba
operations/security_incident_edit.php
PHP
gpl-2.0
6,808
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2007 François du Vignaud This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #include <ql/math/matrixutilities/tapcorrelations.hpp> #include <cmath> namespace QuantLib { Disposable<Matrix> triangularAnglesParametrization(const Array& angles, Size matrixSize, Size rank) { // what if rank == 1? QL_REQUIRE((rank-1) * (2*matrixSize - rank) == 2*angles.size(), "rank-1) * (matrixSize - rank/2) == angles.size()"); Matrix m(matrixSize, matrixSize); // first row filling m[0][0] = 1.0; for (Size j=1; j<matrixSize; ++j) m[0][j] = 0.0; // next ones... Size k = 0; //angles index for (Size i=1; i<m.rows(); ++i) { Real sinProduct = 1.0; Size bound = std::min(i,rank-1); for (Size j=0; j<bound; ++j) { m[i][j] = std::cos(angles[k]); m[i][j] *= sinProduct; sinProduct *= std::sin(angles[k]); ++k; } m[i][bound] = sinProduct; for (Size j=bound+1; j<m.rows(); ++j) m[i][j] = 0; } return m; } Disposable<Matrix> lmmTriangularAnglesParametrization(const Array& angles, Size matrixSize, Size) { Matrix m(matrixSize, matrixSize); for (Size i=0; i<m.rows(); ++i) { Real cosPhi, sinPhi; if (i>0) { cosPhi = std::cos(angles[i-1]); sinPhi = std::sin(angles[i-1]); } else { cosPhi = 1.0; sinPhi = 0.0; } for (Size j=0; j<i; ++j) m[i][j] = sinPhi * m[i-1][j]; m[i][i] = cosPhi; for (Size j=i+1; j<m.rows(); ++j) m[i][j] = 0.0; } return m; } Disposable<Matrix> triangularAnglesParametrizationUnconstrained( const Array& x, Size matrixSize, Size rank) { Array angles(x.size()); //we convert the unconstrained parameters in angles for (Size i = 0; i < x.size(); ++i) angles[i] = M_PI*.5 - std::atan(x[i]); return triangularAnglesParametrization(angles, matrixSize, rank); } Disposable<Matrix> lmmTriangularAnglesParametrizationUnconstrained( const Array& x, Size matrixSize, Size rank) { Array angles(x.size()); //we convert the unconstrained parameters in angles for (Size i = 0; i < x.size(); ++i) angles[i] = M_PI*.5 - std::atan(x[i]); return lmmTriangularAnglesParametrization(angles, matrixSize, rank); } Disposable<Matrix> triangularAnglesParametrizationRankThree( Real alpha, Real t0, Real epsilon, Size matrixSize) { Matrix m(matrixSize, 3); for (Size i=0; i<m.rows(); ++i) { Real t = t0 * (1 - std::exp(epsilon*Real(i))); Real phi = std::atan(alpha * t); m[i][0] = std::cos(t)*std::cos(phi); m[i][1] = std::sin(t)*std::cos(phi); m[i][2] = -std::sin(phi); } return m; } Disposable<Matrix> triangularAnglesParametrizationRankThreeVectorial( const Array& parameters, Size nbRows) { QL_REQUIRE(parameters.size() == 3, "the parameter array must contain exactly 3 values" ); return triangularAnglesParametrizationRankThree(parameters[0], parameters[1], parameters[2], nbRows); } Real FrobeniusCostFunction::value(const Array& x) const { Array temp = values(x); return DotProduct(temp, temp); } Disposable<Array> FrobeniusCostFunction::values(const Array& x) const { Array result((target_.rows()*(target_.columns()-1))/2); Matrix pseudoRoot = f_(x, matrixSize_, rank_); Matrix differences = pseudoRoot * transpose(pseudoRoot) - target_; Size k = 0; // then we store the elementwise differences in a vector. for (Size i=0; i<target_.rows(); ++i) { for (Size j=0; j<i; ++j){ result[k] = differences[i][j]; ++k; } } return result; } }
EuroPlusFinance/Software
Quantum Trading Platforms/QuantLib-1.4/ql/math/matrixutilities/tapcorrelations.cpp
C++
gpl-2.0
5,800
# -*- coding: utf-8 -*- # # Copyright © 2014-2015 Colin Duquesnoy # Copyright © 2009- The Spyder Developmet Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) """ Provides widget classes and functions. .. warning:: Only PyQt4/PySide QtGui classes compatible with PyQt5.QtWidgets are exposed here. Therefore, you need to treat/use this package as if it were the ``PyQt5.QtWidgets`` module. """ from . import PYQT5, PYSIDE2, PYQT4, PYSIDE, PythonQtError from ._patch.qcombobox import patch_qcombobox from ._patch.qheaderview import introduce_renamed_methods_qheaderview if PYQT5: from PyQt5.QtWidgets import * elif PYSIDE2: from PySide2.QtWidgets import * elif PYQT4: from PyQt4.QtGui import * QStyleOptionViewItem = QStyleOptionViewItemV4 del QStyleOptionViewItemV4 QStyleOptionFrame = QStyleOptionFrameV3 del QStyleOptionFrameV3 # These objects belong to QtGui try: # Older versions of PyQt4 do not provide these del (QGlyphRun, QMatrix2x2, QMatrix2x3, QMatrix2x4, QMatrix3x2, QMatrix3x3, QMatrix3x4, QMatrix4x2, QMatrix4x3, QMatrix4x4, QQuaternion, QRadialGradient, QRawFont, QRegExpValidator, QStaticText, QTouchEvent, QVector2D, QVector3D, QVector4D, qFuzzyCompare) except NameError: pass del (QAbstractTextDocumentLayout, QActionEvent, QBitmap, QBrush, QClipboard, QCloseEvent, QColor, QConicalGradient, QContextMenuEvent, QCursor, QDesktopServices, QDoubleValidator, QDrag, QDragEnterEvent, QDragLeaveEvent, QDragMoveEvent, QDropEvent, QFileOpenEvent, QFocusEvent, QFont, QFontDatabase, QFontInfo, QFontMetrics, QFontMetricsF, QGradient, QHelpEvent, QHideEvent, QHoverEvent, QIcon, QIconDragEvent, QIconEngine, QImage, QImageIOHandler, QImageReader, QImageWriter, QInputEvent, QInputMethodEvent, QKeyEvent, QKeySequence, QLinearGradient, QMouseEvent, QMoveEvent, QMovie, QPaintDevice, QPaintEngine, QPaintEngineState, QPaintEvent, QPainter, QPainterPath, QPainterPathStroker, QPalette, QPen, QPicture, QPictureIO, QPixmap, QPixmapCache, QPolygon, QPolygonF, QRegion, QResizeEvent, QSessionManager, QShortcutEvent, QShowEvent, QStandardItem, QStandardItemModel, QStatusTipEvent, QSyntaxHighlighter, QTabletEvent, QTextBlock, QTextBlockFormat, QTextBlockGroup, QTextBlockUserData, QTextCharFormat, QTextCursor, QTextDocument, QTextDocumentFragment, QTextDocumentWriter, QTextFormat, QTextFragment, QTextFrame, QTextFrameFormat, QTextImageFormat, QTextInlineObject, QTextItem, QTextLayout, QTextLength, QTextLine, QTextList, QTextListFormat, QTextObject, QTextObjectInterface, QTextOption, QTextTable, QTextTableCell, QTextTableCellFormat, QTextTableFormat, QTransform, QValidator, QWhatsThisClickedEvent, QWheelEvent, QWindowStateChangeEvent, qAlpha, qBlue, qGray, qGreen, qIsGray, qRed, qRgb, qRgba, QIntValidator, QStringListModel) # These objects belong to QtPrintSupport del (QAbstractPrintDialog, QPageSetupDialog, QPrintDialog, QPrintEngine, QPrintPreviewDialog, QPrintPreviewWidget, QPrinter, QPrinterInfo) # These objects belong to QtCore del (QItemSelection, QItemSelectionModel, QItemSelectionRange, QSortFilterProxyModel) # Patch QComboBox to allow Python objects to be passed to userData patch_qcombobox(QComboBox) # QHeaderView: renamed methods introduce_renamed_methods_qheaderview(QHeaderView) elif PYSIDE: from PySide.QtGui import * QStyleOptionViewItem = QStyleOptionViewItemV4 del QStyleOptionViewItemV4 # These objects belong to QtGui del (QAbstractTextDocumentLayout, QActionEvent, QBitmap, QBrush, QClipboard, QCloseEvent, QColor, QConicalGradient, QContextMenuEvent, QCursor, QDesktopServices, QDoubleValidator, QDrag, QDragEnterEvent, QDragLeaveEvent, QDragMoveEvent, QDropEvent, QFileOpenEvent, QFocusEvent, QFont, QFontDatabase, QFontInfo, QFontMetrics, QFontMetricsF, QGradient, QHelpEvent, QHideEvent, QHoverEvent, QIcon, QIconDragEvent, QIconEngine, QImage, QImageIOHandler, QImageReader, QImageWriter, QInputEvent, QInputMethodEvent, QKeyEvent, QKeySequence, QLinearGradient, QMatrix2x2, QMatrix2x3, QMatrix2x4, QMatrix3x2, QMatrix3x3, QMatrix3x4, QMatrix4x2, QMatrix4x3, QMatrix4x4, QMouseEvent, QMoveEvent, QMovie, QPaintDevice, QPaintEngine, QPaintEngineState, QPaintEvent, QPainter, QPainterPath, QPainterPathStroker, QPalette, QPen, QPicture, QPictureIO, QPixmap, QPixmapCache, QPolygon, QPolygonF, QQuaternion, QRadialGradient, QRegExpValidator, QRegion, QResizeEvent, QSessionManager, QShortcutEvent, QShowEvent, QStandardItem, QStandardItemModel, QStatusTipEvent, QSyntaxHighlighter, QTabletEvent, QTextBlock, QTextBlockFormat, QTextBlockGroup, QTextBlockUserData, QTextCharFormat, QTextCursor, QTextDocument, QTextDocumentFragment, QTextFormat, QTextFragment, QTextFrame, QTextFrameFormat, QTextImageFormat, QTextInlineObject, QTextItem, QTextLayout, QTextLength, QTextLine, QTextList, QTextListFormat, QTextObject, QTextObjectInterface, QTextOption, QTextTable, QTextTableCell, QTextTableCellFormat, QTextTableFormat, QTouchEvent, QTransform, QValidator, QVector2D, QVector3D, QVector4D, QWhatsThisClickedEvent, QWheelEvent, QWindowStateChangeEvent, qAlpha, qBlue, qGray, qGreen, qIsGray, qRed, qRgb, qRgba, QIntValidator, QStringListModel) # These objects belong to QtPrintSupport del (QAbstractPrintDialog, QPageSetupDialog, QPrintDialog, QPrintEngine, QPrintPreviewDialog, QPrintPreviewWidget, QPrinter, QPrinterInfo) # These objects belong to QtCore del (QItemSelection, QItemSelectionModel, QItemSelectionRange, QSortFilterProxyModel) # Patch QComboBox to allow Python objects to be passed to userData patch_qcombobox(QComboBox) # QHeaderView: renamed methods introduce_renamed_methods_qheaderview(QHeaderView) else: raise PythonQtError('No Qt bindings could be found')
davvid/git-cola
qtpy/QtWidgets.py
Python
gpl-2.0
6,411
/* BMP180 Pressure & Temp Sensor Library bmp180.cpp EAS Brian Davis */ #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> #include <sys/ioctl.h> #include <iostream> #include <cstring> #include "bmp180_bosch.h" #include "bmp180.h" // #ifndef BMP180_EAS_H_ // #define BMP180_EAS_H_ #define BMP_180_ADDR 0x77 // //Default Constructor // Example from Bosch datasheet // AC1 = 408; AC2 = -72; AC3 = -14383; AC4 = 32741; AC5 = 32757; AC6 = 23153; // B1 = 6190; B2 = 4; MB = -32768; MC = -8711; MD = 2868; // Example from http://wmrx00.sourceforge.net/Arduino/BMP180-Calcs.pdf // AC1 = 7911; AC2 = -934; AC3 = -14306; AC4 = 31567; AC5 = 25671; AC6 = 18974; // VB1 = 5498; VB2 = 46; MB = -32768; MC = -11075; MD = 2432; bmp180::bmp180(int bus, uint8_t UniqueID_in){ UniqueID = UniqueID_in; // // Default Cal values // ac1 = 408; ac2 = -72; ac3 = -14383; ac4 = 32741; ac5 = 32757; ac6 = 23153; b1 = 6190; b2 = 4; mb = -32768; mc = -8711; mc = 2868; readCalValues(); oss = bmp_mode; rawTemp = 0; rawPress = 0; // // Open I2C Bus // #define MAX_BUS 24 char i2cnamebuf[MAX_BUS]; snprintf(i2cnamebuf, sizeof(i2cnamebuf), "/dev/i2c-%d", bus); if ((i2cBusPtr = open(i2cnamebuf, O_RDWR)) < 0) { /* ERROR HANDLING: you can check errno to see what went wrong */ perror("BMP180 : Failed to open the i2c bus"); return; } // // Associate BMP I2C Addr w/ Bus Ptr // if (ioctl(i2cBusPtr, I2C_SLAVE, BMP_180_ADDR) < 0) { printf("BMP180 : Failed to acquire bus access and/or talk to slave.\n"); /* ERROR HANDLING; you can check errno to see what went wrong */ return; } } /* mode set to 0 All calibration values read out */ //bool bmp180::begin(){ // @@@ Add a Read of the Calibration Values // readCalValues(); // Required for further operations // Wire.begin(); // Calibration value read //ac1 = read16(bmp_ac1); //ac2 = read16(bmp_ac2); //ac3 = read16(bmp_ac3); //ac4 = read16(bmp_ac4); //ac5 = read16(bmp_ac5); //ac6 = read16(bmp_ac6); //b1 = read16(bmp_b1); //b2 = read16(bmp_b2); //mb = read16(bmp_mb); ///mc = read16(bmp_mc); //md = read16(bmp_md); //return true; //} int bmp180::readCalValues(){ return 0; } /* Calculates temperature from selected raw values. Raw values must be floating-point in order for the calculation of floating-point temperatures. */ float bmp180::readTemp(){ int32_t ut,b5; float temperatur; //ut = uncompensated temperature ut = rawTemp; //(); /* Calculation rate of temperatures in Celsius. Data sheet read out. */ int32_t x1 = ((ut - (int32_t)ac6) * (int32_t)ac5) >> 15; int32_t x2 = ((int32_t)mc << 11) / (x1 + (int32_t)md); b5 = x1 + x2; temperatur = (b5 +8) >> 4; temperatur /= 10.0; return temperatur; } /* Uses selected values to calculate pressure. Pressure can be returned as int32_t. Pressure could be calculated here in Pascal units if a new return type was created. */ int32_t bmp180::readPressure(){ int32_t ut,up,b3,b5,b6,x1,x2,x3,p; uint32_t b4,b7; //ut = uncompensated temperature //up = uncompensated pressure //up = readRawPres(); //ut = readRawTemp(); up = rawPress; ut = rawTemp; /* Calculation of real pressure in Pascals. Read out to data sheet. */ int32_t x11 = ((ut - (int32_t)ac6) * (int32_t)ac5) >> 15; int32_t x22 = ((int32_t)mc << 11) / (x11 + (int32_t)md); b5 = x11 + x22; b6 = b5 - 4000; x1 = ((int32_t)b2 * ((b6 * b6) >> 12)) >> 11; x2 = ((int32_t)ac2 * b6) >> 11; x3 = x1 + x2; b3 = (((((int32_t)ac1*4) + x3) << oss) + 2) / 4; x1 = ((int32_t)ac3 * b6) >> 13; x2 = (((int32_t)b1 * (b6 * b6) >> 12)) >> 16; x3 = ((x1 + x2) + 2) >> 2; b4 = ((int32_t)ac4 * (uint32_t)(x3 + 32768)) >> 15; b7 = ((uint32_t)up - b3) * (uint32_t)(50000 >> oss); if (b7 < 0x80000000){ p = (b7 * 2) / b4; } else{ p = (b7 / b4) * 2; } x1 = (p >> 8) * (p >> 8); x1 = (x1 * 3038) >> 16; x2 = (-7357 * p) >> 16; p = p + ((x1 + x2 + (int32_t)3791) >> 4); return p; } //------------------------------------------------------------------- // readRawTemp ( ) // // Primary function - read temperature data from BMP180 device // uint16_t bmp180::updateRawTemp(){ char buf[20] = {0}; // // Start Temperature // buf[0] = BMP180_CTRL_MEAS_REG;; buf[1] = BMP180_T_MEASURE; write(i2cBusPtr, buf, 2); // pause // Temperature Conversion 4.5 mS // Page 21 of datasheet Rev 2.5 usleep(5E3); // // Begin Read from ADC MSB // buf[0] = BMP180_ADC_OUT_MSB_REG; write(i2cBusPtr, buf, 1); // Using I2C Read if (read(i2cBusPtr,buf,2) != 2) { /* ERROR HANDLING: i2c transaction failed */ std::cout << "bmp180_rrT Failed to read from i2c bus: " << strerror(errno) << std::endl << std::endl; return 0; } else { // Correct Read of (2) bytes rawTemp = (buf[0] << 8) | buf[1]; // // Display Temp Value // std::cout << "raw Temp value = 0x"<< std::hex << rawTemp << std::endl; } return rawTemp; } //------------------------------------------------------------------- // readRawPress ( ) // // Primary function - read pressure data from BMP180 device // uint32_t bmp180::updateRawPress(){ char buf[20] = {0}; // // Start Pressure // buf[0] = BMP180_CTRL_MEAS_REG; buf[1] = BMP180_P_MEASURE; write(i2cBusPtr, buf, 2); // pause // Pressure Conversion 4.5 - 25.5 mS // Page 21 of datasheet Rev 2.5 usleep(26E3); // // Begin Read from ADC MSB // buf[0] = BMP180_ADC_OUT_MSB_REG; write(i2cBusPtr, buf, 1); // Using I2C Read if (read(i2cBusPtr,buf,2) != 2) { /* ERROR HANDLING: i2c transaction failed */ std::cout << "bmp180_rrP Failed to read from i2c bus: " << strerror(errno) << std::endl; return 0; } else { rawPress = (buf[0] << 8) | buf[1]; // // Display Press Value //std::cout << "raw Pressure value = 0x" << std::hex << rawPress << std::endl; } return rawPress; } //------------------------------------------------------------ // // uint32_t bmp180::updateRawPressTemp(){ // // Initiating Communication with BMP180 // /* if (ioctl(i2cBusPtr, I2C_SLAVE, BMP_180_ADDR) < 0) { printf("Failed to acquire bus access and/or talk to slave.\n"); // ERROR HANDLING; you can check errno to see what went wrong exit(1); } */ updateRawTemp(); updateRawPress(); return rawPress; } //------------------------------------------------------------ // // EasDAQpack* bmp180::fillEASpack(EasDAQpack &fillPack) { fillPack.setID(EasDAQpack::BAROTEMP); fillPack.u.barotemp.temp = rawTemp; fillPack.u.barotemp.press = rawPress; // fillPack.u.threeAxis_ss16.z = rawData_Z; return &fillPack; } // #endif
jcstrang-edu/eas_bbb_version1
source/bmp180.cpp
C++
gpl-2.0
7,277
/****************************************************************************** * Icinga 2 * * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.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 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software Foundation * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************/ #ifndef NOTIFICATIONCOMPONENT_H #define NOTIFICATIONCOMPONENT_H #include "notification/notificationcomponent.thpp" #include "icinga/service.hpp" #include "base/configobject.hpp" #include "base/timer.hpp" namespace icinga { /** * @ingroup notification */ class NotificationComponent : public ObjectImpl<NotificationComponent> { public: DECLARE_OBJECT(NotificationComponent); DECLARE_OBJECTNAME(NotificationComponent); static void StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata); virtual void Start(void) override; private: Timer::Ptr m_NotificationTimer; void NotificationTimerHandler(void); void SendNotificationsHandler(const Checkable::Ptr& checkable, NotificationType type, const CheckResult::Ptr& cr, const String& author, const String& text); }; } #endif /* NOTIFICATIONCOMPONENT_H */
draskolnikova/icinga2
lib/notification/notificationcomponent.hpp
C++
gpl-2.0
2,276
/* ============================================================ * * This file is a part of kipi-plugins project * http://www.digikam.org * * Date : 2007-10-16 * Description : XMP categories settings page. * * Copyright (C) 2007-2012 by Gilles Caulier <caulier dot gilles at gmail dot com> * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software Foundation; * either version 2, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * ============================================================ */ #include "xmpcategories.moc" // Qt includes #include <QCheckBox> #include <QPushButton> #include <QGridLayout> // KDE includes #include <kdialog.h> #include <kiconloader.h> #include <klineedit.h> #include <klistwidget.h> #include <klocale.h> // Local includes #include "kpmetadata.h" using namespace KIPIPlugins; namespace KIPIMetadataEditPlugin { class XMPCategories::XMPCategoriesPriv { public: XMPCategoriesPriv() { addSubCategoryButton = 0; delSubCategoryButton = 0; repSubCategoryButton = 0; subCategoriesBox = 0; subCategoriesCheck = 0; categoryCheck = 0; categoryEdit = 0; subCategoryEdit = 0; } QStringList oldSubCategories; QPushButton* addSubCategoryButton; QPushButton* delSubCategoryButton; QPushButton* repSubCategoryButton; QCheckBox* subCategoriesCheck; QCheckBox* categoryCheck; KLineEdit* categoryEdit; KLineEdit* subCategoryEdit; KListWidget* subCategoriesBox; }; XMPCategories::XMPCategories(QWidget* const parent) : QWidget(parent), d(new XMPCategoriesPriv) { QGridLayout* grid = new QGridLayout(this); // -------------------------------------------------------- d->categoryCheck = new QCheckBox(i18n("Identify subject of content (3 chars max):"), this); d->categoryEdit = new KLineEdit(this); d->categoryEdit->setClearButtonShown(true); d->categoryEdit->setMaxLength(3); d->categoryEdit->setWhatsThis(i18n("Set here the category of content. This field is limited " "to 3 characters.")); d->subCategoriesCheck = new QCheckBox(i18n("Supplemental categories:"), this); d->subCategoryEdit = new KLineEdit(this); d->subCategoryEdit->setClearButtonShown(true); d->subCategoryEdit->setWhatsThis(i18n("Enter here a new supplemental category of content.")); d->subCategoriesBox = new KListWidget(this); d->subCategoriesBox->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); d->addSubCategoryButton = new QPushButton( i18n("&Add"), this); d->delSubCategoryButton = new QPushButton( i18n("&Delete"), this); d->repSubCategoryButton = new QPushButton( i18n("&Replace"), this); d->addSubCategoryButton->setIcon(SmallIcon("list-add")); d->delSubCategoryButton->setIcon(SmallIcon("edit-delete")); d->repSubCategoryButton->setIcon(SmallIcon("view-refresh")); d->delSubCategoryButton->setEnabled(false); d->repSubCategoryButton->setEnabled(false); // -------------------------------------------------------- grid->setAlignment( Qt::AlignTop ); grid->addWidget(d->categoryCheck, 0, 0, 1, 2); grid->addWidget(d->categoryEdit, 0, 2, 1, 1); grid->addWidget(d->subCategoriesCheck, 1, 0, 1, 3); grid->addWidget(d->subCategoryEdit, 2, 0, 1, 3); grid->addWidget(d->subCategoriesBox, 3, 0, 5, 3); grid->addWidget(d->addSubCategoryButton, 3, 3, 1, 1); grid->addWidget(d->delSubCategoryButton, 4, 3, 1, 1); grid->addWidget(d->repSubCategoryButton, 5, 3, 1, 1); grid->setColumnStretch(1, 10); grid->setRowStretch(6, 10); grid->setMargin(0); grid->setSpacing(KDialog::spacingHint()); // -------------------------------------------------------- connect(d->categoryCheck, SIGNAL(toggled(bool)), d->categoryEdit, SLOT(setEnabled(bool))); connect(d->categoryCheck, SIGNAL(toggled(bool)), d->subCategoriesBox, SLOT(setEnabled(bool))); connect(d->categoryCheck, SIGNAL(toggled(bool)), d->subCategoriesCheck, SLOT(setEnabled(bool))); connect(d->categoryCheck, SIGNAL(toggled(bool)), d->subCategoryEdit, SLOT(setEnabled(bool))); connect(d->categoryCheck, SIGNAL(toggled(bool)), d->addSubCategoryButton, SLOT(setEnabled(bool))); connect(d->categoryCheck, SIGNAL(toggled(bool)), d->delSubCategoryButton, SLOT(setEnabled(bool))); connect(d->categoryCheck, SIGNAL(toggled(bool)), d->repSubCategoryButton, SLOT(setEnabled(bool))); // -------------------------------------------------------- connect(d->subCategoriesCheck, SIGNAL(toggled(bool)), d->subCategoryEdit, SLOT(setEnabled(bool))); connect(d->subCategoriesCheck, SIGNAL(toggled(bool)), d->subCategoriesBox, SLOT(setEnabled(bool))); connect(d->subCategoriesCheck, SIGNAL(toggled(bool)), d->addSubCategoryButton, SLOT(setEnabled(bool))); connect(d->subCategoriesCheck, SIGNAL(toggled(bool)), d->delSubCategoryButton, SLOT(setEnabled(bool))); connect(d->subCategoriesCheck, SIGNAL(toggled(bool)), d->repSubCategoryButton, SLOT(setEnabled(bool))); // -------------------------------------------------------- connect(d->subCategoriesBox, SIGNAL(itemSelectionChanged()), this, SLOT(slotCategorySelectionChanged())); connect(d->addSubCategoryButton, SIGNAL(clicked()), this, SLOT(slotAddCategory())); connect(d->delSubCategoryButton, SIGNAL(clicked()), this, SLOT(slotDelCategory())); connect(d->repSubCategoryButton, SIGNAL(clicked()), this, SLOT(slotRepCategory())); // -------------------------------------------------------- connect(d->categoryCheck, SIGNAL(toggled(bool)), this, SIGNAL(signalModified())); connect(d->subCategoriesCheck, SIGNAL(toggled(bool)), this, SIGNAL(signalModified())); connect(d->addSubCategoryButton, SIGNAL(clicked()), this, SIGNAL(signalModified())); connect(d->delSubCategoryButton, SIGNAL(clicked()), this, SIGNAL(signalModified())); connect(d->repSubCategoryButton, SIGNAL(clicked()), this, SIGNAL(signalModified())); connect(d->categoryEdit, SIGNAL(textChanged(QString)), this, SIGNAL(signalModified())); } XMPCategories::~XMPCategories() { delete d; } void XMPCategories::slotDelCategory() { QListWidgetItem *item = d->subCategoriesBox->currentItem(); if (!item) return; d->subCategoriesBox->takeItem(d->subCategoriesBox->row(item)); delete item; } void XMPCategories::slotRepCategory() { QString newCategory = d->subCategoryEdit->text(); if (newCategory.isEmpty()) return; if (!d->subCategoriesBox->selectedItems().isEmpty()) { d->subCategoriesBox->selectedItems()[0]->setText(newCategory); d->subCategoryEdit->clear(); } } void XMPCategories::slotCategorySelectionChanged() { if (!d->subCategoriesBox->selectedItems().isEmpty()) { d->subCategoryEdit->setText(d->subCategoriesBox->selectedItems()[0]->text()); d->delSubCategoryButton->setEnabled(true); d->repSubCategoryButton->setEnabled(true); } else { d->delSubCategoryButton->setEnabled(false); d->repSubCategoryButton->setEnabled(false); } } void XMPCategories::slotAddCategory() { QString newCategory = d->subCategoryEdit->text(); if (newCategory.isEmpty()) return; bool found = false; for (int i = 0 ; i < d->subCategoriesBox->count(); ++i) { QListWidgetItem *item = d->subCategoriesBox->item(i); if (newCategory == item->text()) { found = true; break; } } if (!found) { d->subCategoriesBox->insertItem(d->subCategoriesBox->count(), newCategory); d->subCategoryEdit->clear(); } } void XMPCategories::readMetadata(QByteArray& xmpData) { blockSignals(true); KPMetadata meta; meta.setXmp(xmpData); QString data; // In first we handle all sub-categories. d->subCategoriesBox->clear(); d->subCategoriesCheck->setChecked(false); d->oldSubCategories = meta.getXmpSubCategories(); if (!d->oldSubCategories.isEmpty()) { d->subCategoriesBox->insertItems(0, d->oldSubCategories); d->subCategoriesCheck->setChecked(true); } // And in second, the main category because all sub-categories status depend of this one. d->categoryEdit->clear(); d->categoryCheck->setChecked(false); data = meta.getXmpTagString("Xmp.photoshop.Category", false); if (!data.isNull()) { d->categoryEdit->setText(data); d->categoryCheck->setChecked(true); } d->categoryEdit->setEnabled(d->categoryCheck->isChecked()); d->subCategoriesCheck->setEnabled(d->categoryCheck->isChecked()); d->subCategoryEdit->setEnabled(d->categoryCheck->isChecked() && d->subCategoriesCheck->isChecked()); d->subCategoriesBox->setEnabled(d->categoryCheck->isChecked() && d->subCategoriesCheck->isChecked()); d->addSubCategoryButton->setEnabled(d->categoryCheck->isChecked() && d->subCategoriesCheck->isChecked()); d->delSubCategoryButton->setEnabled(d->categoryCheck->isChecked() && d->subCategoriesCheck->isChecked()); blockSignals(false); } void XMPCategories::applyMetadata(QByteArray& xmpData) { QStringList newCategories; KPMetadata meta; meta.setXmp(xmpData); if (d->categoryCheck->isChecked()) meta.setXmpTagString("Xmp.photoshop.Category", d->categoryEdit->text()); else meta.removeXmpTag("Xmp.photoshop.Category"); for (int i = 0 ; i < d->subCategoriesBox->count(); ++i) { QListWidgetItem *item = d->subCategoriesBox->item(i); newCategories.append(item->text()); } // We remove in first all existing sub-categories. meta.removeXmpTag("Xmp.photoshop.SupplementalCategories"); // And add new list if necessary. if (d->categoryCheck->isChecked() && d->subCategoriesCheck->isChecked()) meta.setXmpSubCategories(newCategories); xmpData = meta.getXmp(); } } // namespace KIPIMetadataEditPlugin
kratuna/kipi-plugins
metadataedit/xmp/xmpcategories.cpp
C++
gpl-2.0
10,674
#include <iostream> #include <fstream> #include <conio.h> #include <sstream> #include <windows.h> #include <map> #include <OnlineDataManager.h> #include <ConsoleInput.h> #include <StringServer.h> #include "edk.h" #include "edkErrorCode.h" #define TOTAL_CHANNELS 22 EE_DataChannel_t targetChannelList[TOTAL_CHANNELS] = { ED_COUNTER, ED_AF3, ED_F7, ED_F3, ED_FC5, ED_T7, ED_P7, ED_O1, ED_O2, ED_P8, ED_T8, ED_FC6, ED_F4, ED_F8, ED_AF4, ED_GYROX, ED_GYROY, ED_TIMESTAMP, ED_FUNC_ID, ED_FUNC_VALUE, ED_MARKER, ED_SYNC_SIGNAL }; /* const char *labels[TOTAL_CHANNELS] = { "COUNTER", "AF3", "F7", "F3", "FC5", "T7", "P7", "O1", "O2", "P8", "T8", "FC6", "F4", "F8", "AF4", "GYROX", "GYROY", "TIMESTAMP", "FUNC_ID", "FUNC_VALUE", "MARKER", "SYNC_SIGNAL" }; */ EmoEngineEventHandle eEvent; EmoStateHandle eState; unsigned int userID = 0; int port, ctrlPort; char hostname[256]; StringServer ctrlServ; ConsoleInput conIn; void acquisition(const char *configFile, unsigned int fSample) { int sampleCounter = 0; OnlineDataManager<double, double> ODM(0, TOTAL_CHANNELS, (float) fSample); if (ODM.configureFromFile(configFile) != 0) { fprintf(stderr, "Configuration %s file is invalid\n", configFile); return; } else { printf("Streaming %i out of %i channels\n", ODM.getSignalConfiguration().getStreamingSelection().getSize(), TOTAL_CHANNELS); } if (!strcmp(hostname, "-")) { if (!ODM.useOwnServer(port)) { fprintf(stderr, "Could not spawn buffer server on port %d.\n",port); return; } } else { if (!ODM.connectToServer(hostname, port)) { fprintf(stderr, "Could not connect to buffer server at %s:%d.\n",hostname, port); return; } } ODM.enableStreaming(); DataHandle hData = EE_DataCreate(); EE_DataSetBufferSizeInSec(1.0); printf("Starting to transfer data - press [Escape] to quit\n"); while (1) { if (conIn.checkKey() && conIn.getKey()==27) break; ctrlServ.checkRequests(ODM); EE_DataUpdateHandle(0, hData); unsigned int nSamplesTaken=0; EE_DataGetNumberOfSample(hData,&nSamplesTaken); if (nSamplesTaken != 0) { double* data = new double[nSamplesTaken]; double* dest = ODM.provideBlock(nSamplesTaken); for (int i=0;i<TOTAL_CHANNELS;i++) { EE_DataGet(hData, targetChannelList[i], data, nSamplesTaken); for (unsigned int j=0;j<nSamplesTaken;j++) { dest[i + j*TOTAL_CHANNELS] = data[j]; } } delete[] data; if (!ODM.handleBlock()) break; sampleCounter += nSamplesTaken; printf("Wrote %2i samples (%i total)\n", nSamplesTaken, sampleCounter); } Sleep(10); } EE_DataFree(hData); } int main(int argc, char** argv) { //const unsigned short composerPort = 1726; unsigned int samplingRate = 0; if (argc<2) { fprintf(stderr, "Usage: emotiv2ft <config-file> [hostname=localhost [port=1972 [ctrlPort=8000]]]\n"); fprintf(stderr, "Passing a minus (-) for the hostname tells this application to spawn its own buffer server\n"); return 1; } if (argc>2) { strncpy(hostname, argv[2], sizeof(hostname)); } else { strcpy(hostname, "localhost"); } if (argc>3) { port = atoi(argv[3]); } else { port = 1972; } if (argc>4) { ctrlPort = atoi(argv[4]); } else { ctrlPort = 8000; } if (!ctrlServ.startListening(ctrlPort)) { fprintf(stderr, "Cannot listen on port %d for configuration commands\n", ctrlPort); return 1; } eEvent = EE_EmoEngineEventCreate(); eState = EE_EmoStateCreate(); if (EE_EngineConnect() != EDK_OK) { fprintf(stderr, "Emotiv Engine start up failed."); exit(1); } // TODO: provide alternative connection // ... if (EE_EngineRemoteConnect(input.c_str(), composerPort) != EDK_OK) { // Loop here until acquisition can start and sampling rate is known printf("Waiting for the device to become ready - press [Escape] to quit\n"); while (1) { int state = EE_EngineGetNextEvent(eEvent); if (state == EDK_OK) { EE_Event_t eventType = EE_EmoEngineEventGetType(eEvent); EE_EmoEngineEventGetUserId(eEvent, &userID); // Log the EmoState if it has been updated if (eventType == EE_UserAdded) { if (EE_DataGetSamplingRate(userID, &samplingRate) != EDK_OK) { fprintf(stderr, "Cannot retrieve sampling rate\n"); break; } else { EE_DataAcquisitionEnable(userID,true); printf("EDK: User added, will now start acquisition.\n"); } break; } } if (conIn.checkKey() && conIn.getKey()==27) break; } if (samplingRate!=0) { acquisition(argv[1], samplingRate); } EE_EngineDisconnect(); EE_EmoStateFree(eState); EE_EmoEngineEventFree(eEvent); return 0; }
bloyl/fieldtrip
realtime/src/acquisition/emotiv/emotiv2ft.cc
C++
gpl-2.0
4,844
# # Alexander Todorov <atodorov@redhat.com> # # Copyright 2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that it # will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat # trademarks that are incorporated in the source code or documentation are not # subject to the GNU General Public License and may only be used or replicated # with the express permission of Red Hat, Inc. # import unittest from pykickstart.base import DeprecatedCommand from tests.baseclass import CommandTest class F20_TestCase(CommandTest): command = "install" def runTest(self): # pass self.assert_parse("install", "install\n") self.assert_parse("install", "install\n") self.assert_parse("install --root-device=/dev/sda", "install\n") # upgrade is always false cmd = self.handler().commands[self.command] cmd.parse([]) self.assertFalse(cmd.upgrade) # fail self.assert_parse_error("install --bad-flag") # --root-device requires argument self.assert_parse_error("install --root-device") self.assert_parse_error("install --root-device=\"\"") class F29_TestCase(F20_TestCase): def runTest(self): # make sure we've been deprecated parser = self.getParser("install") self.assertTrue(issubclass(parser.__class__, DeprecatedCommand)) # make sure we are still able to parse it self.assert_parse("install") class RHEL8_TestCase(F29_TestCase): pass if __name__ == "__main__": unittest.main()
atodorov/pykickstart
tests/commands/install.py
Python
gpl-2.0
2,107
<?php // // ZoneMinder web filter view file, $Date$, $Revision$ // Copyright (C) 2001-2008 Philip Coombes // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // if ( !canView( 'Events' ) ) { $view = "error"; return; } $selectName = "filterName"; $filterNames = array( ''=>$SLANG['ChooseFilter'] ); foreach ( dbFetchAll( "select * from Filters order by Name" ) as $row ) { $filterNames[$row['Name']] = $row['Name']; if ( $row['Background'] ) $filterNames[$row['Name']] .= "*"; if ( !empty($_REQUEST['reload']) && isset($_REQUEST['filterName']) && $_REQUEST['filterName'] == $row['Name'] ) $dbFilter = $row; } $backgroundStr = ""; if ( isset($dbFilter) ) { if ( $dbFilter['Background'] ) $backgroundStr = '['.strtolower($SLANG['Background']).']'; $_REQUEST['filter'] = jsonDecode( $dbFilter['Query'] ); $_REQUEST['sort_field'] = isset($_REQUEST['filter']['sort_field'])?$_REQUEST['filter']['sort_field']:"DateTime"; $_REQUEST['sort_asc'] = isset($_REQUEST['filter']['sort_asc'])?$_REQUEST['filter']['sort_asc']:"1"; $_REQUEST['limit'] = isset($_REQUEST['filter']['limit'])?$_REQUEST['filter']['limit']:""; unset( $_REQUEST['filter']['sort_field'] ); unset( $_REQUEST['filter']['sort_asc'] ); unset( $_REQUEST['filter']['limit'] ); } $conjunctionTypes = array( 'and' => $SLANG['ConjAnd'], 'or' => $SLANG['ConjOr'] ); $obracketTypes = array(); $cbracketTypes = array(); if ( isset($_REQUEST['filter']['terms']) ) { for ( $i = 0; $i <= count($_REQUEST['filter']['terms'])-2; $i++ ) { $obracketTypes[$i] = str_repeat( "(", $i ); $cbracketTypes[$i] = str_repeat( ")", $i ); } } $attrTypes = array( 'MonitorId' => $SLANG['AttrMonitorId'], 'MonitorName' => $SLANG['AttrMonitorName'], 'Id' => $SLANG['AttrId'], 'Name' => $SLANG['AttrName'], 'Cause' => $SLANG['AttrCause'], 'Notes' => $SLANG['AttrNotes'], 'DateTime' => $SLANG['AttrDateTime'], 'Date' => $SLANG['AttrDate'], 'Time' => $SLANG['AttrTime'], 'Weekday' => $SLANG['AttrWeekday'], 'Length' => $SLANG['AttrDuration'], 'Frames' => $SLANG['AttrFrames'], 'AlarmFrames' => $SLANG['AttrAlarmFrames'], 'TotScore' => $SLANG['AttrTotalScore'], 'AvgScore' => $SLANG['AttrAvgScore'], 'MaxScore' => $SLANG['AttrMaxScore'], 'Archived' => $SLANG['AttrArchiveStatus'], 'DiskPercent' => $SLANG['AttrDiskPercent'], 'DiskBlocks' => $SLANG['AttrDiskBlocks'], 'SystemLoad' => $SLANG['AttrSystemLoad'], ); $opTypes = array( '=' => $SLANG['OpEq'], '!=' => $SLANG['OpNe'], '>=' => $SLANG['OpGtEq'], '>' => $SLANG['OpGt'], '<' => $SLANG['OpLt'], '<=' => $SLANG['OpLtEq'], '=~' => $SLANG['OpMatches'], '!~' => $SLANG['OpNotMatches'], '=[]' => $SLANG['OpIn'], '![]' => $SLANG['OpNotIn'], ); $archiveTypes = array( '0' => $SLANG['ArchUnarchived'], '1' => $SLANG['ArchArchived'] ); $weekdays = array(); for ( $i = 0; $i < 7; $i++ ) { $weekdays[$i] = strftime( "%A", mktime( 12, 0, 0, 1, $i+1, 2001 ) ); } $sort_fields = array( 'Id' => $SLANG['AttrId'], 'Name' => $SLANG['AttrName'], 'Cause' => $SLANG['AttrCause'], 'Notes' => $SLANG['AttrNotes'], 'MonitorName' => $SLANG['AttrMonitorName'], 'DateTime' => $SLANG['AttrDateTime'], 'Length' => $SLANG['AttrDuration'], 'Frames' => $SLANG['AttrFrames'], 'AlarmFrames' => $SLANG['AttrAlarmFrames'], 'TotScore' => $SLANG['AttrTotalScore'], 'AvgScore' => $SLANG['AttrAvgScore'], 'MaxScore' => $SLANG['AttrMaxScore'], ); $sort_dirns = array( '1' => $SLANG['SortAsc'], '0' => $SLANG['SortDesc'] ); if ( empty($_REQUEST['sort_field']) ) { $_REQUEST['sort_field'] = ZM_WEB_EVENT_SORT_FIELD; $_REQUEST['sort_asc'] = (ZM_WEB_EVENT_SORT_ORDER == "asc"); } $hasCal = file_exists( 'tools/jscalendar/calendar.js' ); $focusWindow = true; xhtmlHeaders(__FILE__, $SLANG['EventFilter'] ); ?> <body> <div id="page"> <div id="header"> <div id="headerButtons"> <a href="#" onclick="closeWindow();"><?= $SLANG['Close'] ?></a> </div> <h2><?= $SLANG['EventFilter'] ?></h2> </div> <div id="content"> <form name="contentForm" id="contentForm" method="get" action="<?= $_SERVER['PHP_SELF'] ?>"> <input type="hidden" name="view" value="filter"/> <input type="hidden" name="page" value="<?= requestVar( 'page' ) ?>"/> <input type="hidden" name="reload" value="0"/> <input type="hidden" name="execute" value="0"/> <input type="hidden" name="action" value=""/> <input type="hidden" name="subaction" value=""/> <input type="hidden" name="line" value=""/> <input type="hidden" name="fid" value=""/> <hr/> <div id="filterSelector"><label for="<?= $selectName ?>"><?= $SLANG['UseFilter'] ?></label><?php if ( count($filterNames) > 1 ) { echo buildSelect( $selectName, $filterNames, "submitToFilter( this, 1 );" ); } else { ?><select disabled="disabled"><option><?= $SLANG['NoSavedFilters'] ?></option></select><?php } ?><?= $backgroundStr ?></div> <hr/> <table id="fieldsTable" class="filterTable" cellspacing="0"> <tbody> <?php for ( $i = 0; isset($_REQUEST['filter']) && $i < count($_REQUEST['filter']['terms']); $i++ ) { ?> <tr> <?php if ( $i == 0 ) { ?> <td>&nbsp;</td> <?php } else { ?> <td><?= buildSelect( "filter[terms][$i][cnj]", $conjunctionTypes ); ?></td> <?php } ?> <td><?php if ( count($_REQUEST['filter']['terms']) > 2 ) { echo buildSelect( "filter[terms][$i][obr]", $obracketTypes ); } else { ?>&nbsp;<?php } ?></td> <td><?= buildSelect( "filter[terms][$i][attr]", $attrTypes, "clearValue( this, $i ); submitToFilter( this, 0 );" ); ?></td> <?php if ( isset($_REQUEST['filter']['terms'][$i]['attr']) ) { if ( $_REQUEST['filter']['terms'][$i]['attr'] == "Archived" ) { ?> <td><?= $SLANG['OpEq'] ?><input type="hidden" name="filter[terms][<?= $i ?>][op]" value="="/></td> <td><?= buildSelect( "filter[terms][$i][val]", $archiveTypes ); ?></td> <?php } elseif ( $_REQUEST['filter']['terms'][$i]['attr'] == "DateTime" ) { ?> <td><?= buildSelect( "filter[terms][$i][op]", $opTypes ); ?></td> <td><input type="text" name="filter[terms][<?= $i ?>][val]" id="filter[terms][<?= $i ?>][val]" value="<?= isset($_REQUEST['filter']['terms'][$i]['val'])?validHtmlStr($_REQUEST['filter']['terms'][$i]['val']):'' ?>"/><?php if ( $hasCal ) { ?><script type="text/javascript">Calendar.setup( { inputField: "filter[terms][<?= $i ?>][val]", ifFormat: "%Y-%m-%d %H:%M", showsTime: true, timeFormat: "24", showOthers: true, weekNumbers: false });</script><?php } ?></td> <?php } elseif ( $_REQUEST['filter']['terms'][$i]['attr'] == "Date" ) { ?> <td><?= buildSelect( "filter[terms][$i][op]", $opTypes ); ?></td> <td><input type="text" name="filter[terms][<?= $i ?>][val]" id="filter[terms][<?= $i ?>][val]" value="<?= isset($_REQUEST['filter']['terms'][$i]['val'])?validHtmlStr($_REQUEST['filter']['terms'][$i]['val']):'' ?>"/><?php if ( $hasCal ) { ?><script type="text/javascript">Calendar.setup( { inputField: "filter[terms][<?= $i ?>][val]", ifFormat: "%Y-%m-%d", showOthers: true, weekNumbers: false });</script><?php } ?></td> <?php } elseif ( $_REQUEST['filter']['terms'][$i]['attr'] == "Weekday" ) { ?> <td><?= buildSelect( "filter[terms][$i][op]", $opTypes ); ?></td> <td><?= buildSelect( "filter[terms][$i][val]", $weekdays ); ?></td> <?php } elseif ( false && $_REQUEST['filter']['terms'][$i]['attr'] == "MonitorName" ) { $monitors = array(); foreach ( dbFetchAll( "select Id,Name from Monitors order by Sequence asc" ) as $monitor ) { if ( visibleMonitor( $monitor['Id'] ) ) { $monitors[$monitor['Name']] = $monitor['Name']; } } ?> <td><?= buildSelect( "filter[terms][$i][op]", $opTypes ); ?></td> <td><?= buildSelect( "filter[terms][$i][val]", $monitors ); ?></td> <?php } else { ?> <td><?= buildSelect( "filter[terms][$i][op]", $opTypes ); ?></td> <td><input type="text" name="filter[terms][<?= $i ?>][val]" value="<?= $_REQUEST['filter']['terms'][$i]['val'] ?>"/></td> <?php } } else { ?> <td><?= buildSelect( "filter[terms][$i][op]", $opTypes ); ?></td> <td><input type="text" name="filter[terms][<?= $i ?>][val]" value="<?= isset($_REQUEST['filter']['terms'][$i]['val'])?$_REQUEST['filter']['terms'][$i]['val']:'' ?>"/></td> <?php } ?> <td><?php if ( count($_REQUEST['filter']['terms']) > 2 ) { echo buildSelect( "filter[terms][$i][cbr]", $cbracketTypes ); } else { ?>&nbsp;<?php } ?></td> <td><input type="button" onclick="addTerm( this, <?= $i+1 ?> )" value="+"/><?php if ( $_REQUEST['filter']['terms'] > 1 ) { ?><input type="button" onclick="delTerm( this, <?= $i ?> )" value="-"/><?php } ?></td> </tr> <?php } ?> </tbody> </table> <hr/> <table id="sortTable" class="filterTable" cellspacing="0"> <tbody> <tr> <td><label for="sort_field"><?= $SLANG['SortBy'] ?></label><?= buildSelect( "sort_field", $sort_fields ); ?><?= buildSelect( "sort_asc", $sort_dirns ); ?></td> <td><label for="limit"><?= $SLANG['LimitResultsPre'] ?></label><input type="text" size="6" id="limit" name="limit" value="<?= isset($_REQUEST['limit'])?validInt($_REQUEST['limit']):"" ?>"/><?= $SLANG['LimitResultsPost'] ?></td> </tr> </tbody> </table> <hr/> <table id="actionsTable" class="filterTable" cellspacing="0"> <tbody> <tr> <td><?= $SLANG['FilterArchiveEvents'] ?></td> <td><input type="checkbox" name="autoArchive" value="1"<?php if ( !empty($dbFilter['AutoArchive']) ) { ?> checked="checked"<?php } ?> onclick="updateButtons( this )"/></td> </tr> <?php if ( ZM_OPT_FFMPEG ) { ?> <tr> <td><?= $SLANG['FilterVideoEvents'] ?></td> <td><input type="checkbox" name="autoVideo" value="1"<?php if ( !empty($dbFilter['AutoVideo']) ) { ?> checked="checked"<?php } ?> onclick="updateButtons( this )"/></td> </tr> <?php } if ( ZM_OPT_UPLOAD ) { ?> <tr> <td><?= $SLANG['FilterUploadEvents'] ?></td> <td><input type="checkbox" name="autoUpload" value="1"<?php if ( !empty($dbFilter['AutoUpload']) ) { ?> checked="checked"<?php } ?> onclick="updateButtons( this )"/></td> </tr> <?php } if ( ZM_OPT_EMAIL ) { ?> <tr> <td><?= $SLANG['FilterEmailEvents'] ?></td> <td><input type="checkbox" name="autoEmail" value="1"<?php if ( !empty($dbFilter['AutoEmail']) ) { ?> checked="checked"<?php } ?> onclick="updateButtons( this )"/></td> </tr> <?php } if ( ZM_OPT_MESSAGE ) { ?> <tr> <td><?= $SLANG['FilterMessageEvents'] ?></td> <td><input type="checkbox" name="autoMessage" value="1"<?php if ( !empty($dbFilter['AutoMessage']) ) { ?> checked="checked"<?php } ?> onclick="updateButtons( this )"/></td> </tr> <?php } ?> <tr> <td><?= $SLANG['FilterExecuteEvents'] ?></td> <td><input type="checkbox" name="autoExecute" value="1"<?php if ( !empty($dbFilter['AutoExecute']) ) { ?> checked="checked"<?php } ?>/><input type="text" name="autoExecuteCmd" value="<?= isset($dbFilter['AutoExecuteCmd'])?$dbFilter['AutoExecuteCmd']:"" ?>" size="32" maxlength="255" onchange="updateButtons( this )"/></td> </tr> <tr> <td><?= $SLANG['FilterDeleteEvents'] ?></td> <td colspan="2"><input type="checkbox" name="autoDelete" value="1"<?php if ( !empty($dbFilter['AutoDelete']) ) { ?> checked="checked"<?php } ?> onclick="updateButtons( this )"/></td> </tr> </tbody> </table> <hr/> <div id="contentButtons"> <input type="submit" value="<?= $SLANG['Submit'] ?>" onclick="submitToEvents( this );"/> <input type="button" name="executeButton" id="executeButton" value="<?= $SLANG['Execute'] ?>" onclick="executeFilter( this );"/> <?php if ( canEdit( 'Events' ) ) { ?> <input type="button" value="<?= $SLANG['Save'] ?>" onclick="saveFilter( this );"/><?php } ?> <?php if ( canEdit( 'Events' ) && isset($dbFilter) ) { ?> <input type="button" value="<?= $SLANG['Delete'] ?>" onclick="deleteFilter( this, '<?= $dbFilter['Name'] ?>' );"/><?php } ?> <input type="button" value="<?= $SLANG['Reset'] ?>" onclick="submitToFilter( this, 1 );"/> </div> </form> </div> </div> </body> </html>
guker/ZoneMinder
web/skins/flat/views/filter.php
PHP
gpl-2.0
13,954
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ VoIP (Voice over IP) related functions """ import os ################### ## Testing stuff ## ################### from fcntl import fcntl from scapy.sendrecv import sniff from scapy.layers.inet import IP,UDP from scapy.layers.rtp import RTP from scapy.utils import get_temp_file def merge(x,y,sample_size=2): if len(x) > len(y): y += "\x00"*(len(x)-len(y)) elif len(x) < len(y): x += "\x00"*(len(y)-len(x)) m = "" ss=sample_size for i in xrange(len(x)/ss): m += x[ss*i:ss*(i+1)]+y[ss*i:ss*(i+1)] return m # return "".join(map(str.__add__, x, y)) def voip_play(s1,list=None,**kargs): FIFO=get_temp_file() FIFO1=FIFO % 1 FIFO2=FIFO % 2 os.mkfifo(FIFO1) os.mkfifo(FIFO2) try: os.system("soxmix -t .ul %s -t .ul %s -t ossdsp /dev/dsp &" % (FIFO1,FIFO2)) c1=open(FIFO1,"w", 4096) c2=open(FIFO2,"w", 4096) fcntl.fcntl(c1.fileno(),fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(c2.fileno(),fcntl.F_SETFL, os.O_NONBLOCK) # dsp,rd = os.popen2("sox -t .ul -c 2 - -t ossdsp /dev/dsp") def play(pkt, last=None): if last is None: last = [] if not pkt: return if not pkt.haslayer(UDP): return ip=pkt.getlayer(IP) if s1 in [ip.src, ip.dst]: if not last: last.append(pkt) return load=last.pop() # x1 = load.load[12:] c1.write(load.load[12:]) if load.getlayer(IP).src == ip.src: # x2 = "" c2.write("\x00"*len(load.load[12:])) last.append(pkt) else: # x2 = pkt.load[:12] c2.write(pkt.load[12:]) # dsp.write(merge(x1,x2)) if list is None: sniff(store=0, prn=play, **kargs) else: for p in list: play(p) finally: os.unlink(FIFO1) os.unlink(FIFO2) def voip_play1(s1,list=None,**kargs): dsp,rd = os.popen2("sox -t .ul - -t ossdsp /dev/dsp") def play(pkt): if not pkt: return if not pkt.haslayer(UDP): return ip=pkt.getlayer(IP) if s1 in [ip.src, ip.dst]: from scapy.config import conf dsp.write(pkt.getlayer(conf.raw_layer).load[12:]) try: if list is None: sniff(store=0, prn=play, **kargs) else: for p in list: play(p) finally: dsp.close() rd.close() def voip_play2(s1,**kargs): dsp,rd = os.popen2("sox -t .ul -c 2 - -t ossdsp /dev/dsp") def play(pkt, last=None): if last is None: last = [] if not pkt: return if not pkt.haslayer(UDP): return ip=pkt.getlayer(IP) if s1 in [ip.src, ip.dst]: if not last: last.append(pkt) return load=last.pop() x1 = load.load[12:] # c1.write(load.load[12:]) if load.getlayer(IP).src == ip.src: x2 = "" # c2.write("\x00"*len(load.load[12:])) last.append(pkt) else: x2 = pkt.load[:12] # c2.write(pkt.load[12:]) dsp.write(merge(x1,x2)) sniff(store=0, prn=play, **kargs) def voip_play3(lst=None,**kargs): dsp,rd = os.popen2("sox -t .ul - -t ossdsp /dev/dsp") try: def play(pkt, dsp=dsp): from scapy.config import conf if pkt and pkt.haslayer(UDP) and pkt.haslayer(conf.raw_layer): dsp.write(pkt.getlayer(RTP).load) if lst is None: sniff(store=0, prn=play, **kargs) else: for p in lst: play(p) finally: try: dsp.close() rd.close() except: pass
kinap/scapy
scapy/modules/voip.py
Python
gpl-2.0
4,288
/* Copyright (C) 2006 - 2008 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Warp_Splinter SD%Complete: 80 SDComment: Includes Sapling (need some better control with these). SDCategory: Tempest Keep, The Botanica EndScriptData */ #include "precompiled.h" /*##### # mob_treant (Sapling) #####*/ #define SPELL_HEAL_FATHER 6262 struct TRINITY_DLL_DECL mob_treantAI : public ScriptedAI { mob_treantAI (Creature *c) : ScriptedAI(c) { WarpGuid = 0; } uint64 WarpGuid; uint32 check_Timer; void Reset() { check_Timer = 0; } void EnterCombat(Unit *who) {} void MoveInLineOfSight(Unit*) {} void UpdateAI(const uint32 diff) { if (!UpdateVictim() ) { if(WarpGuid && check_Timer < diff) { if(Unit *Warp = (Unit*)Unit::GetUnit(*m_creature, WarpGuid)) { if(m_creature->IsWithinMeleeRange(Warp,2.5f)) { int32 CurrentHP_Treant = (int32)m_creature->GetHealth(); Warp->CastCustomSpell(Warp,SPELL_HEAL_FATHER,&CurrentHP_Treant, 0, 0, true,0 ,0, m_creature->GetGUID()); m_creature->DealDamage(m_creature, m_creature->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); return; } m_creature->GetMotionMaster()->MoveFollow(Warp,0,0); } check_Timer = 1000; }else check_Timer -= diff; return; } if (m_creature->getVictim()->GetGUID() != WarpGuid) DoMeleeAttackIfReady(); } }; /*##### # boss_warp_splinter #####*/ #define SAY_AGGRO -1553007 #define SAY_SLAY_1 -1553008 #define SAY_SLAY_2 -1553009 #define SAY_SUMMON_1 -1553010 #define SAY_SUMMON_2 -1553011 #define SAY_DEATH -1553012 #define WAR_STOMP 34716 #define SUMMON_TREANTS 34727 // DBC: 34727, 34731, 34733, 34734, 34736, 34739, 34741 (with Ancestral Life spell 34742) // won't work (guardian summon) #define ARCANE_VOLLEY (HeroicMode?39133:36705) #define CREATURE_TREANT 19949 #define TREANT_SPAWN_DIST 50 //50 yards from Warp Splinter's spawn point float treant_pos[6][3] = { {24.301233, 427.221100, -27.060635}, {16.795492, 359.678802, -27.355425}, {53.493484, 345.381470, -26.196192}, {61.867096, 439.362732, -25.921030}, {109.861877, 423.201630, -27.356019}, {106.780159, 355.582581, -27.593357} }; struct TRINITY_DLL_DECL boss_warp_splinterAI : public ScriptedAI { boss_warp_splinterAI(Creature *c) : ScriptedAI(c) { HeroicMode = c->GetMap()->IsHeroic(); Treant_Spawn_Pos_X = c->GetPositionX(); Treant_Spawn_Pos_Y = c->GetPositionY(); } uint32 War_Stomp_Timer; uint32 Summon_Treants_Timer; uint32 Arcane_Volley_Timer; bool HeroicMode; float Treant_Spawn_Pos_X; float Treant_Spawn_Pos_Y; void Reset() { War_Stomp_Timer = 25000 + rand()%15000; Summon_Treants_Timer = 45000; Arcane_Volley_Timer = 8000 + rand()%12000; m_creature->SetSpeed( MOVE_RUN, 0.7f, true); } void EnterCombat(Unit *who) { DoScriptText(SAY_AGGRO, m_creature); } void KilledUnit(Unit* victim) { switch(rand()%2) { case 0: DoScriptText(SAY_SLAY_1, m_creature); break; case 1: DoScriptText(SAY_SLAY_2, m_creature); break; } } void JustDied(Unit* Killer) { DoScriptText(SAY_DEATH, m_creature); } void SummonTreants() { for(int i = 0; i < 6; ++i) { float angle = (M_PI / 3) * i; float X = Treant_Spawn_Pos_X + TREANT_SPAWN_DIST * cos(angle); float Y = Treant_Spawn_Pos_Y + TREANT_SPAWN_DIST * sin(angle); float O = - m_creature->GetAngle(X,Y); if(Creature *pTreant = m_creature->SummonCreature(CREATURE_TREANT,treant_pos[i][0],treant_pos[i][1],treant_pos[i][2],O,TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN,25000)) ((mob_treantAI*)pTreant->AI())->WarpGuid = m_creature->GetGUID(); } switch(rand()%2) { case 0: DoScriptText(SAY_SUMMON_1, m_creature); break; case 1: DoScriptText(SAY_SUMMON_2, m_creature); break; } } void UpdateAI(const uint32 diff) { if (!UpdateVictim() ) return; //Check for War Stomp if(War_Stomp_Timer < diff) { DoCast(m_creature->getVictim(),WAR_STOMP); War_Stomp_Timer = 25000 + rand()%15000; }else War_Stomp_Timer -= diff; //Check for Arcane Volley if(Arcane_Volley_Timer < diff) { DoCast(m_creature->getVictim(),ARCANE_VOLLEY); Arcane_Volley_Timer = 20000 + rand()%15000; }else Arcane_Volley_Timer -= diff; //Check for Summon Treants if(Summon_Treants_Timer < diff) { SummonTreants(); Summon_Treants_Timer = 45000; }else Summon_Treants_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_warp_splinter(Creature *_Creature) { return new boss_warp_splinterAI (_Creature); } CreatureAI* GetAI_mob_treant(Creature *_Creature) { return new mob_treantAI (_Creature); } void AddSC_boss_warp_splinter() { Script *newscript; newscript = new Script; newscript->Name="boss_warp_splinter"; newscript->GetAI = &GetAI_boss_warp_splinter; newscript->RegisterSelf(); newscript = new Script; newscript->Name="mob_warp_splinter_treant"; newscript->GetAI = &GetAI_mob_treant; newscript->RegisterSelf(); }
Bootz/TC-One
src/bindings/scripts/scripts/zone/tempest_keep/botanica/boss_warp_splinter.cpp
C++
gpl-2.0
6,578
# # Copyright (C) 2006 Red Hat, Inc. # Copyright (C) 2006 Daniel P. Berrange <berrange@redhat.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301 USA. # class vmmSecret(object): def __init__(self, name, secret=None, attributes=None): self.name = name self.secret = secret if attributes == None: attributes = {} self.attributes = attributes def set_secret(self, data): self.secret = data def get_secret(self): return self.secret def get_name(self): return self.name def get_attributes(self): return self.attributes def has_attribute(self, key): return key in self.attributes def add_attribute(self, key, value): if type(value) != str: value = str(value) self.attributes[key] = value def list_attributes(self): return self.attributes.keys() def get_attribute(self, key): return self.attributes[key]
dumbbell/virt-manager
src/virtManager/secret.py
Python
gpl-2.0
1,629
<?php /////////////////////////////////////////////////////////////////////////// // // // NOTICE OF COPYRIGHT // // // // Adeada Talleres Electricos // // http://www.grupogisma.com // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details: // // // // http://www.gnu.org/copyleft/gpl.html // // // /////////////////////////////////////////////////////////////////////////// require('../../../functions/globales.php'); require('../include/rutas.php'); require('../functions/main.php'); require('../struct/login2.php'); include('../struct/header_dir.php'); require('../functions/dir_functions.php'); require('dir_preacciones.php'); ?> <script>document.getElementById("lnk_direccion").setAttribute("class", "seleccionado");</script> <script>document.getElementById("lnk_ver_reuniones").setAttribute("class", "seleccionado");</script> <div id="cuerpo2"> <form action="ver_reuniones.php" id="crear_reunion" name="form_crear" method="post"> <input type='hidden' name='new_reunion' value='new_reunion'></input> <table class="tabla_sin_borde" width="100%"> <tr> <td width="25%">Departamento:</td> <td> Selecci&oacute;nalo: <select name='departamento' id='departamento' onChange="$('#departamento_tipo').attr('value', this.value);"> <option value=''></option> <?php $departamentos = mostrar_departamentos(); foreach($departamentos as $key => $valor){ ?> <option value='<?php echo $valor[0]; ?>'><?php echo $valor[0]; ?></option> <?php }?> </select> , o introduce uno nuevo: <input type='text' name='departamento_tipo' id='departamento_tipo' class='requerido' value='' size=35></input> </td> </tr> <tr> <td>Fecha:</td> <td><input type='text' name='fecha' id='fecha' value='' size='14'></input> <img style="cursor:pointer;" src='<?php echo CAL_RUTA_NIVEL1."img/calendar2.png";?>' id='edit_fechacreacion'> <script> Calendar.setup({ trigger : "edit_fechacreacion", inputField : "fecha" }); </script> </td> </tr> <tr> <td>Asistentes:</td> <td><input type="text" name='asistentes' id="asistentes" value='' size='60'></td> </tr> <tr> <td>Objeto de la reuni&oacute;n:</td> <td><input type="text" name='objeto' id="objeto" value='' size='35'></td> </tr> <tr> <td>Fecha siguiente reuni&oacute;n:</td> <td><input type='text' name='fechasig' id='fechasig' value='' size='14'></input> <img style="cursor:pointer;" src='<?php echo CAL_RUTA_NIVEL1."img/calendar2.png";?>' id='cal1'> <script> Calendar.setup({ trigger : "cal1", inputField : "fechasig" }); </script> </td> </tr> <tr> <td>Hora:</td> <td><input type="text" name='hora_siguiente' id="hora_siguiente" value='' size='14'></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td> <input class="bt-accion" type="button" onclick="$('#crear_reunion').submit();" name="img_crear" id="img_crear" value="Crear" /> <input class="bt-accion" type="button" onclick="$('#cancelar_<?php echo $valor['id']; ?>').submit();" name="img_cancelar" id="img_cancelar<?php echo $valor['id']; ?>" value="Cancelar" /> </td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> </form> <form action="ver_reuniones.php" method="post" id="cancelar_<?php echo $valor['id'];?>"> </form> </div> <?php include('../struct/footer2.php');?> </div> </div> </body> </html>
Esleelkartea/kz-adeada-talleres-electricos-
kzadeadatallereselectricos_v1.0.0_win32_installer/windows/xampp/htdocs/kz_adeada_talleres_electricos/commons/calidad/dir/nueva_reunion.php
PHP
gpl-2.0
4,891
/* * Player - One Hell of a Robot Server * Copyright (C) 2010 * Mayte Lázaro, Alejandro R. Mosteo * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SCAN_H_ #define SCAN_H_ #include <vector> #include "types.hh" #include "uloc.hh" class Scan { public: /// Provide laser parameters: maximum range and its pose on top of robot, /// and noise model. Scan(double max_range, double laser_x, double laser_y, double laser_angle, double laser_noise_range, double laser_noise_bearing); const Uloc & uloc(const int i) const; // read only access /// Update laser pose void SetLaserPose(double x, double y, double a); /// Set last laser reading /// Removes out of range values and attaches the uncertainty model void SetLastScan(const DoublesVector& ranges, const DoublesVector& bearings); int ScanCount(void) const; double phi(const int i) const; double rho(const int i) const; const double kOutOfRange_; const double kLaserNoiseRange_; const double kLaserNoiseBearing_; private: Uloc AttachReferenceToScanPoint(double rho, double phi); void addUloc(Uloc u); vector<Uloc> ulocs_; DoublesVector rho_; // Distance DoublesVector phi_; // Bearing Transf xform_laser_to_robot_; }; #endif /* SCAN_H_ */
sunsided/player
server/drivers/localization/ekfvloc/scan.hh
C++
gpl-2.0
2,078
/* html:after { display: none; content: '--small: (max-width: 500px) | --medium: (max-width: 1100px) | --large: (min-width: 1100px)'; } */ (function(window){ /*jshint eqnull:true */ 'use strict'; var docElem = document.documentElement; var create = function(){ if(!window.lazySizes || window.lazySizes.getCustomMedias){return;} var lazySizes = window.lazySizes; lazySizes.getCustomMedias = (function(){ var regCleanPseudos = /['"]/g; var regSplit = /\s*\|\s*/g; var regNamedQueries = /^([a-z0-9_-]+)\s*:\s*(.+)$/i; var getStyle = function(elem, pseudo){ return (getComputedStyle(elem, pseudo).getPropertyValue('content') || 'none').replace(regCleanPseudos, '').trim(); }; var parse = function(string, object){ string.split(regSplit).forEach(function(query){ if(query.match(regNamedQueries)){ object[RegExp.$1] = RegExp.$2; } }); }; return function(object, element){ object = object || lazySizes.cfg.customMedia; element = element || document.querySelector('html'); parse(getStyle(element, ':before'), object); parse(getStyle(element, ':after'), object); return object; }; })(); lazySizes.updateCustomMedia = function(){ var i, len, customMedia; var elems = docElem.querySelectorAll('source[media][data-media][srcset]'); lazySizes.getCustomMedias(); for(i = 0, len = elems.length; i < len; i++){ if( (customMedia = lazySizes.cfg.customMedia[elems[i].getAttribute('data-media') || elems[i].getAttribute('media')]) ){ elems[i].setAttribute('media', customMedia); } } if(!window.HTMLPictureElement){ elems = docElem.querySelector('source[media][data-media][srcset] ~ img'); for(i = 0, len = elems.length; i < len; i++){ lazySizes.uP(elems[i]); } } lazySizes.autoSizer.checkElems(); }; lazySizes.getCustomMedias(); docElem.removeEventListener('lazybeforeunveil', create); }; if(window.addEventListener){ docElem.addEventListener('lazybeforeunveil', create); create(); setTimeout(create); } })(window);
georges5/bcangular
wp-content/plugins/wp-lazysizes-master/js/lazysizes/plugins/custommedia/ls.custommedia.js
JavaScript
gpl-2.0
2,072
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'list', 'pt-br', { bulletedlist: 'Lista sem números', numberedlist: 'Lista numerada' } );
SeeyaSia/www
web/libraries/ckeditor/plugins/list/lang/pt-br.js
JavaScript
gpl-2.0
262
<?php /** * @version $Id: default.php 21463 2011-06-06 15:28:10Z dextercowley $ * @package Joomla.Installation * @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; ?> <div id="step"> <div class="far-right"> <?php if ($this->document->direction == 'ltr') : ?> <div class="button1-right"><div class="prev"><a href="index.php?view=preinstall" onclick="return Install.goToPage('preinstall');" rel="prev" title="<?php echo JText::_('JPREVIOUS'); ?>"><?php echo JText::_('JPREVIOUS'); ?></a></div></div> <div class="button1-left"><div class="next"><a href="index.php?view=database" onclick="return Install.goToPage('database');" rel="next" title="<?php echo JText::_('JNEXT'); ?>"><?php echo JText::_('JNEXT'); ?></a></div></div> <?php elseif ($this->document->direction == 'rtl') : ?> <div class="button1-right"><div class="prev"><a href="index.php?view=database" onclick="return Install.goToPage('database');" rel="next" title="<?php echo JText::_('JNEXT'); ?>"><?php echo JText::_('JNEXT'); ?></a></div></div> <div class="button1-left"><div class="next"><a href="index.php?view=preinstall" onclick="return Install.goToPage('preinstall');" rel="prev" title="<?php echo JText::_('JPREVIOUS'); ?>"><?php echo JText::_('JPREVIOUS'); ?></a></div></div> <?php endif; ?> </div> <span class="steptitle"><?php echo JText::_('INSTL_LICENSE'); ?></span> </div> <form action="index.php" method="post" id="adminForm" class="form-validate"> <div id="installer"> <div class="m"> <h2><?php echo JText::_('INSTL_GNU_GPL_LICENSE'); ?></h2> <iframe src="gpl.html" class="license" marginwidth="25" scrolling="auto"></iframe> </div> </div> <input type="hidden" name="task" value="" /> <?php echo JHtml::_('form.token'); ?> </form>
heqiaoliu/Viral-Dark-Matter
tmp/install_4f20924cbb0a1/installation/views/license/tmpl/default.php
PHP
gpl-2.0
1,877
(function(){ // module factory: start var moduleFactory = function($) { // module body: start var module = this; $.require() .script("moment") .done(function() { var exports = function() { $.moment.lang('ar-ma', { months : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), monthsShort : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), weekdays : "الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"), weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); }; exports(); module.resolveWith(exports); }); // module body: end }; // module factory: end FD50.module("moment/ar-ma", moduleFactory); }());
BetterBetterBetter/B3App
media/foundry/5.0/scripts/moment/ar-ma.js
JavaScript
gpl-2.0
2,156
require "test_helper" module Api class TracesControllerTest < ActionDispatch::IntegrationTest ## # test all routes which lead to this controller def test_routes assert_routing( { :path => "/api/0.6/gpx/create", :method => :post }, { :controller => "api/traces", :action => "create" } ) assert_routing( { :path => "/api/0.6/gpx/1", :method => :get }, { :controller => "api/traces", :action => "show", :id => "1" } ) assert_routing( { :path => "/api/0.6/gpx/1", :method => :put }, { :controller => "api/traces", :action => "update", :id => "1" } ) assert_routing( { :path => "/api/0.6/gpx/1", :method => :delete }, { :controller => "api/traces", :action => "destroy", :id => "1" } ) assert_recognizes( { :controller => "api/traces", :action => "show", :id => "1" }, { :path => "/api/0.6/gpx/1/details", :method => :get } ) assert_routing( { :path => "/api/0.6/gpx/1/data", :method => :get }, { :controller => "api/traces", :action => "data", :id => "1" } ) assert_routing( { :path => "/api/0.6/gpx/1/data.xml", :method => :get }, { :controller => "api/traces", :action => "data", :id => "1", :format => "xml" } ) end # Check getting a specific trace through the api def test_show public_trace_file = create(:trace, :visibility => "public") # First with no auth get api_trace_path(public_trace_file) assert_response :unauthorized # Now with some other user, which should work since the trace is public auth_header = basic_authorization_header create(:user).display_name, "test" get api_trace_path(public_trace_file), :headers => auth_header assert_response :success # And finally we should be able to do it with the owner of the trace auth_header = basic_authorization_header public_trace_file.user.display_name, "test" get api_trace_path(public_trace_file), :headers => auth_header assert_response :success end # Check an anonymous trace can't be specifically fetched by another user def test_show_anon anon_trace_file = create(:trace, :visibility => "private") # First with no auth get api_trace_path(anon_trace_file) assert_response :unauthorized # Now try with another user, which shouldn't work since the trace is anon auth_header = basic_authorization_header create(:user).display_name, "test" get api_trace_path(anon_trace_file), :headers => auth_header assert_response :forbidden # And finally we should be able to get the trace details with the trace owner auth_header = basic_authorization_header anon_trace_file.user.display_name, "test" get api_trace_path(anon_trace_file), :headers => auth_header assert_response :success end # Check the api details for a trace that doesn't exist def test_show_not_found deleted_trace_file = create(:trace, :deleted) # Try first with no auth, as it should require it get api_trace_path(:id => 0) assert_response :unauthorized # Login, and try again auth_header = basic_authorization_header deleted_trace_file.user.display_name, "test" get api_trace_path(:id => 0), :headers => auth_header assert_response :not_found # Now try a trace which did exist but has been deleted auth_header = basic_authorization_header deleted_trace_file.user.display_name, "test" get api_trace_path(deleted_trace_file), :headers => auth_header assert_response :not_found end # Test downloading a trace through the api def test_data public_trace_file = create(:trace, :visibility => "public", :fixture => "a") # First with no auth get api_trace_data_path(public_trace_file) assert_response :unauthorized # Now with some other user, which should work since the trace is public auth_header = basic_authorization_header create(:user).display_name, "test" get api_trace_data_path(public_trace_file), :headers => auth_header follow_redirect! follow_redirect! check_trace_data public_trace_file, "848caa72f2f456d1bd6a0fdf228aa1b9" # And finally we should be able to do it with the owner of the trace auth_header = basic_authorization_header public_trace_file.user.display_name, "test" get api_trace_data_path(public_trace_file), :headers => auth_header follow_redirect! follow_redirect! check_trace_data public_trace_file, "848caa72f2f456d1bd6a0fdf228aa1b9" end # Test downloading a compressed trace through the api def test_data_compressed identifiable_trace_file = create(:trace, :visibility => "identifiable", :fixture => "d") # Authenticate as the owner of the trace we will be using auth_header = basic_authorization_header identifiable_trace_file.user.display_name, "test" # First get the data as is get api_trace_data_path(identifiable_trace_file), :headers => auth_header follow_redirect! follow_redirect! check_trace_data identifiable_trace_file, "c6422a3d8750faae49ed70e7e8a51b93", "application/gzip", "gpx.gz" # Now ask explicitly for XML format get api_trace_data_path(identifiable_trace_file, :format => "xml"), :headers => auth_header check_trace_data identifiable_trace_file, "abd6675fdf3024a84fc0a1deac147c0d", "application/xml", "xml" # Now ask explicitly for GPX format get api_trace_data_path(identifiable_trace_file, :format => "gpx"), :headers => auth_header check_trace_data identifiable_trace_file, "abd6675fdf3024a84fc0a1deac147c0d" end # Check an anonymous trace can't be downloaded by another user through the api def test_data_anon anon_trace_file = create(:trace, :visibility => "private", :fixture => "b") # First with no auth get api_trace_data_path(anon_trace_file) assert_response :unauthorized # Now with some other user, which shouldn't work since the trace is anon auth_header = basic_authorization_header create(:user).display_name, "test" get api_trace_data_path(anon_trace_file), :headers => auth_header assert_response :forbidden # And finally we should be able to do it with the owner of the trace auth_header = basic_authorization_header anon_trace_file.user.display_name, "test" get api_trace_data_path(anon_trace_file), :headers => auth_header follow_redirect! follow_redirect! check_trace_data anon_trace_file, "db4cb5ed2d7d2b627b3b504296c4f701" end # Test downloading a trace that doesn't exist through the api def test_data_not_found deleted_trace_file = create(:trace, :deleted) # Try first with no auth, as it should require it get api_trace_data_path(:id => 0) assert_response :unauthorized # Login, and try again auth_header = basic_authorization_header create(:user).display_name, "test" get api_trace_data_path(:id => 0), :headers => auth_header assert_response :not_found # Now try a trace which did exist but has been deleted auth_header = basic_authorization_header deleted_trace_file.user.display_name, "test" get api_trace_data_path(deleted_trace_file), :headers => auth_header assert_response :not_found end # Test creating a trace through the api def test_create # Get file to use fixture = Rails.root.join("test/gpx/fixtures/a.gpx") file = Rack::Test::UploadedFile.new(fixture, "application/gpx+xml") user = create(:user) # First with no auth post gpx_create_path, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :visibility => "trackable" } assert_response :unauthorized # Rewind the file file.rewind # Now authenticated create(:user_preference, :user => user, :k => "gps.trace.visibility", :v => "identifiable") assert_not_equal "trackable", user.preferences.where(:k => "gps.trace.visibility").first.v auth_header = basic_authorization_header user.display_name, "test" post gpx_create_path, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :visibility => "trackable" }, :headers => auth_header assert_response :success trace = Trace.find(response.body.to_i) assert_equal "a.gpx", trace.name assert_equal "New Trace", trace.description assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag) assert_equal "trackable", trace.visibility assert_not trace.inserted assert_equal File.new(fixture).read, trace.file.blob.download trace.destroy assert_equal "trackable", user.preferences.where(:k => "gps.trace.visibility").first.v # Rewind the file file.rewind # Now authenticated, with the legacy public flag assert_not_equal "public", user.preferences.where(:k => "gps.trace.visibility").first.v auth_header = basic_authorization_header user.display_name, "test" post gpx_create_path, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :public => 1 }, :headers => auth_header assert_response :success trace = Trace.find(response.body.to_i) assert_equal "a.gpx", trace.name assert_equal "New Trace", trace.description assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag) assert_equal "public", trace.visibility assert_not trace.inserted assert_equal File.new(fixture).read, trace.file.blob.download trace.destroy assert_equal "public", user.preferences.where(:k => "gps.trace.visibility").first.v # Rewind the file file.rewind # Now authenticated, with the legacy private flag second_user = create(:user) assert_nil second_user.preferences.where(:k => "gps.trace.visibility").first auth_header = basic_authorization_header second_user.display_name, "test" post gpx_create_path, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :public => 0 }, :headers => auth_header assert_response :success trace = Trace.find(response.body.to_i) assert_equal "a.gpx", trace.name assert_equal "New Trace", trace.description assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag) assert_equal "private", trace.visibility assert_not trace.inserted assert_equal File.new(fixture).read, trace.file.blob.download trace.destroy assert_equal "private", second_user.preferences.where(:k => "gps.trace.visibility").first.v end # Check updating a trace through the api def test_update public_trace_file = create(:trace, :visibility => "public", :fixture => "a") deleted_trace_file = create(:trace, :deleted) anon_trace_file = create(:trace, :visibility => "private") # First with no auth put api_trace_path(public_trace_file), :params => create_trace_xml(public_trace_file) assert_response :unauthorized # Now with some other user, which should fail auth_header = basic_authorization_header create(:user).display_name, "test" put api_trace_path(public_trace_file), :params => create_trace_xml(public_trace_file), :headers => auth_header assert_response :forbidden # Now with a trace which doesn't exist auth_header = basic_authorization_header create(:user).display_name, "test" put api_trace_path(:id => 0), :params => create_trace_xml(public_trace_file), :headers => auth_header assert_response :not_found # Now with a trace which did exist but has been deleted auth_header = basic_authorization_header deleted_trace_file.user.display_name, "test" put api_trace_path(deleted_trace_file), :params => create_trace_xml(deleted_trace_file), :headers => auth_header assert_response :not_found # Now try an update with the wrong ID auth_header = basic_authorization_header public_trace_file.user.display_name, "test" put api_trace_path(public_trace_file), :params => create_trace_xml(anon_trace_file), :headers => auth_header assert_response :bad_request, "should not be able to update a trace with a different ID from the XML" # And finally try an update that should work auth_header = basic_authorization_header public_trace_file.user.display_name, "test" t = public_trace_file t.description = "Changed description" t.visibility = "private" put api_trace_path(t), :params => create_trace_xml(t), :headers => auth_header assert_response :success nt = Trace.find(t.id) assert_equal nt.description, t.description assert_equal nt.visibility, t.visibility end # Test that updating a trace doesn't duplicate the tags def test_update_tags tracetag = create(:tracetag) trace = tracetag.trace auth_header = basic_authorization_header trace.user.display_name, "test" put api_trace_path(trace), :params => create_trace_xml(trace), :headers => auth_header assert_response :success updated = Trace.find(trace.id) # Ensure there's only one tag in the database after updating assert_equal(1, Tracetag.count) # The new tag object might have a different id, so check the string representation assert_equal trace.tagstring, updated.tagstring end # Check deleting a trace through the api def test_destroy public_trace_file = create(:trace, :visibility => "public") # First with no auth delete api_trace_path(public_trace_file) assert_response :unauthorized # Now with some other user, which should fail auth_header = basic_authorization_header create(:user).display_name, "test" delete api_trace_path(public_trace_file), :headers => auth_header assert_response :forbidden # Now with a trace which doesn't exist auth_header = basic_authorization_header create(:user).display_name, "test" delete api_trace_path(:id => 0), :headers => auth_header assert_response :not_found # And finally we should be able to do it with the owner of the trace auth_header = basic_authorization_header public_trace_file.user.display_name, "test" delete api_trace_path(public_trace_file), :headers => auth_header assert_response :success # Try it a second time, which should fail auth_header = basic_authorization_header public_trace_file.user.display_name, "test" delete api_trace_path(public_trace_file), :headers => auth_header assert_response :not_found end private def check_trace_data(trace, digest, content_type = "application/gpx+xml", extension = "gpx") assert_response :success assert_equal digest, Digest::MD5.hexdigest(response.body) assert_equal content_type, response.media_type assert_equal "attachment; filename=\"#{trace.id}.#{extension}\"; filename*=UTF-8''#{trace.id}.#{extension}", @response.header["Content-Disposition"] end ## # build XML for traces # this builds a minimum viable XML for the tests in this suite def create_trace_xml(trace) root = XML::Document.new root.root = XML::Node.new "osm" trc = XML::Node.new "gpx_file" trc["id"] = trace.id.to_s trc["visibility"] = trace.visibility trc["visible"] = trace.visible.to_s desc = XML::Node.new "description" desc << trace.description trc << desc trace.tags.each do |tag| t = XML::Node.new "tag" t << tag.tag trc << t end root.root << trc root.to_s end end end
tomhughes/openstreetmap-website
test/controllers/api/traces_controller_test.rb
Ruby
gpl-2.0
15,842
<?php /** * @package EasyDiscuss * @copyright Copyright (C) 2010 Stack Ideas Private Limited. All rights reserved. * @license GNU/GPL, see LICENSE.php * * EasyDiscuss is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ defined('_JEXEC') or die('Restricted access'); require_once dirname( __FILE__ ) . '/model.php'; class EasyDiscussModelLabels extends EasyDiscussModel { protected $_total = null; protected $_pagination = null; protected $_data = null; public function __construct() { parent::__construct( array() ); $app = JFactory::getApplication(); $limit = $app->getUserStateFromRequest( 'com_easydiscuss.labels.limit', 'limit', DiscussHelper::getListLimit(), 'int'); $limitstart = JRequest::getVar('limitstart', 0, '', 'int'); $this->setState('limit' , $limit); $this->setState('limitstart', $limitstart); } /** * Method to get the total number of the labels * * @access public * @return integer */ public function getTotal() { // Lets load the content if it doesn't already exist if (empty($this->_total)) { $query = $this->_buildQuery(); $this->_total = $this->_getListCount($query); } return $this->_total; } /** * Method to get a pagination object for the labels * * @access public * @return integer */ public function getPagination() { // Lets load the content if it doesn't already exist if (empty($this->_pagination)) { jimport('joomla.html.pagination'); $this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') ); } return $this->_pagination; } /** * Method to build the query for the labels * * @access private * @return string */ private function _buildQuery() { // Get the WHERE and ORDER BY clauses for the query $where = $this->_buildQueryWhere(); $orderby = $this->_buildQueryOrderBy(); $db = DiscussHelper::getDBO(); $query = 'SELECT * FROM ' . $db->nameQuote( '#__discuss_posts_labels' ) . $where . ' ' . $orderby; return $query; } private function _buildQueryWhere() { $app = JFactory::getApplication(); $db = DiscussHelper::getDBO(); $filter_state = $app->getUserStateFromRequest( 'com_easydiscuss.labels.filter_state', 'filter_state', '', 'word' ); $search = $app->getUserStateFromRequest( 'com_easydiscuss.labels.search', 'search', '', 'string' ); $search = $db->getEscaped( trim(JString::strtolower( $search ) ) ); $where = array(); if ( $filter_state ) { if ( $filter_state == 'P' ) { $where[] = $db->nameQuote( 'published' ) . '=' . $db->Quote( '1' ); } else if ($filter_state == 'U' ) { $where[] = $db->nameQuote( 'published' ) . '=' . $db->Quote( '0' ); } } if ($search) { $where[] = ' LOWER( title ) LIKE \'%' . $search . '%\' '; } $where = ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' ); return $where; } private function _buildQueryOrderBy() { $app = JFactory::getApplication(); $filter_order = $app->getUserStateFromRequest( 'com_easydiscuss.labels.filter_order', 'filter_order', 'ordering ASC' , 'int' ); $filter_order_Dir = $app->getUserStateFromRequest( 'com_easydiscuss.labels.filter_order_Dir', 'filter_order_Dir', '' , 'word' ); $orderby = ' ORDER BY '.$filter_order.' '.$filter_order_Dir; return $orderby; } /** * Method to get labels item data * * @access public * @return array */ public function getData() { // Lets load the content if it doesn't already exist if (empty($this->_data)) { $query = $this->_buildQuery(); $this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit')); } return $this->_data; } /** * Method to publish or unpublish labels * * @access public * @return boolean */ public function publish( $labels = array(), $publish = true ) { if( is_integer($labels) ) { $labels = array($labels); } elseif ( !is_array($labels) || count($labels) < 1 ) { return false; } $labels = implode( ',' , $labels ); $publish = $publish ? 1 : 0; $db = DiscussHelper::getDBO(); $query = 'UPDATE ' . $db->nameQuote( '#__discuss_posts_labels' ) . ' SET ' . $db->nameQuote( 'published' ) . '=' . $db->Quote( $publish ) . ' WHERE ' . $db->nameQuote( 'id' ) . ' IN (' . $labels . ')'; $db->setQuery( $query ); if( !$db->query() ) { $this->setError($this->_db->getErrorMsg()); return false; } return true; } public function searchLabel($title) { $db = DiscussHelper::getDBO(); $query = 'SELECT ' . $db->nameQuote('id') . ' ' . 'FROM ' . $db->nameQuote('#__discuss_posts_labels') . ' ' . 'WHERE ' . $db->nameQuote('title') . ' = ' . $db->quote($title) . ' ' . 'LIMIT 1'; $db->setQuery($query); $result = $db->loadObject(); return $result; } public function getLabelTitle($id) { $db = DiscussHelper::getDBO(); $query = 'SELECT ' . $db->nameQuote('title') . ' ' . 'FROM ' . $db->nameQuote('#__discuss_posts_labels') . ' ' . 'WHERE ' . $db->nameQuote('id') . ' = ' . $db->quote($id) . ' ' . 'LIMIT 1'; $db->setQuery($query); $result = $db->loadResult(); return $result; } /** * Method to get total labels * * @access public * @return integer */ public function getTotalLabels( $ignoreUnpublish = false ) { $db = DiscussHelper::getDBO(); $query = 'SELECT COUNT(1) FROM ' . $db->nameQuote( '#__discuss_posts_labels' ); $query .= $ignoreUnpublish ? '' : ' WHERE `published` = 1'; $db->setQuery( $query ); $result = $db->loadResult(); return (empty($result)) ? 0 : $result; } public function getLabels() { $db = DiscussHelper::getDBO(); $query = ' SELECT `id`, `title` ' . ' FROM #__discuss_posts_labels ' . ' WHERE `published` = 1 ' . ' ORDER BY `ordering`'; $db->setQuery($query); $result = $db->loadObjectList(); return $result; } }
BetterBetterBetter/B3App
components/com_easydiscuss/models/labels.php
PHP
gpl-2.0
6,201
/** * Playlist Loader */ import Event from '../events'; import EventHandler from '../event-handler'; import {ErrorTypes, ErrorDetails} from '../errors'; import URLHelper from '../utils/url'; import AttrList from '../utils/attr-list'; //import {logger} from '../utils/logger'; class PlaylistLoader extends EventHandler { constructor(hls) { super(hls, Event.MANIFEST_LOADING, Event.LEVEL_LOADING); } destroy() { if (this.loader) { this.loader.destroy(); this.loader = null; } this.url = this.id = null; EventHandler.prototype.destroy.call(this); } onManifestLoading(data) { this.load(data.url, null); } onLevelLoading(data) { this.load(data.url, data.level, data.id); } load(url, id1, id2) { var config = this.hls.config, retry, timeout, retryDelay; if (this.loading && this.loader) { if (this.url === url && this.id === id1 && this.id2 === id2) { // same request than last pending one, don't do anything return; } else { // one playlist load request is pending, but with different params, abort it before loading new playlist this.loader.abort(); } } this.url = url; this.id = id1; this.id2 = id2; if(this.id === null) { retry = config.manifestLoadingMaxRetry; timeout = config.manifestLoadingTimeOut; retryDelay = config.manifestLoadingRetryDelay; } else { retry = config.levelLoadingMaxRetry; timeout = config.levelLoadingTimeOut; retryDelay = config.levelLoadingRetryDelay; } this.loader = typeof(config.pLoader) !== 'undefined' ? new config.pLoader(config) : new config.loader(config); this.loading = true; this.loader.load(url, '', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), timeout, retry, retryDelay); } resolve(url, baseUrl) { return URLHelper.buildAbsoluteURL(baseUrl, url); } parseMasterPlaylist(string, baseurl) { let levels = [], result; // https://regex101.com is your friend const re = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g; while ((result = re.exec(string)) != null){ const level = {}; var attrs = level.attrs = new AttrList(result[1]); level.url = this.resolve(result[2], baseurl); var resolution = attrs.decimalResolution('RESOLUTION'); if(resolution) { level.width = resolution.width; level.height = resolution.height; } level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'); level.name = attrs.NAME; var codecs = attrs.CODECS; if(codecs) { codecs = codecs.split(','); for (let i = 0; i < codecs.length; i++) { const codec = codecs[i]; if (codec.indexOf('avc1') !== -1) { level.videoCodec = this.avc1toavcoti(codec); } else { level.audioCodec = codec; } } } levels.push(level); } return levels; } avc1toavcoti(codec) { var result, avcdata = codec.split('.'); if (avcdata.length > 2) { result = avcdata.shift() + '.'; result += parseInt(avcdata.shift()).toString(16); result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4); } else { result = codec; } return result; } cloneObj(obj) { return JSON.parse(JSON.stringify(obj)); } parseLevelPlaylist(string, baseurl, id) { var currentSN = 0, totalduration = 0, level = {url: baseurl, fragments: [], live: true, startSN: 0}, levelkey = {method : null, key : null, iv : null, uri : null}, cc = 0, programDateTime = null, frag = null, result, regexp, byteRangeEndOffset, byteRangeStartOffset; regexp = /(?:#EXT-X-(MEDIA-SEQUENCE):(\d+))|(?:#EXT-X-(TARGETDURATION):(\d+))|(?:#EXT-X-(KEY):(.*))|(?:#EXT(INF):([\d\.]+)[^\r\n]*([\r\n]+[^#|\r\n]+)?)|(?:#EXT-X-(BYTERANGE):([\d]+[@[\d]*)]*[\r\n]+([^#|\r\n]+)?|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(PROGRAM-DATE-TIME):(.*))/g; while ((result = regexp.exec(string)) !== null) { result.shift(); result = result.filter(function(n) { return (n !== undefined); }); switch (result[0]) { case 'MEDIA-SEQUENCE': currentSN = level.startSN = parseInt(result[1]); break; case 'TARGETDURATION': level.targetduration = parseFloat(result[1]); break; case 'ENDLIST': level.live = false; break; case 'DIS': cc++; break; case 'BYTERANGE': var params = result[1].split('@'); if (params.length === 1) { byteRangeStartOffset = byteRangeEndOffset; } else { byteRangeStartOffset = parseInt(params[1]); } byteRangeEndOffset = parseInt(params[0]) + byteRangeStartOffset; if (frag && !frag.url) { frag.byteRangeStartOffset = byteRangeStartOffset; frag.byteRangeEndOffset = byteRangeEndOffset; frag.url = this.resolve(result[2], baseurl); } break; case 'INF': var duration = parseFloat(result[1]); if (!isNaN(duration)) { var fragdecryptdata, sn = currentSN++; if (levelkey.method && levelkey.uri && !levelkey.iv) { fragdecryptdata = this.cloneObj(levelkey); var uint8View = new Uint8Array(16); for (var i = 12; i < 16; i++) { uint8View[i] = (sn >> 8*(15-i)) & 0xff; } fragdecryptdata.iv = uint8View; } else { fragdecryptdata = levelkey; } var url = result[2] ? this.resolve(result[2], baseurl) : null; frag = {url: url, duration: duration, start: totalduration, sn: sn, level: id, cc: cc, byteRangeStartOffset: byteRangeStartOffset, byteRangeEndOffset: byteRangeEndOffset, decryptdata : fragdecryptdata, programDateTime: programDateTime}; level.fragments.push(frag); totalduration += duration; byteRangeStartOffset = null; programDateTime = null; } break; case 'KEY': // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4 var decryptparams = result[1]; var keyAttrs = new AttrList(decryptparams); var decryptmethod = keyAttrs.enumeratedString('METHOD'), decrypturi = keyAttrs.URI, decryptiv = keyAttrs.hexadecimalInteger('IV'); if (decryptmethod) { levelkey = { method: null, key: null, iv: null, uri: null }; if ((decrypturi) && (decryptmethod === 'AES-128')) { levelkey.method = decryptmethod; // URI to get the key levelkey.uri = this.resolve(decrypturi, baseurl); levelkey.key = null; // Initialization Vector (IV) levelkey.iv = decryptiv; } } break; case 'PROGRAM-DATE-TIME': programDateTime = new Date(Date.parse(result[1])); break; default: break; } } //logger.log('found ' + level.fragments.length + ' fragments'); if(frag && !frag.url) { level.fragments.pop(); totalduration-=frag.duration; } level.totalduration = totalduration; level.endSN = currentSN - 1; return level; } loadsuccess(event, stats) { var target = event.currentTarget, string = target.responseText, url = target.responseURL, id = this.id, id2 = this.id2, hls = this.hls, levels; this.loading = false; // responseURL not supported on some browsers (it is used to detect URL redirection) if (url === undefined) { // fallback to initial URL url = this.url; } stats.tload = performance.now(); stats.mtime = new Date(target.getResponseHeader('Last-Modified')); if (string.indexOf('#EXTM3U') === 0) { if (string.indexOf('#EXTINF:') > 0) { // 1 level playlist // if first request, fire manifest loaded event, level will be reloaded afterwards // (this is to have a uniform logic for 1 level/multilevel playlists) if (this.id === null) { hls.trigger(Event.MANIFEST_LOADED, {levels: [{url: url}], url: url, stats: stats}); } else { var levelDetails = this.parseLevelPlaylist(string, url, id); stats.tparsed = performance.now(); hls.trigger(Event.LEVEL_LOADED, {details: levelDetails, level: id, id: id2, stats: stats}); } } else { levels = this.parseMasterPlaylist(string, url); // multi level playlist, parse level info if (levels.length) { hls.trigger(Event.MANIFEST_LOADED, {levels: levels, url: url, stats: stats}); } else { hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest'}); } } } else { hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter'}); } } loaderror(event) { var details, fatal; if (this.id === null) { details = ErrorDetails.MANIFEST_LOAD_ERROR; fatal = true; } else { details = ErrorDetails.LEVEL_LOAD_ERROR; fatal = false; } if (this.loader) { this.loader.abort(); } this.loading = false; this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, response: event.currentTarget, level: this.id, id: this.id2}); } loadtimeout() { var details, fatal; if (this.id === null) { details = ErrorDetails.MANIFEST_LOAD_TIMEOUT; fatal = true; } else { details = ErrorDetails.LEVEL_LOAD_TIMEOUT; fatal = false; } if (this.loader) { this.loader.abort(); } this.loading = false; this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, level: this.id, id: this.id2}); } } export default PlaylistLoader;
ChubbyArse/Emby
MediaBrowser.WebDashboard/dashboard-ui/bower_components/hls.js/src/loader/playlist-loader.js
JavaScript
gpl-2.0
10,482
/*************************************************************************** qgsmapthemes.cpp -------------------------------------- Date : September 2014 Copyright : (C) 2014 by Martin Dobias Email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsmapthemes.h" #include "qgsmapthemecollection.h" #include "qgslayertree.h" #include "qgslayertreemapcanvasbridge.h" #include "qgslayertreemodel.h" #include "qgslayertreemodellegendnode.h" #include "qgslayertreeview.h" #include "qgsmaplayerstylemanager.h" #include "qgsproject.h" #include "qgsrenderer.h" #include "qgsvectorlayer.h" #include "qgisapp.h" #include "qgsnewnamedialog.h" #include <QInputDialog> #include <QMessageBox> QgsMapThemes *QgsMapThemes::sInstance; QgsMapThemes::QgsMapThemes() : mMenu( new QMenu ) { mMenu->addAction( QgisApp::instance()->actionShowAllLayers() ); mMenu->addAction( QgisApp::instance()->actionHideAllLayers() ); mMenu->addAction( QgisApp::instance()->actionShowSelectedLayers() ); mMenu->addAction( QgisApp::instance()->actionHideSelectedLayers() ); mMenu->addAction( QgisApp::instance()->actionHideDeselectedLayers() ); mMenu->addSeparator(); mReplaceMenu = new QMenu( tr( "Replace Theme" ) ); mMenu->addMenu( mReplaceMenu ); mActionAddPreset = mMenu->addAction( tr( "Add Theme…" ), this, SLOT( addPreset() ) ); mMenuSeparator = mMenu->addSeparator(); mActionRemoveCurrentPreset = mMenu->addAction( tr( "Remove Current Theme" ), this, SLOT( removeCurrentPreset() ) ); connect( mMenu, &QMenu::aboutToShow, this, &QgsMapThemes::menuAboutToShow ); } QgsMapThemeCollection::MapThemeRecord QgsMapThemes::currentState() { QgsLayerTreeGroup *root = QgsProject::instance()->layerTreeRoot(); QgsLayerTreeModel *model = QgisApp::instance()->layerTreeView()->layerTreeModel(); return QgsMapThemeCollection::createThemeFromCurrentState( root, model ); } QgsMapThemes *QgsMapThemes::instance() { if ( !sInstance ) sInstance = new QgsMapThemes(); return sInstance; } void QgsMapThemes::addPreset( const QString &name ) { QgsProject::instance()->mapThemeCollection()->insert( name, currentState() ); } void QgsMapThemes::updatePreset( const QString &name ) { QgsProject::instance()->mapThemeCollection()->update( name, currentState() ); } QList<QgsMapLayer *> QgsMapThemes::orderedPresetVisibleLayers( const QString &name ) const { QStringList visibleIds = QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayerIds( name ); // also make sure to order the layers according to map canvas order QList<QgsMapLayer *> lst; Q_FOREACH ( QgsMapLayer *layer, QgsProject::instance()->layerTreeRoot()->layerOrder() ) { if ( visibleIds.contains( layer->id() ) ) { lst << layer; } } return lst; } QMenu *QgsMapThemes::menu() { return mMenu; } void QgsMapThemes::addPreset() { QStringList existingNames = QgsProject::instance()->mapThemeCollection()->mapThemes(); QgsNewNameDialog dlg( tr( "theme" ), tr( "Theme" ), QStringList(), existingNames, QRegExp(), Qt::CaseInsensitive, mMenu ); dlg.setWindowTitle( tr( "Map Themes" ) ); dlg.setHintString( tr( "Name of the new theme" ) ); dlg.setOverwriteEnabled( false ); dlg.setConflictingNameWarning( tr( "A theme with this name already exists." ) ); if ( dlg.exec() != QDialog::Accepted || dlg.name().isEmpty() ) return; addPreset( dlg.name() ); } void QgsMapThemes::presetTriggered() { QAction *actionPreset = qobject_cast<QAction *>( sender() ); if ( !actionPreset ) return; applyState( actionPreset->text() ); } void QgsMapThemes::replaceTriggered() { QAction *actionPreset = qobject_cast<QAction *>( sender() ); if ( !actionPreset ) return; int res = QMessageBox::question( mMenu, tr( "Replace Theme" ), trUtf8( "Are you sure you want to replace the existing theme “%1”?" ).arg( actionPreset->text() ), QMessageBox::Yes | QMessageBox::No, QMessageBox::No ); if ( res != QMessageBox::Yes ) return; //adding preset with same name is effectively a replace addPreset( actionPreset->text() ); } void QgsMapThemes::applyState( const QString &presetName ) { if ( !QgsProject::instance()->mapThemeCollection()->hasMapTheme( presetName ) ) return; QgsLayerTreeGroup *root = QgsProject::instance()->layerTreeRoot(); QgsLayerTreeModel *model = QgisApp::instance()->layerTreeView()->layerTreeModel(); QgsProject::instance()->mapThemeCollection()->applyTheme( presetName, root, model ); } void QgsMapThemes::removeCurrentPreset() { for ( QAction *actionPreset : qgis::as_const( mMenuPresetActions ) ) { if ( actionPreset->isChecked() ) { int res = QMessageBox::question( mMenu, tr( "Remove Theme" ), trUtf8( "Are you sure you want to remove the existing theme “%1”?" ).arg( actionPreset->text() ), QMessageBox::Yes | QMessageBox::No, QMessageBox::No ); if ( res == QMessageBox::Yes ) QgsProject::instance()->mapThemeCollection()->removeMapTheme( actionPreset->text() ); break; } } } void QgsMapThemes::menuAboutToShow() { qDeleteAll( mMenuPresetActions ); mMenuPresetActions.clear(); mReplaceMenu->clear(); qDeleteAll( mMenuReplaceActions ); mMenuReplaceActions.clear(); QgsMapThemeCollection::MapThemeRecord rec = currentState(); bool hasCurrent = false; Q_FOREACH ( const QString &grpName, QgsProject::instance()->mapThemeCollection()->mapThemes() ) { QAction *a = new QAction( grpName, mMenu ); a->setCheckable( true ); if ( !hasCurrent && rec == QgsProject::instance()->mapThemeCollection()->mapThemeState( grpName ) ) { a->setChecked( true ); hasCurrent = true; } connect( a, &QAction::triggered, this, &QgsMapThemes::presetTriggered ); mMenuPresetActions.append( a ); QAction *replaceAction = new QAction( grpName, mReplaceMenu ); connect( replaceAction, &QAction::triggered, this, &QgsMapThemes::replaceTriggered ); mReplaceMenu->addAction( replaceAction ); } mMenu->insertActions( mMenuSeparator, mMenuPresetActions ); mReplaceMenu->addActions( mMenuReplaceActions ); mActionAddPreset->setEnabled( !hasCurrent ); mActionRemoveCurrentPreset->setEnabled( hasCurrent ); }
stevenmizuno/QGIS
src/app/qgsmapthemes.cpp
C++
gpl-2.0
7,007
<?php namespace PayPal\Api; use PayPal\Common\PPModel; use PayPal\Common\FormatConverter; use PayPal\Validation\NumericValidator; /** * Class Currency * * Base object for all financial value related fields (balance, payment due, etc.) * * @package PayPal\Api * * @property string currency * @property string value */ class Currency extends PPModel { /** * 3 letter currency code as defined by ISO 4217. * * @param string $currency * * @return $this */ public function setCurrency($currency) { $this->currency = $currency; return $this; } /** * 3 letter currency code as defined by ISO 4217. * * @return string */ public function getCurrency() { return $this->currency; } /** * amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code. * * @param string|double $value * * @return $this */ public function setValue($value) { NumericValidator::validate($value, "Value"); $value = FormatConverter::formatToTwoDecimalPlaces($value); $this->value = $value; return $this; } /** * amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code. * * @return string */ public function getValue() { return $this->value; } }
tectronics/tyres-wordpress
wp-content/plugins/directory/libraries/PayPal-PHP-SDK/lib/PayPal/Api/Currency.php
PHP
gpl-2.0
1,453
(function(){ var PushBullet = {}; PushBullet.init = function(clientId, redirectUri){ this.clientId = clientId; this.redirectUri = redirectUri; this.accessToken = localStorage.pushBulletAccessToken; }; //tests if we are authorized PushBullet.checkAuth = function(callback){ request("https://api.pushbullet.com/v2/users/me",true,function(results){ callback(results != null); }); }; //attempts to obtain a working accessToken, once Obtained it callsback with true PushBullet.doAuth = function(callback){ var popup = window.open("https://www.pushbullet.com/authorize?client_id=" + encodeURIComponent(PushBullet.clientId) + "&redirect_uri=" + encodeURIComponent(this.redirectUri) + "&response_type=token", "_blank","height=600,width=500,left=" + Math.round($(document).width() / 2 - 250) + ",top=" + Math.round($(document).height() / 2 - 300)); function onClosed(){ PushBullet.accessToken = localStorage.pushBulletAccessToken; PushBullet.checkAuth(callback); } var popupInterval = setInterval(function(){ if (popup == null || popup.closed){ clearInterval(popupInterval); onClosed(); } },50); }; PushBullet.Note = function(title, body){ this.type = "note"; this.title = title; this.body = body; }; PushBullet.Link = function(title,body,url){ this.type = "link"; this.title = title; this.body = body; this.url = url; }; PushBullet.CheckList = function(title,items){ this.type = "list"; this.title = title; this.items = items; } PushBullet.pushToChannel = function (channelName,pushBulletMessage){ var params = { channel_tag: channelName }; for (var param in pushBulletMessage){ params[param] = pushBulletMessage[param]; } post("https://api.pushbullet.com/v2/pushes",true,params,function(results){ console.log(results); }); } function request(url, useAuth,callback){ var options = {}; if (useAuth && PushBullet.accessToken != null){ options.headers = { 'Authorization': 'Bearer ' + PushBullet.accessToken }; } options.success = function(response){ callback(response); }; options.error = function(){ callback(null); } $.ajax(url,options); } function post(url,useAuth,params,callback){ var options = {}; if (useAuth && PushBullet.accessToken != null){ options.headers = { 'Authorization': 'Bearer ' + PushBullet.accessToken }; } options.type = "POST"; options.data = params; options.success = function(response){ callback(response); }; options.error = function(){ callback(null); } $.ajax(url,options); } window.PushBullet = PushBullet; })();
Belthazor2008/googulator
public_html/lib/pushbullet.js
JavaScript
gpl-3.0
3,181
/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * 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 the copyright holders 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. * * Authors: Nathan Binkert */ /* @file * Device module for modelling an ethernet hub */ #include "dev/net/etherbus.hh" #include <cmath> #include <deque> #include <string> #include <vector> #include "base/logging.hh" #include "base/trace.hh" #include "debug/Ethernet.hh" #include "debug/EthernetData.hh" #include "dev/net/etherdump.hh" #include "dev/net/etherint.hh" #include "dev/net/etherpkt.hh" #include "params/EtherBus.hh" #include "sim/core.hh" using namespace std; EtherBus::EtherBus(const Params *p) : EtherObject(p), ticksPerByte(p->speed), loopback(p->loopback), event([this]{ txDone(); }, "ethernet bus completion"), sender(0), dump(p->dump) { } void EtherBus::txDone() { devlist_t::iterator i = devlist.begin(); devlist_t::iterator end = devlist.end(); DPRINTF(Ethernet, "ethernet packet received: length=%d\n", packet->length); DDUMP(EthernetData, packet->data, packet->length); while (i != end) { if (loopback || *i != sender) (*i)->sendPacket(packet); ++i; } sender->sendDone(); if (dump) dump->dump(packet); sender = 0; packet = 0; } EtherInt* EtherBus::getEthPort(const std::string &if_name, int idx) { panic("Etherbus doesn't work\n"); } bool EtherBus::send(EtherInt *sndr, EthPacketPtr &pkt) { if (busy()) { DPRINTF(Ethernet, "ethernet packet not sent, bus busy\n", curTick()); return false; } DPRINTF(Ethernet, "ethernet packet sent: length=%d\n", pkt->length); DDUMP(EthernetData, pkt->data, pkt->length); packet = pkt; sender = sndr; int delay = (int)ceil(((double)pkt->simLength * ticksPerByte) + 1.0); DPRINTF(Ethernet, "scheduling packet: delay=%d, (rate=%f)\n", delay, ticksPerByte); schedule(event, curTick() + delay); return true; } EtherBus * EtherBusParams::create() { return new EtherBus(this); }
vineodd/PIMSim
GEM5Simulation/gem5/src/dev/net/etherbus.cc
C++
gpl-3.0
3,498
<?php /** * * @package mahara * @subpackage blocktype-newviews * @author Catalyst IT Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later * @copyright For copyright information on Mahara, please see the README file distributed with this software. * */ defined('INTERNAL') || die(); class PluginBlocktypeNewViews extends MaharaCoreBlocktype { public static function get_title() { return get_string('title1', 'blocktype.newviews'); } public static function get_description() { return get_string('description2', 'blocktype.newviews'); } public static function get_categories() { return array('general' => 21000); } public static function get_viewtypes() { return array('dashboard'); } public static function render_instance(BlockInstance $instance, $editing=false) { global $USER; require_once('view.php'); $configdata = $instance->get('configdata'); $nviews = isset($configdata['limit']) ? intval($configdata['limit']) : 5; $view = $instance->get_view(); $sort = array(array('column' => 'mtime', 'desc' => true)); $views = View::view_search( null, // $query null, // $ownerquery null, // $ownedby null, // $copyableby $nviews, // $limit 0, // $offset true, // $extra $sort, // $sort array('portfolio'), // $types null, // $collection null, // $accesstypes null, // $tag null, // $viewid $view->get('owner'), // $excludeowner true // $groupbycollection ); $smarty = smarty_core(); $smarty->assign('loggedin', $USER->is_logged_in()); $smarty->assign('views', $views->data); return $smarty->fetch('blocktype:newviews:newviews.tpl'); } public static function has_instance_config() { return true; } public static function instance_config_form(BlockInstance $instance) { $configdata = $instance->get('configdata'); return array('limit' => array( 'type' => 'text', 'title' => get_string('viewstoshow1', 'blocktype.newviews'), 'description' => get_string('viewstoshowdescription', 'blocktype.newviews'), 'defaultvalue' => (isset($configdata['limit'])) ? intval($configdata['limit']) : 5, 'size' => 3, 'minvalue' => 1, 'maxvalue' => 100, )); } public static function default_copy_type() { return 'shallow'; } public static function get_instance_title(BlockInstance $instance) { return get_string('title1', 'blocktype.newviews'); } public static function should_ajaxify() { return true; } /** * Shouldn't be linked to any artefacts via the view_artefacts table. * * @param BlockInstance $instance * @return multitype: */ public static function get_artefacts(BlockInstance $instance) { return array(); } }
piersharding/mahara
htdocs/blocktype/newviews/lib.php
PHP
gpl-3.0
3,184
package at.tyron.vintagecraft.Block.Utility; import at.tyron.vintagecraft.VintageCraft; import at.tyron.vintagecraft.Block.BlockContainerVC; import at.tyron.vintagecraft.TileEntity.TECokeOvenDoor; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockCokeOvenDoor extends BlockContainerVC { public static PropertyBool OPENED = PropertyBool.create("opened"); public static PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL); public BlockCokeOvenDoor() { super(Material.iron); setCreativeTab(VintageCraft.craftedBlocksTab); setDefaultState(blockState.getBaseState().withProperty(OPENED, false).withProperty(FACING, EnumFacing.NORTH)); } @Override public int getRenderType() { return 3; } @Override public String getSubType(ItemStack stack) { return null; } @Override public TileEntity createNewTileEntity(World worldIn, int meta) { return new TECokeOvenDoor(); } public IBlockState getStateFromMeta(int meta) { EnumFacing enumfacing = EnumFacing.getFront(meta >> 1); if (enumfacing.getAxis() == EnumFacing.Axis.Y) { enumfacing = EnumFacing.NORTH; } boolean opened = (meta & 1) > 0; return this.getDefaultState().withProperty(FACING, enumfacing).withProperty(OPENED, opened); } public int getMetaFromState(IBlockState state) { boolean opened = (Boolean)state.getValue(OPENED); return (((EnumFacing)state.getValue(FACING)).getIndex() << 1) + (opened ? 1 : 0); } protected BlockState createBlockState() { return new BlockState(this, new IProperty[] {OPENED, FACING}); } @Override public void onNeighborBlockChange(World world, BlockPos pos, IBlockState state, Block neighborBlock) { EnumFacing facing = (EnumFacing) state.getValue(FACING); // if (!suitableGround(world, pos.down())) { // world.destroyBlock(pos, true); // } } @Override public int damageDropped(IBlockState state) { return 0; } @Override public boolean canPlaceBlockOnSide(World world, BlockPos pos, EnumFacing side) { return true; //this.canPlaceBlockAt(world, pos) && suitableGround(world, pos.down()); } @Override public boolean isSideSolid(IBlockAccess world, BlockPos pos, EnumFacing side) { return false; } @Override public boolean shouldSideBeRendered(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { return true; } public boolean isFullCube() { return false; } @Override public boolean isOpaqueCube() { return false; } public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { return this.getDefaultState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()); } public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { worldIn.setBlockState(pos, state.withProperty(FACING, placer.getHorizontalFacing().getOpposite()), 2); } @Override public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ) { boolean opened = (Boolean)state.getValue(OPENED); worldIn.setBlockState(pos, state.withProperty(OPENED, !opened)); if (opened) { worldIn.playSound(pos.getX(), pos.getY(), pos.getZ(), "vintagecraft:ironstovedoor_close", 1f, 1f, false); } else { worldIn.playSound(pos.getX(), pos.getY(), pos.getZ(), "vintagecraft:ironstovedoor_open", 1f, 1f, false); } worldIn.getBlockState(pos).getBlock().setBlockBoundsBasedOnState(worldIn, pos); // TECokeOvenDoor te = (TECokeOvenDoor)worldIn.getTileEntity(pos); // if (te != null) { // System.out.println("valid: " + te.isValidCokeOven()); // } return super.onBlockActivated(worldIn, pos, state, playerIn, side, hitX, hitY, hitZ); } @Override public AxisAlignedBB getCollisionBoundingBox(World worldIn, BlockPos pos, IBlockState state) { EnumFacing face = (EnumFacing) state.getValue(FACING); boolean opened = (Boolean)state.getValue(OPENED); if (opened) { switch (face) { case NORTH: return AxisAlignedBB.fromBounds(pos.getX() + 1f, pos.getY(), pos.getZ() - 0.8125f, pos.getX() + 0.8125f, pos.getY() + 1f, pos.getZ() + 0.1875f); case SOUTH: return AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ() + 0.8125f, pos.getX() + 0.1875f, pos.getY() + 1f, pos.getZ() + 1.8125f); case WEST: return AxisAlignedBB.fromBounds(pos.getX() - 0.8125f, pos.getY(), pos.getZ(), pos.getX() + 0.1875f, pos.getY() + 1f, pos.getZ() + 0.1875f); case EAST: return AxisAlignedBB.fromBounds(pos.getX() + 0.8125f, pos.getY(), pos.getZ() + 0.8125f, pos.getX() + 1.8125f, pos.getY() + 1f, pos.getZ() + 1f); default: return null; } } else { switch (face) { case NORTH: return AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1f, pos.getY() + 1f, pos.getZ() + 0.1875f); case SOUTH: return AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ() + 0.8125f, pos.getX() + 1f, pos.getY() + 1f, pos.getZ() + 1f); case WEST: return AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 0.1875f, pos.getY() + 1f, pos.getZ() + 1f); case EAST: return AxisAlignedBB.fromBounds(pos.getX() + 0.8125f, pos.getY(), pos.getZ(), pos.getX() + 1f, pos.getY() + 1f, pos.getZ() + 1f); default: return null; } } } @Override public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos) { AxisAlignedBB bounds = getCollisionBoundingBox(null, pos, worldIn.getBlockState(pos)); setBlockBounds((float)bounds.minX - pos.getX(), (float)bounds.minY - pos.getY(), (float)bounds.minZ - pos.getZ(), (float)bounds.maxX - pos.getX(), (float)bounds.maxY - pos.getY(), (float)bounds.maxZ - pos.getZ()); } @Override public AxisAlignedBB getSelectedBoundingBox(World worldIn, BlockPos pos) { return getCollisionBoundingBox(worldIn, pos, worldIn.getBlockState(pos)); } }
nanakisan/vintagecraft
src/main/java/at/tyron/vintagecraft/Block/Utility/BlockCokeOvenDoor.java
Java
gpl-3.0
7,072
package net.minecraft.world.chunk; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockStatePaletteLinear implements IBlockStatePalette { private final IBlockState[] states; private final IBlockStatePaletteResizer resizeHandler; private final int bits; private int arraySize; public BlockStatePaletteLinear(int bitsIn, IBlockStatePaletteResizer resizeHandlerIn) { this.states = new IBlockState[1 << bitsIn]; this.bits = bitsIn; this.resizeHandler = resizeHandlerIn; } public int idFor(IBlockState state) { for (int i = 0; i < this.arraySize; ++i) { if (this.states[i] == state) { return i; } } int j = this.arraySize; if (j < this.states.length) { this.states[j] = state; ++this.arraySize; return j; } else { return this.resizeHandler.onResize(this.bits + 1, state); } } /** * Gets the block state by the palette id. */ @Nullable public IBlockState getBlockState(int indexKey) { return indexKey >= 0 && indexKey < this.arraySize ? this.states[indexKey] : null; } @SideOnly(Side.CLIENT) public void read(PacketBuffer buf) { this.arraySize = buf.readVarInt(); for (int i = 0; i < this.arraySize; ++i) { this.states[i] = Block.BLOCK_STATE_IDS.getByValue(buf.readVarInt()); } } public void write(PacketBuffer buf) { buf.writeVarInt(this.arraySize); for (int i = 0; i < this.arraySize; ++i) { buf.writeVarInt(Block.BLOCK_STATE_IDS.get(this.states[i])); } } public int getSerializedSize() { int i = PacketBuffer.getVarIntSize(this.arraySize); for (int j = 0; j < this.arraySize; ++j) { i += PacketBuffer.getVarIntSize(Block.BLOCK_STATE_IDS.get(this.states[j])); } return i; } }
Severed-Infinity/technium
build/tmp/recompileMc/sources/net/minecraft/world/chunk/BlockStatePaletteLinear.java
Java
gpl-3.0
2,268
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "neigh_list_kokkos.h" #include "atom.h" #include "memory.h" using namespace LAMMPS_NS; enum{NSQ,BIN,MULTI}; /* ---------------------------------------------------------------------- */ template<class Device> NeighListKokkos<Device>::NeighListKokkos(class LAMMPS *lmp):NeighList(lmp) { _stride = 1; maxneighs = 16; kokkos = 1; maxatoms = 0; execution_space = ExecutionSpaceFromDevice<Device>::space; }; /* ---------------------------------------------------------------------- */ template<class Device> void NeighListKokkos<Device>::grow(int nmax) { // skip if this list is already long enough to store nmax atoms if (nmax <= maxatoms) return; maxatoms = nmax; k_ilist = DAT::tdual_int_1d("neighlist:ilist",maxatoms); d_ilist = k_ilist.view<Device>(); d_numneigh = typename ArrayTypes<Device>::t_int_1d("neighlist:numneigh",maxatoms); d_neighbors = typename ArrayTypes<Device>::t_neighbors_2d("neighlist:neighbors", maxatoms,maxneighs); } /* ---------------------------------------------------------------------- */ namespace LAMMPS_NS { template class NeighListKokkos<LMPDeviceType>; #ifdef KOKKOS_HAVE_CUDA template class NeighListKokkos<LMPHostType>; #endif }
ovilab/atomify
libs/lammps/src/KOKKOS/neigh_list_kokkos.cpp
C++
gpl-3.0
1,894
#include <stdio.h> int modularInverse(int number, int mod); void extendedEuclid(int, int, int* d, int* x, int* y); int main() { int number, mod; scanf("%d %d", &number, &mod); int ans = modularInverse(number, mod); if (ans == -1) fprintf(stderr, "Couldn't calculate modular inverse!\n"); else printf("%d", ans); } int modularInverse(int number, int mod) { if (1 <= number && number <= mod - 1) { int x, y, d; extendedEuclid(number, mod, &d, &x, &y); if (d == 1) { while (x < 0) x += mod; return x; } else fprintf(stderr, "The number and mod need to be coprime\n"); } else fprintf(stderr, "Number needs to be between 1 and mod!\n"); return -1; } void extendedEuclid(int a, int b, int* d, int* x, int* y) { if (b == 0) { *x = 1; *y = 0; *d = a; return; } int x0, y0; extendedEuclid(b, a % b, d, &x0, &y0); *x = y0; *y = x0 - (a / b) * y0; }
OpenGenus/cosmos
code/mathematical_algorithms/src/modular_inverse/modular_inverse.cpp
C++
gpl-3.0
1,064
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qqmldelayedcallqueue_p.h" #include <private/qv8engine_p.h> #include <private/qqmlengine_p.h> #include <private/qqmljavascriptexpression_p.h> #include <private/qv4value_p.h> #include <private/qv4qobjectwrapper_p.h> #include <QQmlError> QT_BEGIN_NAMESPACE // // struct QQmlDelayedCallQueue::DelayedFunctionCall // void QQmlDelayedCallQueue::DelayedFunctionCall::execute(QV4::ExecutionEngine *engine) const { if (!m_guarded || (!m_objectGuard.isNull() && !QQmlData::wasDeleted(m_objectGuard) && QQmlData::get(m_objectGuard) && !QQmlData::get(m_objectGuard)->isQueuedForDeletion)) { QV4::Scope scope(engine); QV4::ArrayObject *array = m_args.as<QV4::ArrayObject>(); const int argCount = array ? array->getLength() : 0; QV4::ScopedCallData callData(scope, argCount); callData->thisObject = QV4::Encode::undefined(); for (int i = 0; i < argCount; i++) { callData->args[i] = array->getIndexed(i); } const QV4::FunctionObject *callback = m_function.as<QV4::FunctionObject>(); Q_ASSERT(callback); callback->call(scope, callData); if (scope.engine->hasException) { QQmlError error = scope.engine->catchExceptionAsQmlError(); error.setDescription(error.description() + QLatin1String(" (exception occurred during delayed function evaluation)")); QQmlEnginePrivate::warning(QQmlEnginePrivate::get(scope.engine->qmlEngine()), error); } } } // // class QQmlDelayedCallQueue // QQmlDelayedCallQueue::QQmlDelayedCallQueue() : QObject(0), m_engine(0), m_callbackOutstanding(false) { } QQmlDelayedCallQueue::~QQmlDelayedCallQueue() { } void QQmlDelayedCallQueue::init(QV4::ExecutionEngine* engine) { m_engine = engine; const QMetaObject &metaObject = QQmlDelayedCallQueue::staticMetaObject; int methodIndex = metaObject.indexOfSlot("ticked()"); m_tickedMethod = metaObject.method(methodIndex); } void QQmlDelayedCallQueue::addUniquelyAndExecuteLater(const QV4::BuiltinFunction *, QV4::Scope &scope, QV4::CallData *callData) { if (callData->argc == 0) THROW_GENERIC_ERROR("Qt.callLater: no arguments given"); const QV4::FunctionObject *func = callData->args[0].as<QV4::FunctionObject>(); if (!func) THROW_GENERIC_ERROR("Qt.callLater: first argument not a function or signal"); QPair<QObject *, int> functionData = QV4::QObjectMethod::extractQtMethod(func); QVector<DelayedFunctionCall>::Iterator iter; if (functionData.second != -1) { // This is a QObject function wrapper iter = m_delayedFunctionCalls.begin(); while (iter != m_delayedFunctionCalls.end()) { DelayedFunctionCall& dfc = *iter; QPair<QObject *, int> storedFunctionData = QV4::QObjectMethod::extractQtMethod(dfc.m_function.as<QV4::FunctionObject>()); if (storedFunctionData == functionData) { break; // Already stored! } ++iter; } } else { // This is a JavaScript function (dynamic slot on VMEMO) iter = m_delayedFunctionCalls.begin(); while (iter != m_delayedFunctionCalls.end()) { DelayedFunctionCall& dfc = *iter; if (callData->argument(0) == dfc.m_function.value()) { break; // Already stored! } ++iter; } } const bool functionAlreadyStored = (iter != m_delayedFunctionCalls.end()); if (functionAlreadyStored) { DelayedFunctionCall dfc = *iter; m_delayedFunctionCalls.erase(iter); m_delayedFunctionCalls.append(dfc); } else { m_delayedFunctionCalls.append(QV4::PersistentValue(m_engine, callData->argument(0))); } DelayedFunctionCall& dfc = m_delayedFunctionCalls.last(); if (dfc.m_objectGuard.isNull()) { if (functionData.second != -1) { // if it's a qobject function wrapper, guard against qobject deletion dfc.m_objectGuard = QQmlGuard<QObject>(functionData.first); dfc.m_guarded = true; } else if (func->scope()->type == QV4::Heap::ExecutionContext::Type_QmlContext) { QV4::QmlContext::Data *g = static_cast<QV4::QmlContext::Data *>(func->scope()); Q_ASSERT(g->qml->scopeObject); dfc.m_objectGuard = QQmlGuard<QObject>(g->qml->scopeObject); dfc.m_guarded = true; } } storeAnyArguments(dfc, callData, 1, m_engine); if (!m_callbackOutstanding) { m_tickedMethod.invoke(this, Qt::QueuedConnection); m_callbackOutstanding = true; } scope.result = QV4::Encode::undefined(); } void QQmlDelayedCallQueue::storeAnyArguments(DelayedFunctionCall &dfc, const QV4::CallData *callData, int offset, QV4::ExecutionEngine *engine) { const int length = callData->argc - offset; if (length == 0) { dfc.m_args.clear(); return; } QV4::Scope scope(engine); QV4::ScopedArrayObject array(scope, engine->newArrayObject(length)); int i = 0; for (int j = offset; j < callData->argc; ++i, ++j) { array->putIndexed(i, callData->args[j]); } dfc.m_args.set(engine, array); } void QQmlDelayedCallQueue::executeAllExpired_Later() { // Make a local copy of the list and clear m_delayedFunctionCalls // This ensures correct behavior in the case of recursive calls to Qt.callLater() QVector<DelayedFunctionCall> delayedCalls = m_delayedFunctionCalls; m_delayedFunctionCalls.clear(); QVector<DelayedFunctionCall>::Iterator iter = delayedCalls.begin(); while (iter != delayedCalls.end()) { DelayedFunctionCall& dfc = *iter; dfc.execute(m_engine); ++iter; } } void QQmlDelayedCallQueue::ticked() { m_callbackOutstanding = false; executeAllExpired_Later(); } QT_END_NAMESPACE #include "moc_qqmldelayedcallqueue_p.cpp"
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/src/qml/qml/qqmldelayedcallqueue.cpp
C++
gpl-3.0
7,883
import math def PrimeFactors(num): primeFactors = [] for i in range(2, int(math.sqrt(num)) + 1): while num % i == 0: primeFactors.append(i) num //= i if num > 2: primeFactors.append(num) return primeFactors def main(): factors = PrimeFactors(36) print(factors) if __name__ == '__main__': main()
gauravsitlani/programming
prime_factors/prime_factors.py
Python
gpl-3.0
315
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** Zend_Pdf_Filter_Interface */ require_once 'Zend/Pdf/Filter/Interface.php'; /** * ASCII85 stream filter * * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Pdf_Filter_Compression implements Zend_Pdf_Filter_Interface { /** * Paeth prediction function * * @param integer $a * @param integer $b * @param integer $c * @return integer */ private static function _paeth($a, $b, $c) { // $a - left, $b - above, $c - upper left $p = $a + $b - $c; // initial estimate $pa = abs($p - $a); // distances to a, b, c $pb = abs($p - $b); $pc = abs($p - $c); // return nearest of a,b,c, // breaking ties in order a,b,c. if ($pa <= $pb && $pa <= $pc) { return $a; } else if ($pb <= $pc) { return $b; } else { return $c; } } /** * Get Predictor decode param value * * @param array $params * @return integer * @throws Zend_Pdf_Exception */ private static function _getPredictorValue(&$params) { if (isset($params['Predictor'])) { $predictor = $params['Predictor']; if ($predictor != 1 && $predictor != 2 && $predictor != 10 && $predictor != 11 && $predictor != 12 && $predictor != 13 && $predictor != 14 && $predictor != 15) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Invalid value of \'Predictor\' decode param - ' . $predictor . '.' ); } return $predictor; } else { return 1; } } /** * Get Colors decode param value * * @param array $params * @return integer * @throws Zend_Pdf_Exception */ private static function _getColorsValue(&$params) { if (isset($params['Colors'])) { $colors = $params['Colors']; if ($colors != 1 && $colors != 2 && $colors != 3 && $colors != 4) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Invalid value of \'Color\' decode param - ' . $colors . '.' ); } return $colors; } else { return 1; } } /** * Get BitsPerComponent decode param value * * @param array $params * @return integer * @throws Zend_Pdf_Exception */ private static function _getBitsPerComponentValue(&$params) { if (isset($params['BitsPerComponent'])) { $bitsPerComponent = $params['BitsPerComponent']; if ($bitsPerComponent != 1 && $bitsPerComponent != 2 && $bitsPerComponent != 4 && $bitsPerComponent != 8 && $bitsPerComponent != 16 ) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Invalid value of \'BitsPerComponent\' decode param - ' . $bitsPerComponent . '.' ); } return $bitsPerComponent; } else { return 8; } } /** * Get Columns decode param value * * @param array $params * @return integer */ private static function _getColumnsValue(&$params) { if (isset($params['Columns'])) { return $params['Columns']; } else { return 1; } } /** * Convert stream data according to the filter params set before encoding. * * @param string $data * @param array $params * @return string * @throws Zend_Pdf_Exception */ protected static function _applyEncodeParams($data, $params) { $predictor = self::_getPredictorValue($params); $colors = self::_getColorsValue($params); $bitsPerComponent = self::_getBitsPerComponentValue($params); $columns = self::_getColumnsValue($params); /** None of prediction */ if ($predictor == 1) { return $data; } /** TIFF Predictor 2 */ if ($predictor == 2) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Not implemented yet' ); } /** Optimal PNG prediction */ if ($predictor == 15) { /** Use Paeth prediction as optimal */ $predictor = 14; } /** PNG prediction */ if ($predictor == 10 || /** None of prediction */ $predictor == 11 || /** Sub prediction */ $predictor == 12 || /** Up prediction */ $predictor == 13 || /** Average prediction */ $predictor == 14 /** Paeth prediction */ ) { $predictor -= 10; if($bitsPerComponent == 16) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("PNG Prediction with bit depth greater than 8 not yet supported."); } $bitsPerSample = $bitsPerComponent*$colors; $bytesPerSample = (int)(($bitsPerSample + 7)/8); // (int)ceil(...) emulation $bytesPerRow = (int)(($bitsPerSample*$columns + 7)/8); // (int)ceil(...) emulation $rows = strlen($data)/$bytesPerRow; $output = ''; $offset = 0; if (!is_integer($rows)) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Wrong data length.'); } switch ($predictor) { case 0: // None of prediction for ($count = 0; $count < $rows; $count++) { $output .= chr($predictor); $output .= substr($data, $offset, $bytesPerRow); $offset += $bytesPerRow; } break; case 1: // Sub prediction for ($count = 0; $count < $rows; $count++) { $output .= chr($predictor); $lastSample = array_fill(0, $bytesPerSample, 0); for ($count2 = 0; $count2 < $bytesPerRow; $count2++) { $newByte = ord($data[$offset++]); // Note. chr() automatically cuts input to 8 bit $output .= chr($newByte - $lastSample[$count2 % $bytesPerSample]); $lastSample[$count2 % $bytesPerSample] = $newByte; } } break; case 2: // Up prediction $lastRow = array_fill(0, $bytesPerRow, 0); for ($count = 0; $count < $rows; $count++) { $output .= chr($predictor); for ($count2 = 0; $count2 < $bytesPerRow; $count2++) { $newByte = ord($data[$offset++]); // Note. chr() automatically cuts input to 8 bit $output .= chr($newByte - $lastRow[$count2]); $lastRow[$count2] = $newByte; } } break; case 3: // Average prediction $lastRow = array_fill(0, $bytesPerRow, 0); for ($count = 0; $count < $rows; $count++) { $output .= chr($predictor); $lastSample = array_fill(0, $bytesPerSample, 0); for ($count2 = 0; $count2 < $bytesPerRow; $count2++) { $newByte = ord($data[$offset++]); // Note. chr() automatically cuts input to 8 bit $output .= chr($newByte - floor(( $lastSample[$count2 % $bytesPerSample] + $lastRow[$count2])/2)); $lastSample[$count2 % $bytesPerSample] = $lastRow[$count2] = $newByte; } } break; case 4: // Paeth prediction $lastRow = array_fill(0, $bytesPerRow, 0); $currentRow = array(); for ($count = 0; $count < $rows; $count++) { $output .= chr($predictor); $lastSample = array_fill(0, $bytesPerSample, 0); for ($count2 = 0; $count2 < $bytesPerRow; $count2++) { $newByte = ord($data[$offset++]); // Note. chr() automatically cuts input to 8 bit $output .= chr($newByte - self::_paeth( $lastSample[$count2 % $bytesPerSample], $lastRow[$count2], ($count2 - $bytesPerSample < 0)? 0 : $lastRow[$count2 - $bytesPerSample] )); $lastSample[$count2 % $bytesPerSample] = $currentRow[$count2] = $newByte; } $lastRow = $currentRow; } break; } return $output; } require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Unknown prediction algorithm - ' . $predictor . '.' ); } /** * Convert stream data according to the filter params set after decoding. * * @param string $data * @param array $params * @return string */ protected static function _applyDecodeParams($data, $params) { $predictor = self::_getPredictorValue($params); $colors = self::_getColorsValue($params); $bitsPerComponent = self::_getBitsPerComponentValue($params); $columns = self::_getColumnsValue($params); /** None of prediction */ if ($predictor == 1) { return $data; } /** TIFF Predictor 2 */ if ($predictor == 2) { require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Not implemented yet' ); } /** * PNG prediction * Prediction code is duplicated on each row. * Thus all cases can be brought to one */ if ($predictor == 10 || /** None of prediction */ $predictor == 11 || /** Sub prediction */ $predictor == 12 || /** Up prediction */ $predictor == 13 || /** Average prediction */ $predictor == 14 || /** Paeth prediction */ $predictor == 15 /** Optimal prediction */) { $bitsPerSample = $bitsPerComponent*$colors; $bytesPerSample = ceil($bitsPerSample/8); $bytesPerRow = ceil($bitsPerSample*$columns/8); $rows = ceil(strlen($data)/($bytesPerRow + 1)); $output = ''; $offset = 0; $lastRow = array_fill(0, $bytesPerRow, 0); for ($count = 0; $count < $rows; $count++) { $lastSample = array_fill(0, $bytesPerSample, 0); switch (ord($data[$offset++])) { case 0: // None of prediction $output .= substr($data, $offset, $bytesPerRow); for ($count2 = 0; $count2 < $bytesPerRow && $offset < strlen($data); $count2++) { $lastSample[$count2 % $bytesPerSample] = $lastRow[$count2] = ord($data[$offset++]); } break; case 1: // Sub prediction for ($count2 = 0; $count2 < $bytesPerRow && $offset < strlen($data); $count2++) { $decodedByte = (ord($data[$offset++]) + $lastSample[$count2 % $bytesPerSample]) & 0xFF; $lastSample[$count2 % $bytesPerSample] = $lastRow[$count2] = $decodedByte; $output .= chr($decodedByte); } break; case 2: // Up prediction for ($count2 = 0; $count2 < $bytesPerRow && $offset < strlen($data); $count2++) { $decodedByte = (ord($data[$offset++]) + $lastRow[$count2]) & 0xFF; $lastSample[$count2 % $bytesPerSample] = $lastRow[$count2] = $decodedByte; $output .= chr($decodedByte); } break; case 3: // Average prediction for ($count2 = 0; $count2 < $bytesPerRow && $offset < strlen($data); $count2++) { $decodedByte = (ord($data[$offset++]) + floor(( $lastSample[$count2 % $bytesPerSample] + $lastRow[$count2])/2) ) & 0xFF; $lastSample[$count2 % $bytesPerSample] = $lastRow[$count2] = $decodedByte; $output .= chr($decodedByte); } break; case 4: // Paeth prediction $currentRow = array(); for ($count2 = 0; $count2 < $bytesPerRow && $offset < strlen($data); $count2++) { $decodedByte = (ord($data[$offset++]) + self::_paeth($lastSample[$count2 % $bytesPerSample], $lastRow[$count2], ($count2 - $bytesPerSample < 0)? 0 : $lastRow[$count2 - $bytesPerSample]) ) & 0xFF; $lastSample[$count2 % $bytesPerSample] = $currentRow[$count2] = $decodedByte; $output .= chr($decodedByte); } $lastRow = $currentRow; break; default: require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Unknown prediction tag.'); } } return $output; } require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Unknown prediction algorithm - ' . $predictor . '.' ); } }
areeves/openfisma
library/Zend/Pdf/Filter/Compression.php
PHP
gpl-3.0
15,570
/* This file is part of ZAX. ZAX 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. ZAX 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 ZAX. If not, see <http://www.gnu.org/licenses/>. */ package com.inovex.zabbixmobile.widget; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * This broadcast receiver listens for replacements of the application package. * If the package receives an update, widget update alarm needs to be set again. * */ public class PackageReplacedReceiver extends BroadcastReceiver { private static final String TAG = PackageReplacedReceiver.class .getSimpleName(); @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "package replaced. Sending widget update broadcast."); Intent broadcastIntent = new Intent(context, WidgetUpdateBroadcastReceiver.class); broadcastIntent.putExtra(WidgetUpdateBroadcastReceiver.REFRESH_RATE_CHANGED, true); context.sendBroadcast(broadcastIntent); } }
inovex/zax
src/main/java/com/inovex/zabbixmobile/widget/PackageReplacedReceiver.java
Java
gpl-3.0
1,490
/** * Copyright (C) 2005-2013, Stefan Strömberg <stefangs@nethome.nu> * * This file is part of OpenNetHome (http://www.nethome.nu) * * OpenNetHome is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenNetHome is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Peter Lagerhem * * History: * 2010-10-27 pela Created. * */ package nu.nethome.home.items.web.servergui; import nu.nethome.home.item.Attribute; /** * This class can be used to collect errors of home item attributes. You could * typically use it where IllegalFormat (and alike) exceptions are caught and * you want to record the cause for the error and the attribute. * * The printPage() method of the EditItemPage class uses this class for * displaying the attribute errors. */ public class HomeItemError { private Attribute attribute; private String errorMessage; public ErrorType type; public enum ErrorType { general, attribute } /** * @return the attribute */ public Attribute getAttribute() { return attribute; } /** * @return the errorMessage */ public String getErrorMessage() { return errorMessage; } public HomeItemError(Attribute attribute, String errorMessage) { this.attribute = attribute; this.errorMessage = errorMessage; type = ErrorType.attribute; } public HomeItemError(String errorMessage) { this.errorMessage = errorMessage; type = ErrorType.general; } }
stefangs/NetHomeServer
home-items/web-items/src/main/java/nu/nethome/home/items/web/servergui/HomeItemError.java
Java
gpl-3.0
1,950
var gr__expj_8h = [ [ "gr_expj", "gr__expj_8h.html#a7d0144e5774158b746199c1da4d5b5ac", null ] ];
aviralchandra/Sandhi
build/gr36/docs/doxygen/html/gr__expj_8h.js
JavaScript
gpl-3.0
100
#include "./class.h" #include "../../util/trace.h" #include "../../util/log.h" #include <map> #include <algorithm> #include "../common/method.h" #include "../common/property.h" #include "../common/ref.h" #include "./ivar.h" #include "./protocol.h" #include "../TopologySort.h" extern std::map<const void*,Class> g_classPointers; Class RegisterClass(const class_t* cls, intptr_t slide) { LOG << "Processing ObjC class " << cls->data()->className << std::endl; const class_t* meta = cls->isa; Class conv, super; auto itSuper = g_classPointers.find(cls->superclass); if (itSuper != g_classPointers.end()) super = itSuper->second; else super = reinterpret_cast<Class>(cls->superclass); LOG << "...superclass is @" << super << std::endl; conv = objc_allocateClassPair(super, cls->data()->className, 0); const class_ro_t* ro = cls->data(); const class_ro_t* roMeta = meta->data(); if (ro->baseMethods) ConvertMethodListGen(conv, ro->baseMethods); if (roMeta->baseMethods) ConvertMethodListGen(object_getClass(id(conv)), roMeta->baseMethods); if (ro->ivars) ConvertIvarList(conv, ro->ivars); if (ro->baseProtocols) AddClassProtocols(conv, ro->baseProtocols, slide); if (ro->baseProperties) { ConvertProperties(ro->baseProperties, [conv](const char* name, const objc_property_attribute_t* attr, unsigned int count) { class_addProperty(conv, name, attr, count); bug_gnustepFixPropertyCount(conv); }); } // conv->instance_size = ro->instSize; // conv->isa->instance_size = roMeta->instSize; objc_registerClassPair(conv); LOG << "ObjC class " << cls->data()->className << " now @" << conv << std::endl; g_classPointers[cls] = conv; return conv; } void ProcessClassesNew(const struct mach_header* mh, intptr_t slide, const class_t** classes, unsigned long size) { class_t **class_refs, **class_refs_end, **super_refs, **super_refs_end; unsigned long refsize, refsize_s; std::vector<const class_t*> vecClasses; std::set<const class_t*> setClasses; class_refs = reinterpret_cast<class_t**>( getsectdata(mh, SEG_OBJC_CLASSREFS_NEW, SECT_OBJC_CLASSREFS_NEW, &refsize) ); super_refs = reinterpret_cast<class_t**>( getsectdata(mh, SEG_OBJC_SUPERREFS_NEW, SECT_OBJC_SUPERREFS_NEW, &refsize_s) ); if (class_refs) class_refs_end = class_refs + refsize / sizeof(class_t*); if (super_refs) super_refs_end = super_refs + refsize_s / sizeof(class_t*); std::copy(classes, classes+size/sizeof(class_t*), std::inserter(setClasses, setClasses.begin())); topology_sort<const class_t>(setClasses, vecClasses, [&setClasses](const class_t* t) { return setClasses.count(t->superclass) ? std::set<const class_t*>{t->superclass} : std::set<const class_t*>(); } ); for (const class_t* cls : vecClasses) { Class c = RegisterClass(cls, slide); if (class_refs) { find_and_fix(class_refs, class_refs_end, cls, c); find_and_fix(class_refs, class_refs_end, cls->isa, object_getClass(id(c))); } if (super_refs) { find_and_fix(super_refs, super_refs_end, cls, c); find_and_fix(super_refs, super_refs_end, cls->isa, object_getClass(id(c))); } } }
magicpriest/darling-FC-edition
src/libobjcdarwin/new/class.cpp
C++
gpl-3.0
3,116
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/test/channel_transport/include/channel_transport.h" #include <stdio.h> #if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS) #include "testing/gtest/include/gtest/gtest.h" #endif #include "webrtc/test/channel_transport/udp_transport.h" #include "webrtc/video_engine/include/vie_network.h" #include "webrtc/video_engine/vie_defines.h" #include "webrtc/voice_engine/include/voe_network.h" #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) #undef NDEBUG #include <assert.h> #endif namespace webrtc { namespace test { VoiceChannelTransport::VoiceChannelTransport(VoENetwork* voe_network, int channel) : channel_(channel), voe_network_(voe_network) { uint8_t socket_threads = 1; socket_transport_ = UdpTransport::Create(channel, socket_threads); int registered = voe_network_->RegisterExternalTransport(channel, *socket_transport_); #if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS) EXPECT_EQ(0, registered); #else assert(registered == 0); #endif } VoiceChannelTransport::~VoiceChannelTransport() { voe_network_->DeRegisterExternalTransport(channel_); UdpTransport::Destroy(socket_transport_); } void VoiceChannelTransport::IncomingRTPPacket( const int8_t* incoming_rtp_packet, const int32_t packet_length, const char* /*from_ip*/, const uint16_t /*from_port*/) { voe_network_->ReceivedRTPPacket(channel_, incoming_rtp_packet, packet_length); } void VoiceChannelTransport::IncomingRTCPPacket( const int8_t* incoming_rtcp_packet, const int32_t packet_length, const char* /*from_ip*/, const uint16_t /*from_port*/) { voe_network_->ReceivedRTCPPacket(channel_, incoming_rtcp_packet, packet_length); } int VoiceChannelTransport::SetLocalReceiver(uint16_t rtp_port) { int return_value = socket_transport_->InitializeReceiveSockets(this, rtp_port); if (return_value == 0) { return socket_transport_->StartReceiving(kViENumReceiveSocketBuffers); } return return_value; } int VoiceChannelTransport::SetSendDestination(const char* ip_address, uint16_t rtp_port) { return socket_transport_->InitializeSendSockets(ip_address, rtp_port); } VideoChannelTransport::VideoChannelTransport(ViENetwork* vie_network, int channel) : channel_(channel), vie_network_(vie_network) { uint8_t socket_threads = 1; socket_transport_ = UdpTransport::Create(channel, socket_threads); int registered = vie_network_->RegisterSendTransport(channel, *socket_transport_); #if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS) EXPECT_EQ(0, registered); #else assert(registered == 0); #endif } VideoChannelTransport::~VideoChannelTransport() { vie_network_->DeregisterSendTransport(channel_); UdpTransport::Destroy(socket_transport_); } void VideoChannelTransport::IncomingRTPPacket( const int8_t* incoming_rtp_packet, const int32_t packet_length, const char* /*from_ip*/, const uint16_t /*from_port*/) { vie_network_->ReceivedRTPPacket( channel_, incoming_rtp_packet, packet_length, PacketTime()); } void VideoChannelTransport::IncomingRTCPPacket( const int8_t* incoming_rtcp_packet, const int32_t packet_length, const char* /*from_ip*/, const uint16_t /*from_port*/) { vie_network_->ReceivedRTCPPacket(channel_, incoming_rtcp_packet, packet_length); } int VideoChannelTransport::SetLocalReceiver(uint16_t rtp_port) { int return_value = socket_transport_->InitializeReceiveSockets(this, rtp_port); if (return_value == 0) { return socket_transport_->StartReceiving(kViENumReceiveSocketBuffers); } return return_value; } int VideoChannelTransport::SetSendDestination(const char* ip_address, uint16_t rtp_port) { return socket_transport_->InitializeSendSockets(ip_address, rtp_port); } } // namespace test } // namespace webrtc
liyouchang/webrtc-qt
webrtc/test/channel_transport/channel_transport.cc
C++
gpl-3.0
4,688
// ***************************************************************** -*- C++ -*- /* * Copyright (C) 2004-2017 Andreas Huggel <ahuggel@gmx.net> * * This program is part of the Exiv2 distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA. */ /*! @file xmp.hpp @brief Encoding and decoding of XMP data @version $Rev: 3090 $ @author Andreas Huggel (ahu) <a href="mailto:ahuggel@gmx.net">ahuggel@gmx.net</a> @date 13-Jul-07, ahu: created */ #ifndef XMP_HPP_ #define XMP_HPP_ // ***************************************************************************** // included header files #include "metadatum.hpp" #include "properties.hpp" #include "value.hpp" #include "types.hpp" #include "datasets.hpp" #include "properties.hpp" // + standard includes #include <string> #include <vector> // ***************************************************************************** // namespace extensions namespace Exiv2 { // ***************************************************************************** // class declarations class ExifData; // ***************************************************************************** // class definitions /*! @brief Information related to an XMP property. An XMP metadatum consists of an XmpKey and a Value and provides methods to manipulate these. */ class EXIV2API Xmpdatum : public Metadatum { public: //! @name Creators //@{ /*! @brief Constructor for new tags created by an application. The %Xmpdatum is created from a key / value pair. %Xmpdatum copies (clones) the value if one is provided. Alternatively, a program can create an 'empty' %Xmpdatum with only a key and set the value using setValue(). @param key The key of the %Xmpdatum. @param pValue Pointer to a %Xmpdatum value. @throw Error if the key cannot be parsed and converted to a known schema namespace prefix and property name. */ explicit Xmpdatum(const XmpKey& key, const Value* pValue =0); //! Copy constructor Xmpdatum(const Xmpdatum& rhs); //! Destructor virtual ~Xmpdatum(); //@} //! @name Manipulators //@{ //! Assignment operator Xmpdatum& operator=(const Xmpdatum& rhs); /*! @brief Assign std::string \em value to the %Xmpdatum. Calls setValue(const std::string&). */ Xmpdatum& operator=(const std::string& value); /*! @brief Assign const char* \em value to the %Xmpdatum. Calls operator=(const std::string&). */ Xmpdatum& operator=(const char* value); /*! @brief Assign a boolean \em value to the %Xmpdatum. Translates the value to a string "true" or "false". */ Xmpdatum& operator=(const bool& value); /*! @brief Assign a \em value of any type with an output operator to the %Xmpdatum. Calls operator=(const std::string&). */ template<typename T> Xmpdatum& operator=(const T& value); /*! @brief Assign Value \em value to the %Xmpdatum. Calls setValue(const Value*). */ Xmpdatum& operator=(const Value& value); void setValue(const Value* pValue); /*! @brief Set the value to the string \em value. Uses Value::read(const std::string&). If the %Xmpdatum does not have a Value yet, then a %Value of the correct type for this %Xmpdatum is created. If the key is unknown, a XmpTextValue is used as default. Return 0 if the value was read successfully. */ int setValue(const std::string& value); //@} //! @name Accessors //@{ //! Not implemented. Calling this method will raise an exception. long copy(byte* buf, ByteOrder byteOrder) const; std::ostream& write(std::ostream& os, const ExifData* pMetadata =0) const; /*! @brief Return the key of the Xmpdatum. The key is of the form '<b>Xmp</b>.prefix.property'. Note however that the key is not necessarily unique, i.e., an XmpData object may contain multiple metadata with the same key. */ std::string key() const; const char* familyName() const; //! Return the (preferred) schema namespace prefix. std::string groupName() const; //! Return the property name. std::string tagName() const; std::string tagLabel() const; //! Properties don't have a tag number. Return 0. uint16_t tag() const; TypeId typeId() const; const char* typeName() const; // Todo: Remove this method from the baseclass //! The Exif typeSize doesn't make sense here. Return 0. long typeSize() const; long count() const; long size() const; std::string toString() const; std::string toString(long n) const; long toLong(long n =0) const; float toFloat(long n =0) const; Rational toRational(long n =0) const; Value::AutoPtr getValue() const; const Value& value() const; //@} private: // Pimpl idiom struct Impl; Impl* p_; }; // class Xmpdatum //! Container type to hold all metadata typedef std::vector<Xmpdatum> XmpMetadata; /*! @brief A container for XMP data. This is a top-level class of the %Exiv2 library. Provide high-level access to the XMP data of an image: - read XMP information from an XML block - access metadata through keys and standard C++ iterators - add, modify and delete metadata - serialize XMP data to an XML block */ class EXIV2API XmpData { public: //! XmpMetadata iterator type typedef XmpMetadata::iterator iterator; //! XmpMetadata const iterator type typedef XmpMetadata::const_iterator const_iterator; //! @name Manipulators //@{ /*! @brief Returns a reference to the %Xmpdatum that is associated with a particular \em key. If %XmpData does not already contain such an %Xmpdatum, operator[] adds object \em Xmpdatum(key). @note Since operator[] might insert a new element, it can't be a const member function. */ Xmpdatum& operator[](const std::string& key); /*! @brief Add an %Xmpdatum from the supplied key and value pair. This method copies (clones) the value. @return 0 if successful. */ int add(const XmpKey& key, const Value* value); /*! @brief Add a copy of the Xmpdatum to the XMP metadata. @return 0 if successful. */ int add(const Xmpdatum& xmpdatum); /*! @brief Delete the Xmpdatum at iterator position pos, return the position of the next Xmpdatum. @note Iterators into the metadata, including pos, are potentially invalidated by this call. */ iterator erase(iterator pos); //! Delete all Xmpdatum instances resulting in an empty container. void clear(); //! Sort metadata by key void sortByKey(); //! Begin of the metadata iterator begin(); //! End of the metadata iterator end(); /*! @brief Find the first Xmpdatum with the given key, return an iterator to it. */ iterator findKey(const XmpKey& key); //@} //! @name Accessors //@{ //! Begin of the metadata const_iterator begin() const; //! End of the metadata const_iterator end() const; /*! @brief Find the first Xmpdatum with the given key, return a const iterator to it. */ const_iterator findKey(const XmpKey& key) const; //! Return true if there is no XMP metadata bool empty() const; //! Get the number of metadata entries long count() const; //! are we to use the packet? bool usePacket() const { return usePacket_; } ; //! set usePacket_ bool usePacket(bool b) { bool r = usePacket_; usePacket_=b ; return r; }; //! setPacket void setPacket(const std::string& xmpPacket) { xmpPacket_ = xmpPacket ; usePacket(false); }; // ! getPacket const std::string& xmpPacket() const { return xmpPacket_ ; }; //@} private: // DATA XmpMetadata xmpMetadata_; std::string xmpPacket_ ; bool usePacket_ ; }; // class XmpData /*! @brief Stateless parser class for XMP packets. Images use this class to parse and serialize XMP packets. The parser uses the XMP toolkit to do the job. */ class EXIV2API XmpParser { public: //! Options to control the format of the serialized XMP packet. enum XmpFormatFlags { omitPacketWrapper = 0x0010UL, //!< Omit the XML packet wrapper. readOnlyPacket = 0x0020UL, //!< Default is a writeable packet. useCompactFormat = 0x0040UL, //!< Use a compact form of RDF. includeThumbnailPad = 0x0100UL, //!< Include a padding allowance for a thumbnail image. exactPacketLength = 0x0200UL, //!< The padding parameter is the overall packet length. writeAliasComments = 0x0400UL, //!< Show aliases as XML comments. omitAllFormatting = 0x0800UL //!< Omit all formatting whitespace. }; /*! @brief Decode XMP metadata from an XMP packet \em xmpPacket into \em xmpData. The format of the XMP packet must follow the XMP specification. This method clears any previous contents of \em xmpData. @param xmpData Container for the decoded XMP properties @param xmpPacket The raw XMP packet to decode @return 0 if successful;<BR> 1 if XMP support has not been compiled-in;<BR> 2 if the XMP toolkit failed to initialize;<BR> 3 if the XMP toolkit failed and raised an XMP_Error */ static int decode( XmpData& xmpData, const std::string& xmpPacket); /*! @brief Encode (serialize) XMP metadata from \em xmpData into a string xmpPacket. The XMP packet returned in the string follows the XMP specification. This method only modifies \em xmpPacket if the operations succeeds (return code 0). @param xmpPacket Reference to a string to hold the encoded XMP packet. @param xmpData XMP properties to encode. @param formatFlags Flags that control the format of the XMP packet, see enum XmpFormatFlags. @param padding Padding length. @return 0 if successful;<BR> 1 if XMP support has not been compiled-in;<BR> 2 if the XMP toolkit failed to initialize;<BR> 3 if the XMP toolkit failed and raised an XMP_Error */ static int encode( std::string& xmpPacket, const XmpData& xmpData, uint16_t formatFlags =useCompactFormat, uint32_t padding =0); /*! @brief Lock/unlock function type A function of this type can be passed to initialize() to make subsequent registration of XMP namespaces thread-safe. See the initialize() function for more information. @param pLockData Pointer to the pLockData passed to initialize() @param lockUnlock Indicates whether to lock (true) or unlock (false) */ typedef void (*XmpLockFct)(void* pLockData, bool lockUnlock); /*! @brief Initialize the XMP Toolkit. Calling this method is usually not needed, as encode() and decode() will initialize the XMP Toolkit if necessary. The function takes optional pointers to a callback function \em xmpLockFct and related data \em pLockData that the parser uses when XMP namespaces are subsequently registered. The initialize() function itself still is not thread-safe and needs to be called in a thread-safe manner (e.g., on program startup), but if used with suitable additional locking parameters, any subsequent registration of namespaces will be thread-safe. Example usage on Windows using a critical section: @code void main() { struct XmpLock { CRITICAL_SECTION cs; XmpLock() { InitializeCriticalSection(&cs); } ~XmpLock() { DeleteCriticalSection(&cs); } static void LockUnlock(void* pData, bool fLock) { XmpLock* pThis = reinterpret_cast<XmpLock*>(pData); if (pThis) { (fLock) ? EnterCriticalSection(&pThis->cs) : LeaveCriticalSection(&pThis->cs); } } } xmpLock; // Pass the locking mechanism to the XMP parser on initialization. // Note however that this call itself is still not thread-safe. Exiv2::XmpParser::initialize(XmpLock::LockUnlock, &xmpLock); // Program continues here, subsequent registrations of XMP // namespaces are serialized using xmpLock. } @endcode @return True if the initialization was successful, else false. */ static bool initialize(XmpParser::XmpLockFct xmpLockFct =0, void* pLockData =0); /*! @brief Terminate the XMP Toolkit and unregister custom namespaces. Call this method when the XmpParser is no longer needed to allow the XMP Toolkit to cleanly shutdown. */ static void terminate(); private: /*! @brief Register a namespace with the XMP Toolkit. */ static void registerNs(const std::string& ns, const std::string& prefix); /*! @brief Delete a namespace from the XMP Toolkit. XmpProperties::unregisterNs calls this to synchronize namespaces. */ static void unregisterNs(const std::string& ns); /*! @brief Get namespaces registered with XMPsdk */ static void registeredNamespaces(Exiv2::Dictionary&); // DATA static bool initialized_; //! Indicates if the XMP Toolkit has been initialized static XmpLockFct xmpLockFct_; static void* pLockData_; friend class XmpProperties; // permit XmpProperties -> registerNs() and registeredNamespaces() }; // class XmpParser // ***************************************************************************** // free functions, template and inline definitions inline Xmpdatum& Xmpdatum::operator=(const char* value) { return Xmpdatum::operator=(std::string(value)); } inline Xmpdatum& Xmpdatum::operator=(const bool& value) { return operator=(value ? "True" : "False"); } template<typename T> Xmpdatum& Xmpdatum::operator=(const T& value) { setValue(Exiv2::toString(value)); return *this; } } // namespace Exiv2 #endif // #ifndef XMP_HPP_
aferrero2707/PhotoFlow
src/external/exiv2/include/exiv2/xmp.hpp
C++
gpl-3.0
16,837
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division import uuid import base64 import os from django.contrib.gis.db import models from treemap.models import User class APIAccessCredential(models.Model): access_key = models.CharField(max_length=100, null=False, blank=False) secret_key = models.CharField(max_length=256, null=False, blank=False) # If a user is specified then this credential # is always authorized as the given user # # If user is None this credential can access # any user's data if that user's username # and password are also provided user = models.ForeignKey(User, null=True) enabled = models.BooleanField(default=True) @classmethod def create(clz, user=None): secret_key = base64.urlsafe_b64encode(os.urandom(64)) access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\ .replace('=', '') return APIAccessCredential.objects.create( user=user, access_key=access_key, secret_key=secret_key)
ctaylo37/OTM2
opentreemap/api/models.py
Python
gpl-3.0
1,113
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2017-08-14 18:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sessao', '0009_auto_20170619_1441'), ] operations = [ migrations.AddField( model_name='tiporesultadovotacao', name='natureza', field=models.CharField(choices=[('A', 'Aprovado'), ('R', 'Rejeitado')], max_length=100, null=True, verbose_name='Natureza do Tipo'), ), migrations.AlterField( model_name='tiporesultadovotacao', name='nome', field=models.CharField(max_length=100, verbose_name='Nome do Tipo'), ), ]
cmjatai/cmj
sapl/sessao/migrations/0010_auto_20170814_1804.py
Python
gpl-3.0
753
package com.nutiteq.utils; import com.nutiteq.components.Envelope; import com.nutiteq.components.MapPos; import com.nutiteq.projections.Projection; public class TileUtils { private static final double TILESIZE = 256; private static final double initialResolution = 2.0f * Math.PI * 6378137.0f / TILESIZE; private static final double originShift = 2.0f * Math.PI * 6378137.0f / 2.0f; // following is from // http://code.google.com/p/gmap-tile-generator/source/browse/trunk/gmaps-tile-creator/src/gov/ca/maps/tile/geom/GlobalMercator.java?r=15 /** * Returns tile for given Mercator coordinates * * @return */ public static MapPos MetersToTile(MapPos mp, int zoom) { int[] p = MetersToPixels(mp.x, mp.y, zoom); return PixelsToTile(p[0], p[1], zoom); } /** * Returns a tile covering region in given pixel coordinates * * @param px * @param py * @param zoom * @return */ public static MapPos PixelsToTile(int px, int py, int zoom) { int tx = (int) Math.ceil(px / ((double) TILESIZE) - 1); int ty = (int) Math.ceil(py / ((double) TILESIZE) - 1); return new MapPos(tx, (1<<(zoom))-1-ty); } /** * Converts EPSG:900913 to pyramid pixel coordinates in given zoom level * * @param mx * @param my * @param zoom * @return */ public static int[] MetersToPixels(double mx, double my, int zoom) { double res = Resolution(zoom); int px = (int) Math.round((mx + originShift) / res); int py = (int) Math.round((my + originShift) / res); return new int[] { px, py }; } /** * Resolution (meters/pixel) for given zoom level (measured at Equator) * * @return */ public static double Resolution(int zoom) { // return (2 * Math.PI * 6378137) / (this.tileSize * 2**zoom) return initialResolution / Math.pow(2, zoom); } /** * Returns bounds of the given tile in EPSG:900913 (EPSG:3857) coordinates * * @param tx * @param ty (bottom-top) * @param zoom * @return * @deprecated use TileBounds with projection instead */ public static Envelope TileBounds(int tx, int ty, int zoom) { double[] min = PixelsToMeters(tx * TILESIZE, ty * TILESIZE, zoom); double minx = min[0], miny = min[1]; double[] max = PixelsToMeters((tx + 1) * TILESIZE, (ty + 1) * TILESIZE, zoom); double maxx = max[0], maxy = max[1]; return new Envelope( minx, maxx, miny, maxy); } /** * Get bounds of tile * @param tx tile x (left-right) * @param ty tile y (top-bottom) * @param zoom zoom (0 = world) * @param proj * @return bounds, in given projection */ public static Envelope TileBounds(int tx, int ty, int zoom, Projection proj) { double originShift = (proj.getBounds().right-proj.getBounds().left) / 2.0; double res = (originShift * 2.0) / (TILESIZE * (double) (1<<(zoom))); // 1<<(zoom) is same as power(2;zoom) double minx = ((double) tx) * TILESIZE * res - originShift; double miny = (((double) (1<<(zoom))-1-ty) * TILESIZE * res) - originShift; double maxx = (double)(tx+1) * TILESIZE * res - originShift; double maxy = ((double)( (1<<(zoom))-1-ty + 1) * TILESIZE * res) - originShift; return new Envelope( minx, maxx, miny, maxy); } /** * Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 * Datum * * @return */ public static double[] MetersToLatLon(double mx, double my) { double lon = (mx / originShift) * 180.0; double lat = (my / originShift) * 180.0; lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2.0); return new double[] { lat, lon }; } /** * Converts pixel coordinates in given zoom level of pyramid to EPSG:900913 * * @return */ public static double[] PixelsToMeters(double px, double py, int zoom) { double res = Resolution(zoom); double mx = px * res - originShift; double my = originShift - (py * res); return new double[] { mx, my }; } }
FAIMS/faims-android
faimsandroidapp/src/main/java/com/nutiteq/utils/TileUtils.java
Java
gpl-3.0
4,474